text
stringlengths 10
2.72M
|
|---|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans = new ListNode(0);
ListNode answer = ans;
int carry = 0, a= 0, b=0, s=0;
while(l1 != null || l2 != null ){
s = carry;
if(l1 != null){
s += l1.val;
l1 = l1.next;
}
if(l2 != null){
s += l2.val;
l2 = l2.next;
}
System.out.println(s);
answer.next = new ListNode(s % 10);
answer = answer.next;
carry = s / 10;
}
if(carry == 1){
answer.next = new ListNode(carry);
answer = answer.next;
}
return ans.next;
}
}
|
package com.xbang.bootdemo.config.security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Slf4j
public class EvolutionaryAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
//登录成功时回调该方法
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
log.info("用户 {} 登录成功.",authentication.getDetails());
}
}
|
package BUS;
import DAO.UserDAO;
import DTO.UserDTO;
import java.sql.SQLException;
public class UserBUS {
public static boolean checkLoginUser(String username, String password) throws SQLException {
return UserDAO.checkLoginUser(username, password);
}
public static boolean insertUser(UserDTO user) throws SQLException {
if(UserDAO.checkInsUser(user)){
return false;
}
return UserDAO.insertUser(user);
}
public static UserDTO getUserByUsername(String username) throws SQLException {
return UserDAO.getUserByUsername(username);
}
}
|
package com.company.iba.ialeditor.model;
import com.company.iba.ialeditor.service.ClpSerializer;
import com.company.iba.ialeditor.service.ProjectLanguageLocalServiceUtil;
import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.model.BaseModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class ProjectLanguageClp extends BaseModelImpl<ProjectLanguage>
implements ProjectLanguage {
private long _projLangId;
private long _langId;
private long _projectId;
private boolean _isDefaultLang;
private BaseModel<?> _projectLanguageRemoteModel;
private Class<?> _clpSerializerClass = com.company.iba.ialeditor.service.ClpSerializer.class;
public ProjectLanguageClp() {
}
@Override
public Class<?> getModelClass() {
return ProjectLanguage.class;
}
@Override
public String getModelClassName() {
return ProjectLanguage.class.getName();
}
@Override
public long getPrimaryKey() {
return _projLangId;
}
@Override
public void setPrimaryKey(long primaryKey) {
setProjLangId(primaryKey);
}
@Override
public Serializable getPrimaryKeyObj() {
return _projLangId;
}
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj) {
setPrimaryKey(((Long) primaryKeyObj).longValue());
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("projLangId", getProjLangId());
attributes.put("langId", getLangId());
attributes.put("projectId", getProjectId());
attributes.put("isDefaultLang", getIsDefaultLang());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Long projLangId = (Long) attributes.get("projLangId");
if (projLangId != null) {
setProjLangId(projLangId);
}
Long langId = (Long) attributes.get("langId");
if (langId != null) {
setLangId(langId);
}
Long projectId = (Long) attributes.get("projectId");
if (projectId != null) {
setProjectId(projectId);
}
Boolean isDefaultLang = (Boolean) attributes.get("isDefaultLang");
if (isDefaultLang != null) {
setIsDefaultLang(isDefaultLang);
}
}
@Override
public long getProjLangId() {
return _projLangId;
}
@Override
public void setProjLangId(long projLangId) {
_projLangId = projLangId;
if (_projectLanguageRemoteModel != null) {
try {
Class<?> clazz = _projectLanguageRemoteModel.getClass();
Method method = clazz.getMethod("setProjLangId", long.class);
method.invoke(_projectLanguageRemoteModel, projLangId);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getLangId() {
return _langId;
}
@Override
public void setLangId(long langId) {
_langId = langId;
if (_projectLanguageRemoteModel != null) {
try {
Class<?> clazz = _projectLanguageRemoteModel.getClass();
Method method = clazz.getMethod("setLangId", long.class);
method.invoke(_projectLanguageRemoteModel, langId);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getProjectId() {
return _projectId;
}
@Override
public void setProjectId(long projectId) {
_projectId = projectId;
if (_projectLanguageRemoteModel != null) {
try {
Class<?> clazz = _projectLanguageRemoteModel.getClass();
Method method = clazz.getMethod("setProjectId", long.class);
method.invoke(_projectLanguageRemoteModel, projectId);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public boolean getIsDefaultLang() {
return _isDefaultLang;
}
@Override
public boolean isIsDefaultLang() {
return _isDefaultLang;
}
@Override
public void setIsDefaultLang(boolean isDefaultLang) {
_isDefaultLang = isDefaultLang;
if (_projectLanguageRemoteModel != null) {
try {
Class<?> clazz = _projectLanguageRemoteModel.getClass();
Method method = clazz.getMethod("setIsDefaultLang",
boolean.class);
method.invoke(_projectLanguageRemoteModel, isDefaultLang);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
public BaseModel<?> getProjectLanguageRemoteModel() {
return _projectLanguageRemoteModel;
}
public void setProjectLanguageRemoteModel(
BaseModel<?> projectLanguageRemoteModel) {
_projectLanguageRemoteModel = projectLanguageRemoteModel;
}
public Object invokeOnRemoteModel(String methodName,
Class<?>[] parameterTypes, Object[] parameterValues)
throws Exception {
Object[] remoteParameterValues = new Object[parameterValues.length];
for (int i = 0; i < parameterValues.length; i++) {
if (parameterValues[i] != null) {
remoteParameterValues[i] = ClpSerializer.translateInput(parameterValues[i]);
}
}
Class<?> remoteModelClass = _projectLanguageRemoteModel.getClass();
ClassLoader remoteModelClassLoader = remoteModelClass.getClassLoader();
Class<?>[] remoteParameterTypes = new Class[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i].isPrimitive()) {
remoteParameterTypes[i] = parameterTypes[i];
} else {
String parameterTypeName = parameterTypes[i].getName();
remoteParameterTypes[i] = remoteModelClassLoader.loadClass(parameterTypeName);
}
}
Method method = remoteModelClass.getMethod(methodName,
remoteParameterTypes);
Object returnValue = method.invoke(_projectLanguageRemoteModel,
remoteParameterValues);
if (returnValue != null) {
returnValue = ClpSerializer.translateOutput(returnValue);
}
return returnValue;
}
@Override
public void persist() throws SystemException {
if (this.isNew()) {
ProjectLanguageLocalServiceUtil.addProjectLanguage(this);
} else {
ProjectLanguageLocalServiceUtil.updateProjectLanguage(this);
}
}
@Override
public ProjectLanguage toEscapedModel() {
return (ProjectLanguage) ProxyUtil.newProxyInstance(ProjectLanguage.class.getClassLoader(),
new Class[] { ProjectLanguage.class },
new AutoEscapeBeanHandler(this));
}
@Override
public Object clone() {
ProjectLanguageClp clone = new ProjectLanguageClp();
clone.setProjLangId(getProjLangId());
clone.setLangId(getLangId());
clone.setProjectId(getProjectId());
clone.setIsDefaultLang(getIsDefaultLang());
return clone;
}
@Override
public int compareTo(ProjectLanguage projectLanguage) {
int value = 0;
if (getProjLangId() < projectLanguage.getProjLangId()) {
value = -1;
} else if (getProjLangId() > projectLanguage.getProjLangId()) {
value = 1;
} else {
value = 0;
}
if (value != 0) {
return value;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ProjectLanguageClp)) {
return false;
}
ProjectLanguageClp projectLanguage = (ProjectLanguageClp) obj;
long primaryKey = projectLanguage.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
} else {
return false;
}
}
public Class<?> getClpSerializerClass() {
return _clpSerializerClass;
}
@Override
public int hashCode() {
return (int) getPrimaryKey();
}
@Override
public String toString() {
StringBundler sb = new StringBundler(9);
sb.append("{projLangId=");
sb.append(getProjLangId());
sb.append(", langId=");
sb.append(getLangId());
sb.append(", projectId=");
sb.append(getProjectId());
sb.append(", isDefaultLang=");
sb.append(getIsDefaultLang());
sb.append("}");
return sb.toString();
}
@Override
public String toXmlString() {
StringBundler sb = new StringBundler(16);
sb.append("<model><model-name>");
sb.append("com.company.iba.ialeditor.model.ProjectLanguage");
sb.append("</model-name>");
sb.append(
"<column><column-name>projLangId</column-name><column-value><![CDATA[");
sb.append(getProjLangId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>langId</column-name><column-value><![CDATA[");
sb.append(getLangId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>projectId</column-name><column-value><![CDATA[");
sb.append(getProjectId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>isDefaultLang</column-name><column-value><![CDATA[");
sb.append(getIsDefaultLang());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
}
|
package AbstractFactoryPattern03.example.factory;
import AbstractFactoryPattern03.example.product.Button;
import AbstractFactoryPattern03.example.product.ComboBox;
import AbstractFactoryPattern03.example.product.TextFiled;
public abstract class SkinFactory {
public abstract Button getButton();
public abstract ComboBox getComboBox();
public abstract TextFiled getTextFiled();
}
|
package lawscraper.client.ui.panels.dynamictabpanel;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.ui.Widget;
/**
* Created by erik, IT Bolaget Per & Per AB
* Date: 7/13/12
* Time: 6:19 PM
*/
public class DynamicTabPanelChangeEvent extends GwtEvent<DynamicTabPanelChangeHandler> {
private Widget widget;
public DynamicTabPanelChangeEvent() {
super();
}
public final static Type<DynamicTabPanelChangeHandler> TYPE = new Type<DynamicTabPanelChangeHandler>();
public DynamicTabPanelChangeEvent(Widget widget) {
this.widget = widget;
}
@Override
public Type<DynamicTabPanelChangeHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(DynamicTabPanelChangeHandler handler) {
handler.onDynamicTabPanelChange(this);
}
public static Type<DynamicTabPanelChangeHandler> getType() {
return TYPE;
}
public Widget getWidget() {
return widget;
}
}
|
package com.ism.projects.th;
import com.ism.common.Common;
import com.ism.common.util.Utility;
import com.ism.rule.entity.Field;
import com.ism.rule.entity.constant.Constants;
public class AccountValidation2 extends AccountValidationService{
@Override
protected void initVariable() {
account_no = new String(ai.getData()[0][0]).trim();
ic_no = new String(ai.getData()[0][1]).trim();
}
@Override
public byte[] execute(byte[] input) {
byte[] respon =null;
long startTime = System.currentTimeMillis();
init(input);
Field[] flds = getMasterFields(outDS);
int totalOutLen = 0;
String bizErrorCode = TXN_SUCCESS;
boolean isValid = true;
for (int i = 0; i < flds.length; i++) {
int length = flds[i].getLength();
totalOutLen += length;
}
totalOutDataLen = totalOutLen;
byte[] r_val = new byte[totalOutDataLen];
// Start Logic
try {
parseInput(reqmsg.getMessage());
logS02(reqmsg.getMessage(), startTime, null);
initVariable();
logN("input parameters[" + account_no + "][" + ic_no + "]");
/*
* %-- BR 6 Jan 2016 - Add D (Dormant) status
*/
bizErrorCode = "0000" + String.valueOf((verifyAccount(account_no, ic_no, false, new String[]{"M", "S", "Z", "D"}, true, new String[]{"01", "02", "11"}, false, null)));
bizErrorCode = bizErrorCode.substring(bizErrorCode.length() - 4);
logV("bizcode"+bizErrorCode);
checkAGBETX();
respon = setResponse(bizErrorCode);
// if (bizErrorCode.equals(TXN_SUCCESS)) {
//// Get name from db.
// checkAGBETX();
//
// respon = setResponse(bizErrorCode);
//
// } else {
// respon = setError(bizErrorCode);
// }
} catch (Exception e) {
logE("failed to execute biz service", e);
}
long endTime = System.currentTimeMillis();
long elapsed = (endTime - startTime);
if (elapsed >= timeout * 1000) {
isValid = false;
logE("processing time is tool long - elapsed time [" + elapsed
+ "]ms, timeout[" + (timeout * 1000) + "]ms");
}
// End Logic
// Prepare Out Bytes
try {
free();
} catch (Exception ignore) {
}
r_val = respon;
reqmsg.setError(false);
reqmsg.setMessage(r_val);
if(Common._fissLogLevel >= Constants.LOG_VERBOSE) {
logV(this.getClass().getName() + " end. out message [" + r_val.length + "]["+ new String(r_val) + "]");
}
byte[] rtn = Utility.getBytes(reqmsg);
return rtn;
}
}
|
package apascualco.blog.springboot;
import apascualco.blog.springboot.persistence.entidades.CarroceriaEntidad;
import apascualco.blog.springboot.persistence.repositorio.CarroceriaREPO;
import apascualco.blog.springboot.utils.PersistenciaUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CarroceriaRepositorioTests {
@Autowired
private CarroceriaREPO carroceriaREPO;
private long count;
@Test
public void buscarTodos() {
this.count = carroceriaREPO.count();
assertTrue(carroceriaREPO.findAll().size() == this.count);
}
@Test
public void insertar() {
this.count = carroceriaREPO.count();
CarroceriaEntidad carroceriaEntidad = PersistenciaUtils.generarCarroceriaEntidad(carroceriaREPO);
assertNotNull(carroceriaEntidad.getId());
long carroceriaCount = carroceriaREPO.count();
assertTrue(this.count < carroceriaCount);
this.count = carroceriaCount;
}
@Test
public void borrar() {
carroceriaREPO.delete(carroceriaREPO.count());
assertTrue(this.count < carroceriaREPO.count());
}
}
|
package com.t.client.domain;
import com.t.core.domain.Job;
import java.util.List;
/**
* @author tb
* @date 2018/12/18 9:54
*/
public class Response {
private boolean success;
private String msg;
private String code;
// 如果success 为false, 这个才会有值
private List<Job> failedJobs;
}
|
package com.example.a49876.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.SetOptions;
import java.util.HashMap;
import java.util.Map;
/**
* Created by 49876 on 4/24/2018.
*/
public class LogInActivity extends AppCompatActivity implements View.OnClickListener{
private FirebaseAuth mAuth;
private TextView email, password;
private Button login, signup;
public static FirebaseUser user;
private ProgressBar progressBar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
mAuth = FirebaseAuth.getInstance();
email = findViewById(R.id.email);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
login.setOnClickListener(this);
signup = findViewById(R.id.signup);
signup.setOnClickListener(this);
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.INVISIBLE);
}
// sign in
public void logIn(String email, String password) {
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.e("Login", "signInWithEmail:success");
user = mAuth.getCurrentUser();
progressBar.setVisibility(View.INVISIBLE);
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.e("login", "signInWithEmail:failure", task.getException());
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(LogInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
//sign up
public void signUp(String email, String password){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.e("Sign up", "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(LogInActivity.this, "Signup Success.",
Toast.LENGTH_SHORT).show();
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.e("Sign up", "createUserWithEmail:failure");
Toast.makeText(LogInActivity.this, "Signup Failed.",
Toast.LENGTH_SHORT).show();
//updateUI(null);
}
progressBar.setVisibility(View.INVISIBLE);
// ...
}
});
}
private void updateUI(FirebaseUser user) {
if (user != null) {
Log.e("login","success");
Intent intent = new Intent(LogInActivity.this, MainActivity.class);
startActivity(intent);
} else {
Log.e("login","fail");
}
}
// @Override
// public void onStart() {
// super.onStart();
// }
@Override
public void onClick(View v) {
Button b = (Button) v;
progressBar.setVisibility(View.VISIBLE);
switch(b.getId()) {
case R.id.login:
{
logIn(email.getText().toString(),password.getText().toString());
break;
}
case R.id.signup:
{
signUp(email.getText().toString(),password.getText().toString());
break;
}
}
}
}
|
package com.xyt.pageModel;
import java.sql.Timestamp;
import com.xyt.model.Usertbl;
//与插入数据库的表能直接映射的类
public class TopicMessage {
private String messageid;
private String userid;
private String topicid;
private String message;
private Integer committime;
private Integer transmit;
private Timestamp createtime;
public String getMessageid() {
return messageid;
}
public void setMessageid(String messageid) {
this.messageid = messageid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getTopicid() {
return topicid;
}
public void setTopicid(String topicid) {
this.topicid = topicid;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getCommittime() {
return committime;
}
public void setCommittime(Integer committime) {
this.committime = committime;
}
public Integer getTransmit() {
return transmit;
}
public void setTransmit(Integer transmit) {
this.transmit = transmit;
}
public Timestamp getCreatetime() {
return createtime;
}
public void setCreatetime(Timestamp createtime) {
this.createtime = createtime;
}
}
|
package oopTraining;
import java.util.ArrayList;
import java.util.Random;
import java.util.Random;
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
final Random r = new Random();
ArrayList<Viikonpaiva> vpt = new ArrayList<Viikonpaiva>();
for(Viikonpaiva vp : Viikonpaiva.values()){
vpt.add(vp);
}
ArrayList<Kuukausi> kuukaudet = new ArrayList<Kuukausi>();
for(Kuukausi k : Kuukausi.values()){
kuukaudet.add(k);
}
for(int i = 0; i < 20; i++){
Viikonpaiva v = vpt.get(r.nextInt(vpt.size()));
Kuukausi k = kuukaudet.get(r.nextInt(kuukaudet.size()));
System.out.println(k + "N " + (r.nextInt(4) + 1) + ". " + v);
}
}
public enum Viikonpaiva {
RILLUNTAI
}
public enum Kuukausi {
TAMMIKUU, HELMIKUU, MAALISKUU, HUHTIKUU, TOUKOKUU, KESAKUU,
HEINAKUU, ELOKUU, SYYSKUU, LOKAKUU, MARRASKUU, JOULUKUU
}
}
|
package com.company.Net;
import java.util.Arrays;
public class Command {
private String funcName;
private String[] args;
public Command(String funcName, String[] args) {
this.funcName = funcName;
this.args = args;
}
public String getFuncName() {
return funcName;
}
public String[] getArgs() {
return args;
}
@Override
public String toString() {
return funcName + "#" + Arrays.toString(args);
}
public static Command parse(String value) {
String funcName = "";
String[] args = new String[]{""};
int i = 0;
int j = 0;
while (value.charAt(i) != '#')
funcName += value.charAt(i++);
i++;
while (value.length() > i) {
if (value.charAt(i) == '[' || value.charAt(i) == ']') {
i++;
continue;
}
while (value.charAt(i) != ',' || value.length() > i)
args[j] += value.charAt(i++);
j++;
}
Command command = new Command(funcName, args);
return command;
}
}
|
package com.channing.snailhouse.util;
import com.channing.snailhouse.bean.ErrorCode;
public class CheckedException extends RuntimeException {
private static final long serialVersionUID = -7406701992372965750L;
private String msg;
private String code;
public CheckedException(String msg) {
super(msg);
this.msg = msg;
}
public CheckedException(String code,String msg){
super(msg);
this.msg = msg;
this.code = code;
}
public CheckedException(ErrorCode errorCode){
super(errorCode.getMsg());
this.msg = errorCode.getMsg();
this.code = errorCode.getCode();
}
public void setErrorMessage(String errorMessage) {
this.msg = errorMessage;
}
public String getErrorMessage() {
return msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
|
package com.zhongyp.advanced.over.hide;
/**
* @author zhongyp.
* @date 2019/8/14
*/
public class Test {
public static void main(String[] args) {
// 向上强制类型转换
A a = new B();
// 此时输出的是A中的name
System.out.println(a.name);
// 因为强制类型转换到了B,所以此时输出的是B的name
System.out.println(((B)a).name);
// 输出是A的show方法
a.show();
// 此时输出的是B的show方法
((B)a).show();
a.testAccess();
}
}
|
package ec.edu.upse.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import ec.edu.upse.modelo.TblSgaEspaciofisico;
public class EspaciofisicoDao extends ClaseDao {
@SuppressWarnings("unchecked")
public List<TblSgaEspaciofisico> getEspfisico(){
List<TblSgaEspaciofisico> retorno = new ArrayList<TblSgaEspaciofisico>();
Query query = getEntityManager().createNamedQuery("TblSgaEspaciofisico.findAll");
retorno = (List<TblSgaEspaciofisico>) query.getResultList();
return retorno;
}
}
|
package cn.test.demo01;
public class test {
public static void main(String[] args) {
String[] arr = new String[3];
arr[0]="11";
System.out.println(arr[0]);
Person[] arr1 = new Person[2];
Person p = new Person("ww","11");
arr1[0] = new Person("qq","11");
arr1[1] = p;
System.out.println(arr1[1]);
}
}
|
package mb.tianxundai.com.toptoken.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import mb.tianxundai.com.toptoken.R;
import mb.tianxundai.com.toptoken.bean.MallAddressrBean;
public class MallAddressAdapter extends BaseAdapter{
private ArrayList<MallAddressrBean.MallAddress> list;
private Context context;
private MyHolder holder;
public ArrayList<MallAddressrBean.MallAddress> getList() {
return list;
}
public void setList(ArrayList<MallAddressrBean.MallAddress> list) {
this.list = list;
}
public MallAddressAdapter(ArrayList<MallAddressrBean.MallAddress> list, Context context) {
super();
this.list = list;
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mall_address, null);
holder = new MyHolder(convertView);
convertView.setTag(holder);
} else {
holder = (MyHolder) convertView.getTag();
}
if (!list.get(position).getName().equals("")) {
holder.tv_pic.setText(list.get(position).getName().substring(0, 1));
}
holder.tv_name_phone.setText(list.get(position).getName()+" "+list.get(position).getPhone());
holder.tv_address.setText(list.get(position).getDistrict()+" "+list.get(position).getAddress());
holder.iv_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickItemEditListener.onEdit(position);
}
});
holder.iv_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickItemEditListener.onDelete(position);
}
});
return convertView;
}
private OnClickItemEditListener onClickItemEditListener;
public void setOnClickItemEditListener(OnClickItemEditListener onClickItemEditListener) {
this.onClickItemEditListener = onClickItemEditListener;
}
public interface OnClickItemEditListener{
void onEdit(int position);
void onDelete(int position);
}
class MyHolder {
private ImageView iv_edit,iv_delete;
private TextView tv_pic,tv_name_phone,tv_address;
public MyHolder(View view) {
tv_pic = view.findViewById(R.id.tv_pic);
iv_edit = view.findViewById(R.id.iv_edit);
iv_delete = view.findViewById(R.id.iv_delete);
tv_name_phone = view.findViewById(R.id.tv_name_phone);
tv_address = view.findViewById(R.id.tv_address);
}
}
public void reLoadMore(List<MallAddressrBean.MallAddress> data){
this.list.addAll(data);
notifyDataSetChanged();
}
public void refresh(List<MallAddressrBean.MallAddress> data){
this.list.clear();
this.list.addAll(data);
notifyDataSetChanged();
}
}
|
package com.yidatec.weixin.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.axis.utils.StringUtils;
import org.springframework.jdbc.core.RowMapper;
public class StatisticsDao extends DataBase {
/**
* 搜索日每名坐席请求单数
*
* @param fromDt
* @param toDt
* @return
*/
@SuppressWarnings("unchecked")
public List<Object> searchEmployeeTask(Date fromDt, Date toDt,
String serviceId) {
String sql = "select count(type) taskNum,tq.type "
+ " from wei_task_queue_all tq "
+ " where tq.create_date between ? and ? ";
if (!StringUtils.isEmpty(serviceId) && !serviceId.equals("-1"))
sql += " and service_id='" + serviceId+"'";
sql += " group by tq.type ";
List<Object> list = jdbcTemplate.query(sql,
new Object[] { fromDt, toDt }, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
List<Object> tempList = new ArrayList<Object>();
tempList.add(rs.getString("type"));
tempList.add(rs.getInt("taskNum"));
return tempList;
}
});
return list;
}
/**
* 搜索日总请求单数
*
* @param fromDt
* @param toDt
* @return
*/
@SuppressWarnings("unchecked")
public List<HashMap<String, Object>> searchDailyTask(String date,
String serviceId) {
String sql = "select hour(create_date) as hh,count(0) as taskNum "
+ " from wei_task_queue_all " + " where date(create_date) = ?";
if (!StringUtils.isEmpty(serviceId) && !serviceId.equals("-1"))
sql += " and service_id='" + serviceId+"'";
sql += " group by hh " + " order by create_date";
List<HashMap<String, Object>> list = jdbcTemplate.query(sql,
new Object[] { date }, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("categories", rs.getInt("hh"));
map.put("taskNum", rs.getInt("taskNum"));
return map;
}
});
return list;
}
/**
* 日请求单总数
*
* @param fromDt
* @param toDt
* @return
*/
@SuppressWarnings("unchecked")
public int dailyTotalCount(Date fromDt, Date toDt,String serviceId) {
String sql = "select count(0) from wei_task_queue_all where create_date between ? and ?";
if (!StringUtils.isEmpty(serviceId) && !serviceId.equals("-1"))
sql += " and service_id='" + serviceId+"'";
List<Integer> list = jdbcTemplate.query(sql, new Object[] { fromDt,
toDt }, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
return rs.getInt(1);
}
});
return list.get(0);
}
/**
* 搜索月每名坐席请求单数
*
* @param month
* @return
*/
@SuppressWarnings("unchecked")
public List<Object> searchMonthlyEmployeeTask(int month) {
String sql = "select count(service_id) taskNum,pu.name "
+ " from wei_task_queue tq "
+ " left join wei_platform_users pu "
+ " on tq.service_id = pu.id "
+ " where month(tq.create_date) = ? "
+ " group by tq.service_id ";
List<Object> list = jdbcTemplate.query(sql, new Object[] { month },
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
List<Object> tempList = new ArrayList<Object>();
tempList.add(rs.getString("name"));
tempList.add(rs.getInt("taskNum"));
return tempList;
}
});
return list;
}
/**
* 月总请求单数
*
* @param month
* @return
*/
@SuppressWarnings("unchecked")
public List<HashMap<String, Object>> searchMonthlyData(int month) {
String sql = "select year(create_date) year, "
+ " month(create_date) month, " + " day(create_date) day, "
+ " count(service_id) taskNum " + " from wei_task_queue "
+ " where month(create_date) = ? "
+ " group by year(create_date), " + " month(create_date), "
+ " day(create_date) " + " order by day ";
List<HashMap<String, Object>> list = jdbcTemplate.query(sql,
new Object[] { month }, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("year", rs.getString("year"));
map.put("month", rs.getString("month"));
map.put("categories", rs.getInt("day"));
map.put("taskNum", rs.getInt("taskNum"));
return map;
}
});
return list;
}
/**
* 月请求总单数
*
* @param month
* @return
*/
@SuppressWarnings("unchecked")
public int monthlyTotalCount(int month) {
String sql = "select count(0) from wei_task_queue where month(create_date) = ?";
List<Integer> list = jdbcTemplate.query(sql, new Object[] { month },
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
return rs.getInt(1);
}
});
return list.get(0);
}
/**
* 搜索年每名坐席请求单数
*
* @param fromDt
* @param toDt
* @return
*/
@SuppressWarnings("unchecked")
public List<Object> searchEmployeeYearlyTask(String fromDt, String toDt,String serviceId) {
String sql = "select count(type) taskNum,tq.type "
+ " from wei_task_queue_all tq "
+ " where tq.create_date between ? and ? ";
if (!StringUtils.isEmpty(serviceId) && !serviceId.equals("-1"))
sql += " and service_id='" + serviceId+"'";
sql += " group by tq.type ";
List<Object> list = jdbcTemplate.query(sql,
new Object[] { fromDt, toDt }, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
List<Object> tempList = new ArrayList<Object>();
tempList.add(rs.getString("type"));
tempList.add(rs.getInt("taskNum"));
return tempList;
}
});
return list;
}
/**
* 年总请求单数
*
* @param fromDt
* @param toDt
* @return
*/
@SuppressWarnings("unchecked")
public List<HashMap<String, Object>> searchYearlyTask(String fromDt,
String toDt,String serviceId) {
String sql = "select DATE_FORMAT(create_date,'%Y%m') as hh,count(0) as taskNum "
+ " from wei_task_queue_all "
+ " where create_date between ? and ? ";
if (!StringUtils.isEmpty(serviceId) && !serviceId.equals("-1"))
sql += " and service_id='" + serviceId+"'";
sql += " group by hh " + " order by create_date";
List<HashMap<String, Object>> list = jdbcTemplate.query(sql,
new Object[] { fromDt, toDt }, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("categories", rs.getString("hh"));
map.put("taskNum", rs.getInt("taskNum"));
return map;
}
});
return list;
}
/**
* 年请求单总数
*
* @param fromDt
* @param toDt
* @return
*/
@SuppressWarnings("unchecked")
public int yearlyTotalCount(String fromDt, String toDt,String serviceId) {
String sql = "select count(0) from wei_task_queue_all where create_date between ? and ?";
if (!StringUtils.isEmpty(serviceId) && !serviceId.equals("-1"))
sql += " and service_id='" + serviceId+"'";
List<Integer> list = jdbcTemplate.query(sql, new Object[] { fromDt,
toDt }, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
return rs.getInt(1);
}
});
return list.get(0);
}
/**
* 获取坐席id和姓名
*
* @return
*/
@SuppressWarnings("unchecked")
public List<HashMap<String, String>> getServers() {
String sql = "select id,name from wei_platform_users where type=2 or type=3";
return jdbcTemplate.query(sql, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", rs.getString("id"));
map.put("name", rs.getString("name"));
return map;
}
});
}
/**
* 查找注册用户表
* @return
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Map<String, String>> exportTask(String server,String fromDate,String toDate) throws Exception {
String sqlWhere = "";
if(server.equals("-1") || server.equals("")){
sqlWhere = " 1 = 1 ";
} else {
sqlWhere = " service_id = '" + server + "'";
}
String sql = " select a.*,b.account,b.name,c.*,d.create_date from " + getTableName("task_queue_all") + " a "
+ " left join " + getTableName("platform_users") + " b on a.service_id = b.id "
+ " left join " + getTableName("user_detail") + " c on a.id = c.taskid "
+ " left join (select x.task_queue_id,x.create_date from (select task_queue_id, create_date from " + getTableName("task_message_all") + " where create_user <> open_id and create_user <> 'system' order by create_date) x group by x.task_queue_id) d "
+ " on a.id = d.task_queue_id "
+ " where " + sqlWhere + " and a.create_date between ? and ? "
+ " order by a.create_date desc ";
return jdbcTemplate.query(sql,
new Object[]{ fromDate,toDate },
new RowMapper() {
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id",rs.getString("a.id"));
map.put("openid",rs.getString("a.open_id"));
map.put("service_id",rs.getString("a.service_id"));
map.put("task_status",rs.getInt("a.task_status"));
map.put("service_score",rs.getInt("a.service_score"));
map.put("custom_asses_desc",rs.getString("a.custom_asses_desc"));
map.put("custom_score",rs.getInt("a.custom_score"));
map.put("rid",rs.getString("a.rid"));
map.put("type",rs.getString("a.type"));
map.put("cause",rs.getString("a.cause"));
map.put("create_user",rs.getString("a.create_user"));
map.put("create_date",rs.getString("a.create_date"));
map.put("modify_user",rs.getString("a.modify_user"));
map.put("modify_date",rs.getString("a.modify_date"));
map.put("account",rs.getString("b.account"));
map.put("name",rs.getString("b.name"));
map.put("key_account",rs.getString("c.key_account"));
map.put("custom_name",rs.getString("c.name"));
map.put("custom_cellphone",rs.getString("c.cellphone"));
map.put("custom_email",rs.getString("c.email"));
map.put("first_date",rs.getString("d.create_date"));
return map;
}
});
}
}
|
import java.io.*;
import java.io.FileInputStream;
import java.nio.file.Files;
import org.apache.tika.*;
public class FileClassifier {
public static String tarDir="";
public static void searchFiles(File directory) throws Exception{
Tika tika = new Tika();
File[] list = directory.listFiles();
for(File file : list) {
if(file.isDirectory()){
searchFiles(file);
}else {
System.out.println(file.getName());
FileInputStream fIS = new FileInputStream(file);
String type = tika.detect(fIS);
fIS.close();
System.out.println(type);
File temp = new File(tarDir+"/"+type+"/"+"data");
temp.mkdirs();
File tar = new File(tarDir+"/"+type+"/"+"data"+"/"+file.getName());
try {
Files.move(file.toPath(), tar.toPath());
}catch(Exception e){
continue;
}
}
}
}
public static void main(String[] args) throws Exception {
if(args.length < 2){
System.out.println("Usage: FileClassifier.java <sourcefiles_dir> <targetfiles_dir>");
}else {
String[] fileTypes = {"text/plain", "application/pdf", "application/rdf+xml", "application/rss+xml", "application/xhtml+xml", "text/html", "image/png", "image/jpeg", "audio/mpeg", "video/mp4", "video/quicktime", "application/x-sh", "application/gzip", "application/msword", "application/octet-stream"};
int count = 0;
File directory = new File(args[0]);
tarDir = new java.io.File(args[1]).getCanonicalPath();
searchFiles(directory);
System.out.println(count);
for(int i = 0; i < fileTypes.length; i++){
File fileType = new File(tarDir + "/" + fileTypes[i] + "/data");
File dir = new File(tarDir+"/"+fileTypes[i]+"/"+"test_data");
dir.mkdir();
File[] files = fileType.listFiles();
for(int j = 0; j < (files.length * 0.25); j++){
File tar = new File(tarDir+"/"+fileTypes[i]+"/"+"test_data"+"/"+files[j].getName());
Files.move(files[j].toPath(), tar.toPath());
}
}
}
}
}
|
package go4Code.Restaurante.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import go4Code.Restaurante.dto.MenuDTO;
import go4Code.Restaurante.dto.MenuPageDTO;
import go4Code.Restaurante.model.Menu;
import go4Code.Restaurante.repository.MenuRepository;
import go4Code.Restaurante.service.MenuService;
@CrossOrigin("*")
@RestController
@RequestMapping(path = "/api/menu")
public class MenuController {
@Autowired
MenuService menuService;
@GetMapping( params = {"page", "size"})
public ResponseEntity<MenuPageDTO> getAllMenus(Pageable pageable) {
Page<Menu> menus = menuService.findAll(pageable);
MenuPageDTO pageDto = new MenuPageDTO(
dtosFromMenus(menus.getContent()),
menus.isLast()
);
return new ResponseEntity<>(pageDto, HttpStatus.OK);
}
private List<MenuDTO> dtosFromMenus(List<Menu> menus) {
ArrayList<MenuDTO> dtos = new ArrayList<>();
for (Menu menu: menus) {
dtos.add(new MenuDTO(menu));
}
return dtos;
}
// private List<MenuDTO> dtoListFromMenu(Menu menu) {
// ArrayList<MenuDTO> dtos = new ArrayList<>();
// dtos.add(new MenuDTO(menu));
//
// return dtos;
// }
@GetMapping
public ResponseEntity<List<Menu>> getAllMenus(){
List<Menu> menus = menuService.findAll();
return new ResponseEntity<List<Menu>>(menus, HttpStatus.OK);
}
// @GetMapping
// public ResponseEntity<List<MenuDTO>> getMenus(@RequestParam(required = false, defaultValue="") String name) {
// if (name.isEmpty()) {
// List<Menu> menus = menuService.findAll();
// ArrayList<MenuDTO> dtos = new ArrayList<>();
// for (Menu menu: menus) {
// dtos.add(new MenuDTO(menu));
// }
// return new ResponseEntity<>(dtos, HttpStatus.OK);
// }
//
// Menu menu = menuService.findByName(name);
// if (menu == null) {
// return new ResponseEntity(HttpStatus.NOT_FOUND);
// }
//
// return new ResponseEntity<>(dtoListFromMenu(menu), HttpStatus.OK);
// }
@GetMapping(path = "/{id}")
public ResponseEntity<Menu> getById(@PathVariable Long id) {
Optional<Menu> menu = menuService.findOne(id);
if (menu.isPresent()) {
return new ResponseEntity<Menu>(menu.get(), HttpStatus.OK);
} else {
return new ResponseEntity<Menu>(HttpStatus.NOT_FOUND);
}
}
@PostMapping
public ResponseEntity<Menu> create(@RequestBody Menu menu) {
Menu retVal = menuService.save(menu);
return new ResponseEntity<Menu>(retVal, HttpStatus.CREATED);
}
@PutMapping(path = "/{id}")
public ResponseEntity<Menu> update(@PathVariable Long id,
@RequestBody Menu menu) {
if (menuService.findOne(id).isEmpty()) {
return new ResponseEntity<Menu>(HttpStatus.NOT_FOUND);
}
menu.setId(id);
Menu retVal = menuService.save(menu);
return new ResponseEntity<Menu>(retVal, HttpStatus.OK);
}
@DeleteMapping(path = "/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
Optional<Menu> menu = menuService.findOne(id);
if (menu.isPresent()) {
menuService.remove(menu.get());
return new ResponseEntity<Void>(HttpStatus.OK);
} else {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
}
@GetMapping(params = "name")
public ResponseEntity<List<Menu>> getByName(@RequestParam String name){
List<Menu> menus = menuService.findByName(name);
return new ResponseEntity<List<Menu>>(menus, HttpStatus.OK);
}
@GetMapping(params = "infix")
public ResponseEntity<List<Menu>> getByNameContaining(@RequestParam String infix){
List<Menu> menus = menuService.findByNameContainig(infix);
return new ResponseEntity<List<Menu>>(menus, HttpStatus.OK);
}
}
|
package vnfoss2010.smartshop.serverside.map.geocoder;
public class Point {
public double lat;
public double lng;
public double alt;
public Point() {
}
public Point(double lat, double lng, double alt) {
this.lat = lat;
this.lng = lng;
this.alt = alt;
}
/**
* @return the lat
*/
public double getLat() {
return lat;
}
/**
* @param lat
* the lat to set
*/
public void setLat(double lat) {
this.lat = lat;
}
/**
* @return the lng
*/
public double getLng() {
return lng;
}
/**
* @param lng
* the lng to set
*/
public void setLng(double lng) {
this.lng = lng;
}
/**
* @param alt the alt to set
*/
public void setAlt(double alt) {
this.alt = alt;
}
/**
* @return the alt
*/
public double getAlt() {
return alt;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Point [lat=" + lat + ", lng=" + lng + ", alt=" + alt + "]";
}
}
|
package com.lenovohit.hcp.base.manager.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.lenovohit.hcp.HCPConstants;
import com.lenovohit.hcp.base.configuration.RedisSequenceConfig;
import com.lenovohit.hcp.base.dao.ICommonRedisSequenceDao;
import com.lenovohit.hcp.base.dao.IRedisSequenceDao;
import com.lenovohit.hcp.base.manager.ICommonRedisSequenceManager;
import com.lenovohit.hcp.base.manager.IRedisSequenceManager;
import com.lenovohit.hcp.base.model.RedisSequence;
public class CommonRedisSequenceManager implements ICommonRedisSequenceManager {
@Autowired
private ICommonRedisSequenceDao commonRedisSequenceDao;
@Override
public String get(String key) {
return commonRedisSequenceDao.get(key);
}
}
|
package za.ac.cput.chapter5assignment.abstractfactory;
/**
* Created by student on 2015/03/12.
*/
public interface Fruit {
public abstract String getFruitName();
}
|
package com.toda.consultant.util;
/**
* Created by guugangzhu on 2016/9/20.
*/
public class DialogUtil {
}
|
package dao.cashier;
import entity.Cashier;
import java.util.List;
public interface CashierDao {
void save(Cashier cashier);
// List<Cashier> findAll();
Cashier findById(Long id);
}
|
package br.com.itau;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.*;
import br.com.itau.modelo.Lancamento;
import br.com.itau.service.LancamentoService;
public class Faturas {
private List<Lancamento> lancamentos;
public Faturas(List<Lancamento> lancamentos) {
this.lancamentos = lancamentos;
};
//Gastos ordenados por mes
public Map<Integer, Double> getTotalMeses() {
Map<Integer, Double> sortedMes = this.lancamentos.stream()
.collect(
Collectors.groupingBy(
Lancamento::getMes,
Collectors.summingDouble(Lancamento::getValor)));
return sortedMes;
}
//Todos os lancamentos de uma mesma categoria de sua escolha
public List<Lancamento> getCategoria(Integer categoria) {
List<Lancamento> lancamentoCategoria = this.lancamentos.stream()
.filter(c -> c.getCategoria().equals(categoria))
.sorted(Comparator.comparing(Lancamento::getMes))
.collect(Collectors.toList());
return lancamentoCategoria;
}
//Total da fatura de um mes em especifico
public Double getTotalMes(Integer mes) {
Double faturaMes = this.lancamentos.stream()
.filter(m -> m.getMes().equals(mes))
.mapToDouble(v -> v.getValor())
.sum();
return faturaMes;
}
}
|
/*
* 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.tronipm.bruteforce.entities;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Mateus
*/
public class Robot extends Thread {
private WebSite webSite = null;
private Reader reader = null;
private Writer writer = null;
private int delayBetweenAttempts = 0;
private static final boolean needsToRedirectAfterAttemp = false;
public ArrayList<Credential> arraySuccess = new ArrayList<>();
public Robot() {
this.webSite = new WebSite(Settings.url);
this.delayBetweenAttempts = Settings.delay;
reader = new Reader(Settings.file1, Settings.file2);
writer = new Writer(Settings.fileSuccess);
}
@Override
public void run() {
synchronized (this) {
reader.start();
webSite.open(true);
System.out.println("Starting tests...");
int attempts = 1;
int applyDelay = 0;
for (int u = 0; u < reader.arrayUsers.size(); u++) {
String user = reader.arrayUsers.get(u);
for (int p = 0; p < reader.arrayPasswords.size(); p++) {
String pass = reader.arrayPasswords.get(p);
Credential c = new Credential(user, pass);
System.out.println("Attempt: " + (attempts++));
tryToLogin(c);
if (needsToRedirectAfterAttemp) {
restart();
}
if (Settings.quantityOfAttempsUntilApplyDelay > 0) {
applyDelay++;
if (applyDelay == Settings.quantityOfAttempsUntilApplyDelay) {
applyDelay = 0;
try {
Thread.sleep(Settings.delay);
} catch (InterruptedException ex) {
Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
System.out.println("Finishing tests...");
this.notify();
}
}
public synchronized void tryToLogin(Credential c) {
boolean flag = WantedBehaviour.checkNOT(webSite, c);
if (flag) {
arraySuccess.add(c);
writer.writeOnFile(c.getData() + "\n");
//c.print();
webSite.restart();//After success, start over
}
}
synchronized private void restart() {
webSite.restart();
}
}
|
/**
*
* @author Paradox
*/
public class testClass1 {
}
|
package pbo1.nim10118017;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
/**
*
* @author Agung Nurhamidan
* NAMA : Agung Nurhamidan
* KELAS : PBO1
* NIM : 10118017
* Deskripsi Program : Perhitungan lama tabungan sampai mencapai saldo target.
*
*/
public class Tabungan {
public double persenBunga;
public double saldoTarget;
public void tampilkanTargetSaldoTabungan(double saldoAwal) {
//Mengatur simbol format untuk mata uang Indonesia.
DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
formatSymbols.setCurrencySymbol("Rp. ");
formatSymbols.setDecimalSeparator('.');
//Menerapkan simbol format ke bilangan desimal serta mengatur digit pembulatannya.
DecimalFormat format = (DecimalFormat) DecimalFormat.getCurrencyInstance();
format.setDecimalFormatSymbols(formatSymbols);
format.setMaximumFractionDigits(0);
//Menampilkan perulangan hingga mencapai saldo target.
for (int i = 0; saldoAwal <= saldoTarget; i++) {
saldoAwal = saldoAwal + (saldoAwal * persenBunga);
System.out.println("Saldo di bulan ke-" + (i+1) + " " + format.format(saldoAwal));
}
}
}
|
package com.pykj.design.principle.liskovsubstiution.example;
/**
* @description: 长方形
* @author: zhangpengxiang
* @time: 2020/4/20 18:08
*/
public class Rectangle {
private long height;
private long width;
public long getHeight() {
return height;
}
public void setHeight(long height) {
this.height = height;
}
public long getWidth() {
return width;
}
public void setWidth(long width) {
this.width = width;
}
}
|
package portal.listener;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.logevents.SelenideLogger;
import io.qameta.allure.selenide.AllureSelenide;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.openqa.selenium.remote.DesiredCapabilities;
import ch.qos.logback.classic.Logger;
import org.slf4j.LoggerFactory;
import portal.config.WebConfig;
import portal.email.EmailSteps;
import portal.retrofit.RetrofitErrorInterceptor;
import static com.codeborne.selenide.Selenide.closeWebDriver;
import static portal.listener.AttachmentsHelper.*;
public class BaseTestExtension implements AfterEachCallback, BeforeAllCallback, BeforeEachCallback {
private static final String SUCCESS = "Success";
private static final String FAILED = "Failed";
private final ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
@Override
public void afterEach(ExtensionContext context) {
if (getTestStatus(context).equals(FAILED)) {
if(listAppender.list.size()>0){
attachAsText("Logger", listAppender.list.get(0).getMessage());
}
attachAsText("Browser console logs", getBrowserConsoleLogs());
} else {
attachAsText("Browser console logs", getBrowserConsoleLogs());
attachScreenshot("Last screenshot");
}
closeWebDriver();
}
@Override
public void beforeEach(ExtensionContext context) {
Logger logger = (Logger) LoggerFactory.getLogger(RetrofitErrorInterceptor.class);
// create and start a ListAppender
listAppender.start();
// add the appender to the logger
logger.addAppender(listAppender);
}
private String getTestStatus(ExtensionContext context) {
return context.getExecutionException().isPresent() ? FAILED : SUCCESS;
}
@Override
public void beforeAll(ExtensionContext context) {
Configuration.remote = new WebConfig().getCallistoUrl();
// Configuration.remote ="http://localhost:4444/wd/hub";
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("enableVNC", true);
capabilities.setCapability("enableVideo", true);
Configuration.browserCapabilities = capabilities;
SelenideLogger.addListener("AllureSelenide", new AllureSelenide().screenshots(true).savePageSource(true));
Configuration.reportsFolder = "build/selenide-screenshots";
Configuration.downloadsFolder = "build/selenide-downloads";
Configuration.browser = "chrome";
Configuration.browserSize = "1920x1080";
Configuration.headless = false;
Configuration.fastSetValue = true;
Configuration.timeout = 20000;
// Configuration.fileDownload ="PROXY";
// Configuration.proxyEnabled = true;
new EmailSteps().changeStatusAllMessagesToSeen();
}
}
|
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main17 {
private static final int origin = 2;
/**
* 功能:等差数列 2,5,8,11,14...
* 输入:正整数N >0
* 输出:求等差数列前N项和
* 返回:转换成功返回 0 ,非法输入与异常返回-1
*/
public static int dengChaShuLie(int num)
{
int sum = 0;
if(num<0)
sum = -1;
else
{
sum = num*origin + num*(num-1)*3/2;
}
return sum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
try{
int num = scanner.nextInt();
System.out.println(dengChaShuLie(num));
}
catch(InputMismatchException ex)
{
System.out.println(-1);
}
}
}
}
|
package com.wrathOfLoD.Views.CameraView;
import com.wrathOfLoD.Models.Entity.Character.Avatar;
import com.wrathOfLoD.Observers.ViewObjectObservers.MovableVOObserver;
import com.wrathOfLoD.Observers.ViewObjectObservers.VOObserver;
import com.wrathOfLoD.Utility.Direction;
import com.wrathOfLoD.Utility.Position;
import com.wrathOfLoD.Views.ViewObjects.ModelViewObject;
import javafx.geometry.Pos;
/**
* Created by luluding on 4/17/16.
*/
public class CameraCenter implements VOObserver{
private Position cameraCenter;
private Position initialCenter;
public CameraCenter(){
this.cameraCenter = Avatar.getInstance().getPosition();
}
public void setCameraCenter(Position pos){
this.cameraCenter = pos;
}
public Position getCameraCenter(){
return cameraCenter;
}
@Override
public void notifyDestroy(ModelViewObject vo, Position position) {
setCameraCenter(initialCenter);
}
@Override
public void notifyOnMove(ModelViewObject mvo, Position src, Position dest, Direction dir, int ticks) {
setCameraCenter(dest);
}
public void setInitialCenter(Position position){
this.initialCenter = position;
}
}
|
package factoring.math;
import de.tilman_neumann.util.SortedMultiset;
import de.tilman_neumann.util.SortedMultiset_BottomUp;
import factoring.sieve.triple.BitSetWithOffset;
import factoring.trial.TDiv31Barrett;
import java.math.BigInteger;
import java.util.BitSet;
import static java.lang.Math.*;
import static java.lang.Math.log;
public class SmoothNumberGenerator {
int smoothBound;
BitSet smoothNumber;
BitSet smoothNumberReverse;
private int smoothBits;
TDiv31Barrett smallFactoriser = new TDiv31Barrett();
public static SmoothNumberGenerator ofMaxSize(long maxSize){
return new SmoothNumberGenerator(maxSize);
}
public SmoothNumberGenerator(long maxSize) {
this.smoothBound = (int) sqrt(2*maxSize);
initSmoothNumbers();
}
public double factorBaseSize(long n) {
return 1 * sqrt(exp(sqrt(log(n) * log(log(n)))));
}
/**
*
* @param number
* @param numberSqrt
* @param yRange
* @return
*/
BitSetWithOffset getSmoothNumbersBy4Products(long number, int numberSqrt, int yRange) {
// if number is smaller than lookup table just return the Bitset
// do a loop with some higher numbers
long z = numberSqrt;
int diffNumberToSquare = (int) (z * z - number);
double yOptDouble = sqrt(diffNumberToSquare); // <= sqrt(2*sqrt(number)) = sqrt(2)*number^1/4
// we try to write number = z^2 - y^2
int yOptInt = (int) round(yOptDouble);
// (y + yRange)^2 = y^2 + 2y * yRange + yRange^2 ~ 2 * sqrt(2)*number^1/4 * yRange < 3 * *number^1/4 * yRange
int yRangeAdjust = yRange > yOptInt ? yOptInt : yRange;
BitSet ysMinyOffset = new BitSet();
// we search ner sqrt(number). Around a number2 were we know that a product of non-smooth numbers is near
// the original number.
long number2 = z - yOptInt;
// for (int number2 = z - yOptInt - yRange; number2 < z - yOptInt + yRange; number2++) {
int numberSqrt2 = (int) ceil(sqrt(number2));
final double factorBaseSize = factorBaseSize(number2);
// int yRange2 = (int) (2* factorBaseSize);
BitSetWithOffset smoothAscendingFromLower = getSmoothNumbersBy2Products(number2, numberSqrt2, yRange);
for (int yDiff = smoothAscendingFromLower.ysMinyOffset.nextSetBit(0); yDiff >= 0; yDiff = smoothAscendingFromLower.ysMinyOffset.nextSetBit(yDiff + 1)) {
// operate on index i here
if (yDiff == Integer.MAX_VALUE) {
break; // or (i+1) would overflow
}
int y = smoothAscendingFromLower.yOffset + yDiff;
long smoothLowerNumber = (numberSqrt2 - y) * (numberSqrt2 + y);
long complementNumber = (int) (numberSqrt + (numberSqrt - smoothLowerNumber));
int nDivLower = (int) (number / smoothLowerNumber);
if (complementNumber != nDivLower)
System.out.println("number to far away from sqrt?");
int[] rep = potentiallySmoothFermat(nDivLower);
if (rep != null) {
System.out.println("found smooth (x-t) " + smoothLowerNumber + " and (x+t) " + complementNumber);
int rest = (int) (smoothLowerNumber * complementNumber - number2);
System.out.println("smooth number : " + smoothLowerNumber * complementNumber + " and rest " + rest);
}
// }
}
int yOffset = (int) (z + yOptInt - yRange);
BitSetWithOffset result = new BitSetWithOffset(ysMinyOffset, yOffset);
return result;
}
/**
* we want number = z^2 - y^2 = (z - y) * (z + y)
* z^2 = {0,1,4} - number mod 8
* With a mod 2^k argument we find some valid z'
* if we have some z
*
* @return
*/
int[] potentiallySmoothFermat(int number) {
// do some mod arguments here. reuse Smoothumbers class!?
int numberMod8 = number % 8;
int higherSquareSqrt = (int) ceil(sqrt(number));
int z = higherSquareSqrt;
int zRange = (int) exp(sqrt(log(higherSquareSqrt) * log(log(higherSquareSqrt))));
do {
int zMod8 = z % 8;
int zSquaredMod8 = (z * z) % 8;
int diffNumberToSquare = z * z - number;
double yOptDouble = sqrt(diffNumberToSquare); // <= sqrt(2*sqrt(number)) = sqrt(2)*number^1/4
// we try to write number = x^2 - y^2
int yOptInt = (int) round(yOptDouble);
if (yOptInt * yOptInt == diffNumberToSquare) {
int lowerNumber = z - yOptInt;
int higherNumber = z + yOptInt;
if (smoothNumber.get(lowerNumber)) {
if (smoothNumber.get(higherNumber))
return new int[]{lowerNumber, higherNumber};
}
}
z++;
} while (z < higherSquareSqrt + zRange);
return null;
}
/**
* given a number we will return a BitSet of numbers y' and a yOffset
* stored in BitSetWithOffset
* with y = y' + yOffset
*
* z^2 - y^2 = (z - y) * (z + y) = number +/- 3 * number^1/4 * (sqrt(numberSqrt - sqrt(number)) * yRange
* with
* (z - y) and (z + y) being smooth
* z = ceil(sqrt(number)) + l
* ((z+l) + (y+k)) * ((z+l) z - (y+k)) = (z+l)^2 - (y+k)^2) = z^2 + 2zl + l^2 - y^2 -2ky - k^2
* = z^2 + 2zl + l^2 - y^2 -2ky - k^2
* y^2 = 2zl -> y = n^1/4* l^1/2
*
* @param number
* @return
*/
// TODO provide an Iterator here
BitSetWithOffset getSmoothNumbersBy2Products(long number, int numberSqrt, int yRange) {
// if number is smaller than lookup table just return the Bitset
// do a loop with some higher numbers
int z = numberSqrt;
int diffNumberToSquare = (int) (z * z - number);
double yOptDouble = sqrt(diffNumberToSquare); // <= sqrt(2*sqrt(number)) = sqrt(2)*number^1/4
// we try to write number = x^2 - y^2
int yOptInt = (int) round(yOptDouble);
// (y + yRange)^2 = y^2 + 2y * yRange + yRange^2 ~ 2 * sqrt(2)*number^1/4 * yRange < 3 * *number^1/4 * yRange
int yRangeAdjust = yRange > yOptInt ? yOptInt : yRange;
int yBegin = yOptInt - yRangeAdjust;
// Z - Y_opt + range -> Z - y_opt + range
int lowerProduct = z - yBegin;
// z + y_opt - range -> z + y_opt - range
int higherProduct = z + yBegin;
// int smoothRange = Math.max(64, 2 * yRange);
BitSet smoothAscendingFromHigher = smoothNumber.get(higherProduct, higherProduct + 2*yRangeAdjust);
BitSet smoothDescendingFromLower = smoothNumberReverse.get(smoothBound - lowerProduct, smoothBound - (lowerProduct - 2*yRangeAdjust));
smoothAscendingFromHigher.and(smoothDescendingFromLower);
return new BitSetWithOffset(smoothAscendingFromHigher, yBegin);
}
private void initSmoothNumbers() {
long start = System.currentTimeMillis();
smoothNumber = new BitSet(smoothBound);
smoothNumberReverse = new BitSet(smoothBound);
smoothNumber.set(1);
smoothNumberReverse.set(smoothBound - 1);
int smoothCount = 0;
for (long j = 2; j < smoothBound; j++) {
double baseSize = factorBaseSize(j * j);
SortedMultiset<BigInteger> factors = new SortedMultiset_BottomUp<>();
// boolean isSmooth = smallFactoriser.factor((int) j, baseSize, factors);
// since we store the high factors for small numbers use the maximal factor base
if (j % 500000 == 0)
System.out.println("initializing : " + j + " " + ((j* 100.0) /smoothBound) + "% done");
int maxFactorIndex = smallFactoriser.findMaxFactorIndex((int) j, (int) ceil(baseSize)) + 1;
if (maxFactorIndex < baseSize) {
smoothNumber.set((int) j);
smoothNumberReverse.set((int) (smoothBound - j));
}
}
System.out.println("initialization ready ");
}
}
|
package database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import objetos.Pais;
import java.util.ArrayList;
import java.util.List;
public class BancoPaises extends SQLiteOpenHelper {
//Versão do banco de dados
private static final int VERSAO_BANCO = 1;
//Nome do banco de dados utilizado para salvar os países
private static final String NOME_BANCO = "BancoPaises";
//Nome da tabela de países
private static final String TABELA_PAISES = "Paises";
// Colunas da tabela Paises
private static final String KEY_ID = "Id"; //Coluna que guarda o id do país
private static final String KEY_SHORTNAME = "ShortName"; //Coluna que guarda o nome curto do país
private static final String KEY_LONGNAME = "LongName"; //Coluna que guarda o nome completo do país
private static final String KEY_FLAG_URL = "FlagURL"; //Coluna que guarda a URL da bandeira do país
private static final String KEY_CALLINGCODE = "CallingCode"; //Coluna que guarda o código de chamada do país
private static final String KEY_DATAVISITA = "DataVisita"; //Coluna que guarda a data de visita do usuário ao país
private static final String KEY_APELIDO = "Apelido"; //Coluna que guarda o apelidado dado pelo usuário ao país
public BancoPaises(Context context) {
super(context, NOME_BANCO, null, VERSAO_BANCO);
}
//Criação das tabelas
@Override
public void onCreate(SQLiteDatabase db) {
String CRIAR_TABELA_PAISES = "CREATE TABLE IF NOT EXISTS " + TABELA_PAISES + " ("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_SHORTNAME + " TEXT,"
+ KEY_LONGNAME + " TEXT," + KEY_FLAG_URL +" TEXT," + KEY_CALLINGCODE +" TEXT,"
+ KEY_DATAVISITA + " INTEGER," + KEY_APELIDO + " TEXT);";
db.execSQL(CRIAR_TABELA_PAISES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//Adicionar país ao banco
public void insertPais(Pais pais, long timeStamp, String apelido) {
SQLiteDatabase db = this.getWritableDatabase();
//Adicionar os valores às suas respectivas colunas
ContentValues values = new ContentValues();
values.put(KEY_ID, pais.getId());
values.put(KEY_SHORTNAME, pais.getShortName());
values.put(KEY_LONGNAME, pais.getLongName());
values.put(KEY_FLAG_URL, pais.getFlagURL());
values.put(KEY_CALLINGCODE, pais.getCallingCode());
values.put(KEY_DATAVISITA, timeStamp);
values.put(KEY_APELIDO, apelido);
//Inserir a linha
db.insert(TABELA_PAISES, null, values);
db.close();
}
//Recuperar todos os países salvos no banco de dados
public ArrayList<Pais> getPaises() {
//ArrayList que irá guardar todos os países
ArrayList<Pais> paises = new ArrayList<>();
//Query de seleção de todas informações presentes da tabela de países
String selectQuery = "SELECT * FROM " + TABELA_PAISES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Loop para recuperação das informações de todos os países encontrados
if (cursor.moveToFirst()) {
do {
Pais pais = new Pais(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4));
//Adiciona o país ao ArrayList de países
paises.add(pais);
} while (cursor.moveToNext());
}
//Retorna o ArrayList de países
return paises;
}
//Verifica se o país existe do banco de dados através do seu id
public boolean verificaPais(int idPais){
//Query de seleção do país desejado
String selectQuery = "SELECT Id, DataVisita FROM " + TABELA_PAISES + " WHERE Id = " + idPais;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Caso o país exista no banco de dados é retornado true, senão false
if(cursor.moveToFirst()){
return true;
}
return false;
}
//Recupera a data de visita do usuário a um país através do id do país
public long getDataVisita(int idPais){
//Query de seleção da data de visita do país desejado
String selectQuery = "SELECT DataVisita FROM " + TABELA_PAISES + " WHERE Id = " + idPais;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
//Retorna um long contendo o timestamp referente à data de visita
return cursor.getLong(0);
}
//Criação de um novo apelido para um país através do seu id
public void novoApelido(int idPais, String apelido){
ContentValues contentValues = new ContentValues();
//Adiciona o valor indicado pelo usuário à coluna "Apelido"
contentValues.put("Apelido", apelido);
SQLiteDatabase db = this.getWritableDatabase();
db.update(TABELA_PAISES, contentValues, "Id = " + idPais, null);
}
//Recupera o apelido de um país através do seu id
public String getApelido(int idPais){
//Query de seleção do apelido do país desejado
String selectQuery = "SELECT Apelido FROM " + TABELA_PAISES + " WHERE Id = " + idPais;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
//Retorna uma string contendo o apelido
return cursor.getString(0);
}
//Recupera os ids dos países cadastrados no banco de dados
public ArrayList<Integer> getIdPaises(){
//List que guarda os ids dos países
ArrayList<Integer> idPaises = new ArrayList<>();
//Query que recupera os ids de todos os países da tabela
String selectQuery = "SELECT Id FROM " + TABELA_PAISES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Loop para recuperação dos ids dos países encontrados
if(cursor.moveToFirst()){
do{
idPaises.add(cursor.getInt(0));
}while (cursor.moveToNext());
}
//Retorna o List de ids
return idPaises;
}
//Exclui países salvos no banco de dados selecionados pelo usuário
public void excluirPaises(ArrayList<String> paises){
//Criação do array que recebe os ids dos paises selecionados
String[] arrayIds = new String[paises.size()];
arrayIds = paises.toArray(arrayIds);
SQLiteDatabase db = this.getWritableDatabase();
String args = TextUtils.join(", ", arrayIds);
//Execução da query de remoção dos países selecionados
db.execSQL(String.format("DELETE FROM " + TABELA_PAISES + " WHERE Id IN (%s);", args));
}
//Exclui um único país do banco de dados
public void excluirUmPais(int idPais){
//Query que remove o país do bando de dados
String deleteQuery = "DELETE FROM " + TABELA_PAISES + " WHERE Id = " + idPais;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(deleteQuery);
}
}
|
import javafx.beans.value.ChangeListener;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.FlowPane;
import java.util.ArrayList;
import java.util.HashMap;
public class ControlPane extends FlowPane {
HashMap<String, Node> elements;
public ControlPane(int x, int y, int width, int height) {
super();
elements = new HashMap<>();
setMaxSize(width, height);
setMinSize(width, height);
setHgap(10); // Hardcoded af
setPadding(new Insets(10, 10, 10, 10)); // Hardcoded deluxe
relocate(x, y);
}
public void addButton(String name, EventHandler<ActionEvent> onAction) {
Button button = new Button(name);
button.setOnAction(onAction);
getChildren().add(button);
elements.put(name, button);
}
public void addChoiceBox(String name, String[] choices, ChangeListener<String> listener) {
ChoiceBox choiceBox = new ChoiceBox();
for (int i = 0; i < choices.length; i++) {
choiceBox.getItems().add(choices[i]);
}
choiceBox.getSelectionModel().select(0);
choiceBox.getSelectionModel().selectedItemProperty().addListener(listener);
getChildren().add(choiceBox);
elements.put(name, choiceBox);
}
public void disableElement(String name) {
Node element = elements.get(name);
if (element == null)
return;
element.setDisable(true);
}
}
|
package alien4cloud.tosca.parser.mapping;
import org.springframework.stereotype.Component;
import alien4cloud.model.components.CSARDependency;
import alien4cloud.tosca.parser.impl.base.TypeNodeParser;
@Component
public class CsarMetaDependencyMapping extends AbstractMapper<CSARDependency> {
public CsarMetaDependencyMapping() {
super(new TypeNodeParser<CSARDependency>(CSARDependency.class, "CSAR dependency."));
}
@Override
public void initMapping() {
quickMap("name");
quickMap("version");
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
import com.google.common.collect.Lists;
import org.giddap.dreamfactory.leetcode.onlinejudge.implementations.MissingRangesImpl;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Created by peng on 12/10/14.
*/
public class MissingRangesTest {
private MissingRanges solution = new MissingRangesImpl();
@Test
public void small01() {
List<String> actual = solution.findMissingRanges(new int[]{0, 1, 3, 50, 75}, 0, 99);
List<String> expected = Lists.newArrayList("2", "4->49", "51->74", "76->99");
assertEquals(expected.size(), actual.size());
assertEquals(expected, actual);
}
}
|
package com.sportzcourt.booking.controller;
import android.content.Context;
import com.sportzcourt.booking.BuildConfig;
import com.sportzcourt.booking.database.DatabaseManager;
import com.sportzcourt.booking.service.webservices.ApiService;
import com.sportzcourt.booking.service.webservices.RestAdapterRequestInterceptor;
import com.sportzcourt.booking.util.Constants;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
/**
* Created by ravindra.kambale on 11/30/2015.
*/
public class DataController {
private static DataController dcInstance = new DataController();
private DatabaseManager dbManager;
private ApiService apiManager;
public static DataController getInstance() {
return dcInstance;
}
private DataController() {
}
public DatabaseManager getDatabaseManager(Context context){
if(dbManager == null){
dbManager = DatabaseManager.getInstance(context);
}
return dbManager;
}
public ApiService getAPIManager(){
if(apiManager == null){
Retrofit retrofit = provideRestAdapter(provideRestAdapterRequestInterceptor());
apiManager = retrofit.create(ApiService.class);
}
return apiManager;
}
RestAdapterRequestInterceptor provideRestAdapterRequestInterceptor() {
return new RestAdapterRequestInterceptor();
}
Retrofit provideRestAdapter(RestAdapterRequestInterceptor restRequestInterceptor) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(Constants.Http.READ_TIMEOUT, TimeUnit.SECONDS);
builder.connectTimeout(Constants.Http.CONNECT_TIMEOUT, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(interceptor);
}
builder.addInterceptor(provideRestAdapterRequestInterceptor());
OkHttpClient client = builder.build();
return new Retrofit.Builder()
.baseUrl(Constants.Http.URL_BASE)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
|
package com.yusys.warrantHomePage2;
import java.util.List;
import java.util.Map;
public interface WarrantHomePageDao {
//统计资产各状态数量
public List<Map<String, String>> queryAssetStateCount();
//统计某个月资产领用的数量
public int queryUseAssetNumByMonth(String type);
//统计某个月资产入库的数量
public int queryInAssetNumByMonth(String type);
//查询前几名的资产信息
public List<Map<String, String>> queryTopAssetInfo(String num);
//统计前几名的资产数量
public List<Map<String, String>> queryTopAssetNumByDate(Map<String, Object> map);
//统计除了前几名其他资产的数量
public int queryOtherAssetNumByDate(Map<String, Object> map);
//权证-------------入库申请未审批数
public int queryWarrantInNum(String string);
//权证入库申请未审批数
public int queryWarrantOutNum(String string);
//------------------资产申请数
public int queryAssetApplyNum(String state);
//资产领用登记数
public int queryAssetResignNum(String state);
//资产转移数
public List<Map<String, String>> queryAssetTranNum(String state);
//资产调拨分配数
public int queryAssetAsignNum(String state);
//盘点管理-待制定方案
public int queryDraftSchemeNum(String state);
}
|
package models;
import java.awt.Image;
import java.awt.event.KeyEvent;
import ui.KeyInput;
public final class Background extends Object2D {
public Background(Image img, int y, int dx) {
setImg(img);
setWidth(img.getWidth(null));
setHeight(img.getHeight(null));
setX(0);
setY(y);
setDx(0);
setStoreDx(dx);
}
@Override
public void updateObjectCoordinates() {
//the first space the player will press will make the game began
if (KeyInput.keyIs(KeyEvent.VK_SPACE)) {
//make background move left
setDx(getStoreDx());
}
setX(getX() - getDx());
//repeat the background and border
if (getX() <= -(getImg().getWidth(null) / 2)) {
setX(0);
}
}
}
|
package ch05;
public class Ferari extends Car1 implements Control{
String name;
private Engine5000 engine5000;
@Override
public void ¿¢¼¿() {
// TODO Auto-generated method stub
}
@Override
public void ºê·¹ÀÌÅ©() {
// TODO Auto-generated method stub
}
}
|
package com.tiy.ssa.weektwo.dayone;
//int atBats = atBats;
public class atBatter {
//// private int atBats = 0;
//// private int singles = 0;
//// private int doubles = 0;
//// private int triples = 0;
//// private int homers = 0;
//// private int hits = 0;
//// private int totalBases = 0;
//// private int outs = 0;
////
//// public atBatter(int atBats, int singles, int doubles, int triples, int homers, int hits, int totalBases, int outs) {
//// super();
//// this.atBats = atBats;
//// this.singles = singles;
//// this.doubles = doubles;
//// this.triples = triples;
//// this.homers = homers;
//// this.hits = hits;
//// this.totalBases = totalBases;
//// this.outs = outs;
//// }
////
////
//// }
////
////
////}
|
package com.zhongyp.transaction;
/**
* project: demo
* author: zhongyp
* date: 2018/3/1
* mail: zhongyp001@163.com
*/
public interface IStockProcessService {
void openAccount(String aname, double money);
void openStock(String sname, int amount);
void buyStock(String aname, double money, String sname, int amount) throws StockException;
void testBuy();
}
|
package com.melodygram.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.melodygram.constants.ChatGlobalStates;
import com.melodygram.model.ChatMessageModel;
import com.melodygram.singleton.AppController;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
/**
* Created by LALIT on 15-06-2016.
*/
public class ChatMessageDataSource {
private SQLiteDatabase sqlDatabase;
private DbSqliteHelper sqlHelper;
private String userId;
private Context context;
private String[] allColumns = { DbSqliteHelper.chatPrimaryKey,
DbSqliteHelper.chatMessageId,
DbSqliteHelper.chatMessageSenderName,
DbSqliteHelper.chatMessageSenderPic, DbSqliteHelper.chatMessageRoomId,
DbSqliteHelper.chatMessageUserId, DbSqliteHelper.chatMessage,
DbSqliteHelper.chatMessageType, DbSqliteHelper.chatMessageFileUrl,
DbSqliteHelper.chatMessageLat, DbSqliteHelper.chatMessageLan,
DbSqliteHelper.chatMessageUserTime,
DbSqliteHelper.chatMessageUserDate,
DbSqliteHelper.chatMessageToFromFlag,
DbSqliteHelper.chatMessageSingleTickFlag, DbSqliteHelper.chatMessageSeen,
DbSqliteHelper.chatMessageSeenTime,
DbSqliteHelper.chatFileThumbnail, DbSqliteHelper.chatIsRemoved,
DbSqliteHelper.chatIsSent, DbSqliteHelper.chatTempMessageId,
DbSqliteHelper.chatDisappear,DbSqliteHelper.chatAudioTime ,DbSqliteHelper.stickerId,DbSqliteHelper.CHAT_IS_EDIT_SENT,DbSqliteHelper.imageDownload};
public ChatMessageDataSource(Context context) {
sqlHelper = new DbSqliteHelper(context);
userId = AppController.getInstance().getUserId();
this.context = context;
}
public void open() throws SQLException {
sqlDatabase = sqlHelper.getWritableDatabase();
}
public void close() {
sqlHelper.close();
}
public Long createChatMessage(String chatMessageId,
String chatMessageSenderName, String chatMessageSenderPic,
String chatMessageRoomId, String chatMessageUserId,
String chatMessage, String chatMessageType,
String chatMessageFileUrl, String chatMessageLat,
String chatMessageLan, String chatMessageUserTime,
String chatMessageUserDate, String chatMessageToFromFlag,
String chatMessageSingleTickFlag,
String chatMessageSeen, String chatMessageSeenTime,
String chatFileThumbnail,
String chatIsRemoved, String chatIsSent, String chatTempMessageId,
String chatAudioTime,String disappear,String stickerId,String chatIsEditSent,int imageDownload) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId, Integer.valueOf(chatMessageId));
values.put(DbSqliteHelper.chatMessageSenderName, chatMessageSenderName);
values.put(DbSqliteHelper.chatMessageSenderPic, chatMessageSenderPic);
values.put(DbSqliteHelper.chatMessageRoomId, chatMessageRoomId);
values.put(DbSqliteHelper.chatMessageUserId, chatMessageUserId);
values.put(DbSqliteHelper.chatMessage, chatMessage);
values.put(DbSqliteHelper.chatMessageType, chatMessageType);
values.put(DbSqliteHelper.chatMessageFileUrl, chatMessageFileUrl);
values.put(DbSqliteHelper.chatMessageLat, chatMessageLat);
values.put(DbSqliteHelper.chatMessageLan, chatMessageLan);
values.put(DbSqliteHelper.chatMessageUserTime, chatMessageUserTime);
values.put(DbSqliteHelper.chatMessageUserDate, chatMessageUserDate);
values.put(DbSqliteHelper.chatMessageToFromFlag, chatMessageToFromFlag);
values.put(DbSqliteHelper.chatMessageSingleTickFlag,
chatMessageSingleTickFlag);
values.put(DbSqliteHelper.chatMessageSeen, chatMessageSeen);
values.put(DbSqliteHelper.chatMessageSeenTime, chatMessageSeenTime);
values.put(DbSqliteHelper.chatFileThumbnail, chatFileThumbnail);
values.put(DbSqliteHelper.chatIsRemoved, chatIsRemoved);
values.put(DbSqliteHelper.chatIsSent, chatIsSent);
values.put(DbSqliteHelper.chatTempMessageId, chatTempMessageId);
values.put(DbSqliteHelper.chatAudioTime, chatAudioTime);
values.put(DbSqliteHelper.chatDisappear, disappear);
values.put(DbSqliteHelper.stickerId, stickerId);
values.put(DbSqliteHelper.CHAT_IS_EDIT_SENT, chatIsEditSent);
values.put(DbSqliteHelper.imageDownload, imageDownload);
Long insertId = sqlDatabase.insert(DbSqliteHelper.chatMessageTable,
null, values);
ChatMessageModel chatMessageModel = getLatestMsgContent(chatMessageRoomId);
if(chatMessageModel !=null)
{
FriendsDataSource friendsDataSource = new FriendsDataSource(context);
friendsDataSource.open();
friendsDataSource.updateFriendsMessage(chatMessageRoomId, chatMessageModel.getActualMsg(), chatMessageModel.getMessageType(), chatMessageModel.getMsgTime());
friendsDataSource.close();
}
return insertId;
}
public boolean isMsgAvailable(String messageId) {
Cursor cursor = sqlDatabase.query(
DbSqliteHelper.chatMessageTable, allColumns,
DbSqliteHelper.chatMessageId + " = " + "'"
+ messageId + "'", null, null, null, null);
return cursor.moveToFirst();
}
public ChatMessageModel getLatestMsgContent(String roomId)
{
ChatMessageModel chatMessageModel = null;
Cursor cursor = sqlDatabase.rawQuery("SELECT "+ DbSqliteHelper.chatMessage+","+DbSqliteHelper.chatMessageType+","+DbSqliteHelper.chatMessageUserTime+ " FROM " + DbSqliteHelper.chatMessageTable + " WHERE "+DbSqliteHelper.chatMessageRoomId + " = " + "'" + roomId + "' ORDER BY "+DbSqliteHelper.chatPrimaryKey+
" DESC LIMIT 1", null);
if (cursor != null && cursor.getCount() > 0)
{
cursor.moveToFirst();
chatMessageModel = new ChatMessageModel();
chatMessageModel.setActualMsg(cursor.getString(0));
chatMessageModel.setMessageType(cursor.getString(1));
chatMessageModel.setMsgTime(cursor.getString(2));
return chatMessageModel;
}
else
return chatMessageModel;
}
public int updateEditMsg(String chatMessageId, String actualMsg,String chatIsEditSent) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId,
Integer.parseInt(chatMessageId));
values.put(DbSqliteHelper.chatMessage, actualMsg);
values.put(DbSqliteHelper.CHAT_IS_EDIT_SENT, chatIsEditSent);
int insertId = sqlDatabase.update(
DbSqliteHelper.chatMessageTable, values,
DbSqliteHelper.chatMessageId + " = " + "'"
+ chatMessageId + "'", null);
return insertId;
}
public int updateChatMessage(String chatMessageId,
String chatMessageSenderName, String chatMessageSenderPic,
String chatMessageRoomId, String chatMessageUserId,
String chatMessage, String chatMessageType,
String chatMessageFileUrl, String chatMessageLat,
String chatMessageLan, String chatMessageUserTime,
String chatMessageUserDate, String chatMessageToFromFlag,
String chatMessageSingleTickFlag,
String chatMessageSeen, String chatMessageSeenTime, String chatIsRemoved, String chatIsSent,
String chatTempMessageId, String chatAudioTime,String disappear,String stickerId,String chatEditisSent,int imageDownload) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId, Integer.valueOf(chatMessageId));
values.put(DbSqliteHelper.chatMessageSenderName, chatMessageSenderName);
values.put(DbSqliteHelper.chatMessageSenderPic, chatMessageSenderPic);
values.put(DbSqliteHelper.chatMessageRoomId, chatMessageRoomId);
values.put(DbSqliteHelper.chatMessageUserId, chatMessageUserId);
values.put(DbSqliteHelper.chatMessage, chatMessage);
values.put(DbSqliteHelper.chatMessageType, chatMessageType);
values.put(DbSqliteHelper.chatMessageFileUrl, chatMessageFileUrl);
values.put(DbSqliteHelper.chatMessageLat, chatMessageLat);
values.put(DbSqliteHelper.chatMessageLan, chatMessageLan);
values.put(DbSqliteHelper.chatMessageUserTime, chatMessageUserTime);
values.put(DbSqliteHelper.chatMessageUserDate, chatMessageUserDate);
values.put(DbSqliteHelper.chatMessageToFromFlag, chatMessageToFromFlag);
values.put(DbSqliteHelper.chatMessageSingleTickFlag,
chatMessageSingleTickFlag);
values.put(DbSqliteHelper.chatMessageSeen, chatMessageSeen);
values.put(DbSqliteHelper.chatMessageSeenTime, chatMessageSeenTime);
values.put(DbSqliteHelper.chatDisappear, disappear);
values.put(DbSqliteHelper.chatIsRemoved, chatIsRemoved);
values.put(DbSqliteHelper.chatIsSent, chatIsSent);
values.put(DbSqliteHelper.chatTempMessageId, chatTempMessageId);
values.put(DbSqliteHelper.chatAudioTime, chatAudioTime);
values.put(DbSqliteHelper.stickerId, stickerId);
values.put(DbSqliteHelper.CHAT_IS_EDIT_SENT, chatEditisSent);
values.put(DbSqliteHelper.imageDownload, imageDownload);
int insertId;
if (chatMessageUserId.equals(userId)) {
insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatTempMessageId + " = '"
+ chatTempMessageId + "' AND "
+ DbSqliteHelper.chatMessageUserId + " = '"
+ chatMessageUserId + "' AND "
+ DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "'", null);
} else {
insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatMessageId + " = "
+ chatMessageId + " AND "
+ DbSqliteHelper.chatMessageUserId + " = '"
+ chatMessageUserId + "' AND "
+ DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "'", null);
}
return insertId;
}
public int updateMediaUrl(String chatMessageId, String chatMessageFileUrl) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId, chatMessageId);
values.put(DbSqliteHelper.chatMessageFileUrl, chatMessageFileUrl);
int insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatMessageId + " = " + "'"
+ chatMessageId + "'", null);
return insertId;
}
public int updateDownloadImage(String chatMessageId, int imageDownLoadId) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId, chatMessageId);
values.put(DbSqliteHelper.imageDownload, imageDownLoadId);
int insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatMessageId + " = " + "'"
+ chatMessageId + "'", null);
return insertId;
}
public int updateLastseen(String chatMessageSeenId,
String chatMessageSeenTime) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId, chatMessageSeenId);
values.put(DbSqliteHelper.chatMessageSeen, "1");
values.put(DbSqliteHelper.chatMessageSeenTime, chatMessageSeenTime);
int insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatMessageId + " = " + "'"
+ chatMessageSeenId + "'", null);
return insertId;
}
public String getLatestMsgId(String chatMessageRoomId)
{
Cursor cursor = sqlDatabase.rawQuery("SELECT "
+ DbSqliteHelper.chatMessageId + " FROM "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + " = '" + chatMessageRoomId
+ "'" + " AND " + DbSqliteHelper.chatIsSent + " = '1' ORDER BY " + DbSqliteHelper.chatMessageId + " DESC LIMIT 1", null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
if(cursor.getString(0)!=null)
{
return cursor.getString(0);
}
}
return "-1";
}
public String getLatestUnDeletedMsgId(String chatMessageRoomId) {
Cursor cursor = sqlDatabase.rawQuery("SELECT "
+ DbSqliteHelper.chatMessageId + " FROM "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + " = '" + chatMessageRoomId
+ "'" + " AND " + DbSqliteHelper.chatIsRemoved + " = '" + ""
+ "'" + " order by " + DbSqliteHelper.chatMessageId + " DESC LIMIT 1", null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
if(cursor.getString(0)!=null)
{
return cursor.getString(0);
}
}
return "-1";
}
public ChatMessageModel getLatestMsg(String chatMessageRoomId) {
ChatMessageModel chatMessageModel=null;
Cursor cursor = sqlDatabase.query(DbSqliteHelper.chatMessageTable,
allColumns, DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "' AND "
+ DbSqliteHelper.chatIsRemoved + " = '" + "" + "'",
null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
chatMessageModel = cursorToChatMessage(cursor);
cursor.moveToNext();
}
cursor.close();
return chatMessageModel;
}
public String getUnseenMsgId(String chatMessageRoomId) {
Cursor cursor = sqlDatabase.rawQuery("SELECT "
+ DbSqliteHelper.chatMessageId + " FROM "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + " = '" + chatMessageRoomId
+ "'" + " AND " + DbSqliteHelper.chatMessageSeen + " != '1' ORDER BY "+DbSqliteHelper.chatMessageId + " ASC LIMIT 1", null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
if(cursor.getString(0)!=null)
{
return cursor.getString(0);
}
}
return "-1";
}
public List<ChatMessageModel> getAllChatMessage(String chatMessageRoomId) {
List<ChatMessageModel> chatMessageModelList = new ArrayList<ChatMessageModel>();
Cursor cursor = sqlDatabase.query(DbSqliteHelper.chatMessageTable,
allColumns, DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "' AND "
+ DbSqliteHelper.chatIsRemoved + " = '" + "" + "'",
null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChatMessageModel chatMessageModel = cursorToChatMessage(cursor);
chatMessageModelList.add(chatMessageModel);
cursor.moveToNext();
}
cursor.close();
return chatMessageModelList;
}
public ArrayList<ChatMessageModel> getAllChatTextMessage(String chatType)
{
ArrayList<ChatMessageModel> chatMessageModelList = new ArrayList<>();
Cursor cursor = sqlDatabase.query(DbSqliteHelper.chatMessageTable, allColumns, DbSqliteHelper.chatMessageType + " = " + "'" + chatType + "' AND " + DbSqliteHelper.chatIsRemoved
+ " = '" + "" + "'", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
ChatMessageModel chatMessageModel = cursorToChatMessage(cursor);
chatMessageModelList.add(chatMessageModel);
cursor.moveToNext();
}
cursor.close();
return chatMessageModelList;
}
public LinkedHashMap<String, ChatMessageModel> getAllUnsentMsg(
String chatMessageRoomId) {
LinkedHashMap<String, ChatMessageModel> unsentItemList = new LinkedHashMap<String, ChatMessageModel>();
Cursor cursor = sqlDatabase.query(DbSqliteHelper.chatMessageTable,
allColumns, DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "' AND "
+ DbSqliteHelper.chatIsRemoved + " = '" + "" + "'"
+ " AND " + DbSqliteHelper.chatIsSent + " = '" + "0"
+ "'", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChatMessageModel chatMessageModel = cursorToChatMessage(cursor);
unsentItemList.put(cursor.getString(20), chatMessageModel);
cursor.moveToNext();
}
cursor.close();
return unsentItemList;
}
public List<ChatMessageModel> getLimitedChatMessage(
String chatMessageRoomId) {
List<ChatMessageModel> chatMessageModelList = new ArrayList<ChatMessageModel>();
String rawQuery = "select * from (select * from "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + " = '" + chatMessageRoomId
+ "' AND " + DbSqliteHelper.chatIsRemoved + " = '" + "" + "'"
+ " order by " + DbSqliteHelper.chatPrimaryKey + " DESC ) order by " + DbSqliteHelper.chatPrimaryKey
+ " ASC";
Cursor cursor = sqlDatabase.rawQuery(rawQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChatMessageModel chatMessageModel = cursorToChatMessage(cursor);
chatMessageModelList.add(chatMessageModel);
cursor.moveToNext();
}
cursor.close();
return chatMessageModelList;
}
private ChatMessageModel cursorToUserId(Cursor cursor) {
ChatMessageModel chatMessageModel = new ChatMessageModel();
chatMessageModel.setMsgId(cursor.getString(0));
return chatMessageModel;
}
public Integer getFstMsgPrimaryKey(String chatMessageId,
boolean isDummyMsgId) {
Cursor cursor;
if (isDummyMsgId) {
cursor = sqlDatabase.rawQuery("SELECT "
+ DbSqliteHelper.chatPrimaryKey + " FROM "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatTempMessageId + " = '" + chatMessageId
+ "'", null);
} else {
cursor = sqlDatabase.rawQuery("SELECT "
+ DbSqliteHelper.chatPrimaryKey + " FROM "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageId + " = '" + chatMessageId
+ "'", null);
}
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
return cursor.getInt(0);
} else
return null;
}
public List<ChatMessageModel> getLimitedChatMessage(
String chatMessageRoomId, String chatMessageId,
boolean isDummyMsgId) {
List<ChatMessageModel> chatMessageModelList = new ArrayList<ChatMessageModel>();
Integer fstMsgPrimaryKey = getFstMsgPrimaryKey(chatMessageId,
isDummyMsgId);
if (fstMsgPrimaryKey != null) {
String rawQuery = "select * from (select * from "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + " = '"
+ chatMessageRoomId + "' AND "
+ DbSqliteHelper.chatPrimaryKey + " < '" + fstMsgPrimaryKey
+ "' AND " + DbSqliteHelper.chatIsRemoved + " = '" + ""
+ "'" + " order by " + DbSqliteHelper.chatPrimaryKey
+ " DESC limit 20 ) order by "
+ DbSqliteHelper.chatPrimaryKey + " ASC";
Cursor cursor = sqlDatabase.rawQuery(rawQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChatMessageModel chatMessageModel = cursorToChatMessage(cursor);
chatMessageModelList.add(chatMessageModel);
cursor.moveToNext();
}
cursor.close();
}
return chatMessageModelList;
}
public List<ChatMessageModel> getChatMessageAvailable(
String chatMessageUserId, String chatMessageRoomId,
String chatTempMessageId) {
List<ChatMessageModel> chatMessageModelList = new ArrayList<ChatMessageModel>();
Cursor cursor = null;
if (chatMessageUserId.equals(userId))
cursor = sqlDatabase.query(DbSqliteHelper.chatMessageTable,
allColumns, DbSqliteHelper.chatTempMessageId + " = " + "'"
+ chatTempMessageId + "' AND "
+ DbSqliteHelper.chatMessageUserId + " = "
+ chatMessageUserId + " AND "
+ DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "'", null, null, null, null);
else
cursor = sqlDatabase.query(DbSqliteHelper.chatMessageTable,
allColumns, DbSqliteHelper.chatMessageId + " = " + "'"
+ chatTempMessageId + "' AND "
+ DbSqliteHelper.chatMessageUserId + " = "
+ chatMessageUserId + " AND "
+ DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "'", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChatMessageModel chatMessageModel = cursorToChatMessage(cursor);
chatMessageModelList.add(chatMessageModel);
cursor.moveToNext();
}
cursor.close();
return chatMessageModelList;
}
public boolean isMsgAvailable(String messageId,String roomId) {
String[] column = { DbSqliteHelper.chatMessageId };
Cursor cursor = sqlDatabase.query(DbSqliteHelper.chatMessageTable,
column, DbSqliteHelper.chatMessageId + " = " + "'" + messageId
+ "' AND "
+ DbSqliteHelper.chatMessageRoomId + "!= " + "'"
+ roomId + "'", null, null, null, null);
if (cursor.getCount() > 0)
return true;
else
return false;
}
public void deleteAllChatMessage(String chatMessageRoomId) {
String lastMessageId = getLatestMsgId(chatMessageRoomId);
sqlDatabase.delete(DbSqliteHelper.chatMessageTable,
DbSqliteHelper.chatMessageRoomId + " = " + "'"
+ chatMessageRoomId + "' AND "
+ DbSqliteHelper.chatMessageId + "!= " + "'"
+ lastMessageId + "'", null);
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId, lastMessageId);
values.put(DbSqliteHelper.chatMessageSeen, "1");
values.put(DbSqliteHelper.chatIsRemoved, "1");
sqlDatabase.update(DbSqliteHelper.chatMessageTable, values,
DbSqliteHelper.chatMessageId + " = " + "'" + lastMessageId
+ "'", null);
}
public int deleteSelectedChatMessage(String chatMessageId) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatMessageId, chatMessageId);
values.put(DbSqliteHelper.chatIsRemoved, "1");
int insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatMessageId + " = " + "'"
+ chatMessageId + "'", null);
return insertId;
}
public int noOfRows(String chatMessageRoomId) {
Cursor mCount = sqlDatabase.rawQuery("select count(*) from "
+ (DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + "='"
+ chatMessageRoomId + "' AND "
+ DbSqliteHelper.chatIsRemoved + " = '" + "" + "'"),
null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return count;
}
public int noOfMessages(String chatMessageRoomId) {
Cursor mCount = sqlDatabase.rawQuery("select count(*) from "
+ (DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + "='"
+ chatMessageRoomId + "'"), null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return count;
}
private ChatMessageModel cursorToChatMessage(Cursor cursor) {
ChatMessageModel chatMessageModel = new ChatMessageModel();
chatMessageModel.setMsgId(cursor.getString(1));
chatMessageModel.setSenderName(cursor.getString(2));
chatMessageModel.setProfileImgUrl(cursor.getString(3));
chatMessageModel.setMessageRoomId(cursor.getString(4));
chatMessageModel.setUserId(cursor.getString(5));
chatMessageModel.setActualMsg(cursor.getString(6));
chatMessageModel.setMessageType(cursor.getString(7));
chatMessageModel.setPostImgUrl(cursor.getString(8));
chatMessageModel.setLatitude(cursor.getString(9));
chatMessageModel.setLangitude(cursor.getString(10));
chatMessageModel.setMsgTime(cursor.getString(11));
chatMessageModel.setChatMessageSeen(cursor.getString(15));
chatMessageModel.setChatMessageSeenTime(cursor.getString(16));
chatMessageModel.setChatFileThumbnail(cursor.getString(17));
chatMessageModel.setChatIsRemoved(cursor.getString(18));
chatMessageModel.setChatIsSent(cursor.getString(19));
chatMessageModel.setChatTempMessageId(cursor.getString(20));
chatMessageModel.setChatAudioTime(cursor.getString(22));
chatMessageModel.setChatDisappear(cursor.getString(21));
chatMessageModel.setChatStickerAudioBuzzId(cursor.getString(23));
chatMessageModel.setChatEditMsg(cursor.getString(24));
chatMessageModel.setImageDownlaod(cursor.getInt(25));
return chatMessageModel;
}
public int updatePicLocalPath(String path, String msgId) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatFileThumbnail, path);
int insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatMessageId + " = " + "'" + msgId
+ "'", null);
return insertId;
}
public int updateAudioVideo(String msgId) {
ContentValues values = new ContentValues();
values.put(DbSqliteHelper.chatIsSent, "1");
int insertId = sqlDatabase.update(DbSqliteHelper.chatMessageTable,
values, DbSqliteHelper.chatTempMessageId + " = " + "'" + msgId
+ "'", null);
return insertId;
}
public long getNextChatMessageCount(String chatMessageRoomId,
String chatMessageId, boolean isDummyMsgId) {
long count = 0;
Integer fstMsgPrimaryKey = getFstMsgPrimaryKey(chatMessageId,
isDummyMsgId);
if (fstMsgPrimaryKey != null) {
String rawQuery = "select COUNT(*) from (select * from "
+ DbSqliteHelper.chatMessageTable + " where "
+ DbSqliteHelper.chatMessageRoomId + " = '"
+ chatMessageRoomId + "' AND "
+ DbSqliteHelper.chatPrimaryKey + " < '" + fstMsgPrimaryKey
+ "' AND " + DbSqliteHelper.chatIsRemoved + " = '" + ""
+ "'" + " order by " + DbSqliteHelper.chatPrimaryKey
+ " DESC limit " + 0 + ") order by "
+ DbSqliteHelper.chatPrimaryKey + " ASC";
Cursor cursor = sqlDatabase.rawQuery(rawQuery, null);
if (cursor.moveToFirst()) {
count = cursor.getLong(0);
}
cursor.close();
}
return count;
}
}
|
package com.minismap.data;
/**
* Created by nbp184 on 2016/03/24.
*/
public class GridPoint {
public int x;
public int y;
public GridPoint() {
x = 0;
y = 0;
}
public GridPoint(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if(o instanceof GridPoint) {
GridPoint gp = (GridPoint)o;
return x == gp.x && y == gp.y;
} else {
return false;
}
}
public boolean equals(int x, int y) {
return this.x == x && this.y == y;
}
public static GridPoint load(String line) {
int index = line.indexOf(",");
return new GridPoint(Integer.parseInt(line.substring(0, index)), Integer.parseInt(line.substring(index+1)));
}
}
|
public interface OneWayListNode<T> {
// return node value
T get();
// return next node or null in case of absence
OneWayListNode<T> next();
}
|
package classes;
/**
* Enumeration TypeBoisson - écrire ici la description de l'énumération
*
* @author (votre nom)
* @version (numéro de version ou date)
*/
public enum TypeBoisson
{
EAU_MINERALE,JUS,GAZEUSE,CAFE,THE
}
|
/*
* 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.neo.heladeria.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author laura.romerot
*/
@Entity
@Table(name = "delivery")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Delivery.findAll", query = "SELECT d FROM Delivery d"),
@NamedQuery(name = "Delivery.findByIdDelivery", query = "SELECT d FROM Delivery d WHERE d.idDelivery = :idDelivery"),
@NamedQuery(name = "Delivery.findByName", query = "SELECT d FROM Delivery d WHERE d.name = :name"),
@NamedQuery(name = "Delivery.findByLastname", query = "SELECT d FROM Delivery d WHERE d.lastname = :lastname"),
@NamedQuery(name = "Delivery.findByPhone", query = "SELECT d FROM Delivery d WHERE d.phone = :phone")})
public class Delivery implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_delivery")
private Integer idDelivery;
@Column(name = "name")
private String name;
@Column(name = "lastname")
private String lastname;
@Column(name = "phone")
private String phone;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "deliveryIdDelivery")
@JsonIgnore
private List<ListOrder> listOrderList;
public Delivery() {
}
public Delivery(Integer idDelivery) {
this.idDelivery = idDelivery;
}
public Integer getIdDelivery() {
return idDelivery;
}
public void setIdDelivery(Integer idDelivery) {
this.idDelivery = idDelivery;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@XmlTransient
public List<ListOrder> getListOrderList() {
return listOrderList;
}
public void setListOrderList(List<ListOrder> listOrderList) {
this.listOrderList = listOrderList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idDelivery != null ? idDelivery.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Delivery)) {
return false;
}
Delivery other = (Delivery) object;
if ((this.idDelivery == null && other.idDelivery != null) || (this.idDelivery != null && !this.idDelivery.equals(other.idDelivery))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.neo.heladeria.entities.Delivery[ idDelivery=" + idDelivery + " ]";
}
}
|
package com.onlyu.reactiveprog.repositories;
import com.onlyu.reactiveprog.domain.Recipe;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.Optional;
import java.util.Set;
public interface RecipeRepository extends MongoRepository<Recipe, String> {
Set<Recipe> findAllByOrderById();
Optional<Recipe> findRecipeById(String id);
// @Query("{ 'id': ?0 }")
// Set<Category> findCategoriesById(String id);
//
// @Query("{ 'id': ?0 }")
// Set<Ingredient> findIngredientsById(String id);
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE file for licensing information.
*/
package pl.edu.icm.unity.stdext.identity;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.MessageSource;
import pl.edu.icm.unity.exceptions.IllegalIdentityValueException;
import pl.edu.icm.unity.stdext.utils.EmailUtils;
import pl.edu.icm.unity.types.basic.Attribute;
import pl.edu.icm.unity.types.basic.AttributeType;
import pl.edu.icm.unity.types.basic.IdentityParam;
import pl.edu.icm.unity.types.basic.VerifiableEmail;
/**
* Email identity type definition
*
* @author P. Piernik
*/
@Component
public class EmailIdentity extends AbstractStaticIdentityTypeProvider
{
public static final String ID = "email";
/**
* {@inheritDoc}
*/
@Override
public String getId()
{
return ID;
}
/**
* {@inheritDoc}
*/
@Override
public String getDefaultDescription()
{
return "Email";
}
/**
* {@inheritDoc}
*/
@Override
public Set<AttributeType> getAttributesSupportedForExtraction()
{
return Collections.emptySet();
}
@Override
public void validate(String value) throws IllegalIdentityValueException
{
String error = EmailUtils.validate(value);
if (error != null)
throw new IllegalIdentityValueException(error);
}
@Override
public IdentityParam convertFromString(String stringRepresentation, String remoteIdp,
String translationProfile) throws IllegalIdentityValueException
{
VerifiableEmail converted = EmailUtils.convertFromString(stringRepresentation);
validate(converted.getValue());
return toIdentityParam(converted, remoteIdp, translationProfile);
}
public static IdentityParam toIdentityParam(VerifiableEmail email, String remoteIdp, String translationProfile)
{
IdentityParam ret = new IdentityParam(ID, email.getValue(), remoteIdp, translationProfile);
ret.setConfirmationInfo(email.getConfirmationInfo());
return ret;
}
public static VerifiableEmail fromIdentityParam(IdentityParam idParam)
{
VerifiableEmail ret = new VerifiableEmail(idParam.getValue());
if (idParam.getConfirmationInfo() != null)
ret.setConfirmationInfo(idParam.getConfirmationInfo());
return ret;
}
/**
* {@inheritDoc}
*/
@Override
public String getComparableValue(String from, String realm, String target)
throws IllegalIdentityValueException
{
return new VerifiableEmail(from).getComparableValue();
}
/**
* {@inheritDoc}
*/
@Override
public List<Attribute<?>> extractAttributes(String from, Map<String, String> toExtract)
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public String toPrettyStringNoPrefix(IdentityParam from)
{
VerifiableEmail ve = fromIdentityParam(from);
StringBuilder ret = new StringBuilder(ve.getValue());
return ret.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String getHumanFriendlyDescription(MessageSource msg)
{
return msg.getMessage("EmailIdentity.description");
}
@Override
public boolean isDynamic()
{
return false;
}
@Override
public boolean isVerifiable()
{
return true;
}
@Override
public String getHumanFriendlyName(MessageSource msg)
{
return msg.getMessage("EmailIdentity.name");
}
}
|
package edu.lewis.ap.sweezy.kenneth;
import edu.jenks.dist.lewis.ap.*;
public class Name extends AbstractName {
public static void main(String[] args) {
Name testing1 = new Name("Bill", "Cosbo");
Name testing2 = new Name("Bill", "Cosby");
System.out.println(testing1.compareTo(testing2));
}
public Name(String firstName, String lastName) {
super(firstName, lastName);
}
public int compareTo(AbstractName arg0) {
if(getLast().equals(arg0.getLast())) {
if(getFirst().equals(arg0.getFirst())) {
setDuplicates(getDuplicates() + 1);
return 0;
}
int temp1 = getFirst().compareTo(arg0.getFirst());
return temp1;
}
int temp2 = getLast().compareTo(arg0.getLast());
return temp2;
}
public String toString() {
return getLast() + ", " + getFirst();
}
}
|
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
package pwnbrew.xml.maltego;
import java.util.List;
import pwnbrew.xml.XmlObject;
/**
*
* @author Securifera
*/
abstract public class Entity extends XmlObject {
private static final String ATTRIBUTE_Type = "Type";
//Internal Objects
protected Value mainPropertyValue = new Value();
protected Weight entityWeight = null;
protected DisplayInformation displayInfo = null;
protected AdditionalFields fieldList = null;
protected IconURL urlToIcon = null;
// ==========================================================================
/**
* Constructor
* @param passedType
*/
public Entity( String passedType ) {
theAttributeMap.put( ATTRIBUTE_Type, passedType );
}
// ==========================================================================
/**
* Returns the type of the entity
*
* @return the type of entity
*/
public String getType() {
return getAttribute( ATTRIBUTE_Type );
}
// ==========================================================================
/**
* Add the field to the entity
*
* @param aField
*/
public void addField( Field aField ) {
//If the object is null then create it
if( fieldList == null )
fieldList = new AdditionalFields();
fieldList.addField(aField);
}
// ==========================================================================
/**
* Add the field to the entity
*
* @param fieldName
* @return
*/
public Field getField( String fieldName ) {
//If the object is null then create it
Field aField = null;
if( fieldList != null )
aField = fieldList.getField(fieldName);
return aField;
}
//===========================================================================
/**
*
* @return
*/
public String getDisplayValue() {
return mainPropertyValue.getXmlObjectContent();
}
//===========================================================================
/**
*
* @param passedValue
*/
public void setDisplayValue( String passedValue ) {
mainPropertyValue.setXmlObjectContent( passedValue );
}
// ==========================================================================
/**
* Returns a list of this object's subcomponents that should be added to its
* XML data.
* <p>
* NOTE: This overrides a method in {@link XmlObject}.
*
* @return an {@link ArrayList} of the {@link XmlObject} components for this
* object
*/
@Override
public List<XmlObject> getXmlComponents() {
List<XmlObject> rtnList = super.getXmlComponents();
//Add the internal objects
rtnList.add( mainPropertyValue );
//Add weight if it has been set
if( entityWeight != null )
rtnList.add( entityWeight );
//Add any display info
if( displayInfo != null )
rtnList.add( displayInfo );
//Add any additional fields
if( fieldList != null )
rtnList.add( fieldList );
//Add any additional fields
if( urlToIcon != null )
rtnList.add( urlToIcon );
return rtnList;
}
}
|
package com.fanfte.rpc.spring;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* Created by tianen on 2018/11/8
*
* @author fanfte
* @date 2018/11/8
**/
public class UserBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(Element element) {
return User.class;
}
@Override
protected void doParse(Element element, BeanDefinitionBuilder builder) {
String id = element.getAttribute("id");
String name = element.getAttribute("name");
String email = element.getAttribute("email");
Integer age = Integer.parseInt(element.getAttribute("age"));
if(StringUtils.hasText(id)) {
builder.addPropertyValue("id", id);
}
if(StringUtils.hasText(name)) {
builder.addPropertyValue("name", name);
}
if(StringUtils.hasText(email)) {
builder.addPropertyValue("email", email);
}
if(age != null) {
builder.addPropertyValue("aget", age);
}
}
}
|
package com.classroom.services.facade.dto.entities;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.classroom.services.web.dto.mappers.LocalDateTimeAdapter;
import org.joda.time.LocalDateTime;
@XmlRootElement(name="circularBatchDetails")
public class CircularBatchDTO extends AbstractDTO<Integer>{
private Integer id;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private String errorCode;
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.core.objects;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.datacrow.console.ComponentFactory;
import net.datacrow.core.DcRepository;
import net.datacrow.core.data.DataManager;
import net.datacrow.core.db.DatabaseManager;
import net.datacrow.core.db.InsertQuery;
import net.datacrow.core.db.Query;
import net.datacrow.core.db.QueryQueue;
import net.datacrow.core.db.UpdateQuery;
import net.datacrow.core.modules.DcModule;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.helpers.ExternalReference;
import net.datacrow.core.objects.helpers.Movie;
import net.datacrow.core.objects.helpers.Software;
import net.datacrow.core.objects.template.Templates;
import net.datacrow.core.resources.DcResources;
import net.datacrow.core.wf.WorkFlow;
import net.datacrow.core.wf.requests.IRequest;
import net.datacrow.core.wf.requests.Requests;
import net.datacrow.core.wf.requests.UpdateUIAfterDeleteRequest;
import net.datacrow.core.wf.requests.UpdateUIAfterInsertRequest;
import net.datacrow.core.wf.requests.UpdateUIAfterUpdateRequest;
import net.datacrow.enhancers.IValueEnhancer;
import net.datacrow.enhancers.ValueEnhancers;
import net.datacrow.settings.DcSettings;
import net.datacrow.settings.definitions.DcFieldDefinition;
import net.datacrow.settings.definitions.DcFieldDefinitions;
import net.datacrow.util.Base64;
import net.datacrow.util.DcImageIcon;
import net.datacrow.util.Hash;
import net.datacrow.util.StringUtils;
import net.datacrow.util.Utilities;
import org.apache.log4j.Logger;
/**
* This class is what it is all about. Each DcObject represents an item
* within Data Crow. DcObjects are very generic by nature. There are no direct
* getters and setters for their values. Instead the values are stored in a Map object
* and the values are retrieved by using the field indices.
* <br>
* It's recommended before starting new development of plugins to create so called
* helper classes for your new module. Examples of helper classes are {@link Software}
* and {@link Movie}.
* <br>
* DcObjects are managed and maintained by the Data Manager class ({@link DataManager}.
* Each DcObject belongs to a (@link {@link DcModule}).
*
* @author Robert Jan van der Waals
*/
public class DcObject implements Comparable<DcObject>, Serializable {
private static final long serialVersionUID = -6969856564828155152L;
private static Logger logger = Logger.getLogger(DcObject.class.getName());
private final int module;
private Map<Integer, DcValue> values = new HashMap<Integer, DcValue>();
private Requests requests = new Requests();
protected List<DcObject> children = new ArrayList<DcObject>();
private boolean validate = true;
private boolean updateGUI = true;
public static final int _ID = 0;
public static final int _SYS_MODULE = 201;
public static final int _SYS_AVAILABLE = 202;
public static final int _SYS_LENDBY = 203;
public static final int _SYS_LOANDURATION = 204;
public static final int _SYS_CREATED = 205;
public static final int _SYS_MODIFIED = 206;
public static final int _SYS_SERVICE = 207;
public static final int _SYS_SERVICEURL = 208;
public static final int _SYS_FILEHASH = 209;
public static final int _SYS_FILESIZE = 210;
public static final int _SYS_FILENAME = 211;
public static final int _SYS_FILEHASHTYPE = 212;
public static final int _SYS_CONTAINER = 213;
public static final int _SYS_DISPLAYVALUE = 214;
public static final int _SYS_LOANDUEDATE = 215;
public static final int _SYS_LOANSTATUSDAYS = 216;
public static final int _SYS_LOANSTATUS = 219;
public static final int _SYS_LOANSTARTDATE = 220;
public static final int _SYS_LOANENDDATE = 221;
public static final int _SYS_TAGS = 222;
public static final int _VALUE = 217;
public static final int _SYS_EXTERNAL_REFERENCES = 218;
private boolean loaded = false;
private boolean isNew = true;
private boolean lastInLine = true;
/**
* Creates a new instance.
* @param module
*/
public DcObject(int module) {
this.module = module;
// initialize the values map
int[] fields = getModule().getFieldIndices();
for (int i = 0; i < fields.length; i++) {
values.put(fields[i], new DcValue());
}
markAsUnchanged();
}
/**
* Indicates the item is last in line of a save or delete action.
* Items last in line (of a batch) will cause additional GUI updates to be performed.
*/
public boolean isLastInLine() {
return lastInLine;
}
/**
* Indicates the item is last in line of a save or delete action.
* Items last in line (of a batch) will cause additional GUI updates to be performed.
*/
public void setLastInLine(boolean lastInLine) {
this.lastInLine = lastInLine;
}
/**
* Indicates whether ANY interface updates should be performed.
*/
public boolean isUpdateGUI() {
return updateGUI;
}
/**
* Indicate whether ANY interface updates should be performed.
* Setting this to false will only cause the database to be updated but will no push the update
* to the GUI. By default this value is set to true.
*/
public void setUpdateGUI(boolean updateGUI) {
this.updateGUI = updateGUI;
}
public boolean isLoaded() {
return loaded;
}
public void reload() {
loaded = isNew;
load(getFieldIndices());
}
public void load(int[] fields) {
load(fields, false);
}
/**
* Loads the item from the database.
* Initializes images, references and loan information.
*/
public void load(int[] fields, boolean overruleLoadCheck) {
long start = logger.isDebugEnabled() ? new Date().getTime() : 0;
if ((loaded && !overruleLoadCheck) || isNew) return;
String ID = getID();
fields = fields == null ? getFieldIndices() : fields;
try {
String sql = "SELECT * FROM " + getTableName() + " WHERE ID = '" + getID() + "'";
clearValues();
ResultSet rs = DatabaseManager.executeSQL(sql);
while (rs.next()) {
WorkFlow.setValues(rs, this, fields, fields);
markAsUnchanged();
break;
}
rs.close();
} catch (Exception e) {
logger.error("An error occurred while loading the item", e);
setValue(DcObject._ID, ID);
}
if (logger.isDebugEnabled()) {
logger.info("Item " + toString() + " was loaded in " + (new Date().getTime() - start) + "ms");
}
loaded = true;
}
public int getSystemDisplayFieldIdx() {
return getModule().getSystemDisplayFieldIdx();
}
public boolean isDestroyed() {
return values == null;
}
/**
* Educated guess..
*/
public int getDisplayFieldIdx() {
return getModule().getDisplayFieldIdx();
}
/**
* The default sort field index. In case the user has not specified the field to sort on
* this value will be used.
*/
public int getDefaultSortFieldIdx() {
return DcObject._ID;
}
/**
* Returns the name of this object based on the field settings. If the field settings do
* no specify any descriptive fields the default name field index is used as defined in the
* module definition.
*/
public String getName() {
String name = "";
for (DcFieldDefinition definition : DcModules.get(module).getFieldDefinitions().getDefinitions()) {
if (definition.isDescriptive() && definition.isEnabled()) {
int idx = definition.getIndex();
String disp = getDisplayString(idx);
if (disp.length() > 0)
name += (name.length() > 0 ? ", " + disp : disp);
}
}
if (name.length() == 0)
name = getDisplayString(getModule().getNameFieldIdx());
return name;
}
/**
* Is this object capable of storing IDs? In most cases the answer should be yes.
*/
public boolean hasPrimaryKey() {
return getField(_ID) != null;
}
/**
* Clears the requests.
*/
public void removeRequests() {
if (requests != null)
requests.clear();
}
/**
* Retrieves the value objects.
*/
public Map<Integer, DcValue> getValues() {
return values;
}
/**
* Set the value using the database field name as key.
* @param column
* @param value
*/
public void setValueForColumn(String column, Object value) {
for (DcField field : getFields()) {
if (field.getDatabaseFieldName().equalsIgnoreCase(column)) {
setValue(field.getIndex(), value);
break;
}
}
}
/**
* Set the value using the system name of the field.
* @param sysName
* @param value
*/
public void setValueForName(String sysName, Object value) {
for (DcField field : getFields()) {
if (field.getSystemName().equalsIgnoreCase(sysName)) {
setValue(field.getIndex(), value);
break;
}
}
}
@SuppressWarnings("unchecked")
public String getExternalReference(String type) {
Collection<DcObject> references = (Collection<DcObject>) getValue(_SYS_EXTERNAL_REFERENCES);
references = references == null ? new ArrayList<DcObject>() : references;
for (DcObject mapping : references) {
DcObject reference = ((DcMapping) mapping).getReferencedObject();
if ( reference != null &&
reference.getValue(ExternalReference._EXTERNAL_ID_TYPE) != null &&
reference.getValue(ExternalReference._EXTERNAL_ID_TYPE).equals(type)) {
return (String) reference.getValue(ExternalReference._EXTERNAL_ID);
}
}
return null;
}
/**
* Adds or updates the existing external key of the specified type.
* @param type The type of the key
* @param key The external key / ID
*/
@SuppressWarnings("unchecked")
public void addExternalReference(String type, String key) {
Collection<DcObject> c = (Collection<DcObject>) getValue(_SYS_EXTERNAL_REFERENCES);
c = c == null ? new ArrayList<DcObject>() : c;
Collection<DcObject> references = new ArrayList<DcObject>();
for (DcObject mapping : c) {
if (mapping != null)
references.add(mapping);
}
c.clear();
setValue(_SYS_EXTERNAL_REFERENCES, references);
boolean set = false;
try {
for (DcObject mapping : references) {
DcObject reference = ((DcMapping) mapping).getReferencedObject();
if (reference != null && reference.getDisplayString(ExternalReference._EXTERNAL_ID_TYPE).equals(type)) {
reference.setValue(ExternalReference._EXTERNAL_ID, key);
set = true;
}
}
} catch (Exception e) {
logger.error("Could not determine if external ID already exists", e);
}
if (!set && !Utilities.isEmpty(type)) {
DcObject er = DcModules.get(module + DcModules._EXTERNALREFERENCE).getItem();
er.setValue(ExternalReference._EXTERNAL_ID, key);
er.setValue(ExternalReference._EXTERNAL_ID_TYPE, type);
er.setIDs();
DataManager.createReference(this, DcObject._SYS_EXTERNAL_REFERENCES, er);
}
}
/**
* Retrieves all the requests. These requests will be executed after a save or a delete.
* @return
*/
public Requests getRequests() {
return requests;
}
/**
* The database table name.
*/
public String getTableName() {
return getModule().getTableName();
}
public String getTableShortName() {
return getModule().getTableShortName();
}
/**
* Retrieves the database column count. This count will differ from the field count as
* some fields are calculated and not stored in the database.
* @return
*/
public int getDatabaseFieldCount() {
int count = 0;
for (DcField field : getFields())
count += field.isUiOnly() ? 0 : 1;
return count;
}
public String getLabel(int index) {
return getField(index).getLabel();
}
/**
* Loads the actual image / picture information. Changes are overwritten. Useful
* when reloading an object.
*/
public void initializeImages() {
// Remove all the old picture. This makes sure no weird stuff happens.
for (DcField field : getFields()) {
if (field.getValueType() == DcRepository.ValueTypes._PICTURE)
setValueLowLevel(field.getIndex(), null);
}
for (DcObject picture : DataManager.getPictures(getID())) {
picture.setValue(Picture._D_IMAGE, null);
picture.markAsUnchanged();
setValueForColumn((String) picture.getValue(Picture._B_FIELD), picture);
}
}
public void initializeReferences(int index, boolean full) {
DcField field = getField(index);
if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
int mappingModIdx = DcModules.getMappingModIdx(getModule().getIndex(), field.getReferenceIdx(), field.getIndex());
Collection<DcObject> mo = DataManager.getReferences(mappingModIdx, getID(), full);
setValue(index, mo);
} else if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE &&
getValue(field.getIndex()) != null) {
Object o = getValue(field.getIndex());
if (o instanceof String)
setValue(index, DataManager.getItem(field.getReferenceIdx(), (String) o));
}
}
/**
* Loads the actual reference information. Uses the Data Manager to retrieve the
* references and stores them in this object.
*/
public void initializeReferences() {
int[] fields = getFieldIndices();
for (int i = 0; i < fields.length; i++) {
DcField field = getField(fields[i]);
if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION ||
field.getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE) {
initializeReferences(fields[i], true);
}
}
}
/**
* Add a request. This request will be executed after saving or deleting the object.
* @param request
*/
public void addRequest(IRequest request) {
requests.add(request);
}
/**
* Does this field contains a value?
* @param index
*/
public boolean isFilled(int index) {
return !Utilities.isEmpty(getValue(index));
}
/**
* Remove all children from this object
*/
public void removeChildren() {
if (children != null)
children.clear();
}
public void setNew(boolean b) {
this.isNew = b;
}
public boolean isNew() {
return isNew;
}
/**
* Load all children. Children will only be loaded when no child information
* is present yet. Will not overwrite existing values.
*/
public void loadChildren(int[] fields) {
if (getModule().getChild() == null || isNew())
return;
children.clear();
int childIdx = getModule().getChild().getIndex();
for (DcObject dco : DataManager.getChildren(getID(), childIdx, fields)) {
children.add(dco);
}
}
public void setChildren(Collection<DcObject> children) {
if (this.children == null) {
this.children = new ArrayList<DcObject>(children);
} else {
this.children.clear();
this.children.addAll(children);
}
for (DcObject child : children)
child.setValue(child.getParentReferenceFieldIndex(), getID());
}
public void addChild(DcObject child) {
if (child.getParentReferenceFieldIndex() == DcObject._SYS_CONTAINER) {
DataManager.createReference(child, child.getParentReferenceFieldIndex(), this);
} else {
child.setValue(child.getParentReferenceFieldIndex(), getID());
this.children = children == null ? new ArrayList<DcObject>() : children;
children.add(child);
}
}
/**
* Retrieves the child objects belonging to this item.
* @return The children or null of none.
*/
public List<DcObject> getChildren() {
if ((children == null || children.size() == 0) && getModule().getChild() != null)
loadChildren(null);
return getCurrentChildren();
}
/**
* Gets the children as they have been currently set (without reloading them).
*/
public List<DcObject> getCurrentChildren() {
return children != null ? new ArrayList<DcObject>(children) : new ArrayList<DcObject>();
}
/**
* Retrieves the ID of the parent of this object.
* @return The parent ID or null.
*/
public String getParentID() {
Object o = getValue(getParentReferenceFieldIndex());
if (o instanceof DcObject)
return ((DcObject) o).getID();
else
return (String) o;
}
/**
* Retrieves the index of the field which is used to hold the link to the parent.
*/
public int getParentReferenceFieldIndex() {
return getModule().getParentReferenceFieldIndex();
}
public DcImageIcon getIcon() {
return DataManager.getIcon(this);
}
/**
* The icon used to represent this item.
*/
public DcImageIcon createIcon() {
DcField field = getModule().getIconField();
if (field != null) {
String value = (String) getValue(field.getIndex());
DcImageIcon icon = null;
if (value != null && value.length() > 1)
icon = Utilities.base64ToImage(value);
return icon;
}
return null;
}
public DcField getFileField() {
return getModule().getFileField();
}
/**
* Retrieves the filename value. This will only generate a result if the object
* has a file field.
* @return The file name or null.
*/
public String getFilename() {
DcField field = getFileField();
return field != null ? Utilities.getValidPath((String) getValue(field.getIndex())) : null;
}
/**
* Retrieves the module to which this object belongs.
*/
public DcModule getModule() {
return DcModules.get(module);
}
/**
* Retrieves all fields belonging to this object .
*/
public Collection<DcField> getFields() {
return getModule().getFields();
}
/**
* Mark all fields as unchanged. This does not reset the values to their
* original values! (use {@link #load()})
*/
public void markAsUnchanged() {
try {
for (DcValue value : values.values())
value.setChanged(false);
} catch (Exception ignore) {}
// 22032008: Removed "markAsUnchanged" on child objects!
// this broke saving the permissions (and possibly other item save's).
}
/**
* Update the loan information.
*/
public void setLoanInformation() {
if (getModule().canBeLend()) {
Loan loan = DataManager.getCurrentLoan(getID());
setLoanInformation(loan);
}
}
/**
* Update the loan information based on the supplied loan object.
*/
public void setLoanInformation(Loan loan) {
if (getModule().canBeLend()) {
boolean overdue = loan.isOverdue();
boolean available = loan.isAvailable(getID());
String status = overdue ? DcResources.getText("lblLoanOverdue") :
available ? DcResources.getText("lblAvailable") :
DcResources.getText("lblLoanLent");
Long daysTillOverdue = loan.getDaysTillDueDate();
daysTillOverdue = daysTillOverdue == null ? Long.valueOf(0) : daysTillOverdue;
Long daysLoaned = loan.getDaysLoaned();
daysLoaned = daysLoaned == null ? Long.valueOf(0) : daysLoaned;
setValue(DcObject._SYS_LOANSTARTDATE, loan.getValue(Loan._A_STARTDATE));
setValue(DcObject._SYS_LOANENDDATE, loan.getValue(Loan._B_ENDDATE));
setValue(DcObject._SYS_LENDBY, loan.getPerson());
setValue(DcObject._SYS_AVAILABLE, loan.isAvailable(getID()));
setValue(DcObject._SYS_LENDBY, loan.getPerson());
setValue(DcObject._SYS_LOANDUEDATE, loan.getDueDate());
setValue(DcObject._SYS_LOANDURATION, loan.getDaysLoaned());
setValue(DcObject._SYS_LOANSTATUS, status);
setValue(DcObject._SYS_LOANSTATUSDAYS, available ? null : Long.valueOf(overdue ? daysTillOverdue * -1 : daysLoaned));
}
}
/**
* Actions to be performed before saving the object.
*/
protected void beforeSave() throws ValidationException {
if (getModule().isFileBacked())
Hash.getInstance().calculateHash(this);
if ( getField(_SYS_EXTERNAL_REFERENCES) != null &&
getExternalReference(DcRepository.ExternalReferences._PDCR) == null &&
!Utilities.isEmpty(getDisplayString(getSystemDisplayFieldIdx()))) {
// Only create this ONCE. It is supposed to remain the same for ever
addExternalReference(DcRepository.ExternalReferences._PDCR,
getDisplayString(getSystemDisplayFieldIdx()));
}
DcField fld;
for (DcField field : getFields()) {
if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
if (isChanged(field.getIndex())) {
fld = getModule().getPersistentField(field.getIndex());
@SuppressWarnings("unchecked")
List<DcObject> references = (List<DcObject>) getValue(field.getIndex());
references = Utilities.sort(references);
if (references == null || references.size() == 0) {
setValue(fld.getIndex(), null);
} else {
setValue(fld.getIndex(), references.get(0).getValue(DcMapping._B_REFERENCED_ID));
}
}
}
}
saveIcon();
}
private void saveIcon() {
for (DcField field : getFields()) {
if (field.getValueType() != DcRepository.ValueTypes._ICON) continue;
if (!isChanged(field.getIndex())) continue;
String value = (String) getValue(field.getIndex());
if (value != null && value.length() > 0) {
byte[] bytes = Base64.decode(value.toCharArray());
DcImageIcon current = new DcImageIcon(bytes);
if (current.getIconHeight() > 16 || current.getIconWidth() > 16) {
BufferedImage img = Utilities.toBufferedImage(current, 16, 16);
try {
bytes = Utilities.getBytes(new DcImageIcon(img), DcImageIcon._TYPE_PNG);
setValue(field.getIndex(), new String(Base64.encode(bytes)));
} catch (Exception e) {
logger.error("Could not save scaled image for object with ID " + getID(), e);
}
}
}
}
}
/**
* Frees the resources hold by this items pictures.
*/
public void flushImages() {
for (DcField field : getFields()) {
if (field.getValueType() == DcRepository.ValueTypes._PICTURE) {
Picture picture = (Picture) getValue(field.getIndex());
if (picture != null) {
DcImageIcon icon = (DcImageIcon) picture.getValue(Picture._D_IMAGE);
if (icon != null) icon.flush();
}
}
}
}
/**
* Sets a value on this object.
* @param index The field index.
* @param o The value to be set.
*/
@SuppressWarnings("unchecked")
public void setValue(int index, Object o) {
if (isDestroyed()) {
logger.warn("System tried to set a value while the object was already destroyed");
return;
}
DcValue value = getValueDef(index);
if (value != null) {
if (index == _SYS_EXTERNAL_REFERENCES && getValue(index) != null && o != null ) {
mergeReferences((Collection<DcMapping>) o);
} else if (getField(index).getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
o = Utilities.sort((List<DcObject>) o);
value.setValue(o, getModule().getField(index));
} else {
value.setValue(o, getModule().getField(index));
}
}
}
@SuppressWarnings("unchecked")
private void mergeReferences(Collection<DcMapping> mappings) {
Collection<DcMapping> currentMappings = (Collection<DcMapping>) getValue(DcObject._SYS_EXTERNAL_REFERENCES);
// external references are always merged!
for (DcMapping mapping : mappings) {
DcObject reference = mapping.getReferencedObject();
boolean exists = false;
if (currentMappings != null) {
for (DcMapping mappingCurrent : currentMappings) {
DcObject referenceCurrent = mappingCurrent.getReferencedObject();
exists = referenceCurrent != null && referenceCurrent.getValue(ExternalReference._EXTERNAL_ID_TYPE).equals(reference.getValue(ExternalReference._EXTERNAL_ID_TYPE));
if (exists) {
mappingCurrent.setValue(DcMapping._B_REFERENCED_ID, referenceCurrent.getID());
getValueDef(DcObject._SYS_EXTERNAL_REFERENCES).setChanged(true);
break;
}
}
}
if (mapping.getReferencedObject() == null) {
logger.debug("External referenced object was empty. Exteneral reference has not been created for " + this);
} else if (!exists) {
DcMapping newMapping = (DcMapping) DcModules.get(DcModules.getMappingModIdx(
getModule().getIndex(), mapping.getReferencedObject().getModule().getIndex(), DcObject._SYS_EXTERNAL_REFERENCES)).getItem();
newMapping.setValue(DcMapping._A_PARENT_ID, getID());
newMapping.setValue(DcMapping._B_REFERENCED_ID, mapping.getReferencedObject().getID());
newMapping.setReference(mapping.getReferencedObject());
currentMappings.add(newMapping);
getValueDef(DcObject._SYS_EXTERNAL_REFERENCES).setChanged(true);
}
}
}
/**
* Applies the value directly on this item. All checks are bypasses.
* @param index The field index.
* @param o The value to be set.
*/
public void setValueLowLevel(int index, Object o) {
DcValue value = getValueDef(index);
if (value != null)
value.setValueLowLevel(o, getModule().getField(index));
}
/**
* Marks the object as changed.
*/
public void markAsChanged() {
for (DcValue value : values.values())
value.setChanged(true);
if (children != null)
for (DcObject child : children) child.markAsChanged();
}
/**
* Checks whether the object holds unchanged values.
* @see DcValue#isChanged()
*/
public boolean isChanged() {
if (isDestroyed()) {
logger.warn("System tried to check if a value was changed while the object was already destroyed");
return false;
}
try {
for (DcField field : getFields()) {
boolean changed = getValueDef(field.getIndex()).isChanged();
if ((!field.isUiOnly() || field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) && changed)
return true;
}
} catch (Exception e) {
logger.debug("Item was probably already destroyed!", e);
}
return false;
}
/**
* Checks whether the specified field holds a changed value.
* @see DcValue#isChanged()
* @param index The field index
*/
public boolean isChanged(int index) {
if (isDestroyed()) {
logger.warn("System tried to check if the value was changed while the object was already destroyed");
return false;
}
return getValueDef(index) != null ? getValueDef(index).isChanged() : false;
}
/**
* Manually mark a field as changed
* @see DcValue#isChanged()
* @param index The field index
* @param b Changed true / false
*/
public void setChanged(int index, boolean b) {
if (isDestroyed()) {
logger.warn("System tried to mark a field as changed while the object was already destroyed");
} else {
getValueDef(index).setChanged(b);
}
}
/**
* Indicates whether the field is enabled.
* This depends on the field settings which can be altered by the user.
* @see DcFieldDefinitions
* @see DcField#isEnabled()
* @param index
*/
public boolean isEnabled(int index) {
return getModule().getField(index).isEnabled();
}
/**
* Checks whether the field is marked as required.
* This depends on the field settings which can be altered by the user.
* @see DcFieldDefinitions
* @param index The field index
*/
public boolean isRequired(int index) {
return getModule().getField(index).isRequired();
}
/**
* Indicates whether the specified field can be searched on.
* @param index The field index
*/
public boolean isSearchable(int index) {
return getModule().getField(index).isSearchable();
}
/**
* The internal ID
*/
public String getID() {
return hasPrimaryKey() ? ((String) getValue(_ID)) : null;
}
/**
* Retrieves all fields on which cannot be searched.
*/
public Collection<DcField> getNotSearchableFields() {
Collection<DcField> notSearchable = new ArrayList<DcField>();
for (DcField field : getFields()) {
if (!field.isSearchable())
notSearchable.add(field);
}
return notSearchable;
}
/**
* Unloads this items. Its resources are freed and its pictures are unloaded.
* The item is unusable after this operation (!).
*/
public void release() {
getModule().release(this);
}
public void destroy() {
try {
if (requests != null)
requests.clear();
if (children != null)
children.clear();
if (values != null) {
clearValues();
values.clear();
}
if (children != null)
children.clear();
if (requests != null)
requests.clear();
requests = null;
children = null;
loaded = false;
values = null;
} catch (Exception e) {
logger.error(e, e);
}
}
/**
* Resets this item. All values are set to empty.
* @param nochecks Just do it, do not check whether we are dealing with an edited item
*/
public void clearValues() {
if (!isDestroyed()) {
for (Integer key : values.keySet()) {
if (key.intValue() != _ID) {
DcValue value = values.get(key);
value.clear();
}
}
markAsUnchanged();
}
loaded = false;
}
/**
* Retrieves the maximum field / value length.
* @param index The field index
*/
public int getMaxFieldLength(int index) {
return getField(index).getMaximumLength();
}
/**
* Retrieves the value for the specified field.
* @param index The field index.
*/
public Object getValue(int index) {
if (values == null || getValueDef(index) == null)
return null;
if (isDestroyed()) {
logger.warn("System tried to retrieve a value while the object was already destroyed");
} else if (getField(index) == null) {
logger.warn("Field with index " + index + " does not exist for module " + getModule());
}
Object value = null;
if (index == _SYS_DISPLAYVALUE) {
value = toString();
} else if (index == _SYS_MODULE) {
value = getModule();
} else {
value = getValueDef(index).getValue();
}
return value;
}
public String getNormalizedString(int index) {
String s = getDisplayString(index);
return StringUtils.normalize2(s);
}
/**
* Gets the display value for the specified field.
* @see DcObject#_SYS_DISPLAYVALUE
* @param index The field index
*/
public String getDisplayString(int index) {
if (index == _SYS_DISPLAYVALUE)
return getValueDef(getSystemDisplayFieldIdx()).getDisplayString(getField(getSystemDisplayFieldIdx()));
else if (index == _SYS_MODULE)
return getModule().getObjectNamePlural();
return getValueDef(index) != null ? getValueDef(index).getDisplayString(getField(index)) : "";
}
/**
* Retrieves the field type.
* @see ComponentFactory
* @param index The field index.
*/
public int getFieldType(int index) {
return getField(index).getFieldType();
}
/**
* Retrieves the database column name.
* @param index The field index.
* @return The database field name or null for UI only fields.
*/
public String getDatabaseFieldName(int index) {
return getField(index).getDatabaseFieldName();
}
/**
* Applies the enhancers on this item.
* @see ValueEnhancers
* @param update Indicates if the item is new or existing.
*/
public void applyEnhancers(boolean update) {
Object value;
Object newVal;
Object oldVal;
for (DcField field : getFields()) {
value = getValue(field.getIndex());
for (IValueEnhancer enhancer : field.getValueEnhancers()) {
if (enhancer.isEnabled() &&
(update && enhancer.isRunOnUpdating() || !update && enhancer.isRunOnInsert())) {
newVal = enhancer.apply(field, value);
oldVal = getValue(field.getIndex());
if (newVal != null && (oldVal == null || !newVal.equals(oldVal)))
setValue(field.getIndex(), newVal);
}
}
}
}
private Date getCurrentDate() {
return new Date();
}
/**
* Inserts the item into the database.
* @param queued Indicates if the item should be saved using the query queue.
* @see Query
* @see DatabaseManager
* @see QueryQueue
* @throws ValidationException
*/
public void saveNew(boolean queued) throws ValidationException {
try {
markAsChanged();
applyEnhancers(false);
checkIntegrity();
beforeSave();
setValue(_SYS_CREATED, getCurrentDate());
setValue(_SYS_MODIFIED, getCurrentDate());
setIDs();
if (updateGUI)
addRequest(new UpdateUIAfterInsertRequest(this, isLastInLine()));
if (queued) {
WorkFlow.insert(this);
} else {
new InsertQuery(this).run();
}
} catch (ValidationException ve) {
executeRequests(false);
throw ve;
} catch (Exception e) {
logger.error("An error (" + e + ") occurred while inserting " + this, e);
}
}
/**
* Save the changed item to the database.
* @param queued Indicates if the item should be saved using the query queue.
* @see Query
* @see DatabaseManager
* @see QueryQueue
* @throws ValidationException
*/
public void saveUpdate(boolean queued) throws ValidationException {
saveUpdate(queued, true);
}
/**
* Save the changed item to the database.
* @param queued Indicates if the item should be saved using the query queue.
* @param validate Indicates if the item should be validated before saving.
* @see Query
* @see DatabaseManager
* @see QueryQueue
* @throws ValidationException
*/
public void saveUpdate(boolean queued, boolean validate) throws ValidationException {
try {
applyEnhancers(true);
if (validate)
checkIntegrity();
beforeSave();
setValue(_SYS_MODIFIED, getCurrentDate());
if (updateGUI)
addRequest(new UpdateUIAfterUpdateRequest(this, isLastInLine()));
if (queued) {
WorkFlow.update(this);
} else {
new UpdateQuery(this).run();
}
} catch (ValidationException exp) {
executeRequests(false);
throw exp;
} catch (Exception e) {
logger.error("An error (" + e + ") occurred while updating " + this, e);
}
}
/**
* Permanently deletes the item.
*/
public void delete(boolean validate) throws ValidationException {
if (validate)
beforeDelete();
if (updateGUI)
addRequest(new UpdateUIAfterDeleteRequest(this, isLastInLine()));
WorkFlow.delete(this);
}
protected void beforeDelete() throws ValidationException {
Collection<DcObject> items = DataManager.getReferencingItems(this);
if (items.size() > 0)
throw new ValidationException(DcResources.getText("msgCannotDeleteDueToReferences", items.toString()));
}
/**
* Indicates if validation should take place when the item is saved.
*/
public void setValidate(boolean validate) {
this.validate = validate;
}
/**
* Retrieves the field
* @param index Field index
*/
public DcField getField(int index) {
return getModule().getField(index);
}
/**
* Checks the integrity of the item.
* @param update Indicates if the item is new or not.
* @throws ValidationException
*/
public void checkIntegrity() throws ValidationException {
if (DcSettings.getBoolean(DcRepository.Settings.stCheckRequiredFields))
validateRequiredFields();
if (DcSettings.getBoolean(DcRepository.Settings.stCheckUniqueness))
isUnique();
}
/**
* Checks if the item is unique.
* @param o The item to be checked.
* @param update Indicates if the item is new or not.
* @throws ValidationException
*/
public void isUnique() throws ValidationException {
boolean bUnique = WorkFlow.checkUniqueness(this, !isNew());
if (!bUnique && validate) {
String fields = "";
for (DcFieldDefinition definition : getModule().getFieldDefinitions().getDefinitions()) {
if (definition.isUnique()) {
fields += fields.length() > 0 ? ", " : "";
fields += getField(definition.getIndex()).getLabel();
}
}
throw new ValidationException(DcResources.getText("msgItemNotUnique", new String[] {toString(), fields}));
}
}
/**
* Retrieves all field indices.
*/
public int[] getFieldIndices() {
return getModule().getFieldIndices();
}
public void setIDs() {
if (hasPrimaryKey()) {
String ID = getID();
while (Utilities.isEmpty(ID))
ID = Utilities.getUniqueID();
setValue(DcObject._ID, ID);
if (children != null) {
for (DcObject child : children) {
if (child.hasPrimaryKey()) {
child.setIDs();
child.setValue(child.getParentReferenceFieldIndex(), ID);
}
}
}
}
}
protected DcValue getValueDef(int index) {
return values == null ? null : values.get(index);
}
protected void executeRequests(boolean saveSuccessful) {
if (requests != null) {
IRequest[] requestArray = requests.get();
for (int i = 0; i < requestArray.length; i++) {
IRequest request = requestArray[i];
if (saveSuccessful || request.getExecuteOnFail())
request.execute();
else
request.end();
}
}
}
protected void validateRequiredFields() throws ValidationException {
if (!validate) return;
String s = "";
for (DcField field : getFields()) {
if (field.isRequired()) {
if (!isFilled(field.getIndex())) {
if (s.length() > 0) s += ",";
s += getLabel(field.getIndex());
}
}
}
if (s.trim().length() > 1)
throw new ValidationException(DcResources.getText("msgMissingRequiredValues",
new String[] {s, toString()}));
}
/**
* Merges the values of this and the source item.
* Only empty values are updated with the values of the source item.
* @param dco The source item.
*/
public void merge(DcObject dco) {
copy(dco, false, false);
}
/**
* Copies all values from the specified Data Crow object.
* @param overwrite Indicates whether existing values should be overwritten.
* @param allowDeletes Allows existing values to be cleared.
* @param dco Source item.
*/
@SuppressWarnings("unchecked")
public void copy(DcObject dco, boolean overwrite, boolean allowDeletes) {
int[] fields = dco.getFieldIndices();
for (int i = 0; i < fields.length; i++) {
int field = fields[i];
// Do not overwrite when:
// - the to be copied value is empty and deletes are not allowed
// - overwriting is not allowed and the current value is not empty
if (!dco.isFilled(field) && !allowDeletes)
continue;
else if (!overwrite && isFilled(field))
continue;
if (field != _ID) {
Object o = dco.getValue(field);
if (o instanceof DcImageIcon) {
DcImageIcon oldIcon = (DcImageIcon) o;
DcImageIcon icon = new DcImageIcon(oldIcon.getImage());
icon.setFilename(oldIcon.getFilename());
setValue(field, icon);
} else if (o != null && getField(field).getValueType() == DcRepository.ValueTypes._PICTURE) {
Picture curPic = (Picture) dco.getValue(field);
Picture newPic = (Picture) DcModules.get(DcModules._PICTURE).getItem();
newPic.copy(curPic, overwrite, allowDeletes);
newPic.isDeleted(curPic.isDeleted());
newPic.isEdited(curPic.isEdited());
setValue(field, newPic);
} else if (o != null && getField(field).getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) {
Collection<DcMapping> newMappings = new ArrayList<DcMapping>();
for (DcObject mapping : (Collection<DcObject>) o)
newMappings.add((DcMapping) mapping.clone());
setValue(field, newMappings);
} else if (o != null && getField(field).getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE) {
setValue(field, ((DcObject) o).clone());
} else {
setValue(field, o);
}
}
}
}
public void applyTemplate() {
if (getModule().getTemplateModule() != null) {
DcTemplate template = Templates.getDefault(getModule().getTemplateModule().getIndex());
if (template != null)
applyTemplate(template);
}
}
public void applyTemplate(DcTemplate template) {
if (template == null) {
applyTemplate();
return;
}
int[] fields = getFieldIndices();
for (int i = 0; i < fields.length; i++) {
int idx = fields[i];
// 20121112 - do not allow templates to overwrite existing values
if (isFilled(idx) || !template.isFilled(idx))
continue;
DcField field = getField(idx);
Object templateVal = template.getValue(idx);
if ( idx != _ID &&
idx != _SYS_EXTERNAL_REFERENCES &&
field.getValueType() != DcRepository.ValueTypes._PICTURE &&
templateVal != null) {
setValue(idx, template.getValue(idx));
} else if ( field.getValueType() == DcRepository.ValueTypes._PICTURE &&
template.getValue(idx) != null &&
((Picture) template.getValue(idx)).hasImage()
) {
Picture templatePic = (Picture) template.getValue(idx);
Picture pic = (Picture) DcModules.get(DcModules._PICTURE).getItem();
templatePic.loadImage(false);
pic.setValue(Picture._D_IMAGE, templatePic.getValue(Picture._D_IMAGE));
pic.setValue(Picture._E_HEIGHT, templatePic.getValue(Picture._E_HEIGHT));
pic.setValue(Picture._F_WIDTH, templatePic.getValue(Picture._F_WIDTH));
pic.isEdited(true);
setValue(idx, pic);
}
}
}
/**
* Copy an existing picture and set it on this item. This is the safest way to copy
* an picture of another item to this item.
*/
public void copyImage(Picture picture, int field) {
if (picture != null) {
DcImageIcon icon = (DcImageIcon) picture.getValue(Picture._D_IMAGE);
if (icon != null)
setValue(field, new DcImageIcon(icon.getImage()));
}
}
/**
* Clones this objects. All values are copies as well as its children.
* The clone operates on copies of the pictures and the children and can be used entirely
* in parallel with its clone(s).
*
* Note; this is not a shallow copy and costs just as much resources as its original.
* After using the clone it is best to discard it by calling the destroy method.
*/
@Override
public DcObject clone() {
DcObject dco = getModule().getItem();
dco.copy(this, true, true);
dco.setValue(DcObject._ID, getID());
dco.markAsUnchanged();
if (children != null) {
for (DcObject child : children)
dco.addChild(child.clone());
}
int[] indices = getFieldIndices();
for (int i = 0; i < indices.length; i++) {
dco.setChanged(indices[i], isChanged(indices[i]));
}
return dco;
}
@Override
public int hashCode() {
return getID() != null ? getID().hashCode() : super.hashCode();
}
@Override
public String toString() {
return getName();
}
@Override
protected void finalize() throws Throwable {
destroy();
super.finalize();
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
boolean equals = false;
if (o instanceof String) {
equals = getID() != null ? getID().equals(o) : false;
} else if (o instanceof DcObject) {
String id1 = ((DcObject) o).getID();
String id2 = getID();
if ((id1 == null && id2 != null) || (id1 != null && id2 == null) )
return false;
if (id1 == null && id2 == null)
return false;
else
return id1.equals(id2);
} else {
equals = super.equals(o);
}
return equals;
}
@Override
public int compareTo(DcObject o) {
return toString().compareTo(o.toString());
}
}
|
package sql.requete;
import java.sql.*;
import java.util.StringTokenizer;
public class InterrogPostgresql {
private String username;
private String password;
private String url;
private String requete;
public InterrogPostgresql() {
// ---- configure START
username = "lo17xxx";
password = "dblo17";
// The URL that will connect to TECFA's MySQL server
// Syntax: jdbc:TYPE:machine:port/DB_NAME
url = "jdbc:postgresql://tuxa.sme.utc/dblo17";
}
public void exec_sql() {
// INSTALL/load the Driver (Vendor specific Code)
try {
Class.forName("org.postgresql.Driver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
Connection con;
Statement stmt;
// Establish Connection to the database at URL with usename and password
con = DriverManager.getConnection(url, username, password);
stmt = con.createStatement();
// Send the query and bind to the result set
ResultSet rs = stmt.executeQuery(requete);
// while (rs.next()) {
// String s = rs.getString("page");
// System.out.print(s);
// System.out.print("\t");
// s = rs.getString("rubrique");
// System.out.print(s);
// System.out.println();
// }
while (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
if (i > 1) {
System.out.print(",");
}
int type = rsmd.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.print(rs.getString(i));
} else {
System.out.print(rs.getLong(i));
}
}
System.out.println();
}
// Close resources
stmt.close();
con.close();
}
// print out decent erreur messages
catch(SQLException ex) {
System.err.println("==> SQLException: ");
while (ex != null) {
System.out.println("Message: " + ex.getMessage ());
System.out.println("SQLState: " + ex.getSQLState ());
System.out.println("ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
System.out.println("");
}
}
}
public void setRequete(String re) {
requete = re;
}
public String getRequete() {
return requete;
}
public StringTokenizer affich(String req) {
String tr, tmp = "";
StringTokenizer st = new StringTokenizer(req);
int i = 0;
while (st.hasMoreTokens()) {
tr = st.nextToken();
tr = tr.replace(",", "");
if (tr.compareTo("from") == 0) {
i = 0;
}
if (i == 1) {
if (tr.contains("count(") == true) {
tmp = tmp.concat("count ");
} else {
tmp = tmp.concat(tr + " ");
}
}
if (tr.compareTo("select") == 0) {
i = 1;
}
}
st = new StringTokenizer(tmp);
return st;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util.xml;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Abstract base class for SAX {@code XMLReader} implementations that use StAX as a basis.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see #setContentHandler(org.xml.sax.ContentHandler)
* @see #setDTDHandler(org.xml.sax.DTDHandler)
* @see #setEntityResolver(org.xml.sax.EntityResolver)
* @see #setErrorHandler(org.xml.sax.ErrorHandler)
*/
abstract class AbstractStaxXMLReader extends AbstractXMLReader {
private static final String NAMESPACES_FEATURE_NAME = "http://xml.org/sax/features/namespaces";
private static final String NAMESPACE_PREFIXES_FEATURE_NAME = "http://xml.org/sax/features/namespace-prefixes";
private static final String IS_STANDALONE_FEATURE_NAME = "http://xml.org/sax/features/is-standalone";
private boolean namespacesFeature = true;
private boolean namespacePrefixesFeature = false;
@Nullable
private Boolean isStandalone;
private final Map<String, String> namespaces = new LinkedHashMap<>();
@Override
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
return switch (name) {
case NAMESPACES_FEATURE_NAME -> this.namespacesFeature;
case NAMESPACE_PREFIXES_FEATURE_NAME -> this.namespacePrefixesFeature;
case IS_STANDALONE_FEATURE_NAME -> {
if (this.isStandalone != null) {
yield this.isStandalone;
}
else {
throw new SAXNotSupportedException("startDocument() callback not completed yet");
}
}
default -> super.getFeature(name);
};
}
@Override
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
if (NAMESPACES_FEATURE_NAME.equals(name)) {
this.namespacesFeature = value;
}
else if (NAMESPACE_PREFIXES_FEATURE_NAME.equals(name)) {
this.namespacePrefixesFeature = value;
}
else {
super.setFeature(name, value);
}
}
protected void setStandalone(boolean standalone) {
this.isStandalone = standalone;
}
/**
* Indicates whether the SAX feature {@code http://xml.org/sax/features/namespaces} is turned on.
*/
protected boolean hasNamespacesFeature() {
return this.namespacesFeature;
}
/**
* Indicates whether the SAX feature {@code http://xml.org/sax/features/namespaces-prefixes} is turned on.
*/
protected boolean hasNamespacePrefixesFeature() {
return this.namespacePrefixesFeature;
}
/**
* Convert a {@code QName} to a qualified name, as used by DOM and SAX.
* The returned string has a format of {@code prefix:localName} if the
* prefix is set, or just {@code localName} if not.
* @param qName the {@code QName}
* @return the qualified name
*/
protected String toQualifiedName(QName qName) {
String prefix = qName.getPrefix();
if (!StringUtils.hasLength(prefix)) {
return qName.getLocalPart();
}
else {
return prefix + ":" + qName.getLocalPart();
}
}
/**
* Parse the StAX XML reader passed at construction-time.
* <p><b>NOTE:</b>: The given {@code InputSource} is not read, but ignored.
* @param ignored is ignored
* @throws SAXException a SAX exception, possibly wrapping a {@code XMLStreamException}
*/
@Override
public final void parse(InputSource ignored) throws SAXException {
parse();
}
/**
* Parse the StAX XML reader passed at construction-time.
* <p><b>NOTE:</b>: The given system identifier is not read, but ignored.
* @param ignored is ignored
* @throws SAXException a SAX exception, possibly wrapping a {@code XMLStreamException}
*/
@Override
public final void parse(String ignored) throws SAXException {
parse();
}
private void parse() throws SAXException {
try {
parseInternal();
}
catch (XMLStreamException ex) {
Locator locator = null;
if (ex.getLocation() != null) {
locator = new StaxLocator(ex.getLocation());
}
SAXParseException saxException = new SAXParseException(ex.getMessage(), locator, ex);
if (getErrorHandler() != null) {
getErrorHandler().fatalError(saxException);
}
else {
throw saxException;
}
}
}
/**
* Template method that parses the StAX reader passed at construction-time.
*/
protected abstract void parseInternal() throws SAXException, XMLStreamException;
/**
* Start the prefix mapping for the given prefix.
* @see org.xml.sax.ContentHandler#startPrefixMapping(String, String)
*/
protected void startPrefixMapping(@Nullable String prefix, String namespace) throws SAXException {
if (getContentHandler() != null && StringUtils.hasLength(namespace)) {
if (prefix == null) {
prefix = "";
}
if (!namespace.equals(this.namespaces.get(prefix))) {
getContentHandler().startPrefixMapping(prefix, namespace);
this.namespaces.put(prefix, namespace);
}
}
}
/**
* End the prefix mapping for the given prefix.
* @see org.xml.sax.ContentHandler#endPrefixMapping(String)
*/
protected void endPrefixMapping(String prefix) throws SAXException {
if (getContentHandler() != null && this.namespaces.containsKey(prefix)) {
getContentHandler().endPrefixMapping(prefix);
this.namespaces.remove(prefix);
}
}
/**
* Implementation of the {@code Locator} interface based on a given StAX {@code Location}.
* @see Locator
* @see Location
*/
private static class StaxLocator implements Locator {
private final Location location;
public StaxLocator(Location location) {
this.location = location;
}
@Override
public String getPublicId() {
return this.location.getPublicId();
}
@Override
public String getSystemId() {
return this.location.getSystemId();
}
@Override
public int getLineNumber() {
return this.location.getLineNumber();
}
@Override
public int getColumnNumber() {
return this.location.getColumnNumber();
}
}
}
|
package com.company;
import java.awt.*;
class Random {
static int interval(int min, int max) {
max -= min;
return (int) (Math.random() * ++ max) + min;
}
static void drawAmountFlowers(Graphics2D gr, int amountFlowers) {
for (int i = 0; i < amountFlowers; i++) {
int x = Random.interval(0, 2000);
int y = Random.interval(500 , 800);
Flower flower = new Flower(x, y);
flower.draw(gr);
}
}
static void drawAmountTree(Graphics2D gr, int amountTree) {
for (int i = 0; i < amountTree; i++) {
int x = Random.interval(0, 1010);
int y = Random.interval(100 , 800);
Tree tree = new Tree(x, y);
tree.draw(gr);
}
}
static void drawAmountAlien(Graphics2D gr, int amountAlien) {
for (int i = 0; i < amountAlien; i++) {
int x = Random.interval(0, 300);
int y = Random.interval(200 , 400);
Alien alien = new Alien(x, y);
alien.draw(gr);
}
}
}
|
package com.antonybaasan.justraduire.web.rest;
import com.antonybaasan.justraduire.JustraduireApp;
import com.antonybaasan.justraduire.domain.Talk;
import com.antonybaasan.justraduire.repository.TalkRepository;
import com.antonybaasan.justraduire.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static com.antonybaasan.justraduire.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.antonybaasan.justraduire.domain.enumeration.Language;
import com.antonybaasan.justraduire.domain.enumeration.Language;
/**
* Test class for the TalkResource REST controller.
*
* @see TalkResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JustraduireApp.class)
public class TalkResourceIntTest {
private static final String DEFAULT_SOURCE_TEXT = "AAAAAAAAAA";
private static final String UPDATED_SOURCE_TEXT = "BBBBBBBBBB";
private static final String DEFAULT_TARGET_TEXT = "AAAAAAAAAA";
private static final String UPDATED_TARGET_TEXT = "BBBBBBBBBB";
private static final Language DEFAULT_SOURCE_LANGUAGE = Language.FRENCH;
private static final Language UPDATED_SOURCE_LANGUAGE = Language.ENGLISH;
private static final Language DEFAULT_TARGET_LANGUAGE = Language.FRENCH;
private static final Language UPDATED_TARGET_LANGUAGE = Language.ENGLISH;
private static final LocalDate DEFAULT_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATE = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_SERVER_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_SERVER_DATE = LocalDate.now(ZoneId.systemDefault());
@Autowired
private TalkRepository talkRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restTalkMockMvc;
private Talk talk;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final TalkResource talkResource = new TalkResource(talkRepository);
this.restTalkMockMvc = MockMvcBuilders.standaloneSetup(talkResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Talk createEntity(EntityManager em) {
Talk talk = new Talk()
.sourceText(DEFAULT_SOURCE_TEXT)
.targetText(DEFAULT_TARGET_TEXT)
.sourceLanguage(DEFAULT_SOURCE_LANGUAGE)
.targetLanguage(DEFAULT_TARGET_LANGUAGE)
.date(DEFAULT_DATE)
.serverDate(DEFAULT_SERVER_DATE);
return talk;
}
@Before
public void initTest() {
talk = createEntity(em);
}
@Test
@Transactional
public void createTalk() throws Exception {
int databaseSizeBeforeCreate = talkRepository.findAll().size();
// Create the Talk
restTalkMockMvc.perform(post("/api/talks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(talk)))
.andExpect(status().isCreated());
// Validate the Talk in the database
List<Talk> talkList = talkRepository.findAll();
assertThat(talkList).hasSize(databaseSizeBeforeCreate + 1);
Talk testTalk = talkList.get(talkList.size() - 1);
assertThat(testTalk.getSourceText()).isEqualTo(DEFAULT_SOURCE_TEXT);
assertThat(testTalk.getTargetText()).isEqualTo(DEFAULT_TARGET_TEXT);
assertThat(testTalk.getSourceLanguage()).isEqualTo(DEFAULT_SOURCE_LANGUAGE);
assertThat(testTalk.getTargetLanguage()).isEqualTo(DEFAULT_TARGET_LANGUAGE);
assertThat(testTalk.getDate()).isEqualTo(DEFAULT_DATE);
assertThat(testTalk.getServerDate()).isEqualTo(DEFAULT_SERVER_DATE);
}
@Test
@Transactional
public void createTalkWithExistingId() throws Exception {
int databaseSizeBeforeCreate = talkRepository.findAll().size();
// Create the Talk with an existing ID
talk.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restTalkMockMvc.perform(post("/api/talks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(talk)))
.andExpect(status().isBadRequest());
// Validate the Talk in the database
List<Talk> talkList = talkRepository.findAll();
assertThat(talkList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllTalks() throws Exception {
// Initialize the database
talkRepository.saveAndFlush(talk);
// Get all the talkList
restTalkMockMvc.perform(get("/api/talks?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(talk.getId().intValue())))
.andExpect(jsonPath("$.[*].sourceText").value(hasItem(DEFAULT_SOURCE_TEXT.toString())))
.andExpect(jsonPath("$.[*].targetText").value(hasItem(DEFAULT_TARGET_TEXT.toString())))
.andExpect(jsonPath("$.[*].sourceLanguage").value(hasItem(DEFAULT_SOURCE_LANGUAGE.toString())))
.andExpect(jsonPath("$.[*].targetLanguage").value(hasItem(DEFAULT_TARGET_LANGUAGE.toString())))
.andExpect(jsonPath("$.[*].date").value(hasItem(DEFAULT_DATE.toString())))
.andExpect(jsonPath("$.[*].serverDate").value(hasItem(DEFAULT_SERVER_DATE.toString())));
}
@Test
@Transactional
public void getTalk() throws Exception {
// Initialize the database
talkRepository.saveAndFlush(talk);
// Get the talk
restTalkMockMvc.perform(get("/api/talks/{id}", talk.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(talk.getId().intValue()))
.andExpect(jsonPath("$.sourceText").value(DEFAULT_SOURCE_TEXT.toString()))
.andExpect(jsonPath("$.targetText").value(DEFAULT_TARGET_TEXT.toString()))
.andExpect(jsonPath("$.sourceLanguage").value(DEFAULT_SOURCE_LANGUAGE.toString()))
.andExpect(jsonPath("$.targetLanguage").value(DEFAULT_TARGET_LANGUAGE.toString()))
.andExpect(jsonPath("$.date").value(DEFAULT_DATE.toString()))
.andExpect(jsonPath("$.serverDate").value(DEFAULT_SERVER_DATE.toString()));
}
@Test
@Transactional
public void getNonExistingTalk() throws Exception {
// Get the talk
restTalkMockMvc.perform(get("/api/talks/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTalk() throws Exception {
// Initialize the database
talkRepository.saveAndFlush(talk);
int databaseSizeBeforeUpdate = talkRepository.findAll().size();
// Update the talk
Talk updatedTalk = talkRepository.findOne(talk.getId());
// Disconnect from session so that the updates on updatedTalk are not directly saved in db
em.detach(updatedTalk);
updatedTalk
.sourceText(UPDATED_SOURCE_TEXT)
.targetText(UPDATED_TARGET_TEXT)
.sourceLanguage(UPDATED_SOURCE_LANGUAGE)
.targetLanguage(UPDATED_TARGET_LANGUAGE)
.date(UPDATED_DATE)
.serverDate(UPDATED_SERVER_DATE);
restTalkMockMvc.perform(put("/api/talks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedTalk)))
.andExpect(status().isOk());
// Validate the Talk in the database
List<Talk> talkList = talkRepository.findAll();
assertThat(talkList).hasSize(databaseSizeBeforeUpdate);
Talk testTalk = talkList.get(talkList.size() - 1);
assertThat(testTalk.getSourceText()).isEqualTo(UPDATED_SOURCE_TEXT);
assertThat(testTalk.getTargetText()).isEqualTo(UPDATED_TARGET_TEXT);
assertThat(testTalk.getSourceLanguage()).isEqualTo(UPDATED_SOURCE_LANGUAGE);
assertThat(testTalk.getTargetLanguage()).isEqualTo(UPDATED_TARGET_LANGUAGE);
assertThat(testTalk.getDate()).isEqualTo(UPDATED_DATE);
assertThat(testTalk.getServerDate()).isEqualTo(UPDATED_SERVER_DATE);
}
@Test
@Transactional
public void updateNonExistingTalk() throws Exception {
int databaseSizeBeforeUpdate = talkRepository.findAll().size();
// Create the Talk
// If the entity doesn't have an ID, it will be created instead of just being updated
restTalkMockMvc.perform(put("/api/talks")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(talk)))
.andExpect(status().isCreated());
// Validate the Talk in the database
List<Talk> talkList = talkRepository.findAll();
assertThat(talkList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteTalk() throws Exception {
// Initialize the database
talkRepository.saveAndFlush(talk);
int databaseSizeBeforeDelete = talkRepository.findAll().size();
// Get the talk
restTalkMockMvc.perform(delete("/api/talks/{id}", talk.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Talk> talkList = talkRepository.findAll();
assertThat(talkList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Talk.class);
Talk talk1 = new Talk();
talk1.setId(1L);
Talk talk2 = new Talk();
talk2.setId(talk1.getId());
assertThat(talk1).isEqualTo(talk2);
talk2.setId(2L);
assertThat(talk1).isNotEqualTo(talk2);
talk1.setId(null);
assertThat(talk1).isNotEqualTo(talk2);
}
}
|
package com.zhuhao.hcharts.views;
import android.graphics.Canvas;
import java.util.ArrayList;
/**
* Author : zhuhao
* Date : 26/9/2017
*
* @Last Modified Time :26/9/2017
* Description :
*/
public class BrokenLineChart implements BaseView {
@Override
public void initCommons() {
}
@Override
public void initRegion(int position) {
}
@Override
public int getTouchedPath(int x, int y) {
return 0;
}
@Override
public void setData(ArrayList data) {
}
@Override
public void startAnimator() {
}
@Override
public void onClickAnimator(Canvas canvas, int position) {
}
}
|
package com.nepc.asset.manager.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.math.BigInteger;
import java.util.List;
@Entity
@Table(name = "LIQUIDITY")
@EqualsAndHashCode(callSuper = false)
@ToString
public class Liquidity
{
@Setter
@Getter
@Id
@Column(name = "LIQUIDITY_PK", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger id;
@Setter
@Getter
@Column(name = "Liquidity_Name", length = 250)
private String liquidityName;
@Setter
@Getter
@OneToMany(fetch = FetchType.LAZY, mappedBy = "liquidity")
private List<AssetAllocationModelingBenchMark> assetAllocationModelingBenchMarks;
@Setter
@Getter
@OneToMany(fetch = FetchType.LAZY, mappedBy = "liquidity")
private List<InvestmentStructureComponent> investmentStructureComponents;
}
|
package com.v1_4.mydiaryapp.com;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Adapter_List_Menu_Style_1 extends ArrayAdapter<Obj_Screen> {
int resource;
public Adapter_List_Menu_Style_1(Context _context, int _resource, List<Obj_Screen> _items) {
super(_context, _resource, _items);
resource = _resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout itemView;
Obj_Screen item = getItem(position);
String iconFileName = item.getMenuIcon();
String titleString = item.getMenuText();
Bitmap imgMenuIcon = item.getImgMenuIcon();
int showAsSelected = item.getShowAsSelected();
if (convertView == null) {
itemView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, itemView, true);
} else {
itemView = (LinearLayout) convertView;
}
//icon (defaults to blank.png in xml layout)
ImageView iconView = (ImageView)itemView.findViewById(R.id.imgIcon);
if(imgMenuIcon != null){
iconView.setImageBitmap(imgMenuIcon);
}
//text view
TextView titleView = (TextView)itemView.findViewById(R.id.txtTitle);
titleView.setText(titleString);
//chevron (defaults to blank.png in xml layout unless we have a title)
ImageView chevronView = (ImageView)itemView.findViewById(R.id.imgChevron);
if(titleString.length() > 1){
if(showAsSelected == 1){
chevronView.setImageResource(R.drawable.chevron_1_red);
}else{
chevronView.setImageResource(R.drawable.chevron_1);
}
}
return itemView;
}
}
|
package us.alexl.jsouptest;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class JSoupTest {
/**
* The default behavior is to use the Certificate Authorities that come with your Java installation.
* The fact that everything works out of the box means that the remote host is using a certificate
* signed by a certificate authority (is not self-signed).
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String url = "https://quotes.wsj.com/GOOG/financials/annual/cash-flow";
Document doc = Jsoup.connect(url).get();
// <span id="ms_quote_val">1,121.30</span>
// https://jsoup.org/cookbook/extracting-data/selector-syntax
Element quoteElem = doc.select("span[id=quote_val]").first();
String quote = quoteElem.text();
System.out.println(quote);
}
}
|
package com.example.studentmanagment;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateAcademicDetailsActivity extends Activity implements
OnClickListener {
Button b1, b2;
EditText t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15,
t16, t17, t18, t19, t20, t21, t22, t23, t24, t25, t26, t27, t28,
t29, t30, t31, t32, t33, t34, t35, t36, t37, t38, t39, t40, t41;
String collegeId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_academic_details);
t1 = (EditText) findViewById(R.id.editText1);
t2 = (EditText) findViewById(R.id.editText2);
t3 = (EditText) findViewById(R.id.editText3);
t4 = (EditText) findViewById(R.id.editText4);
t5 = (EditText) findViewById(R.id.editText5);
t6 = (EditText) findViewById(R.id.editText6);
t7 = (EditText) findViewById(R.id.editText7);
t8 = (EditText) findViewById(R.id.editText8);
t9 = (EditText) findViewById(R.id.editText9);
t10 = (EditText) findViewById(R.id.editText10);
t11 = (EditText) findViewById(R.id.editText11);
t12 = (EditText) findViewById(R.id.editText12);
t13 = (EditText) findViewById(R.id.editText13);
t14 = (EditText) findViewById(R.id.editText14);
t15 = (EditText) findViewById(R.id.editText15);
t16 = (EditText) findViewById(R.id.editText16);
t17 = (EditText) findViewById(R.id.editText17);
t18 = (EditText) findViewById(R.id.editText18);
t19 = (EditText) findViewById(R.id.editText19);
t20 = (EditText) findViewById(R.id.editText20);
t21 = (EditText) findViewById(R.id.editText21);
t22 = (EditText) findViewById(R.id.editText22);
t23 = (EditText) findViewById(R.id.editText23);
t24 = (EditText) findViewById(R.id.editText24);
t25 = (EditText) findViewById(R.id.editText25);
t26 = (EditText) findViewById(R.id.editText26);
t27 = (EditText) findViewById(R.id.editText27);
t28 = (EditText) findViewById(R.id.editText28);
t29 = (EditText) findViewById(R.id.editText29);
t30 = (EditText) findViewById(R.id.editText30);
t31 = (EditText) findViewById(R.id.editText31);
t32 = (EditText) findViewById(R.id.editText32);
t33 = (EditText) findViewById(R.id.editText33);
t34 = (EditText) findViewById(R.id.editText34);
t35 = (EditText) findViewById(R.id.editText35);
t36 = (EditText) findViewById(R.id.editText36);
t37 = (EditText) findViewById(R.id.editText37);
t38 = (EditText) findViewById(R.id.editText38);
t39 = (EditText) findViewById(R.id.editText39);
t40 = (EditText) findViewById(R.id.editText40);
t41 = (EditText) findViewById(R.id.editText41);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.update_academic_details, menu);
return true;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.button2:
collegeId = t41.getText().toString();
DataBaseHelper dh1 = new DataBaseHelper(getApplicationContext());
SQLiteDatabase db1 = dh1.getReadableDatabase();
String q = "select qualification , year , percentage, board from ten1 where collegeId=?";
Cursor c = db1.rawQuery(q, new String[] { collegeId });
if (c.moveToFirst()) {
t1.setText(c.getString(0));
t2.setText(c.getString(1));
t3.setText(c.getString(2));
t4.setText(c.getString(3));
}
String q2 = "select qualification , year , percentage, board from twelf1 where collegeId=?";
Cursor c2 = db1.rawQuery(q2, new String[] { collegeId });
if (c2.moveToFirst()) {
t5.setText(c2.getString(0));
t6.setText(c2.getString(1));
t7.setText(c2.getString(2));
t8.setText(c2.getString(3));
}
String q3 = "select qualification , year , percentage, board from sem11 where collegeId=?";
Cursor c3 = db1.rawQuery(q3, new String[] { collegeId });
if (c3.moveToFirst()) {
t9.setText(c3.getString(0));
t10.setText(c3.getString(1));
t11.setText(c3.getString(2));
t12.setText(c3.getString(3));
}
String q4 = "select qualification , year , percentage, board from sem21 where collegeId=?";
Cursor c4 = db1.rawQuery(q4, new String[] { collegeId });
if (c4.moveToFirst()) {
t13.setText(c4.getString(0));
t14.setText(c4.getString(1));
t15.setText(c4.getString(2));
t16.setText(c4.getString(3));
}
String q5 = "select qualification , year , percentage, board from sem31 where collegeId=?";
Cursor c5 = db1.rawQuery(q5, new String[] { collegeId });
if (c5.moveToFirst()) {
t17.setText(c5.getString(0));
t18.setText(c5.getString(1));
t19.setText(c5.getString(2));
t20.setText(c5.getString(3));
}
String q6 = "select qualification , year , percentage, board from sem41 where collegeId=?";
Cursor c6 = db1.rawQuery(q6, new String[] { collegeId });
if (c6.moveToFirst()) {
t21.setText(c6.getString(0));
t22.setText(c6.getString(1));
t23.setText(c6.getString(2));
t24.setText(c6.getString(3));
}
String q7 = "select qualification , year , percentage, board from sem51 where collegeId=?";
Cursor c7 = db1.rawQuery(q7, new String[] { collegeId });
if (c7.moveToFirst()) {
t25.setText(c7.getString(0));
t26.setText(c7.getString(1));
t27.setText(c7.getString(2));
t28.setText(c7.getString(3));
}
String q8 = "select qualification , year , percentage, board from sem61 where collegeId=?";
Cursor c8 = db1.rawQuery(q8, new String[] { collegeId });
if (c8.moveToFirst()) {
t29.setText(c8.getString(0));
t30.setText(c8.getString(1));
t31.setText(c8.getString(2));
t32.setText(c8.getString(3));
}
String q9 = "select qualification , year , percentage, board from sem71 where collegeId=?";
Cursor c9 = db1.rawQuery(q9, new String[] { collegeId });
if (c9.moveToFirst()) {
t33.setText(c9.getString(0));
t34.setText(c9.getString(1));
t35.setText(c9.getString(2));
t36.setText(c9.getString(3));
}
String q10 = "select qualification , year , percentage, board from sem81 where collegeId=?";
Cursor c10 = db1.rawQuery(q10, new String[] { collegeId });
if (c10.moveToFirst()) {
t37.setText(c10.getString(0));
t38.setText(c10.getString(1));
t39.setText(c10.getString(2));
t40.setText(c10.getString(3));
}
break;
case R.id.button1:
DataBaseHelper dh = new DataBaseHelper(getApplicationContext());
SQLiteDatabase db = dh.getWritableDatabase();
String qualification = t1.getText().toString();
String year = t2.getText().toString();
String percentage = t3.getText().toString();
String board = t4.getText().toString();
ContentValues cv2 = new ContentValues();
cv2.put("qualification", qualification);
cv2.put("year", year);
cv2.put("percentage", percentage);
cv2.put("board", board);
cv2.put("collegeId", collegeId);
long check2 = db.update("ten1", cv2, "collegeId=?", new String[]{collegeId});
String qualification2 = t5.getText().toString();
String year2 = t6.getText().toString();
String percentage2 = t7.getText().toString();
String board2 = t8.getText().toString();
ContentValues cv3 = new ContentValues();
cv3.put("qualification", qualification2);
cv3.put("year", year2);
cv3.put("percentage", percentage2);
cv3.put("board", board2);
cv3.put("collegeId",collegeId);
long check3 = db.update("twelf1", cv3, "collegeId=?", new String[]{collegeId});
String qualification3 = t9.getText().toString();
String year3 = t10.getText().toString();
String percentage3 = t11.getText().toString();
String board3 = t12.getText().toString();
ContentValues cv4 = new ContentValues();
cv4.put("qualification", qualification3);
cv4.put("year", year3);
cv4.put("percentage", percentage3);
cv4.put("board", board3);
cv4.put("collegeId", collegeId);
long check4 = db.update("sem11", cv4, "collegeId=?", new String[]{collegeId});
String qualification4 = t13.getText().toString();
String year4 = t14.getText().toString();
String percentage4 = t15.getText().toString();
String board4 = t16.getText().toString();
ContentValues cv5 = new ContentValues();
cv5.put("qualification", qualification4);
cv5.put("year", year4);
cv5.put("percentage", percentage4);
cv5.put("board", board4);
cv5.put("collegeId", collegeId);
long check5 = db.update("sem21", cv5, "collegeId=?", new String[]{collegeId});
String qualification5 = t17.getText().toString();
String year5 = t18.getText().toString();
String percentage5 = t19.getText().toString();
String board5 = t20.getText().toString();
ContentValues cv6 = new ContentValues();
cv6.put("qualification", qualification5);
cv6.put("year", year5);
cv6.put("percentage", percentage5);
cv6.put("board", board5);
cv6.put("collegeId", collegeId);
long check6 = db.update("sem31", cv6, "collegeId=?", new String[]{collegeId});
String qualification6 = t21.getText().toString();
String year6 = t22.getText().toString();
String percentage6 = t23.getText().toString();
String board6 = t24.getText().toString();
ContentValues cv7 = new ContentValues();
cv7.put("qualification", qualification6);
cv7.put("year", year6);
cv7.put("percentage", percentage6);
cv7.put("board", board6);
cv7.put("collegeId", collegeId);
long check7 = db.update("sem41", cv7, "collegeId=?", new String[]{collegeId});
String qualification7 = t25.getText().toString();
String year7 = t26.getText().toString();
String percentage7 = t27.getText().toString();
String board7 = t28.getText().toString();
ContentValues cv8 = new ContentValues();
cv8.put("qualification", qualification7);
cv8.put("year", year7);
cv8.put("percentage", percentage7);
cv8.put("board", board7);
cv8.put("collegeId", collegeId);
long check8 =db.update("sem51", cv8, "collegeId=?", new String[]{collegeId});
String qualification8 = t29.getText().toString();
String year8 = t30.getText().toString();
String percentage8 = t31.getText().toString();
String board8 = t32.getText().toString();
ContentValues cv9 = new ContentValues();
cv9.put("qualification", qualification8);
cv9.put("year", year8);
cv9.put("percentage", percentage8);
cv9.put("board", board8);
cv9.put("collegeId", collegeId);
long check9 = db.update("sem61", cv9, "collegeId=?", new String[]{collegeId});
String qualification9 = t33.getText().toString();
String year9 = t34.getText().toString();
String percentage9 = t35.getText().toString();
String board9 = t36.getText().toString();
ContentValues cv10 = new ContentValues();
cv10.put("qualification", qualification9);
cv10.put("year", year9);
cv10.put("percentage", percentage9);
cv10.put("board", board9);
cv10.put("collegeId", collegeId);
long check10 = db.update("sem71", cv10, "collegeId=?", new String[]{collegeId});
String qualification10 = t37.getText().toString();
String year10 = t38.getText().toString();
String percentage10 = t39.getText().toString();
String board10 = t40.getText().toString();
ContentValues cv11 = new ContentValues();
cv11.put("qualification", qualification10);
cv11.put("year", year10);
cv11.put("percentage", percentage10);
cv11.put("board", board10);
cv11.put("collegeId", collegeId);
long check11 = db.update("sem81", cv11, "collegeId=?", new String[]{collegeId});
if ( check2 > 0 && check3 > 0 && check4 > 0 && check5 > 0 && check6 > 0 && check7 > 0 && check8 > 0 && check9 > 0 && check10 > 0 && check11 > 0) {
Toast.makeText(this, "Record Successfully Updated", 2000)
.show();
Intent i=new Intent(UpdateAcademicDetailsActivity.this,AdminHomePageActivity.class);
startActivity(i);
} else {
Toast.makeText(this, "Record Successfully Not Updated", 2000)
.show();
}
break;
default:
break;
}
}
}
|
package verwalteStudent;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import source.studenten.VerwalteStudent;
import exceptions.FalscherEintragException;
/**
* Tests der Methode pruefeAdresseAufGueltigkeit der Klasse VerwalteStudent
*
*
* @author Timea Magyar
*
*/
@RunWith(Parameterized.class)
public class PruefeAdresse
{
static String adresse;
static VerwalteStudent gueltigerStudent = new VerwalteStudent();
static String kompletteAdresseFalsch;
static String kompletteAdresseKorrekt;
/**
* Konstruktor der Testklasse.
* <p>
* Wird für die Speicherung der Werte der in {@link #generiereDaten}
* erzeugten Parameterliste benötigt.
* <p>
* Die unten genannte Parameterliste besteht aus einem Array Collection. Die
* Anzahl der Klassenattribute (adresse) muss der Anzahl der Elemente in
* jedem einzelnen Array entsprechen.
* <p>
*/
public PruefeAdresse(String testParameter)
{
PruefeAdresse.adresse = testParameter;
}
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Definiert mögliche falschen Eingaben.
* <p>
* Falsche Eingaben werden in der Testmethode
* {@link #testPruefeAdresseAufUngueltig} automatisch nacheinander als
* Testparameter übergeben und geprüft. Somit kann man mehrere falschen
* Eingabenkonstellationen in einer einzigen Testmethode nacheinander auf
* ein Exception prüfen.
* <p>
* Durch Parameterliste wird sowohl die Reihenfolge der Adresskomponenten,
* die Struktur der Eingabe, dass alle Adresskomponenten eingetragen wurden
* als auch der Fall, dass die jeweilige Adresskomponente ungültige Zeichen
* enthält geprüft.
*
* @return adressDaten
*
*/
@Parameters
public static Collection<Object[]> generiereDaten()
{
Object[][] adressDaten = new Object[][] { { "34 70193 Stuttgart" },
{ "Markelstr. 70193 Stuttgart" },
{ "Markelstr. 34 Stuttgart" }, { "Markelstr. 34 70193" },
{ "70193 Markelstr. Stuttgart 34" },
{ "34 70193 Stuttgart Markelstr." },
{ "34 70193Stuttgart Markelstr." },
{ "34 70193Stuttgart Markelstr." } };
return Arrays.asList(adressDaten);
}
/**
* Die jeweiligen Arrayelemente der in {@link #generiereDaten} definierten
* Parameterliste werden nacheinander zum Testen über das Klassenattribut
* adresse übergeben.
* <p>
* Dieser enthält den jeweiligen Parameterwert pro Testdurchlauf.
*
* @throws FalscherEintragException
* @throws ParseException
*
*/
@Test
public void testPruefeAdresseAufUngueltig()
throws FalscherEintragException, ParseException
{
kompletteAdresseFalsch = adresse;
thrown.expect(FalscherEintragException.class);
gueltigerStudent.pruefeAdresseAufGueltigkeit(kompletteAdresseFalsch);
}
/**
* Zeigt, dass eine richtige Adresseingabe auch als solche akzeptiert wird.
* Hinweis: dieser Test wird nach jedem parametrisierten Test einmal
* ausgeführt, daher liegt die Anzahl der Tests insgesamt bei 16.
*
* @throws FalscherEintragException
*/
@Test
public void testPruefeAdresseAufGueltig() throws FalscherEintragException
{
kompletteAdresseKorrekt = "Markelstr. 34 70193 Stuttgart";
assertTrue(gueltigerStudent
.pruefeAdresseAufGueltigkeit(kompletteAdresseKorrekt));
}
}
|
package ru.kurtov.jgrep;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class JGrepMappedByteBuffer extends JGrep {
private final static Charset charset = Charset.forName("UTF-8"); //"ISO-8859-15"
private final static CharsetDecoder decoder = charset.newDecoder();
public JGrepMappedByteBuffer(String pattern) {
super(pattern);
}
public JGrepMappedByteBuffer(String pattern, int SearcherType) {
super(pattern, SearcherType);
}
@Override
public void find() throws IOException {
for(String fileName : this.fileNames) {
File f = new File(fileName);
// Open the file and then get a channel from the stream
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
// Get the file's size and then map it into memory
int sz = (int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
// Decode the file into a char buffer
CharBuffer cb = decoder.decode(bb);
// Perform the search
searcher.search(cb.array());
// Close the channel and the stream
fc.close();
printResult(f, searcher.terminate());
searcher.reset();
}
}
}
|
package slimeknights.tconstruct.library.book.content;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import slimeknights.mantle.util.ItemStackList;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.materials.Material;
import slimeknights.tconstruct.library.modifiers.IModifier;
import slimeknights.tconstruct.tools.TinkerTools;
@SideOnly(Side.CLIENT)
public class ContentModifierFortify extends ContentModifier {
public static final transient String ID = "modifier_fortify";
public ContentModifierFortify() {
}
public ContentModifierFortify(IModifier modifier) {
super(modifier);
}
@Override
protected ItemStackList getDemoTools(ItemStack[][] inputItems) {
if(inputItems.length == 0) {
return ItemStackList.create();
}
ItemStackList demo = super.getDemoTools(inputItems);
ItemStackList out = ItemStackList.create();
for(int i = 0; i < inputItems[0].length; i++) {
if(inputItems[0][i].getItem() == TinkerTools.sharpeningKit) {
Material material = TinkerTools.sharpeningKit.getMaterial(inputItems[0][i]);
IModifier modifier = TinkerRegistry.getModifier("fortify" + material.getIdentifier());
if(modifier != null) {
ItemStack stack = demo.get(i % demo.size()).copy();
modifier.apply(stack);
out.add(stack);
}
}
}
return out;
}
}
|
package com.dbsys.rs.controller;
import java.util.List;
import javax.persistence.PersistenceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dbsys.rs.lib.ApplicationException;
import com.dbsys.rs.lib.EntityRestMessage;
import com.dbsys.rs.lib.ListEntityRestMessage;
import com.dbsys.rs.lib.entity.Dokter;
import com.dbsys.rs.lib.entity.Pegawai;
import com.dbsys.rs.service.PegawaiService;
@Controller
@RequestMapping("/dokter")
public class DokterController {
@Autowired
private PegawaiService pegawaiService;
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public EntityRestMessage<Pegawai> save(@RequestBody Dokter dokter) throws ApplicationException, PersistenceException {
dokter = (Dokter)pegawaiService.save(dokter);
return EntityRestMessage.createPegawai(dokter);
}
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public ListEntityRestMessage<Dokter> getAll() throws ApplicationException, PersistenceException {
List<Dokter> list = pegawaiService.getDokter();
return ListEntityRestMessage.createListDokter(list);
}
}
|
package online.lahloba.www.lahloba.ui.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.LifecycleOwner;
import com.google.firebase.auth.FirebaseAuth;
import online.lahloba.www.lahloba.databinding.FragmentPointsBinding;
import online.lahloba.www.lahloba.ui.login.LoginViewModel;
public class PointsFragment extends DialogFragment {
LoginViewModel loginViewModel;
private FragmentPointsBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentPointsBinding.inflate(inflater,container, false);
loginViewModel.startGetUserDetails(FirebaseAuth.getInstance().getUid());
return binding.getRoot();
}
@Override
public void onResume() {
super.onResume();
loginViewModel.getCurrentUserDetails().observe((LifecycleOwner) getContext(), userItem -> {
if (userItem == null)return;
binding.setPoint(userItem.getPoints()+"");
});
}
public void setLoginViewModel(LoginViewModel loginViewModel) {
this.loginViewModel = loginViewModel;
}
}
|
import java.util.List;
public class Titulo {
//atributos
String titulo;
String edicion;
String ISBN
List<Autor> autores;
List<Categoria> categorias;
//METODO CONSTRUCTOR por defecto
public Titulo(){
}
}
|
public abstract class Piece implements Runnable {
//Properties
public String strName;
public String strColour;
public boolean blnNotMoved = true;
public boolean blnCanMove = true;
public int intCount;
//Methods
public abstract int[][] checkMove(int intX, int intY, Piece[][] object);
public void run(){
blnCanMove = false;
intCount = 0;
while(true){
pause();
intCount++;
if(intCount >= 10*1000/60){
break;
}
}
intCount = 0;
blnCanMove = true;
}
public void pause(){
try{
Thread.sleep(1000/60);
}catch(InterruptedException e){
}
}
//Constructor
public Piece(String strC){
this.strColour = strC;
}
}
|
package com.qumla.service.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import io.katharsis.queryParams.QueryParams;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.springframework.util.Assert;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qumla.domain.answer.Answer;
import com.qumla.domain.answer.AnswerStat;
import com.qumla.domain.answer.AnswerStatLocation;
import com.qumla.domain.answer.AnswerStatOption;
import com.qumla.domain.answer.LocationResult;
import com.qumla.domain.location.Country;
import com.qumla.domain.location.Location;
import com.qumla.domain.location.LocationData;
import com.qumla.domain.question.Question;
import com.qumla.domain.question.QuestionFilter;
import com.qumla.domain.user.Session;
import com.qumla.service.impl.AnswerDaoMapper;
import com.qumla.service.impl.AnswerServiceImpl;
import com.qumla.service.impl.AnswerStatServiceImpl;
import com.qumla.service.impl.QuestionDaoMapper;
import com.qumla.service.impl.QuestionServiceImpl;
import com.qumla.web.controller.RequestWrapper;
public class AnswerDaoTest extends QuestionDaoTest {
public void before() {
super.before(AnswerDaoMapper.class);
}
@Test
public void testAnswerInsert() throws Exception {
AnswerServiceImpl asimpl=new AnswerServiceImpl();
asimpl.setAnswerServiceMapper((AnswerDaoMapper)getMapper(AnswerDaoMapper.class));
QuestionServiceImpl qsi=new QuestionServiceImpl();
qsi.setQuestionServiceMapper((QuestionDaoMapper)getMapper(QuestionDaoMapper.class));
asimpl.setQuestionServiceImpl(qsi);
AnswerStatServiceImpl anwerSerImpl=new AnswerStatServiceImpl();
anwerSerImpl.setAnswerServiceMapper((AnswerDaoMapper)getMapper(AnswerDaoMapper.class));
QuestionServiceImpl questionService=createQuestionService();
Question q=createQuestion(questionService);
Answer a=new Answer();
a.setCreateDt(new Date());
Session s=new Session();
s.setCode("testtoken");
s.setLocation(11L);
s.setCountry("HU");
a.setSession(s.getCode());
a.setOption(q.getOptions().get(0).getId());
a.setQuestion(q.getId());
RequestWrapper.setSession(s);
asimpl.save(a);
Answer a1=asimpl.findOne(a.getId(),new QueryParams());
assertNotNull(a1);
assertNotNull(a1.getOption());
assertNotNull(a1.getCreateDt());
a1.setCountry("HU");
try{
asimpl.save(a1);
}catch(Exception e){
assertNotNull(e);
}
ObjectMapper om=new ObjectMapper();
List<AnswerStat> result=anwerSerImpl.findByQuestion(q.getId());
assertNotNull(result);
assertTrue(result.size()>0);
}
@Test
public void testAnswerStatInsert() throws Exception {
AnswerDaoMapper mapper=(AnswerDaoMapper)getMapper(AnswerDaoMapper.class);
QuestionServiceImpl questionService=createQuestionService();
Session s=new Session();
s.setCode("testtoken");
s.setCountry("HU");
RequestWrapper.setSession(s);
Question q=createQuestion(questionService);
Country c=new Country();
c.setCode("HU");
AnswerStat a=new AnswerStat();
a.setCountry(c);
LocationData l = new LocationData();
l.setId(new Long(11)); // Budapest
a.setLocation(l);
a.setAnswerdate(LocalDate.now());
a.setHour((byte)10);
a.setOption(q.getOptions().get(0));
mapper.saveAnswerStat(a);
AnswerStat a1=mapper.findOneAnswerStat(a.getId());
assertNotNull(a1);
assertNotNull(a1.getId());
assertNotNull(a1.getOption().getId());
assertNotNull(a1.getQuestion().getId());
assertNotNull(a1.getLocation().getId());
assertNotNull(a1.getCountry().getCode());
assertNotNull(a1.getCountry().getCountryName());
assertNotNull(a1.getCount());
assertNotNull(a1.getHour());
assertNotNull(a1.getAnswerdate());
a1.setCount(20);
mapper.updateAnswerStatById(a1);
AnswerStat a3=mapper.findOneAnswerStat(a1.getId());
assertEquals(a3.getCount(), 20);
// AnswerStat a4=mapper.findAnswerStatQuestion(a1.getQuestion().getId());
// assertNotNull(a4);
// assertEquals(a3.getQuestion().getId(),a4.getQuestion().getId());
// assertEquals(10,a4.getHour());
}
@Test
public void testAnswerStatOptionLocationFind() throws Exception {
AnswerDaoMapper mapper=(AnswerDaoMapper)getMapper(AnswerDaoMapper.class);
List<AnswerStatLocation> location=mapper.findAnswerStatLocationForQuestion(950L);
Assert.isTrue(location.size()>0);
Assert.isTrue(location.get(0).getCountry()!=null);
Assert.isTrue(location.get(0).getLocation()!=null);
Assert.isTrue(location.get(0).getCount()>0);
Assert.isTrue(location.get(0).getOption()!=null);
List<AnswerStatOption> options=mapper.findAnswerStatOptionForQuestion(950L);
Assert.isTrue(options.size()>0);
Assert.isTrue(options.get(0).getOption()!=null);
}
@Test
public void testLocationResult() throws Exception {
AnswerDaoMapper mapper=(AnswerDaoMapper)getMapper(AnswerDaoMapper.class);
List<LocationResult> locationResult=(List<LocationResult>)mapper.locationResult(950L, "HU");
Assert.isTrue(locationResult.size()>0);
}
public void createAnswerStat() throws Exception {
beforeClass();
before();
QuestionDaoMapper question=(QuestionDaoMapper)getMapper(QuestionDaoMapper.class);
AnswerDaoMapper mapper=(AnswerDaoMapper)getMapper(AnswerDaoMapper.class);
AnswerServiceImpl answerService=new AnswerServiceImpl();
answerService.setAnswerServiceMapper(mapper);
QuestionFilter filter=new QuestionFilter(RequestWrapper.getSession().getCountry());
filter.setSession("aaaa");
filter.setId(951L);
filter.setOffset(0);
filter.setLimit(100);
List<Question> questions=question.findPopularQuestion(filter);
for (Question question2 : questions) {
answerService.resetStatForQuestion(question2.getId());
List<Answer> answers= answerService.findAnswerForQuestion(question2.getId());
for (Answer answer : answers) {
if(answer.getLocation()!=null){
answerService.updateAnswerStat(answer);
}
}
for (SqlSession sqlsession : sessions) {
sqlsession.commit();
}
}
}
public static final void main(String args[]) throws Exception{
System.out.println();
AnswerDaoTest t=new AnswerDaoTest();
t.createAnswerStat();
}
}
|
package com.xianzaishi.wms.tmscore.dao.itf;
import com.xianzaishi.wms.common.dao.itf.IBaseDao;
public interface IDistributionDao extends IBaseDao {
public Boolean reset(Long id);
}
|
// Copyright (c) Philipp Wagner. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package de.bytefish.sqlmapper.test;
import de.bytefish.sqlmapper.ResultSetMapping;
import de.bytefish.sqlmapper.SqlMapper;
import de.bytefish.sqlmapper.result.SqlMappingResult;
import org.junit.Assert;
import org.junit.Test;
import java.sql.*;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamingMapperTest extends TransactionalTestBase {
private class Person {
private String firstName;
private String lastName;
private LocalDate birthDate;
public Person() {}
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 LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
}
public class PersonMap extends ResultSetMapping<Person>
{
public PersonMap() {
map("first_name", String.class, Person::setFirstName);
map("last_name", String.class, Person::setLastName);
map("birth_date", LocalDate.class, Person::setBirthDate);
}
}
@Override
protected void onSetUpInTransaction() throws Exception {
createTable();
}
@Test
public void testToEntity() throws Exception {
SqlMapper<Person> sqlMapper = new SqlMapper<>(() -> new Person(), new PersonMap());
insert(1);
ResultSet resultSet = selectAll();
while (resultSet.next() ) {
SqlMappingResult<Person> person = sqlMapper.toEntity(resultSet);
Assert.assertEquals(true, person.isValid());
Assert.assertEquals("Philipp", person.getResult().getFirstName());
Assert.assertEquals("Wagner", person.getResult().getLastName());
Assert.assertEquals(LocalDate.of(1986, 5, 12), person.getResult().getBirthDate());
}
}
@Test
public void testToEntityStream() throws Exception {
// Number of persons to insert:
int numPersons = 10000;
// Insert the given number of persons:
insert(numPersons);
// Get all row of the Table:
ResultSet resultSet = selectAll();
// Create a SqlMapper, which maps between a ResultSet row and a Person entity:
SqlMapper<Person> sqlMapper = new SqlMapper<>(() -> new Person(), new PersonMap());
// Create the Stream using the StreamSupport class:
Stream<SqlMappingResult<Person>> stream = sqlMapper.toStream(resultSet);
// Collect the Results as a List:
List<SqlMappingResult<Person>> result = stream.collect(Collectors.toList());
// Assert the results:
Assert.assertEquals(numPersons, result.size());
}
private boolean createTable() throws SQLException {
String sqlStatement = "CREATE TABLE sample.unit_test\n" +
" (\n" +
" first_name text,\n" +
" last_name text,\n" +
" birth_date date\n" +
" );";
Statement statement = connection.createStatement();
return statement.execute(sqlStatement);
}
private ResultSet selectAll() throws SQLException {
Statement stmt = connection.createStatement();
return stmt.executeQuery("select * from sample.unit_test");
}
private void insert(int numPersons) throws SQLException {
Person person0 = new Person();
person0.firstName = "Philipp";
person0.lastName = "Wagner";
person0.birthDate = LocalDate.of(1986, 5, 12);
for(int i = 0; i < numPersons; i++) {
insert(person0);
}
}
private void insert(Person person) throws SQLException {
PreparedStatement pstmt = null;
try {
String query = "insert into sample.unit_test(first_name, last_name, birth_date) values(?, ?, ?)";
pstmt = connection.prepareStatement(query); // create a statement
pstmt.setString(1, person.getFirstName());
pstmt.setString(2, person.getLastName());
pstmt.setTimestamp(3, Timestamp.valueOf(person.getBirthDate().atStartOfDay()));
pstmt.execute();
} finally {
pstmt.close();
}
}
}
|
package com.phoosop.gateway.filter;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.Collections;
import java.util.Set;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.*;
@Component
public class LoggingGatewayFilterFactory extends AbstractGatewayFilterFactory<LoggingGatewayFilterFactory.Config> {
private final Logger logger = LoggerFactory.getLogger(LoggingGatewayFilterFactory.class);
public LoggingGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
if (config.isPreLogger() || config.isPostLogger()) {
Set<URI> uris = exchange.getAttributeOrDefault(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, Collections.emptySet());
String originalUri = (uris.isEmpty()) ? "Unknown" : uris.iterator().next().toString();
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
URI routeUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
if (config.isPreLogger()) {
// Pre-processing
logger.info("Pre: {} is routed to id: {}, uri: {}", originalUri, route.getId(), routeUri);
}
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
// Post-processing
if (config.isPostLogger()) {
HttpStatus httpStatus = exchange.getResponse().getStatusCode();
logger.info("Post: {} is routed to id: {}, uri: {}, response status: {}", originalUri, route.getId(), routeUri, httpStatus.value());
}
}));
}
return chain.filter(exchange);
};
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public static class Config {
private boolean preLogger;
private boolean postLogger;
}
}
|
package com.hg.sb_helloworld;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import com.hg.sb_helloworld.web.UserController;
@RunWith( SpringJUnit4ClassRunner.class )
@SpringApplicationConfiguration( classes = MockServletContext.class )
@WebAppConfiguration
public class UserControllerTest
{
private MockMvc mvc;
@Before
public void setUp() throws Exception
{
mvc = MockMvcBuilders.standaloneSetup( new UserController() ).build();
}
@Test
@Transactional
@Rollback( true )
public void userTest() throws Exception
{
RequestBuilder request = MockMvcRequestBuilders.get( "/users/userProfile/hugui" );
mvc.perform( ((MockHttpServletRequestBuilder)request).accept( MediaType.APPLICATION_JSON ) )
.andExpect( status().is4xxClientError() );
request = MockMvcRequestBuilders.get( "/users/" );
mvc.perform( request ).andExpect( status().isOk() ).andExpect( content().string( equalTo( "[]" ) ) );
request = MockMvcRequestBuilders.post( "/users/" ).param( "id", "1" ).param( "userName", "hugui" )
.param( "age", "1" ).param( "gender", "1" );
mvc.perform( request ).andExpect( status().isOk() ).andExpect( content().string( equalTo( "success" ) ) );
request = MockMvcRequestBuilders.get( "/users/1" );
mvc.perform( request ).andExpect( status().isOk() ).andExpect(
content().string( equalTo( "{\"id\":1,\"userName\":\"hugui\",\"age\":1,\"gender\":true}" ) ) );
request = MockMvcRequestBuilders.put( "/users/1" ).param( "userName", "trim.ghu" ).param( "age", "2" );
mvc.perform( request ).andExpect( status().isOk() ).andExpect( content().string( equalTo( "success" ) ) );
request = MockMvcRequestBuilders.get( "/users/1" );
mvc.perform( request ).andExpect( status().isOk() ).andExpect(
content().string( equalTo( "{\"id\":1,\"userName\":\"trim.ghu\",\"age\":2,\"gender\":true}" ) ) );
request = MockMvcRequestBuilders.delete( "/users/1" );
mvc.perform( request ).andExpect( status().isOk() ).andExpect( content().string( equalTo( "success" ) ) );
request = MockMvcRequestBuilders.get( "/users/" );
mvc.perform( request ).andExpect( status().isOk() ).andExpect( content().string( equalTo( "[]" ) ) );
}
}
|
package Utilities;
public interface Constants {
String UNAME="com.mysql.jdbc.Driver";
String URL= "jdbc:mysql://localhost/cdk";
String UID="root";
String PASSWORD="CDKcdk11";
}
|
package br.com.ufrn.imd.lpii.classes.persistence;
import br.com.ufrn.imd.lpii.classes.entities.Bem;
import br.com.ufrn.imd.lpii.classes.entities.Categoria;
import br.com.ufrn.imd.lpii.classes.entities.Localizacao;
import br.com.ufrn.imd.lpii.classes.main.Bot;
import br.com.ufrn.imd.lpii.exceptions.BemNaoEncontradoException;
import br.com.ufrn.imd.lpii.exceptions.LocalizacaoNaoEncontradaException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
public class ConnectionBem extends ConnectionSQLite {
/**
* Método para criação da tabela BEM no banco de dados
* @return Boolean indicando se ocorreu tudo pelo fluxo normal ou aconteceu alguma exceção
* */
public Boolean criarTabela(){
try {
if (!connection.isClosed()){
statement = connection.createStatement();
//se a tabela já existir no banco ele continua se capturar exceção
//o codigo como autoincrement é gerado pelo próprio banco de dados de forma incremental
String sql = "CREATE TABLE IF NOT EXISTS BEM" +
"(CODIGO INTEGER PRIMARY KEY AUTOINCREMENT," +
" NOME TEXT NOT NULL, " +
" TOMBO TEXT ," +
" DESCRICAO TEXT NOT NULL," +
" LOCALIZACAOCODIGO INTEGER NOT NULL," +
" CATEGORIACODIGO INTEGER NOT NULL," +
" FOREIGN KEY(LOCALIZACAOCODIGO) REFERENCES LOCALIZACAO (CODIGO),"+
" FOREIGN KEY(CATEGORIACODIGO) REFERENCES CATEGORIA (CODIGO));";
statement.executeUpdate(sql);
statement.close();
return true;
}else{
conectar();
criarTabela();
}
}catch (SQLException e){
System.out.println("Erro ao criar tabela Bem");
e.printStackTrace();
return false;
}
return null;
}
public Boolean cadastrarBem(Bem bem){
try {// String nome, String descricao, Integer codigoLocalizacao, Integer codigoCategoria
if (!connection.isClosed()){
System.out.println(bem.toString());
statement = connection.createStatement();
String sql ="INSERT INTO BEM(CODIGO, NOME, TOMBO, DESCRICAO, LOCALIZACAOCODIGO, CATEGORIACODIGO) " +
"VALUES (\""+bem.getCodigo()+"\", \""+bem.getNome()+"\",\""+bem.getTombo()+"\",\""+bem.getDescricao()+"\","+bem.getLocalizacao().getCodigo()+", "+bem.getCategoria().getCodigo()+");";
statement.executeUpdate(sql);
statement.close();
return true;
}else{
conectar();
criarTabela();
return cadastrarBem(bem);
}
}catch (SQLException e){
System.out.println("Erro ao cadastrar Bem");
e.printStackTrace();
return false;
}
}
/**
*Método que a tabela Bem no banco e retorna todos os valores nela presentes
* @return ArrayList<HashMap<String, String> > : ArrayList com um map(chave, valor) indicando o nome o atributo e o valor dele em cada tupla
* */
public ArrayList<HashMap<String, String> > listarBem(){
ArrayList< HashMap<String, String> > camposList = null; //array para retornar todos campos cadastrados organizando-os em 3-tuplas
try {
if (!connection.isClosed()){
//configurações de variáveis para o banco
statement = connection.createStatement();
connection.setAutoCommit(false);
statement = connection.createStatement();
//script SQL
ResultSet rs = statement.executeQuery( "SELECT * FROM BEM;" );
camposList = new ArrayList<>();
//organizando o Set lido do banco em outra variável (arraylist)
while ( rs.next() ) {
HashMap<String, String> tupla= new HashMap<>();
tupla.clear();
Integer codigo = rs.getInt("codigo");
tupla.put("codigo", codigo.toString());
String nome = rs.getString("nome");
tupla.put("nome", nome);
String tombo = rs.getString("tombo");
tupla.put("tombo", tombo);
String descricao = rs.getString("descricao");
tupla.put("descricao", descricao);
Integer localizacaoCodigo = rs.getInt("localizacaocodigo");
tupla.put("localizacaocodigo", localizacaoCodigo.toString());
Integer categoriaCodigo = rs.getInt("categoriacodigo");
tupla.put("categoriacodigo", categoriaCodigo.toString());
camposList.add(tupla);
}
rs.close();
statement.close();
}else{
conectar();
criarTabela();
listarBem();
}
}catch (SQLException e){
System.out.println("Erro ao listar Bem");
e.printStackTrace();
}
return camposList;
}
/**Busca no banco um bem com o atributo correspondente ao enviado
* @param
* @return */
public ArrayList<Bem> buscarBemByAtributo(String atributo, String value){
ArrayList<Bem> bens = null;
try {
if (!connection.isClosed()){
//configurações de variáveis para o banco
statement = connection.createStatement();
connection.setAutoCommit(false);
statement = connection.createStatement();
//script SQL
ResultSet rs = statement.executeQuery( "SELECT * FROM BEM;" );
//organizando o Set lido do banco em outra variável (arraylist)
while ( rs.next() ) {
Bem bem = null;
Integer codigo = rs.getInt("codigo");
String nome = rs.getString("nome");
String tombo = rs.getString("tombo");
String descricao = rs.getString("descricao");
Integer localizacaoCodigo = rs.getInt("localizacaocodigo");
Integer categoriaCodigo = rs.getInt("categoriacodigo");
ConnectionLocalizacao connectionLocalizacao = new ConnectionLocalizacao();
connectionLocalizacao.conectar();
Localizacao localizacao = connectionLocalizacao.buscarLocalizacaoByCodigo(localizacaoCodigo);
connectionLocalizacao.desconectar();
ConnectionCategoria connectionCategoria = new ConnectionCategoria();
connectionCategoria.conectar();
Categoria categoria = connectionCategoria.buscarCategoriaByCodigo(categoriaCodigo);
connectionCategoria.desconectar();
bem = new Bem(codigo, nome,tombo, descricao, localizacao, categoria);
System.out.println(bem.toString());
bens.add(bem);
}
rs.close();
statement.close();
}else{
conectar();
criarTabela();
return buscarBemByAtributo(atributo, value);
}
}catch (SQLException e){
System.out.println("Erro ao buscar");
e.printStackTrace();
}
return bens;
}
public ArrayList<Bem> buscarBemByLocalizacao(Localizacao localizacao){
return null;
}
public Boolean atualizarLocalizacao(Localizacao localizacao, Bem bem) throws LocalizacaoNaoEncontradaException{
desconectar();
conectar();
try {// String nome, String descricao, Integer codigoLocalizacao, Integer codigoCategoria
if (!connection.isClosed()){
statement = connection.createStatement();
if (localizacao.getCodigo() != null){
String sql ="UPDATE bem SET localizacaocodigo = "+ localizacao.getCodigo()
+" WHERE codigo = "+bem.getCodigo()+";";
System.out.println(sql);
statement.executeUpdate(sql);
statement.close();
return true;
}else{
throw new LocalizacaoNaoEncontradaException();
}
}else{
conectar();
criarTabela();
return atualizarLocalizacao(localizacao, bem);
}
}catch (SQLException e){
System.out.println("Erro ao movimentar Bem");
e.printStackTrace();
return false;
}
}
public ArrayList<Bem> listarBens(){
ArrayList<Bem> bens = null; //array para retornar todos campos cadastrados organizando-os em 3-tuplas
try {
if (!connection.isClosed()){
//configurações de variáveis para o banco
statement = connection.createStatement();
connection.setAutoCommit(false);
statement = connection.createStatement();
//script SQL
ResultSet rs = statement.executeQuery( "SELECT * FROM BEM;" );
bens = new ArrayList<>();
//organizando o Set lido do banco em outra variável (arraylist)
while ( rs.next() ) {
Bem bem = null;
Integer codigo = rs.getInt("codigo");
String nome = rs.getString("nome");
String tombo = rs.getString("tombo");
String descricao = rs.getString("descricao");
Integer localInt = rs.getInt("localizacaocodigo");
Integer catInt = rs.getInt("categoriacodigo");
Localizacao localizacao = Bot.buscarLocalizacao(localInt);
Categoria categoria = Bot.buscarCategoria(catInt);
bem = new Bem(codigo, nome, tombo, descricao, localizacao, categoria);
bens.add(bem);
}
rs.close();
statement.close();
}else{
conectar();
criarTabela();
//return "errou"; //listarCategorias();
}
}catch (SQLException e){
System.out.println("Erro ao listar");
e.printStackTrace();
}
return bens;
}
public Boolean apagarBem(String campo, String value) throws BemNaoEncontradoException{
try {// String nome, String descricao, Integer codigoLocalizacao, Integer codigoCategoria
if (!connection.isClosed()){
statement = connection.createStatement();
if (value != null && campo !=null ){
String sql ="DELETE FROM bem WHERE "+campo+" = "+value+" ;";
System.out.println(sql);
statement.executeUpdate(sql);
statement.close();
return true;
}else{
throw new BemNaoEncontradoException();
}
}else{
conectar();
criarTabela();
return apagarBem(campo, value);
}
}catch (SQLException e){
System.out.println("Erro ao apagar Bem");
e.printStackTrace();
return false;
}
}
}
|
package com.lenovohit.hwe.treat.dao;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.lenovohit.core.utils.JSONUtils;
public class HisRestRequest {
public static final String SEND_TYPE_LOCATION = "location";
public static final String SEND_TYPE_POST = "post";
@JSONField(name = "AS_TOKEN")
private String token;
@JSONField(name = "AS_CODE")
private String code;
@JSONField(name = "AS_DATA")
private String data;
@JsonIgnore
private Object param;
@JsonIgnore
private String sendType;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getData() {
if (data == null && param != null) {
return JSONUtils.serialize(param);
} else
return "";
}
public void setData(String data) {
this.data = data;
}
public Object getParam() {
return param;
}
public void setParam(Object param) {
this.param = param;
}
public String getSendType() {
return sendType;
}
public void setSendType(String sendType) {
this.sendType = sendType;
}
}
|
package com.fubang.wanghong.model;
import com.fubang.wanghong.entities.HomeHeadPicEntity;
import retrofit2.Callback;
/**
* Created by dell on 2016/4/5.
*/
public interface HomeHeadPicModel {
void getHeadPicData(Callback<HomeHeadPicEntity> callback);
}
|
package com.softwareengineeringapp.kamys.findmean;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;
/**
* Created by kamys on 10/26/2016.
*/
public class facebookInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
LayoutInflater inflater = null;
private TextView eventName;
private TextView eventAddress;
private TextView eventTime;
private TextView eventDate;
public facebookInfoWindowAdapter(LayoutInflater inflater) {
this.inflater = inflater;
}
@Override
public View getInfoWindow(Marker marker) {
View v = inflater.inflate(R.layout.building_info_window, null);
if (marker != null) {
eventName = (TextView) v.findViewById(R.id.bName);
eventName.setText(marker.getTitle());
eventTime = (TextView) v.findViewById(R.id.bList);
eventTime.setText(marker.getTitle());
eventDate = (TextView) v.findViewById(R.id.bList);
eventDate.setText(marker.getTitle());
eventAddress = (TextView) v.findViewById(R.id.bList);
eventAddress.setText(marker.getTitle());
}
return (v);
}
@Override
public View getInfoContents(Marker marker) {
return (null);
}
}
|
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
/**
* Leetcode做题-验证二叉搜索树 https://leetcode-cn.com/problems/validate-binary-search-tree/
*/
public class 验证二叉搜索树 {
public boolean isValidBSTInOrder_Stack(TreeNode root) {
Deque<TreeNode> stack=new ArrayDeque<>();
Integer prev=null;
while (root!=null||!stack.isEmpty()){
while (root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
if(prev!=null&&root.val<=prev){
return false;
}
prev=root.val;
root=root.right;
}
return true;
}
Integer pre=null;
public boolean isValidBSTInOrder(TreeNode root) {
if(root==null){
return true;
}
if(!isValidBSTInOrder(root.left)){
return false;
}
if(pre!=null&&root.val<=pre){
return false;
}
pre=root.val;
return isValidBSTInOrder(root.right);
}
public boolean isValidBSTStack(TreeNode root) {//模拟递归栈
Deque<TreeNode> stack=new LinkedList<>();
Deque<Integer> lower=new LinkedList<>();
Deque<Integer> upper=new LinkedList<>();
stack.push(root);
lower.push(null);
upper.push(null);
while (!stack.isEmpty()){
TreeNode node=stack.pop();
Integer min=lower.pop();
Integer max=upper.pop();
if(node==null){
continue;
}
if(min!=null&&node.val<=min){
return false;
}
if(max!=null&&node.val>=max){
return false;
}
stack.push(node.left);
lower.push(min);
upper.push(node.val);
stack.push(node.right);
lower.push(node.val);
upper.push(max);
}
return true;
}
public boolean isValidBST(TreeNode root) {
return _recursion(root,null,null);
}
private boolean _recursion(TreeNode root,Integer lower,Integer upper) {
if(root==null){
return true;
}
if (lower!=null&&root.val<=lower){
return false;
}
if (upper!=null&&root.val>=upper){
return false;
}
return _recursion(root.left,lower,root.val)&&_recursion(root.right,root.val,upper);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
|
package com.wxt.designpattern.factorymethod.test01.witddp;
/**
* @Auther: weixiaotao
* @ClassName ExportXmlFile
* @Date: 2018/10/22 13:38
* @Description:
*/
public class ExportXmlFile implements ExportFileApi {
@Override
public boolean export(String data) {
System.out.println("导出数据"+data+"到xml文件");
return true;
}
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package app;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.Watchdog;
import interfaces.RobotIntf;
import systems.RamLight;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Main extends IterativeRobot
{
private RobotIntf robot = null;
private Autonomous auto = null;
private TeleOp tele = null;
private RamLight light = null;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit()
{
//System.out.println("robotInit");
robot = new CompetitionRobot();
//robot = new PracticeRobot();
robot.init();
getWatchdog().setExpiration(.75);
//light = new RamLight(robot);
// Wait for gyro to stabilize
Timer.delay(10.0);
}
public void autonomousInit()
{
Watchdog.getInstance().feed();
//System.out.println("autonomousInit");
auto = new Autonomous(robot);
auto.Init();
// start the thread that lights the RAM light if we have a ball
//light.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic()
{
Watchdog.getInstance().feed();
//System.out.println("autonomousPeriodic");
// Update robot systems
robot.update();
auto.Periodic();
}
public void teleopInit()
{
Watchdog.getInstance().feed();
//System.out.println("teleopInit");
tele = new TeleOp(robot);
tele.Init();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic()
{
Watchdog.getInstance().feed();
//System.out.println("teleopPeriodic");
// Update robot systems
robot.update();
tele.Periodic();
}
}
|
/*
* Created by JFormDesigner on Thu Nov 28 22:15:49 EST 2019
*/
package view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* @author Jun Li
*/
public class Login extends JFrame {
public Login() {
initComponents();
}
private void button_loginMouseReleased(MouseEvent e) {
CourseList courseList = new CourseList();
courseList.setVisible(true);
this.dispose();
}
private void button_exitMouseReleased(MouseEvent e) {
this.dispose();
}
private void thisWindowClosing(WindowEvent e) {
System.exit(0);
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - unknown
button_login = new JButton();
button_exit = new JButton();
label1 = new JLabel();
label2 = new JLabel();
label3 = new JLabel();
textField1 = new JTextField();
textField2 = new JTextField();
hSpacer4 = new JPanel(null);
vSpacer1 = new JPanel(null);
//======== this ========
setIconImage(new ImageIcon(getClass().getResource("/images/icon.png")).getImage());
setTitle("Grading System");
setResizable(false);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
thisWindowClosing(e);
}
});
Container contentPane = getContentPane();
contentPane.setLayout(null);
//---- button_login ----
button_login.setText("Login");
button_login.setIcon(new ImageIcon(getClass().getResource("/images/login.png")));
button_login.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
button_loginMouseReleased(e);
}
});
contentPane.add(button_login);
button_login.setBounds(60, 115, 85, button_login.getPreferredSize().height);
//---- button_exit ----
button_exit.setText("Exit");
button_exit.setIcon(new ImageIcon(getClass().getResource("/images/exit.png")));
button_exit.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
button_exitMouseReleased(e);
}
});
contentPane.add(button_exit);
button_exit.setBounds(180, 115, 85, button_exit.getPreferredSize().height);
//---- label1 ----
label1.setText("Grading System");
label1.setFont(new Font("Impact", Font.PLAIN, 30));
contentPane.add(label1);
label1.setBounds(65, 5, 205, label1.getPreferredSize().height);
//---- label2 ----
label2.setText("Username:");
contentPane.add(label2);
label2.setBounds(new Rectangle(new Point(30, 60), label2.getPreferredSize()));
//---- label3 ----
label3.setText("Password:");
contentPane.add(label3);
label3.setBounds(new Rectangle(new Point(30, 85), label3.getPreferredSize()));
contentPane.add(textField1);
textField1.setBounds(105, 55, 185, textField1.getPreferredSize().height);
contentPane.add(textField2);
textField2.setBounds(105, 80, 185, textField2.getPreferredSize().height);
contentPane.add(hSpacer4);
hSpacer4.setBounds(new Rectangle(new Point(305, 10), hSpacer4.getPreferredSize()));
contentPane.add(vSpacer1);
vSpacer1.setBounds(155, 145, 35, 10);
{
// compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < contentPane.getComponentCount(); i++) {
Rectangle bounds = contentPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = contentPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
contentPane.setMinimumSize(preferredSize);
contentPane.setPreferredSize(preferredSize);
}
pack();
setLocationRelativeTo(null);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - unknown
private JButton button_login;
private JButton button_exit;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JTextField textField1;
private JTextField textField2;
private JPanel hSpacer4;
private JPanel vSpacer1;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
|
package com.crm.qa.tests;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.crm.qa.base.TestBase;
import com.crm.qa.pages.LoginPage;
import com.crm.qa.pages.SignUpPage;
import com.crm.qa.util.TestUtil;
public class SignUpTest extends TestBase {
LoginPage login;
SignUpPage sign=null;
public SignUpTest(){
super();
}
@BeforeClass
public void setup() {
initialization();
login=new LoginPage();
sign=new SignUpPage();
login.signUp();
}
@Test
public void m()
{
String title=sign.vaalidateTitle();
Assert.assertEquals(title, "ytdruyhgrf");
}
@Test(dataProvider="getData1")//
public void register(String un,String ps,String rps,String fullN,String email1)
{
//sign.signUp("1", "2", "3", "4", "5");
sign.signUp(un,ps,rps,fullN,email1);
}
@DataProvider(name="getData1")
public Object[][] getData() throws Exception
{
Object data[][]=TestUtil.fileRead("a");
return data;
}
@org.testng.annotations.AfterClass
public void teardown() {
//driver.quit();
}
}
|
/*
* 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.hcl.neo.eloader.microservices.model;
import java.util.List;
/**
*
* @author Sakshi Jain
*/
public class UploadJobMessage {
private String name;
private String type;
private String userId;
private String userName;
private String userEmail;
private String packageChecksum;
private long contentSize;
private long packageSize;
private long packageFolderCount;
private long packageFileCount;
private long repositoryId;
private long transportServerId;
private String transportServerPath;
private String clientos;
private String folderTypes;
private String businessGroup;
private String kmGroup;
private List<String> repositoryPaths;
private Long landZoneId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getPackageChecksum() {
return packageChecksum;
}
public void setPackageChecksum(String packageChecksum) {
this.packageChecksum = packageChecksum;
}
public long getContentSize() {
return contentSize;
}
public void setContentSize(long contentSize) {
this.contentSize = contentSize;
}
public long getPackageSize() {
return packageSize;
}
public void setPackageSize(long packageSize) {
this.packageSize = packageSize;
}
public long getPackageFolderCount() {
return packageFolderCount;
}
public void setPackageFolderCount(long packageFolderCount) {
this.packageFolderCount = packageFolderCount;
}
public long getPackageFileCount() {
return packageFileCount;
}
public void setPackageFileCount(long packageFileCount) {
this.packageFileCount = packageFileCount;
}
public long getRepositoryId() {
return repositoryId;
}
public void setRepositoryId(long repositoryId) {
this.repositoryId = repositoryId;
}
public long getTransportServerId() {
return transportServerId;
}
public void setTransportServerId(long transportServerId) {
this.transportServerId = transportServerId;
}
public String getTransportServerPath() {
return transportServerPath;
}
public void setTransportServerPath(String transportServerPath) {
this.transportServerPath = transportServerPath;
}
public String getClientos() {
return clientos;
}
public void setClientos(String clientos) {
this.clientos = clientos;
}
public String getFolderTypes() {
return folderTypes;
}
public void setFolderTypes(String folderTypes) {
this.folderTypes = folderTypes;
}
public String getBusinessGroup() {
return businessGroup;
}
public void setBusinessGroup(String businessGroup) {
this.businessGroup = businessGroup;
}
public String getKmGroup() {
return kmGroup;
}
public void setKmGroup(String kmGroup) {
this.kmGroup = kmGroup;
}
public List<String> getRepositoryPaths() {
return repositoryPaths;
}
public void setRepositoryPaths(List<String> repositoryPaths) {
this.repositoryPaths = repositoryPaths;
}
/**
* @return the landZoneId
*/
public Long getLandZoneId() {
return landZoneId;
}
/**
* @param landZoneId the landZoneId to set
*/
public void setLandZoneId(Long landZoneId) {
this.landZoneId = landZoneId;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "UploadJobMessage [name=" + name + ", type=" + type + ", userId=" + userId + ", userName=" + userName
+ ", userEmail=" + userEmail + ", packageChecksum=" + packageChecksum + ", contentSize=" + contentSize
+ ", packageSize=" + packageSize + ", packageFolderCount=" + packageFolderCount + ", packageFileCount="
+ packageFileCount + ", repositoryId=" + repositoryId + ", transportServerId=" + transportServerId
+ ", transportServerPath=" + transportServerPath + ", clientos=" + clientos + ", folderTypes="
+ folderTypes + ", businessGroup=" + businessGroup + ", kmGroup=" + kmGroup + ", repositoryPaths="
+ repositoryPaths + ", landZoneId=" + landZoneId + "]";
}
}
|
package com.culturaloffers.maps.repositories;
import com.culturaloffers.maps.model.CulturalOffer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CulturalOfferRepository extends JpaRepository<CulturalOffer, Integer> {
CulturalOffer findByTitle(String title);
CulturalOffer findByTitleAndIdNot(String title, Integer integer);
List<CulturalOffer> findByTitleContaining(String title);
List<CulturalOffer> findByDescriptionContaining(String description);
@Query("Select offer from CulturalOffer offer join offer.subtype subtype where subtype.name like %:name%")
List<CulturalOffer> findBySubtypeContaining(String name);
@Query("Select distinct(offer) from CulturalOffer offer join offer.subscribers subscribers where size(subscribers) >= :amount")
List<CulturalOffer> findBySubscriberAmountGreaterEq(Integer amount);
@Query("Select distinct(offer) from CulturalOffer offer join offer.userGrades grades where size(grades) > 0")
List<CulturalOffer> findGraded();
@Query("Select offer from CulturalOffer offer join offer.subtype subtype where subtype.offerType.name like %:name%")
List<CulturalOffer> findByTypeContaining(String name);
@Query(
value = "SELECT * FROM CULTURAL_OFFER C JOIN GEO_LOCATION G ON C.GEO_LOCATION_ID=G.ID AND " +
"G.LATITUDE BETWEEN ?1 AND ?2 AND G.LONGITUDE BETWEEN ?3 AND ?4",
nativeQuery = true
)
List<CulturalOffer> findAllByZoom(
double latitudeLowerCorner,
double latitudeUpperCorner,
double longitudeUpperCorner,
double longitudeLowerCorner
);
}
|
package boletin4;
import java.util.Scanner;
public class ejercicio6 {
private static Scanner sc;
public static void main(String[]arg){
sc = new Scanner(System.in);
int [] num = new int[12];
int [] num2 = new int[12];
int [] numr = new int[24];
int i1=0,i2=0,k=0,l=0;
System.out.print("\nIngresar 2 tablas de 12 numeros");
while (i1<12) {
num[i1]=sc.nextInt();
i1++;
}
System.out.print("\nIngresar 10 numeros mas");
while (i2<12) {
num2[i2]=sc.nextInt();
i2++;
}
System.out.print("\nLos numeros son:");
while (l<4) {
numr[6*l]=num[3*l];
numr[6*l+1]=num[3*l+1];
numr[6*l+2]=num[3*l+2];
numr[6*l+3]=num2[3*l];
numr[6*l+4]=num2[3*l+1];
numr[6*l+5]=num2[3*l+2];
l++;
}
while (k<24) {
System.out.print("\n"+numr[k]);
k++;
}
}
}
|
package com.test.demo.Services.Implementation;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.demo.Entities.Funds;
import com.test.demo.Entities.Investors;
import com.test.demo.Repository.InvestorRepository;
import com.test.demo.Services.AppService;
import com.test.demo.Services.MarketValueService;
@Service("investorMarketValueService")
public class InvestorMarketValueServiceImpl implements MarketValueService {
@Autowired
InvestorRepository investorRepository;
@Autowired
AppService appService;
@Override
public double fetchMarkedValue(Integer id, List<Integer> exclusionHoldingList) {
double marketValue = 0.0;
// TODO Auto-generated method stub
Investors investors = getNodeById(id);
Set<Funds> funds = investors.getFunds();
if (funds != null && funds.size() != 0) {
for (Funds fund : funds) {
marketValue += appService.calculateMarketValue(fund,exclusionHoldingList);
}
}
return marketValue;
}
@Override
public Investors getNodeById(int id) {
// TODO Auto-generated method stub
Optional<Investors> investors = investorRepository.findById(id);
if (investors.isPresent())
return investors.get();
return null;
}
}
|
package com.timewarp.games.onedroidcode.editor;
import com.badlogic.gdx.graphics.Color;
import com.timewarp.engine.Math.Mathf;
import com.timewarp.engine.SceneManager;
import com.timewarp.engine.Vector2D;
import com.timewarp.engine.entities.GameObject;
import com.timewarp.engine.gui.GUI;
import com.timewarp.games.onedroidcode.AssetManager;
import com.timewarp.games.onedroidcode.editor.actions.IAction;
import com.timewarp.games.onedroidcode.editor.actions.NodeControllerAction;
import com.timewarp.games.onedroidcode.scenes.VSLEditorScene;
import com.timewarp.games.onedroidcode.vsl.Node;
import com.timewarp.games.onedroidcode.vsl.nodes.RootNode;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GridNodeEditor {
public static GridNodeEditor instance;
private NodeProvider nodeProvider;
private boolean isMoving;
private Vector2D startMovementPoint;
private int width, height;
private NodeCellComponent[][] field;
private final int STATE_EMPTY = 0;
private final int STATE_NEW_NODE = 1;
private final int STATE_NODE_EDIT = 2;
private final int STATE_WIRE_ASSIGN = 3;
private final int STATE_NODE_WIRE_ASSIGN = 4;
private int state = STATE_EMPTY;
private String windowName = "CLICK ON ANY CELL";
private NodeCellComponent currentCell;
private NodeIO targetNodeOutput;
private Vector2D lastTouchPosition;
private int currentScroll = 0;
private final int EDIT_PANEL_WIDTH_P = 30;
int EDIT_PANEL_WIDTH;
private final int NODE_CELL_SPACING = 30;
private final int NODE_CELLS_PER_COLUMN = 4;
private final int NODE_CELL_SIZE = (GUI.Height - NODE_CELL_SPACING * (NODE_CELLS_PER_COLUMN + 1)) / NODE_CELLS_PER_COLUMN;
private static NodeController[][] controllers;
public static Node[] code;
public GridNodeEditor(NodeProvider provider, int width, int height) {
GridNodeEditor.instance = this;
this.nodeProvider = provider;
this.width = width;
this.height = height;
this.generateField(width, height);
if (controllers != null) loadControllers();
}
private void generateField(int width, int height) {
field = new NodeCellComponent[height][width];
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
final NodeCell cell = GameObject.instantiate(NodeCell.class);
final NodeCellComponent component = field[y][x] = cell.cellComponent;
component.setSize(NODE_CELL_SIZE);
component.setPosition(
x * (NODE_CELL_SIZE + NODE_CELL_SPACING) + NODE_CELL_SPACING,
y * (NODE_CELL_SIZE + NODE_CELL_SPACING) + NODE_CELL_SPACING
);
}
}
field[0][0].nodeController = nodeProvider.getControllerFor(RootNode.class).copy();
field[0][0].nodeController.texture = AssetManager.rootNodeTexture;
}
public void update() {
// If editor panel caught click then don't check main field
this.updateEditorPanel();
if (GUI.isTouched && GUI.touchStartPosition.x >= GUI.Width - EDIT_PANEL_WIDTH) {
return;
}
if (!isMoving && GUI.isTouched && GUI.touchPosition.sub(GUI.touchStartPosition).getLengthSquared() >= 25) {
isMoving = true;
startMovementPoint = GUI.touchPosition.copy();
} else if (!GUI.isTouched) {
isMoving = false;
}
if (isMoving) {
GUI.translateBy(GUI.touchPosition.sub(startMovementPoint));
startMovementPoint = GUI.touchPosition.copy();
return;
}
this.updateNodes();
}
private void updateEditorPanel() {
EDIT_PANEL_WIDTH = GUI.Width * EDIT_PANEL_WIDTH_P / 100;
}
private void updateNodes() {
for (NodeCellComponent[] csc : field) {
for (NodeCellComponent cell : csc) {
if (!cell.gameObject.isClicked()) continue;
Logger.getAnonymousLogger().log(
Level.WARNING,
String.format(
Locale.US,
"cam: %s\npos:%s",
GUI.cameraPosition.toString(),
cell.transform.position.toString()
)
);
if (cell.gameObject.touchStartPosition.x
>= GUI.Width - GridNodeEditor.instance.EDIT_PANEL_WIDTH)
continue;
if (state == STATE_WIRE_ASSIGN) {
currentCell.nodeController.next = cell.nodeController;
removeSelection();
} else if (state == STATE_NODE_WIRE_ASSIGN) {
targetNodeOutput.value = cell.nodeController;
removeSelection();
} else {
if (currentCell != null) currentCell.removeSelection();
cell.addSelection();
if (cell.nodeController == null) createNode(cell);
else selectNode(cell);
}
}
}
}
private void createNode(NodeCellComponent cell) {
state = STATE_NEW_NODE;
windowName = "CREATE NEW NODE";
currentCell = cell;
}
private void selectNode(NodeCellComponent cell) {
state = STATE_NODE_EDIT;
windowName = cell.nodeController.name.toUpperCase();
currentCell = cell;
}
public void render() {
this.renderWires();
this.renderUI();
}
private void renderWires() {
GUI.endStaticBlock();
for (NodeCellComponent[] nodesRow : field) {
for (NodeCellComponent cell : nodesRow) {
if (cell.nodeController == null) continue;
if (cell.nodeController.next != null) {
if (cell.nodeController.next.parentCell == null) {
cell.nodeController.next = null;
} else {
final Vector2D from = cell.transform.position.add(NODE_CELL_SIZE - 10, 10);
final Vector2D to = cell.nodeController.next.parentCell.transform.position.add(10, 10);
GUI.drawLine(from.x, from.y, to.x, to.y, 5, Color.WHITE);
}
}
int index = 0;
for (Object io : cell.nodeController.outputs) {
NodeIO out = (NodeIO) io;
if (out.getType() != Node.class) continue;
if (!(out.value instanceof NodeController)
|| ((NodeController) out.value).parentCell == null) {
out.value = null;
continue;
}
++index;
final Vector2D from = cell.transform.position.add(
NODE_CELL_SIZE - 10,
20 + NODE_CELL_SIZE * index / 10
);
final NodeController target = (NodeController) out.value;
final Vector2D to = target.parentCell.transform.position.add(
10,
NODE_CELL_SIZE * 3 / 10
);
GUI.drawLine(from.x, from.y, to.x, to.y, 5, Color.LIGHT_GRAY);
}
}
}
GUI.beginStaticBlock();
}
private void renderUI() {
GUI.drawPanel(GUI.Width - EDIT_PANEL_WIDTH, 0, EDIT_PANEL_WIDTH, GUI.Height, Color.DARK_GRAY);
switch (state) {
case STATE_NEW_NODE:
this.renderNewNodeCreationUI();
break;
case STATE_NODE_EDIT:
this.renderNodeEditUI();
break;
case STATE_WIRE_ASSIGN:
this.renderWireAssignUI();
break;
}
GUI.drawPanel(GUI.Width - EDIT_PANEL_WIDTH, 0, EDIT_PANEL_WIDTH, 100, Color.OLIVE);
GUI.drawText(windowName, GUI.Width - EDIT_PANEL_WIDTH + 10, 10, EDIT_PANEL_WIDTH - 20, 80, Color.WHITE);
}
private void renderNewNodeCreationUI() {
final Vector2D actionSize = new Vector2D(EDIT_PANEL_WIDTH / 2, EDIT_PANEL_WIDTH / 2);
// ===--- DRAW DIRECTORIES/CONTROLLERS ---===
final IAction[] actions = nodeProvider.getCurrentGroup().getActions();
final int maxScrollForGroup = (int) (actions.length * (actionSize.y + 40) - 40);
final int height = GUI.Height - 260;
if (GUI.isTouched) {
if (!GUI.isLastTouched) lastTouchPosition = GUI.touchPosition.copy();
currentScroll -= GUI.touchPosition.y - lastTouchPosition.y;
lastTouchPosition.set(GUI.touchPosition);
currentScroll = Mathf.clamp(currentScroll, 0, maxScrollForGroup - height);
}
final Vector2D barPos = new Vector2D(GUI.Width - 50, 120);
final Vector2D barSize = new Vector2D(30, height + 20);
final float scrollBarSize = Mathf.clamp((float) height / maxScrollForGroup, 0f, 1f) * barSize.y;
final float scrollProgress = (float) currentScroll / (maxScrollForGroup - height);
final float scrollBarOffset = scrollProgress * (barSize.y - scrollBarSize);
GUI.drawPanel(barPos.x, barPos.y, barSize.x, barSize.y, Color.GRAY);
GUI.drawPanel(barPos.x, barPos.y + scrollBarOffset, barSize.x, scrollBarSize, Color.LIGHT_GRAY);
int index = 0;
for (IAction action : actions) {
final Vector2D actionPosition = new Vector2D(
GUI.Width - EDIT_PANEL_WIDTH * 3 / 4,
140 - currentScroll + index++ * (40 + actionSize.y)
);
GUI.drawTextureRegion(
action.getTexture(),
actionPosition.x, actionPosition.y,
actionSize.x, actionSize.y
);
if (GUI.isClicked
&& GUI.touchPosition.y < GUI.Height - 100 && GUI.touchPosition.y > 100
&& Mathf.inRectangle(GUI.touchPosition, actionPosition, actionSize)) {
action.onClick(nodeProvider);
if (action instanceof NodeControllerAction) {
currentCell.setController(nodeProvider.getCurrentNodeController().copy());
currentCell.nodeController.texture = action.getTexture();
currentCell.nodeController.parentCell = currentCell;
removeSelection();
}
}
}
// ===--- DRAW BUTTONS ---===
final Vector2D size = new Vector2D(EDIT_PANEL_WIDTH - 40, 80);
final Vector2D position = new Vector2D(GUI.Width - EDIT_PANEL_WIDTH / 2 - size.x / 2, GUI.Height - 100);
GUI.drawPanel(GUI.Width - EDIT_PANEL_WIDTH, GUI.Height - 120, EDIT_PANEL_WIDTH, 120, Color.DARK_GRAY);
GUI.drawPanel(position, size, Color.ORANGE);
GUI.drawText("back", position.x, position.y, size.x, size.y);
if (GUI.isClicked && Mathf.inRectangle(GUI.touchPosition, position, size)) {
nodeProvider.selectGroup(nodeProvider.getBaseGroup());
currentScroll = 0;
}
}
private void renderNodeEditUI() {
// ===--- DRAW BUTTONS ---===
final Vector2D buttonSize = new Vector2D(EDIT_PANEL_WIDTH - 40, 80);
final Vector2D p = new Vector2D(
GUI.Width - EDIT_PANEL_WIDTH / 2 - buttonSize.x / 2,
140
);
GUI.drawPanel(p, buttonSize, Color.ORANGE);
String name = currentCell.nodeController.next == null ? "" : currentCell.nodeController.next.name;
GUI.drawText("link to [ " + name + " ]", p.x, p.y, buttonSize.x, buttonSize.y);
if (GUI.isClicked && Mathf.inRectangle(GUI.touchPosition, p, buttonSize)) {
state = STATE_WIRE_ASSIGN;
windowName = "SELECT NEXT NODE";
}
// ===--- DRAW NODE CONTAINERS ---===
int index = 0;
for (Object io : currentCell.nodeController.outputs) {
final NodeIO out = (NodeIO) io;
if (out.getType() != Node.class) continue;
final Vector2D position = new Vector2D(GUI.Width - EDIT_PANEL_WIDTH + 20, 280 + index * 90);
final Vector2D size = new Vector2D(EDIT_PANEL_WIDTH - 40, 60);
GUI.drawPanel(position.x, position.y, size.x, size.y, Color.ORANGE);
GUI.drawText(out.getDisplayName(), position.x, position.y, size.x, size.y);
if (GUI.isClicked && Mathf.inRectangle(GUI.touchPosition, position, size)) {
state = STATE_NODE_WIRE_ASSIGN;
windowName = "SELECT TARGET NODE";
targetNodeOutput = out;
}
++index;
}
// ===--- DRAW BUTTONS ---===
final Vector2D position = new Vector2D(p.x, GUI.Height - 100);
if (currentCell.nodeController.nodeType == RootNode.class) {
final Vector2D bp = new Vector2D(GUI.Width - EDIT_PANEL_WIDTH, GUI.Height - 100);
final Vector2D bs = new Vector2D(EDIT_PANEL_WIDTH, 100);
GUI.drawPanel(bp, bs, Color.OLIVE);
GUI.drawText("start playing", position.x, position.y, buttonSize.x, buttonSize.y);
if (GUI.isClicked && Mathf.inRectangle(GUI.touchPosition, bp, bs)) {
saveAndExit();
}
} else {
GUI.drawPanel(position, buttonSize, new Color(1f, 0.25f, 0f, 1f));
GUI.drawText("remove", position.x, position.y, buttonSize.x, buttonSize.y);
if (GUI.isClicked && Mathf.inRectangle(GUI.touchPosition, position, buttonSize)) {
currentCell.nodeController.reset();
currentCell.nodeController = null;
removeSelection();
}
}
}
private void saveControllers() {
int x = 0, y = 0;
controllers = new NodeController[height][width];
for (NodeCellComponent[] row : field) {
x = 0;
for (NodeCellComponent component : row) {
controllers[y][x++] = component.nodeController;
}
++y;
}
}
private void loadControllers() {
int x = 0, y = 0;
for (NodeController[] row : controllers) {
x = 0;
for (NodeController controller : row) {
if (controller == null) {
++x;
continue;
}
field[y][x].nodeController = controller;
controller.parentCell = field[y][x++];
}
++y;
}
}
private void renderWireAssignUI() {
final Vector2D s = new Vector2D(EDIT_PANEL_WIDTH - 40, 80);
final Vector2D p = new Vector2D(GUI.Width - EDIT_PANEL_WIDTH / 2 - s.x / 2, GUI.Height - 100);
GUI.drawPanel(p, s, Color.RED);
GUI.drawText("cancel", p.x, p.y, s.x, s.y);
if (GUI.isClicked && Mathf.inRectangle(GUI.touchPosition, p, s)) {
removeSelection();
}
}
private void removeSelection() {
nodeProvider.selectGroup(nodeProvider.getBaseGroup());
state = STATE_EMPTY;
windowName = "CLICK ON ANY CELL";
currentCell.removeSelection();
currentScroll = 0;
}
private Node[] generateCode() {
ArrayList<Node> nodes = new ArrayList<Node>();
NodeController<RootNode> root = field[0][0].nodeController;
generateNode(nodes, root);
clearControllerInfo(root);
return nodes.toArray(new Node[nodes.size()]);
}
private void clearControllerInfo(NodeController controller) {
if (controller == null) return;
if (controller.node == null) return;
controller.node = null;
clearControllerInfo(controller.next);
for (Object io : controller.outputs) {
NodeIO out = (NodeIO) io;
if (!(out.value instanceof NodeController))
continue;
clearControllerInfo((NodeController) out.value);
}
}
private Node generateNode(ArrayList<Node> code, NodeController controller) {
if (controller == null) return null;
if (controller.node != null) return controller.node;
try {
final Constructor<Node> constructor = controller.nodeType.getConstructor();
constructor.setAccessible(true);
final Node node = constructor.newInstance();
code.add(node);
controller.node = node;
node.append(generateNode(code, controller.next));
for (Object io : controller.outputs) {
NodeIO out = (NodeIO) io;
if (!(out.value instanceof NodeController))
continue;
out.patchField(node, generateNode(code, (NodeController) out.value));
}
return node;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Can not generate code");
}
}
public void saveAndExit() {
code = generateCode();
saveControllers();
SceneManager.instance.loadScene(VSLEditorScene.previousLevelScene);
}
}
|
package pscan;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class SCAN {
public static class Map extends Mapper<LongWritable, Text, Text, Text> {
public String convert(String[] neighbors) {
StringBuilder sb = new StringBuilder();
for (String s : neighbors) {
sb.append(s);
sb.append(",");
}
return sb.substring(0, sb.length()-1).toString();
}
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
// System.out.println(line);
int index = line.indexOf(":");
if(index == -1)
return;
String node = line.substring(0, index);
String[] neighbors = line.substring(index + 1).split(
",");
for (String neighbor : neighbors) {
Text edge = new Text();
if (Integer.valueOf(node) < Integer.valueOf(neighbor))
edge.set(node + "," + neighbor);
else
edge.set(neighbor + "," + node);
Text t = new Text();
t.set(convert(neighbors));
context.write(edge, t);
}
}
}
public static class Reduce extends Reducer<Text, Text, Text, Text> {
/**
* 计算结点的结构化相似度
* @param s1
* @param s2
* @return
*/
public double calSim(Set<Integer> s1,Set<Integer> s2) {
double common = 2.0;
for(Integer i : s1)
if(s2.contains(i))
common += 1.0;
return common/Math.sqrt((s1.size()+1)*(s2.size()+1));
}
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
double alpha = Double.valueOf(context.getConfiguration().get("alpha"));
//System.out.println("reduce alpha:" + alpha);
Iterator<Text> iter = values.iterator();
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for(String s : iter.next().toString().split(","))
set1.add(Integer.valueOf(s));
try{
for(String s : iter.next().toString().split(","))
set2.add(Integer.valueOf(s));
}catch(Exception e){
System.out.println("Error: " + key);
}
double sim = calSim(set1, set2);
//System.out.println(key+": "+sim);
if(sim >= alpha){
context.write(null,key);
}
}
}
public static void main(String[] args) throws Exception {
// Configuration conf = new Configuration();
if (args.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
for(int iterTime=1;iterTime<10;iterTime++){
//System.out.println("iterTime: "+iterTime);
Job job = new Job();
job.setJarByClass(SCAN.class);
job.setJobName("scan");
double alpha = iterTime/10.0;
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat
.setOutputPath(job, new Path("hdfs://localhost/output/pscan_"+alpha));
Configuration conf = job.getConfiguration();
//System.out.println("main alpha:" + alpha);
conf.set("alpha", Double.toString(alpha));
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
// job.setNumReduceTasks(4);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.waitForCompletion(true);
}
System.exit(0);
}
}
|
package model;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author ivani
*/
public class Usuari {
static int numRegistrats = 0;
protected String nom;
protected String cognom;
protected String usuari;
protected int contrasenya;
protected int edat;
protected String rol = "usuari";
public Usuari(String nom, String cognom, String usuari, int contrasenya, int edat) {
this.nom = nom;
this.cognom = cognom;
this.usuari = usuari;
this.contrasenya = contrasenya;
this.edat = edat;
this.numRegistrats++;
}
public Usuari(String nom, String cognom, int edat, String usuari) {
this.nom = nom;
this.cognom = cognom;
this.edat = edat;
this.usuari = usuari;
}
public Usuari(String nom, String cognom, String usuari, int contrasenya, int edat, String rol) {
this.nom = nom;
this.cognom = cognom;
this.usuari = usuari;
this.contrasenya = contrasenya;
this.edat = edat;
this.rol = rol;
this.numRegistrats++;
}
public Usuari(String usuari, int contrasenya) {
this.usuari = usuari;
this.contrasenya = contrasenya;
}
public String getRol() {
return this.rol;
}
public void ferAdministrador() {
this.rol = "administrador";
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getCognom() {
return cognom;
}
public void setCognom(String cognom) {
this.cognom = cognom;
}
public String getUsuari() {
return usuari;
}
public void setUsuari(String usuari) {
this.usuari = usuari;
}
public int getContrasenya() {
return contrasenya;
}
public void setContrasenya(int contrasenya) {
this.contrasenya = contrasenya;
}
public int getEdat() {
return edat;
}
public void setEdat(int edat) {
this.edat = edat;
}
public static int getNumRegistrats() {
return numRegistrats;
}
public static void setNumRegistrats(int numRegistrats) {
Usuari.numRegistrats = numRegistrats;
}
}
|
/*
* 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 studypoint3.examen2;
import Facade.Logic;
import entity.Employee;
import entity.PhdStudent;
import entity.Student;
import java.util.Date;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* @author RolfMoikjær
*/
public class StudyPoint3Examen2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Persistence.generateSchema("StudyPoint3.examen2PU", null);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudyPoint3.examen2PU");
try (Logic logic = new Logic(emf)) {
Student student = new Student();
student.setMatDate(new Date());
student.setMatNr(12);
student.setFirstName("Rolf");
logic.add(student);
Employee employee = new Employee();
employee.setFirstName("Bjarke");
employee.setSoSecNr(123);
logic.add(employee);
PhdStudent phdStudent = new PhdStudent();
phdStudent.setDissSubject("sdgsgfdgfd");
phdStudent.setLastName("ronald");
logic.add(phdStudent);
}
try(Logic logic = new Logic(emf)){
Student student = logic.find(Student.class, 1);
System.out.println(student.getFirstName());
}
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.expression.spel;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Supplier;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Operation;
import org.springframework.expression.OperatorOverloader;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypeComparator;
import org.springframework.expression.TypeConverter;
import org.springframework.expression.TypedValue;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* ExpressionState is for maintaining per-expression-evaluation state: any changes to
* it are not seen by other expressions, but it gives a place to hold local variables and
* for component expressions in a compound expression to communicate state. This is in
* contrast to the EvaluationContext, which is shared amongst expression evaluations, and
* any changes to it will be seen by other expressions or any code that chooses to ask
* questions of the context.
*
* <p>It also acts as a place to define common utility routines that the various AST
* nodes might need.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.0
*/
public class ExpressionState {
private final EvaluationContext relatedContext;
private final TypedValue rootObject;
private final SpelParserConfiguration configuration;
@Nullable
private Deque<TypedValue> contextObjects;
@Nullable
private Deque<VariableScope> variableScopes;
// When entering a new scope there is a new base object which should be used
// for '#this' references (or to act as a target for unqualified references).
// This ArrayDeque captures those objects at each nested scope level.
// For example:
// #list1.?[#list2.contains(#this)]
// On entering the selection we enter a new scope, and #this is now the
// element from list1
@Nullable
private ArrayDeque<TypedValue> scopeRootObjects;
public ExpressionState(EvaluationContext context) {
this(context, context.getRootObject(), new SpelParserConfiguration(false, false));
}
public ExpressionState(EvaluationContext context, SpelParserConfiguration configuration) {
this(context, context.getRootObject(), configuration);
}
public ExpressionState(EvaluationContext context, TypedValue rootObject) {
this(context, rootObject, new SpelParserConfiguration(false, false));
}
public ExpressionState(EvaluationContext context, TypedValue rootObject, SpelParserConfiguration configuration) {
Assert.notNull(context, "EvaluationContext must not be null");
Assert.notNull(configuration, "SpelParserConfiguration must not be null");
this.relatedContext = context;
this.rootObject = rootObject;
this.configuration = configuration;
}
/**
* The active context object is what unqualified references to properties/etc are resolved against.
*/
public TypedValue getActiveContextObject() {
if (CollectionUtils.isEmpty(this.contextObjects)) {
return this.rootObject;
}
return this.contextObjects.element();
}
public void pushActiveContextObject(TypedValue obj) {
if (this.contextObjects == null) {
this.contextObjects = new ArrayDeque<>();
}
this.contextObjects.push(obj);
}
public void popActiveContextObject() {
if (this.contextObjects == null) {
this.contextObjects = new ArrayDeque<>();
}
try {
this.contextObjects.pop();
}
catch (NoSuchElementException ex) {
throw new IllegalStateException("Cannot pop active context object: stack is empty");
}
}
public TypedValue getRootContextObject() {
return this.rootObject;
}
public TypedValue getScopeRootContextObject() {
if (CollectionUtils.isEmpty(this.scopeRootObjects)) {
return this.rootObject;
}
return this.scopeRootObjects.element();
}
/**
* Assign the value created by the specified {@link Supplier} to a named variable
* within the evaluation context.
* <p>In contrast to {@link #setVariable(String, Object)}, this method should
* only be invoked to support assignment within an expression.
* @param name the name of the variable to assign
* @param valueSupplier the supplier of the value to be assigned to the variable
* @return a {@link TypedValue} wrapping the assigned value
* @since 5.2.24
* @see EvaluationContext#assignVariable(String, Supplier)
*/
public TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
return this.relatedContext.assignVariable(name, valueSupplier);
}
/**
* Set a named variable in the evaluation context to a specified value.
* <p>In contrast to {@link #assignVariable(String, Supplier)}, this method
* should only be invoked programmatically.
* @param name the name of the variable to set
* @param value the value to be placed in the variable
* @see EvaluationContext#setVariable(String, Object)
*/
public void setVariable(String name, @Nullable Object value) {
this.relatedContext.setVariable(name, value);
}
public TypedValue lookupVariable(String name) {
Object value = this.relatedContext.lookupVariable(name);
return (value != null ? new TypedValue(value) : TypedValue.NULL);
}
public TypeComparator getTypeComparator() {
return this.relatedContext.getTypeComparator();
}
public Class<?> findType(String type) throws EvaluationException {
return this.relatedContext.getTypeLocator().findType(type);
}
public Object convertValue(Object value, TypeDescriptor targetTypeDescriptor) throws EvaluationException {
Object result = this.relatedContext.getTypeConverter().convertValue(
value, TypeDescriptor.forObject(value), targetTypeDescriptor);
if (result == null) {
throw new IllegalStateException("Null conversion result for value [" + value + "]");
}
return result;
}
public TypeConverter getTypeConverter() {
return this.relatedContext.getTypeConverter();
}
@Nullable
public Object convertValue(TypedValue value, TypeDescriptor targetTypeDescriptor) throws EvaluationException {
Object val = value.getValue();
return this.relatedContext.getTypeConverter().convertValue(
val, TypeDescriptor.forObject(val), targetTypeDescriptor);
}
/*
* A new scope is entered when a function is invoked.
*/
public void enterScope(Map<String, Object> argMap) {
initVariableScopes().push(new VariableScope(argMap));
initScopeRootObjects().push(getActiveContextObject());
}
public void enterScope() {
initVariableScopes().push(new VariableScope(Collections.emptyMap()));
initScopeRootObjects().push(getActiveContextObject());
}
public void enterScope(String name, Object value) {
initVariableScopes().push(new VariableScope(name, value));
initScopeRootObjects().push(getActiveContextObject());
}
public void exitScope() {
initVariableScopes().pop();
initScopeRootObjects().pop();
}
public void setLocalVariable(String name, Object value) {
initVariableScopes().element().setVariable(name, value);
}
@Nullable
public Object lookupLocalVariable(String name) {
for (VariableScope scope : initVariableScopes()) {
if (scope.definesVariable(name)) {
return scope.lookupVariable(name);
}
}
return null;
}
private Deque<VariableScope> initVariableScopes() {
if (this.variableScopes == null) {
this.variableScopes = new ArrayDeque<>();
// top-level empty variable scope
this.variableScopes.add(new VariableScope());
}
return this.variableScopes;
}
private Deque<TypedValue> initScopeRootObjects() {
if (this.scopeRootObjects == null) {
this.scopeRootObjects = new ArrayDeque<>();
}
return this.scopeRootObjects;
}
public TypedValue operate(Operation op, @Nullable Object left, @Nullable Object right) throws EvaluationException {
OperatorOverloader overloader = this.relatedContext.getOperatorOverloader();
if (overloader.overridesOperation(op, left, right)) {
Object returnValue = overloader.operate(op, left, right);
return new TypedValue(returnValue);
}
else {
String leftType = (left == null ? "null" : left.getClass().getName());
String rightType = (right == null? "null" : right.getClass().getName());
throw new SpelEvaluationException(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES, op, leftType, rightType);
}
}
public List<PropertyAccessor> getPropertyAccessors() {
return this.relatedContext.getPropertyAccessors();
}
public EvaluationContext getEvaluationContext() {
return this.relatedContext;
}
public SpelParserConfiguration getConfiguration() {
return this.configuration;
}
/**
* A new scope is entered when a function is called and it is used to hold the
* parameters to the function call. If the names of the parameters clash with
* those in a higher level scope, those in the higher level scope will not be
* accessible whilst the function is executing. When the function returns,
* the scope is exited.
*/
private static class VariableScope {
private final Map<String, Object> vars = new HashMap<>();
public VariableScope() {
}
public VariableScope(@Nullable Map<String, Object> arguments) {
if (arguments != null) {
this.vars.putAll(arguments);
}
}
public VariableScope(String name, Object value) {
this.vars.put(name,value);
}
public Object lookupVariable(String name) {
return this.vars.get(name);
}
public void setVariable(String name, Object value) {
this.vars.put(name,value);
}
public boolean definesVariable(String name) {
return this.vars.containsKey(name);
}
}
}
|
package com.gsccs.sme.api.domain;
import java.util.Date;
import java.util.List;
import com.gsccs.sme.api.domain.base.Domain;
import com.gsccs.sme.api.domain.shop.PropValue;
/**
* 商品属性
* @author x.d zhang
*
*/
public class ItemProp extends Domain {
private static final long serialVersionUID = 3145493243855193151L;
/**
* 子属性的模板(卖家自行输入属性时需要用到)
*/
private String childTemplate;
/**
* 类目ID
*/
private Long cid;
/**
* 是否允许别名。可选值:true(是),false(否)
*/
private Boolean isAllowAlias;
/**
* 是否颜色属性。可选值:true(是),false(否)
*/
private Boolean isColorProp;
/**
* 是否是可枚举属性。可选值:true(是),false(否)
*/
private Boolean isEnumProp;
/**
* 在is_enum_prop是true的前提下,是否是卖家可以自行输入的属性(注:如果is_enum_prop返回false,该参数统一返回false)。可选值:true(是),false(否)。<b>对于品牌和型号属性(包括子属性):如果用户是C卖家,则可自定义属性;如果是B卖家,则不可自定义属性,而必须要授权的属性。</b>
*/
private Boolean isInputProp;
/**
* 是否商品属性。可选值:true(是),false(否)
*/
private Boolean isItemProp;
/**
* 是否关键属性。可选值:true(是),false(否)
*/
private Boolean isKeyProp;
/**
* 是否销售属性。可选值:true(是),false(否)
*/
private Boolean isSaleProp;
/**
* 是否度量衡属性项
*/
private Boolean isTaosir;
/**
* 属性修改时间(增量类目专用)
*/
private Date modifiedTime;
/**
* 三种枚举类型:modify,add,delete(增量类目专用)
*/
private String modifiedType;
/**
* 发布产品或商品时是否可以多选。可选值:true(是),false(否)
*/
private Boolean multi;
/**
* 发布产品或商品时是否为必选属性。可选值:true(是),false(否)
*/
private Boolean must;
/**
* 属性名
*/
private String name;
/**
* 上级属性ID
*/
private Long parentPid;
/**
* 上级属性值ID
*/
private Long parentVid;
/**
* 属性 ID 例:品牌的PID=20000
*/
private Long pid;
/**
* null
*/
private List<PropValue> propValues;
/**
* 发布产品或商品时是否为必选属性(与must相同)。可选值:true(是),false(否)
*/
private Boolean required;
/**
* 排列序号。取值范围:大于零的整排列序号。取值范围:大于零的整数
*/
private Long sortOrder;
/**
* 状态。可选值:normal(正常),deleted(删除)
*/
private String status;
/**
* 属性值类型。可选值:
multiCheck(枚举多选)
optional(枚举单选)
multiCheckText(枚举可输入多选)
optionalText(枚举可输入单选)
text(非枚举可输入)
*/
private String type;
}
|
package bfs;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* 宝岛探险
* 注意: 0代表海洋,1~9代表陆地,求落地时面积
*
* @author 丹丘生
*/
public class BFS_6 {
private static int[][] map;
private static int[][] book;
private static Queue<Node> queue = new LinkedList<Node>();
static int startx;
static int starty;
static int n;
static int m;
static int count = 0;
private static int[][] direction = {
{0, -1},
{1, 0},
{0, 1},
{-1, 0}
};
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
// 输入行列
n = read.nextInt();
m = read.nextInt();
// 落地点
startx = read.nextInt();
starty = read.nextInt();
map = new int[n][m];
book = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = read.nextInt();
}
}
Node start = new Node(startx, starty);
queue.add(start);
book[startx][starty] = 1;
count = 1;
Node head;
while ((head = queue.poll()) != null) {
for (int index = 0; index < 4; index++) {
int tx = head.x + direction[index][0];
int ty = head.y + direction[index][1];
if (tx < 0 || ty < 0 || tx >= n || ty >= m) // 判断是否越界
continue;
if (map[tx][ty] > 0 && book[tx][ty] == 0) {
count++;
Node next = new Node(tx, ty);
book[tx][ty] = 1;
queue.add(next);
}
}
}
System.out.println(count);
}
static class Node {
int x;
int y;
public Node() {
}
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
}
}
|
package com.soldevelo.vmi.scheduler.model;
import com.soldevelo.vmi.xml.DateTimeAdapter;
import org.joda.time.DateTime;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name = "nodeInfo")
public class NodeInfo {
private String address;
private DateTime dateRegistered;
private String uptime;
private Boolean httpEnabled;
private Boolean udpEchoPlusEnabled;
@XmlElement
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@XmlElement
@XmlJavaTypeAdapter(DateTimeAdapter.class)
public DateTime getDateRegistered() {
return dateRegistered;
}
public void setDateRegistered(DateTime dateRegistered) {
this.dateRegistered = dateRegistered;
}
@XmlElement
public String getUptime() {
return uptime;
}
public void setUptime(String uptime) {
this.uptime = uptime;
}
@XmlElement
public Boolean getHttpEnabled() {
return httpEnabled;
}
public void setHttpEnabled(Boolean httpEnabled) {
this.httpEnabled = httpEnabled;
}
@XmlElement
public Boolean getUdpEchoPlusEnabled() {
return udpEchoPlusEnabled;
}
public void setUdpEchoPlusEnabled(Boolean udpEchoPlusEnabled) {
this.udpEchoPlusEnabled = udpEchoPlusEnabled;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.