text
stringlengths 10
2.72M
|
|---|
package com.rms.risproject.conf;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource(locations={"classpath:spring/spring-*.xml"})
public class XmlBeanConfig {
}
|
package com.todo.persistence.query;
import com.todo.model.User;
import com.todo.persistence.entity.TodoEntity;
import com.todo.persistence.entity.UserEntity;
import com.todo.persistence.repository.UserRepository;
import com.todo.util.EntityConverter;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Optional;
public class UserQuery {
@Autowired
private EntityConverter entityConverter;
@Autowired
private UserRepository userRepository;
public Optional<User> findByUsername(String username) {
final UserEntity userEntity = userRepository.findByUsername(username);
if (userEntity == null) {
return Optional.empty();
}
return Optional.of(entityConverter.convert(userEntity));
}
public Optional<User> findByUsernameAndPassword(final String username, final String password) {
final UserEntity userEntity = userRepository.findByUsernameAndPassword(username, password);
if (userEntity == null) {
return Optional.empty();
}
return Optional.of(entityConverter.convert(userEntity));
}
}
|
package cn.zhoudbw.mapper;
import cn.zhoudbw.model.Employee;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author zhoudbw
* 使用mybatis整合,就需要dao层的支持了
* @Repository 声明该类是DAO层
* <p>
* 由于是mybatis的整合,所以dao层命名为mapper。实际上是一样的。
*/
//@Repository
//public class EmployeeMapper {
//
// /**
// * 查询全部
// * @return 返回存有所有Employee的列表
// */
// public List<Employee> employeeList() {
// return null;
// }
//}
/**
* @author zhoudbw
* 现在这个方法整个就变化了,利用 @Mapper声明,变成接口,没有具体的方法实现
*
* @Mapper
* 1. 在启动类中使用@MapperScan("mapper接口所在包全名")即可,不用一个一个的在Mapper接口中加@Mapper注解。
* 2. @Mapper注解声明该接口是mybatis的mapper接口,能够自动的把加@Mapper注解的接口生成动态代理类。
* 3. 让springboot认识你的mapper层,也可以在启动类上面加MapperScan("mapper层所在包的全名")
* 4. 不用写Mapper映射文件(XML)
*/
@Mapper
public interface EmployeeMapper {
/**
* 查询全部
* @Select 该注解是为了取代EmployeeMapper.xml中的<select></>标签的
* 通过 @Mapper @Select 就可以不用写EmployeeMapper.xml了。
* @return 返回存有所有Employee的列表
*/
@Select("SELECT id, name, job, birthday, sex FROM employee")
List<Employee> employeeList();
}
|
package com.tencent.mm.plugin.expt;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.kernel.api.c;
import com.tencent.mm.kernel.b.f;
import com.tencent.mm.kernel.b.g;
import com.tencent.mm.kernel.e;
import com.tencent.mm.platformtools.u;
import com.tencent.mm.platformtools.u.a;
import com.tencent.mm.plugin.expt.roomexpt.b;
import com.tencent.mm.plugin.messenger.foundation.a.o;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
public class PluginExpt extends f implements c, a {
private static HashMap<Integer, d> hsC;
private a hsE;
static {
HashMap hashMap = new HashMap();
hsC = hashMap;
hashMap.put(Integer.valueOf("EXPT_TABLE".hashCode()), new 1());
hsC.put(Integer.valueOf("EXPT_KEY_MAP_ID_TABLE".hashCode()), new 2());
hsC.put(Integer.valueOf("CHATROOM_MUTE_EXPT_TABLE".hashCode()), new 3());
}
public void installed() {
alias(a.class);
}
public void dependency() {
dependsOn(o.class);
}
public void execute(g gVar) {
com.tencent.mm.kernel.g.a(com.tencent.mm.plugin.expt.a.a.class, com.tencent.mm.plugin.expt.b.a.aIu());
com.tencent.mm.kernel.g.a(com.tencent.mm.plugin.expt.roomexpt.d.class, com.tencent.mm.plugin.expt.roomexpt.a.aIx());
}
public String toString() {
return "plugin-expt";
}
public void onAccountInitialized(e.c cVar) {
boolean z = false;
x.i("MicroMsg.PluginExpt", "Plugin expt onAccountInitialized [%d] [%d]", new Object[]{Integer.valueOf(hashCode()), Integer.valueOf(com.tencent.mm.plugin.expt.b.a.aIu().hashCode())});
initDB();
com.tencent.mm.plugin.expt.b.a aIu = com.tencent.mm.plugin.expt.b.a.aIu();
a aVar = this.hsE;
String str = "MicroMsg.ExptService";
String str2 = "reset DB [%d] dataDB[%b]";
Object[] objArr = new Object[2];
objArr[0] = Integer.valueOf(aIu.hashCode());
if (aVar != null) {
z = true;
}
objArr[1] = Boolean.valueOf(z);
x.i(str, str2, objArr);
if (aVar != null) {
aIu.iHQ = new com.tencent.mm.plugin.expt.c.d(aVar);
aIu.iHR = new com.tencent.mm.plugin.expt.c.c(aVar);
}
com.tencent.mm.plugin.expt.roomexpt.a.aIx().iIl = new b(this.hsE);
}
public void onAccountRelease() {
x.i("MicroMsg.PluginExpt", "Plugin expt onAccountRelease [%d] [%d]", new Object[]{Integer.valueOf(hashCode()), Integer.valueOf(com.tencent.mm.plugin.expt.b.a.aIu().hashCode())});
closeDB();
}
private void initDB() {
if (this.hsE != null) {
closeDB();
}
this.hsE = u.a(hashCode(), com.tencent.mm.kernel.g.Ei().cachePath + "WxExpt.db", hsC, true);
}
private void closeDB() {
if (this.hsE != null) {
this.hsE.iQ(hashCode());
}
this.hsE = null;
}
}
|
package pages.header;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.SelenideElement;
import pages.login.LoginPageObject;
import pages.signup.SignupPageObject;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.page;
public class NavigationPageObject {
// page elements
private SelenideElement getMyAccountButton() {
return $("test");
}
private SelenideElement getSignupButton() {
return $("test");
}
private SelenideElement getLoginButton() {
return $("test");
}
// Landing page action methods
public void selectMyAccountButton() {
getMyAccountButton().click();
}
public SignupPageObject selectSignupButton() {
getSignupButton().click();
return page(SignupPageObject.class);
}
public LoginPageObject selectLoginButton() {
getLoginButton().click();
return page(LoginPageObject.class);
}
public void visibleMyAccountButton() {
getMyAccountButton().shouldBe(Condition.visible);
}
}
|
package com.bowlong.concurrent.async;
import java.sql.ResultSet;
import java.util.concurrent.Callable;
public abstract class CallableForResultSet implements Callable<ResultSet> {
@Override
public ResultSet call() throws Exception {
try {
return exec();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public abstract ResultSet exec() throws Exception;
}
|
package com.semantyca.officeframe.modules.organizations.model;
import com.semantyca.nb.core.dataengine.jpa.model.SimpleReferenceEntity;
import com.semantyca.nb.core.user.IUser;
import com.semantyca.nb.modules.administrator.model.User;
import com.semantyca.officeframe.modules.organizations.init.ModuleConst;
import com.semantyca.officeframe.modules.organizations.model.constants.RoleType;
import com.semantyca.officeframe.modules.reference.model.Position;
import org.eclipse.persistence.annotations.Cache;
import org.eclipse.persistence.annotations.Convert;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = ModuleConst.CODE + "__employees", uniqueConstraints = {@UniqueConstraint(columnNames = {"identifier", "organization_id"}),
@UniqueConstraint(columnNames = {"user_id", "organization_id"})})
@Cache(refreshOnlyIfNewer = true)
public class Employee extends SimpleReferenceEntity {
@OneToOne(cascade = {CascadeType.DETACH}, optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "birth_date")
private Date birthDate;
private String iin = "";
private String phone;
@NotNull
@ManyToOne(optional = true)
@JoinColumn(nullable = false)
private Organization organization;
@Convert("dep_conv")
@Basic(fetch = FetchType.LAZY, optional = true)
private Department department;
@Convert("emp_conv")
@Basic(fetch = FetchType.LAZY, optional = true)
private Employee boss;
@ManyToOne(optional = true)
@JoinColumn(nullable = false)
private Position position;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = ModuleConst.CODE + "__employee_role")
private List<Role> roles;
private int rank = 999;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Employee getBoss() {
return boss;
}
public void setBoss(Employee boss) {
this.boss = boss;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getIin() {
return iin;
}
public void setIin(String iin) {
this.iin = iin;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public IUser getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public void addRole(Role r) {
if (roles == null) {
roles = new ArrayList<>();
}
roles.add(r);
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public List<String> getAllRoles() {
List<String> list = new ArrayList<>();
if (roles == null) {
return list;
}
for (Role r : roles) {
list.add(r.getName());
}
return list;
}
public boolean hasRole(String roleName) {
if (roles == null) {
return false;
}
for (Role role : roles) {
if (role.getName().equals(roleName)) {
return true;
}
}
return false;
}
public boolean isFired() {
if (roles == null) {
return false;
}
for (Role role : roles) {
if (role.getName().equals(RoleType.FIRED)) {
return true;
}
}
return false;
}
}
|
package com.prashanth.sunvalley.service;
import com.prashanth.sunvalley.Model.GradeDTO;
import com.prashanth.sunvalley.Model.StudentDTO;
import com.prashanth.sunvalley.domain.Grade;
import java.util.List;
public interface GradeService {
List<GradeDTO> getAllGrades();
GradeDTO getGradeById(Long id);
GradeDTO createGrade(GradeDTO gradeDTO);
GradeDTO updateGrade(Long id, GradeDTO gradeDTO);
void deleteGrade(Long id);
List<StudentDTO> getAllStudentsOfGrade(Long id);
}
|
package yao.bean;
public class WordMeaning
{
private int wordMeaningID;
private int wordID;
private int meaningID;
private String wordname;
private String meaningName;
private String englishwordName;
private String languageName;
public WordMeaning()
{
}
public int getWordMeaningID() {
return wordMeaningID;
}
public void setWordMeaningID(int wordMeaningID) {
this.wordMeaningID = wordMeaningID;
}
public int getWordID() {
return wordID;
}
public void setWordID(int wordID) {
this.wordID = wordID;
}
public String getWordName() {
return wordname;
}
public void setWordName(String wordName) {
this.wordname = wordName;
}
public int getMeaningID() {
return meaningID;
}
public void setMeaningID(int meaningID) {
this.meaningID = meaningID;
}
public String getMeaningName() {
return meaningName;
}
public void setMeaningName(String meaningName) {
this.meaningName = meaningName;
}
public String getEnglishWordName() {
return englishwordName;
}
public void setEnglishWordName(String englishWordName) {
this.englishwordName = englishWordName;
}
public String getlanguageName() {
return languageName;
}
public void setLanguageName(String languageName) {
this.languageName = languageName;
}
}
|
package com.tencent.mm.ui.chatting.g;
import android.database.Cursor;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.messenger.foundation.a.i;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.bd;
import com.tencent.mm.storage.u;
import com.tencent.mm.ui.chatting.a.b;
import com.tencent.mm.y.g.a;
import java.util.Date;
import java.util.LinkedList;
class d$1 implements Runnable {
final /* synthetic */ boolean tXV = true;
final /* synthetic */ d tYl;
d$1(d dVar) {
this.tYl = dVar;
}
public final void run() {
Object linkedList = new LinkedList();
au.HU();
Cursor bA = c.FT().bA(this.tYl.gBf, this.tYl.gBh);
if (bA == null) {
x.e("MicroMsg.FileHistoryListPresenter", "[loadData] cursor is null!");
return;
}
u ih;
if (s.fq(this.tYl.gBf)) {
au.HU();
ih = c.Ga().ih(this.tYl.gBf);
} else {
ih = null;
}
long j = 0;
while (bA.moveToNext()) {
try {
bd bdVar = new bd();
bdVar.d(bA);
String str = bdVar.field_content;
if (str != null) {
a gp = a.gp(str);
if ((6 == gp.type ? 1 : null) != null) {
long b = com.tencent.mm.ui.gridviewheaders.a.czj().b(new Date(bdVar.field_createTime));
if (j != b) {
linkedList.add(new b.c(bdVar.field_createTime));
d dVar = this.tYl;
dVar.tYk++;
}
String i = d.i(bdVar, s.fq(this.tYl.gBf));
ab Yg = ((i) g.l(i.class)).FR().Yg(i);
String str2 = "";
if (ih != null) {
str2 = ih.gT(i);
}
int Bx = com.tencent.mm.plugin.fav.ui.c.Bx(gp.dwp);
d$a d_a = new d$a(this.tYl, bdVar.field_createTime, gp.type, gp.title, bdVar.field_msgId, Yg.field_username, Yg.BK(), Yg.field_conRemark, str2);
d_a.iconRes = Bx;
d_a.desc = bi.bF((long) gp.dwo);
linkedList.add(d_a);
j = b;
}
}
} finally {
bA.close();
}
}
this.tYl.gBc.addAll(linkedList);
this.tYl.tYc = this.tYl.gBc;
linkedList.clear();
x.i("MicroMsg.FileHistoryListPresenter", "[loadData] data:%s", new Object[]{Integer.valueOf(this.tYl.gBc.size())});
ah.A(new 1(this));
}
}
|
package com.tencent.mm.g.c;
import android.content.ContentValues;
import android.database.Cursor;
import com.tencent.mm.sdk.e.c;
public abstract class fe extends c {
private static final int cVE = "RecordId".hashCode();
private static final int cVF = "AppId".hashCode();
private static final int cVG = "AppName".hashCode();
private static final int cVH = "UserName".hashCode();
private static final int cVI = "IconUrl".hashCode();
private static final int cVJ = "BriefIntro".hashCode();
private static final int cVK = "isSync".hashCode();
public static final String[] ciG = new String[0];
private static final int ciP = "rowid".hashCode();
private static final int ckb = "createTime".hashCode();
private static final int clG = "debugType".hashCode();
private boolean cVA = true;
private boolean cVB = true;
private boolean cVC = true;
private boolean cVD = true;
private boolean cVx = true;
private boolean cVy = true;
private boolean cVz = true;
private boolean cjF = true;
private boolean clA = true;
public String field_AppId;
public String field_AppName;
public String field_BriefIntro;
public String field_IconUrl;
public String field_RecordId;
public String field_UserName;
public long field_createTime;
public int field_debugType;
public boolean field_isSync;
public final void d(Cursor cursor) {
String[] columnNames = cursor.getColumnNames();
if (columnNames != null) {
int length = columnNames.length;
for (int i = 0; i < length; i++) {
int hashCode = columnNames[i].hashCode();
if (cVE == hashCode) {
this.field_RecordId = cursor.getString(i);
this.cVx = true;
} else if (cVF == hashCode) {
this.field_AppId = cursor.getString(i);
} else if (cVG == hashCode) {
this.field_AppName = cursor.getString(i);
} else if (cVH == hashCode) {
this.field_UserName = cursor.getString(i);
} else if (cVI == hashCode) {
this.field_IconUrl = cursor.getString(i);
} else if (cVJ == hashCode) {
this.field_BriefIntro = cursor.getString(i);
} else if (cVK == hashCode) {
this.field_isSync = cursor.getInt(i) != 0;
} else if (clG == hashCode) {
this.field_debugType = cursor.getInt(i);
} else if (ckb == hashCode) {
this.field_createTime = cursor.getLong(i);
} else if (ciP == hashCode) {
this.sKx = cursor.getLong(i);
}
}
}
}
public final ContentValues wH() {
ContentValues contentValues = new ContentValues();
if (this.cVx) {
contentValues.put("RecordId", this.field_RecordId);
}
if (this.cVy) {
contentValues.put("AppId", this.field_AppId);
}
if (this.cVz) {
contentValues.put("AppName", this.field_AppName);
}
if (this.cVA) {
contentValues.put("UserName", this.field_UserName);
}
if (this.cVB) {
contentValues.put("IconUrl", this.field_IconUrl);
}
if (this.cVC) {
contentValues.put("BriefIntro", this.field_BriefIntro);
}
if (this.cVD) {
contentValues.put("isSync", Boolean.valueOf(this.field_isSync));
}
if (this.clA) {
contentValues.put("debugType", Integer.valueOf(this.field_debugType));
}
if (this.cjF) {
contentValues.put("createTime", Long.valueOf(this.field_createTime));
}
if (this.sKx > 0) {
contentValues.put("rowid", Long.valueOf(this.sKx));
}
return contentValues;
}
}
|
package com.scf.skyware.calendar.service;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scf.skyware.calendar.dao.CalendarDAO;
import com.scf.skyware.calendar.domain.Calendar_temp;
@Service
public class CalendarServiceImpl implements CalendarService {
@Autowired
private CalendarDAO calendarDAO;
// 캘린더 리스트
@Override
public ArrayList<Calendar_temp> calendarList() {
ArrayList<Calendar_temp> calendarList = calendarDAO.calendarList();
return calendarList;
}
}
|
package com.sinotao.business.dao.entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "t_clinicar_item")
public class ClinicarItem {
/**
* 检查项目编号
*/
@Id
private String code;
/**
* 检查项目名称
*/
private String name;
/**
* 是否启用
*/
private Boolean enabled;
/**
* 科室编号
*/
@Column(name = "dpt_code")
private String dptCode;
/**
* 科室
*/
@Column(name = "dpt_name")
private String dptName;
/**
* 备注
*/
private String remark;
/**
* 检查设备编号,用于接口对接
*/
@Column(name = "device_code")
private String deviceCode;
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the enabled
*/
public Boolean getEnabled() {
return enabled;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
/**
* @return the dptCode
*/
public String getDptCode() {
return dptCode;
}
/**
* @param dptCode the dptCode to set
*/
public void setDptCode(String dptCode) {
this.dptCode = dptCode;
}
/**
* @return the dptName
*/
public String getDptName() {
return dptName;
}
/**
* @param dptName the dptName to set
*/
public void setDptName(String dptName) {
this.dptName = dptName;
}
/**
* @return the remark
*/
public String getRemark() {
return remark;
}
/**
* @param remark the remark to set
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* @return the deviceCode
*/
public String getDeviceCode() {
return deviceCode;
}
/**
* @param deviceCode the deviceCode to set
*/
public void setDeviceCode(String deviceCode) {
this.deviceCode = deviceCode;
}
}
|
package br.inf.ufg.mddsm.broker.state;
/**
* Created by IntelliJ IDEA.
* User: gustavo
* Date: Aug 3, 2012
* Time: 5:29:30 PM
* To change this template use File | Settings | File Templates.
*/
public interface StateChangeListener {
void registerCreated(StateHolder register);
void registerDestroyed(StateHolder register);
void registerChanged(StateHolder register, String[] properties);
}
|
package orionlofty.com.apps.gadspracticeproject;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import orionlofty.com.apps.gadspracticeproject.adapters.LearningLeadersRecyclerviewAdapter;
import orionlofty.com.apps.gadspracticeproject.model.LearningLeaders;
import orionlofty.com.apps.gadspracticeproject.services.LeadersService;
import orionlofty.com.apps.gadspracticeproject.services.ServiceBuilder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LearningLeadersFragment extends Fragment{
private static final String TAG = "LearningLeadersFragment";
private RecyclerView recyclerView;
Context context;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_learning_leaders, container, false);
recyclerView = view.findViewById(R.id.learning_leaders_rv);
initRecyclerView();
setupRetrofit();
return view;
}
private void initRecyclerView(){
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void setupRetrofit(){
LeadersService leadersService = ServiceBuilder.buildService(LeadersService.class);
Call<List<LearningLeaders>> call = leadersService.getLearningLeaders();
call.enqueue(new Callback<List<LearningLeaders>>() {
@Override
public void onResponse(Call<List<LearningLeaders>> call, Response<List<LearningLeaders>> response) {
Log.d(TAG, "onResponse: Server response "+ response.toString());
recyclerView.setAdapter(new LearningLeadersRecyclerviewAdapter(context, response.body()));
}
@Override
public void onFailure(Call<List<LearningLeaders>> call, Throwable t) {
Log.d(TAG, "onFailure: Unable to retrieve");
Toast.makeText(getContext(), "Unable to retrieve data", Toast.LENGTH_SHORT).show();
}
});
}
}
|
package de.jmda9.core.util.xml.jaxb;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.validation.SchemaFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* TODO add sanity checks (completeness, unmodifiable, ...)
* TODO add dynamic context configuration ...
*
* @author ruu@jmda.de
*/
public class ConfigUtil
{
private final static Logger LOGGER = LogManager.getLogger(ConfigUtil.class);
/**
* Information for namespace - schemafile and namespace - prefix mappings.
*/
public static class NamespaceInfo
{
private final String namespaceURI;
private final String schemaFilename;
private final String namespacePrefix;
public NamespaceInfo(
String namespaceURI, String schemaFilename, String namespacePrefix)
{
super();
this.namespaceURI = namespaceURI;
this.schemaFilename = schemaFilename;
this.namespacePrefix = namespacePrefix;
}
public String getNamespaceURI()
{
return namespaceURI;
}
public String getSchemaFilename()
{
return schemaFilename;
}
public String getNamespacePrefix()
{
return namespacePrefix;
}
}
// /**
// * Information for namespace - prefix mapper, can be used to specify namespace
// * prefix mapper values for {@link Marshaller#setProperty(String, Object)}.
// */
// public static class NamespacePrefixMapperInfo
// {
// public final static String NAMESPACE_PREFIX_MAPPER_KEY_JAXB_IMPL_JDK =
// "com.sun.xml.internal.bind.namespacePrefixMapper";
// public final static String NAMESPACE_PREFIX_MAPPER_KEY_JAXB_IMPL_RI =
// "com.sun.xml.bind.namespacePrefixMapper";
//
// private NamespacePrefixMapper namespacePrefixMapper;
//
// /**
// * Initialises {@link #namespacePrefixMapper} with {@link
// * NamespacePrefixMapperInternal} using <code>map</code>.
// *
// * @param map
// */
// public NamespacePrefixMapperInfo(Map<String, String> map)
// {
// namespacePrefixMapper = new NamespacePrefixMapperInternal(map);
// }
//
// public NamespacePrefixMapper getNamespacePrefixMapper()
// {
// return namespacePrefixMapper;
// }
// }
// private static class NamespacePrefixMapperInternal
// extends NamespacePrefixMapper
// {
// private final static Logger LOGGER =
// Logger.getLogger(NamespacePrefixMapperInternal.class);
//
// private Map<String, String> namespaceURIs_namespacePrefixes;
//
// private NamespacePrefixMapperInternal(
// Map<String, String> namespaceURIs_namespacePrefixes)
// {
// this.namespaceURIs_namespacePrefixes = namespaceURIs_namespacePrefixes;
// }
//
// @Override
// public String getPreferredPrefix(
// String namespaceURI, String suggestion, boolean required)
// {
// String result = namespaceURIs_namespacePrefixes.get(namespaceURI);
//
// LOGGER.debug(
// "namespaceURI [" + namespaceURI + "] " +
// "suggestion [" + suggestion + "] " +
// "required [" + required + "] " +
// "returning [" + result + "]");
//
// return result;
// }
//
// @Override
// public String[] getPreDeclaredNamespaceUris()
// {
// return namespaceURIs_namespacePrefixes.keySet().toArray(new String[] {});
// }
// }
private final Set<String> namespaceURIs = new HashSet<String>();
private final Map<String, String> namespaceURIs_schemaFilenames =
new HashMap<String, String>();
private final Map<String, String> namespaceURIs_namespacePrefix =
new HashMap<String, String>();
public void add(NamespaceInfo metadataItem)
{
namespaceURIs.add(metadataItem.namespaceURI);
namespaceURIs_schemaFilenames.put(metadataItem.namespaceURI, metadataItem.schemaFilename);
namespaceURIs_namespacePrefix.put(metadataItem.namespaceURI, metadataItem.namespacePrefix);
}
public String getSchemaFilenameForNamespaceURI(String namespaceURI)
{
return namespaceURIs_schemaFilenames.get(namespaceURI);
}
public String getNamespacePrefixForNamespaceURI(String namespaceURI)
{
return namespaceURIs_namespacePrefix.get(namespaceURI);
}
public String[] getNamespaceURIs()
{
return namespaceURIs.toArray(new String[] {});
}
public String[] getSchemaFilenames()
{
Set<String> result = new HashSet<String>();
result.addAll(namespaceURIs_schemaFilenames.values());
return result.toArray(new String[] {});
}
// public NamespacePrefixMapperInfo getNamespacePrefixMapperInfo()
// {
// return new NamespacePrefixMapperInfo(namespaceURIs_namespacePrefix);
// }
//
// public void activateNamespacePrefixMapping(Marshaller marshaller)
// {
// NamespacePrefixMapperInfo namespacePrefixMapperInfo =
// getNamespacePrefixMapperInfo();
//
// try
// {
// marshaller.setProperty(
// NamespacePrefixMapperInfo.NAMESPACE_PREFIX_MAPPER_KEY_JAXB_IMPL_JDK,
// namespacePrefixMapperInfo.getNamespacePrefixMapper());
// return;
// }
// catch (PropertyException e)
// {
// LOGGER.debug(
// "failure setting namespace prefix mapper property using key [" +
// NamespacePrefixMapperInfo.NAMESPACE_PREFIX_MAPPER_KEY_JAXB_IMPL_JDK +
// "]", e);
// }
//
// try
// {
// marshaller.setProperty(
// NamespacePrefixMapperInfo.NAMESPACE_PREFIX_MAPPER_KEY_JAXB_IMPL_RI,
// namespacePrefixMapperInfo.getNamespacePrefixMapper());
// return;
// }
// catch (PropertyException e)
// {
// LOGGER.debug(
// "failure setting namespace prefix mapper property using key [" +
// NamespacePrefixMapperInfo.NAMESPACE_PREFIX_MAPPER_KEY_JAXB_IMPL_RI +
// "]", e);
// }
//
// LOGGER.error("failure setting namespace prefix mapper property");
// }
public void activateFormattedOutput(Marshaller marshaller)
{
try
{
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
}
catch (PropertyException e)
{
LOGGER.error(
"failure setting " + Marshaller.JAXB_FORMATTED_OUTPUT + " property");
}
}
public static SchemaFactory getSchemaFactory()
{
return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
}
}
|
package crossing.preProcessor;
import bplusTree.BPlusTree;
import crossing.MatchingContext;
import crossing.MatchingUtil;
import data.ExecutionReportData;
import leafNode.OrderEntry;
import leafNode.OrderList;
import leafNode.OrderListCursor;
import orderBook.OrderBook;
import sbe.msg.ExecutionTypeEnum;
import sbe.msg.OrderCancelRequestEncoder;
import sbe.msg.OrderStatusEnum;
import java.util.Iterator;
public class CancelOrderPreProcessor implements MatchingPreProcessor {
@Override
public void preProcess(MatchingContext context) {
//context.getTemplateId() == OrderCancelRequestEncoder.TEMPLATE_ID
if(context.getOrderType() == null) {
MATCHING_ACTION action = process(context.getOrderBook(), context.getOrderEntry());
context.setAction(action);
}
}
private MATCHING_ACTION process(OrderBook orderBook,OrderEntry orderEntry) {
populateExecutionData(orderEntry);
boolean isParkedOrder = MatchingUtil.isParkedOrder(orderEntry);
OrderBook.SIDE side = OrderBook.getSide(orderEntry.getSide());
BPlusTree<Long, OrderList> tree = getTree(side,orderBook,orderEntry,isParkedOrder);
long price = orderEntry.getPrice();
OrderList orderList = tree.get(price);
if(orderList != null) {
Iterator<OrderListCursor> orderListIterator = orderList.iterator();
while (orderListIterator.hasNext()) {
//orderListIterator.next().value.getOrderId() == orderEntry.getOrderId()
if (orderListIterator.next().value.getClientOrderId() == orderEntry.getOrigClientOrderId()) {
orderListIterator.remove();
}
}
if (!isParkedOrder && orderList.total() == 0) {
orderBook.removePrice(price, side);
}
}
return MATCHING_ACTION.NO_ACTION;
}
private BPlusTree<Long, OrderList> getTree(OrderBook.SIDE side,OrderBook orderBook,OrderEntry orderEntry,boolean isParkedOrder){
if(isParkedOrder) {
if (side == OrderBook.SIDE.BID) {
return orderBook.getParkedBidTree();
} else {
return orderBook.getParkedOfferTree();
}
}else{
if (side == OrderBook.SIDE.BID) {
return orderBook.getBidTree();
} else {
return orderBook.getOfferTree();
}
}
}
private void populateExecutionData(OrderEntry orderEntry){
//UnsafeBuffer clientOrderId = new UnsafeBuffer(ByteBuffer.allocateDirect(OrderViewEncoder.clientOrderIdLength()));
// clientOrderId.wrap(BuilderUtil.fill(Long.toString(aggOrder.getClientOrderId()), OrderViewEncoder.clientOrderIdLength()).getBytes());
ExecutionReportData executionReportData = ExecutionReportData.INSTANCE;
executionReportData.setOrderId((int)orderEntry.getOrderId());
executionReportData.setExecutionType(ExecutionTypeEnum.Cancelled);
executionReportData.setOrderStatus(OrderStatusEnum.Cancelled);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package unalcol.types.collection.tree.bplus;
/**
* @author jgomez
*/
public interface BPlusInnerNode<T> extends BPlusNode<T> {
public BPlusInnerNode<T> newInstance(BPlusNode<T>[] nodes, int n);
// Next methods
public BPlusNode<T>[] next();
public BPlusNode<T> next(int i);
public boolean append(BPlusNode<T> key);
public boolean insert(int pos, BPlusNode<T> key);
public boolean remove(int pos);
public void set(int i, BPlusNode<T> key);
public BPlusLeafNode<T> mostLeft();
}
|
package customer;
public class Osterhase extends Hase {
public Osterhase(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void ostereier_verteilen()
{
System.out.println(this.getName() + " versteckt blaue Eier ...");
}
@Override
public void hoppeln() {
System.out.println(this.getName() + " hoppelt zum Eierfärben");
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.f;
import com.tencent.mm.plugin.appbrand.jsapi.h;
class i$b extends h {
private static final int CTRL_INDEX = 142;
private static final String NAME = "onMapMarkerClick";
private i$b() {
}
/* synthetic */ i$b(byte b) {
this();
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.ui.helper;
import static edu.tsinghua.lumaqq.models.ClusterType.*;
import static edu.tsinghua.lumaqq.resource.Messages.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.MessageBox;
import edu.tsinghua.lumaqq.LumaQQ;
import edu.tsinghua.lumaqq.MessageQueue;
import edu.tsinghua.lumaqq.ecore.group.GroupFactory;
import edu.tsinghua.lumaqq.ecore.group.XCluster;
import edu.tsinghua.lumaqq.ecore.group.XGroup;
import edu.tsinghua.lumaqq.ecore.group.XGroups;
import edu.tsinghua.lumaqq.ecore.group.XOrganization;
import edu.tsinghua.lumaqq.ecore.group.XUser;
import edu.tsinghua.lumaqq.ecore.remark.Remark;
import edu.tsinghua.lumaqq.eutil.GroupUtil;
import edu.tsinghua.lumaqq.models.Cluster;
import edu.tsinghua.lumaqq.models.ClusterType;
import edu.tsinghua.lumaqq.models.Dummy;
import edu.tsinghua.lumaqq.models.DummyType;
import edu.tsinghua.lumaqq.models.Group;
import edu.tsinghua.lumaqq.models.GroupType;
import edu.tsinghua.lumaqq.models.Model;
import edu.tsinghua.lumaqq.models.ModelRegistry;
import edu.tsinghua.lumaqq.models.ModelUtils;
import edu.tsinghua.lumaqq.models.Organization;
import edu.tsinghua.lumaqq.models.Status;
import edu.tsinghua.lumaqq.models.User;
import edu.tsinghua.lumaqq.qq.beans.DownloadFriendEntry;
import edu.tsinghua.lumaqq.resource.Resources;
import edu.tsinghua.lumaqq.ui.MainShell;
import edu.tsinghua.lumaqq.ui.ReceiveSystemMessageShell;
import edu.tsinghua.lumaqq.ui.dialogs.SelectGroupDialog;
import edu.tsinghua.lumaqq.ui.listener.ClusterDragSourceListener;
import edu.tsinghua.lumaqq.ui.listener.ClusterDropTargetListener;
import edu.tsinghua.lumaqq.ui.listener.DefaultQTreeListener;
import edu.tsinghua.lumaqq.ui.listener.GroupDropTargetListener;
import edu.tsinghua.lumaqq.ui.listener.GroupNameChangedListener;
import edu.tsinghua.lumaqq.ui.listener.ItemDragSourceListener;
import edu.tsinghua.lumaqq.ui.listener.ItemMouseListener;
import edu.tsinghua.lumaqq.ui.listener.ItemMouseTrackListener;
import edu.tsinghua.lumaqq.ui.provider.FriendTreeModeContentProvider;
import edu.tsinghua.lumaqq.ui.provider.GroupContentProvider;
import edu.tsinghua.lumaqq.ui.provider.ModelLabelProvider;
import edu.tsinghua.lumaqq.ui.sorter.LatestSorter;
import edu.tsinghua.lumaqq.ui.sorter.ModelSorter;
import edu.tsinghua.lumaqq.widgets.qstyle.Animation;
import edu.tsinghua.lumaqq.widgets.qstyle.Blind;
import edu.tsinghua.lumaqq.widgets.qstyle.IFilter;
import edu.tsinghua.lumaqq.widgets.qstyle.IQTreeListener;
import edu.tsinghua.lumaqq.widgets.qstyle.ISlatLabelProvider;
import edu.tsinghua.lumaqq.widgets.qstyle.ISlatListener;
import edu.tsinghua.lumaqq.widgets.qstyle.ItemLayout;
import edu.tsinghua.lumaqq.widgets.qstyle.QTreeViewer;
import edu.tsinghua.lumaqq.widgets.qstyle.Slat;
/**
* 管理Blind控件的显示模式
*
* @author luma
*/
public class BlindHelper {
private MainShell main;
// 所有的缺省组和用户自定义组
private Group latestGroup;
private Group clusterGroup;
private Group myFriendGroup;
private Group strangerGroup;
private Group blacklistGroup;
private List<Group> normalGroups;
// QTreeViewer注册表
private Map<Group, QTreeViewer<Model>> viewers;
private IFilter<Model> onlineFilter;
private Map<Integer, Group> addTo;
public BlindHelper(MainShell main) {
this.main = main;
normalGroups = new ArrayList<Group>();
viewers = new HashMap<Group, QTreeViewer<Model>>();
onlineFilter = new OnlineFilter();
addTo = new HashMap<Integer, Group>();
}
/**
* @return
* 当前组对象,没有返回null
*/
public Group getCurrentGroup() {
Control control = main.getBlind().getCurrentSlatControl();
for(Group g : viewers.keySet()) {
if(viewers.get(g).getQTree() == control) {
if(isTreeMode()) {
// 如果是树形模式,且当前在好友组中,判断当前选择了哪个组
QTreeViewer<Model> viewer = viewers.get(myFriendGroup);
if(viewer.getQTree() == control)
return myFriendGroup;
else
return g;
} else
return g;
}
}
return null;
}
/**
* 设置视图背景颜色
*
* @param bg
* Color
*/
public void setBackground(Color bg) {
for(QTreeViewer<Model> viewer : viewers.values()) {
viewer.getQTree().setBackground(bg);
}
}
/**
* 设置是否使用小头像
*
* @param b
* true表示使用小头像
*/
public void setShowSmallHead(boolean b) {
ItemLayout layout = b ? ItemLayout.HORIZONTAL : ItemLayout.VERTICAL;
// 改变好友组
if(isTreeMode()) {
QTreeViewer<Model> viewer = viewers.get(myFriendGroup);
changeViewerLayout(viewer, 1, layout);
} else {
QTreeViewer<Model> viewer = viewers.get(myFriendGroup);
changeViewerLayout(viewer, 0, layout);
for(Group g : normalGroups) {
viewer = viewers.get(g);
changeViewerLayout(viewer, 0, layout);
}
changeViewerLayout(viewers.get(strangerGroup), 0, layout);
changeViewerLayout(viewers.get(blacklistGroup), 0, layout);
}
// 改变最近联系人组
changeViewerLayout(viewers.get(latestGroup), 0, layout);
}
/**
* 改变viewer的布局
*
* @param viewer
* @param level
* @param layout
*/
private void changeViewerLayout(QTreeViewer<Model> viewer, int level, ItemLayout layout) {
switch(layout) {
case HORIZONTAL:
viewer.getQTree().setLevelImageSize(level, 20);
viewer.getQTree().setLevelIndent(16);
viewer.getQTree().setLevelLayout(level, layout);
break;
case VERTICAL:
viewer.getQTree().setLevelImageSize(level, 40);
viewer.getQTree().setLevelIndent(0);
viewer.getQTree().setLevelLayout(level, layout);
break;
default:
SWT.error(SWT.ERROR_INVALID_RANGE);
break;
}
}
/**
* 得到model所在QTreeViewer对象
*
* @param model
* model对象
* @return
* 包含这个model的QTreeViewer
*/
public QTreeViewer<Model> getViewer(Model model) {
if(model == null)
return null;
switch(model.type) {
case USER:
return viewers.get(((User)model).group);
case CLUSTER:
case DUMMY:
return viewers.get(clusterGroup);
case GROUP:
return viewers.get(model);
default:
SWT.error(SWT.ERROR_INVALID_RANGE);
return null;
}
}
/**
* @param model
* @return
* true表示这个item有一个动画在进行
*/
public boolean hasAnimation(Model model) {
QTreeViewer<Model> viewer = getViewer(model);
if(viewer == null)
return false;
return viewer.hasAnimation(model);
}
/**
* 闪烁文字
*
* @param m
*/
public void startBlinkText(Model m) {
QTreeViewer<Model> viewer = getViewer(m);
if(viewer == null)
return;
if(!viewer.hasAnimation(m))
viewer.startAnimation(m, Animation.TEXT_BLINK);
}
/**
* 停止文本闪烁
*
* @param m
*/
public void stopBlinkText(Model m) {
QTreeViewer<Model> viewer = getViewer(m);
if(viewer == null)
return;
if(viewer.hasAnimation(m))
viewer.stopAnimation(m);
}
/**
* 开始跳动一个图标
*
* @param model
*/
public void startBounceImage(Model model) {
QTreeViewer<Model> viewer = getViewer(model);
if(viewer == null)
return;
if(!viewer.hasAnimation(model))
viewer.startAnimation(model, Animation.ICON_BOUNCE);
}
/**
* 开始在一个组上闪烁图标
*
* @param g
* @param img
*/
public void startBlinkGroupImage(Group g, Image img) {
QTreeViewer<Model> viewer = viewers.get(g);
if(viewer == null)
return;
Blind blind = main.getBlind();
int index = blind.indexOf(viewer.getQTree());
if(!blind.getSlat(index).isBlinking())
blind.startBlink(index, img);
}
/**
* 停止在一个组上闪烁
*
* @param g
*/
public void stopBlinkGroupImage(Group g) {
QTreeViewer<Model> viewer = viewers.get(g);
if(viewer == null)
return;
Blind blind = main.getBlind();
int index = blind.indexOf(viewer.getQTree());
if(blind.getSlat(index).isBlinking())
blind.stopBlink(index);
}
/**
* 给定一个控件或者一个slat,得到对应的Group对象,如果当前处于树形模式,且
* 这个control正好是好友树,则返回我的好友组
*
* @param c
* Control或者slat
* @return
* Group对象,没有返回null
*/
public Group getSlatGroup(Control c) {
Blind blind = main.getBlind();
int index = blind.indexOf(c);
Control slatControl = blind.getSlatControl(index);
for(Map.Entry<Group, QTreeViewer<Model>> entry : viewers.entrySet()) {
if(entry.getValue().getQTree() == slatControl) {
if(isTreeMode()) {
if(viewers.get(myFriendGroup).getQTree() == slatControl)
return myFriendGroup;
else
return entry.getKey();
} else
return entry.getKey();
}
}
return null;
}
/**
* 刷新某个组
*
* @param g
*/
public void refreshGroup(Group g) {
QTreeViewer<Model> viewer = viewers.get(g);
if(viewer != null) {
viewer.refresh();
main.getBlind().refreshSlat(viewer.getQTree());
}
}
/**
* 初始化传统模式
*/
private void initTraditionalMode() {
Blind blind = main.getBlind();
blind.setLabelProvider(new ISlatLabelProvider() {
public String getText(Control slatControl) {
for(Group g : viewers.keySet()) {
QTreeViewer<Model> viewer = viewers.get(g);
if(viewer.getQTree() == slatControl)
return getGroupText(g);
}
return "";
}
});
MouseListener itemMouseListener = new ItemMouseListener(main);
MouseTrackListener itemMouseTrackListener = new ItemMouseTrackListener(main);
IQTreeListener qtreeListener = new DefaultQTreeListener(main);
DropTargetListener groupDropTargetListener = new GroupDropTargetListener(main);
DragSourceListener itemDragSourceListener = new ItemDragSourceListener();
Transfer[] dummyTransfer = new Transfer[] { TextTransfer.getInstance() };
ISlatListener slatListener = new GroupNameChangedListener(main);
// 我的好友组
QTreeViewer<Model> viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(myFriendGroup));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(myFriendGroup, viewer);
blind.addSlat(viewer.getQTree());
blind.addSlatDropSupport(viewer.getQTree(), DND.DROP_MOVE, dummyTransfer, groupDropTargetListener);
// 自定义组
for(Group g : normalGroups) {
viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(g));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(g, viewer);
blind.addSlat(viewer.getQTree()).addSlatListener(slatListener);
blind.addSlatDropSupport(viewer.getQTree(), DND.DROP_MOVE, dummyTransfer, groupDropTargetListener);
}
// 陌生人组
viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(strangerGroup));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(strangerGroup, viewer);
blind.addSlat(viewer.getQTree());
blind.addSlatDropSupport(viewer.getQTree(), DND.DROP_MOVE, dummyTransfer, groupDropTargetListener);
// 黑名单组
viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(blacklistGroup));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(blacklistGroup, viewer);
blind.addSlat(viewer.getQTree());
blind.addSlatDropSupport(viewer.getQTree(), DND.DROP_MOVE, dummyTransfer, groupDropTargetListener);
// 群组
viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(clusterGroup));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, new ClusterDragSourceListener());
viewer.addDropSupport(DND.DROP_MOVE, dummyTransfer, new ClusterDropTargetListener(main));
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(clusterGroup, viewer);
blind.addSlat(viewer.getQTree());
// 最近联系人组
viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(latestGroup));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(LatestSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(latestGroup, viewer);
blind.addSlat(viewer.getQTree());
}
/**
* 得到一个组的显示文本,主要是要添加上一些统计数据
*
* @param g
* Group
* @return
* 显示文本
*/
private String getGroupText(Group g) {
switch(g.groupType) {
case CLUSTER_GROUP:
return g.name;
case LATEST_GROUP:
return g.name + ' ' + '(' + g.getOnlineUserCount() + '/' + (g.users.size() + g.clusters.size()) + ')';
default:
return g.name + ' ' + '(' + g.getOnlineUserCount() + '/' + g.users.size() + ')';
}
}
/**
* 初始化树形模式
*/
private void initTreeMode() {
Blind blind = main.getBlind();
blind.setLabelProvider(new ISlatLabelProvider() {
public String getText(Control slatControl) {
for(Group g : viewers.keySet()) {
QTreeViewer<Model> viewer = viewers.get(g);
if(viewer.getQTree() == slatControl) {
QTreeViewer<Model> temp = viewers.get(myFriendGroup);
if(temp == viewer)
return myFriendGroup.name;
else
return getGroupText(g);
}
}
return "";
}
});
MouseListener slatMouseListener = new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
/*
* 点击我的好友组时,收起或者恢复展开状态,但是如果
* 我的好友组不是当前组,则不应该执行以下代码
*/
if(main.getBlind().getPreviousSlat() == 0) {
QTreeViewer<Model> viewer = getViewer(myFriendGroup);
if(viewer.isAllRootCollapsed())
viewer.restoreExpandStatus();
else {
viewer.saveExpandStatus();
viewer.getQTree().goTop();
viewer.collapseAll();
}
}
}
};
MouseListener itemMouseListener = new ItemMouseListener(main);
MouseTrackListener itemMouseTrackListener = new ItemMouseTrackListener(main);
DropTargetListener groupDropTargetListener = new GroupDropTargetListener(main);
DragSourceListener itemDragSourceListener = new ItemDragSourceListener();
IQTreeListener qtreeListener = new DefaultQTreeListener(main);
Transfer[] dummyTransfer = new Transfer[] { TextTransfer.getInstance() };
// 好友组,陌生人组,黑名单组
QTreeViewer<Model> viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new FriendTreeModeContentProvider(main));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.addDropSupport(DND.DROP_MOVE, dummyTransfer, groupDropTargetListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(myFriendGroup, viewer);
viewers.put(blacklistGroup, viewer);
viewers.put(strangerGroup, viewer);
for(Group g : normalGroups)
viewers.put(g, viewer);
blind.addSlat(viewer.getQTree());
blind.addSlatDropSupport(viewer.getQTree(), DND.DROP_MOVE, dummyTransfer, groupDropTargetListener);
blind.getSlat(0).addMouseListener(slatMouseListener);
// 群组
viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(clusterGroup));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, new ClusterDragSourceListener());
viewer.addDropSupport(DND.DROP_MOVE, dummyTransfer, new ClusterDropTargetListener(main));
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(clusterGroup, viewer);
blind.addSlat(viewer.getQTree());
// 最近联系人组
viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(latestGroup));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(LatestSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewers.put(latestGroup, viewer);
blind.addSlat(viewer.getQTree());
}
/**
* 初始化model
*/
@SuppressWarnings("unchecked")
public void initModels() {
main.getBlind().removeAll();
viewers.clear();
ModelRegistry.clearAll();
normalGroups.clear();
// 初始化,载入分组文件
ConfigHelper configHelper = main.getConfigHelper();
File groupFile = new File(LumaQQ.GROUPS);
if(!configHelper.checkGroupFile(groupFile))
return;
XGroups groups = GroupUtil.load(groupFile);
if(groups == null)
return;
Group g = null;
for(XGroup group : (List<XGroup>)groups.getGroup()) {
// 创建Group
GroupType groupType = GroupType.valueOf(group.getType());
switch(groupType) {
case BLACKLIST_GROUP:
blacklistGroup = ModelUtils.createGroup(group);
g = blacklistGroup;
break;
case CLUSTER_GROUP:
clusterGroup = ModelUtils.createGroup(group);
g = clusterGroup;
break;
case DEFAULT_FRIEND_GROUP:
myFriendGroup = ModelUtils.createGroup(group);
g = myFriendGroup;
break;
case FRIEND_GROUP:
g = ModelUtils.createGroup(group);
normalGroups.add(g);
break;
case LATEST_GROUP:
latestGroup = ModelUtils.createGroup(group);
g = latestGroup;
break;
case STRANGER_GROUP:
strangerGroup = ModelUtils.createGroup(group);
g = strangerGroup;
break;
}
if(g == null)
continue;
g.groupType = groupType;
// 创建User或者Cluster
if(g == clusterGroup) {
// 添加一个多人对话容器
Cluster dialogContainer = new Cluster();
dialogContainer.name = cluster_dialogs;
dialogContainer.clusterType = ClusterType.DIALOG_CONTAINER;
g.addCluster(dialogContainer);
ModelRegistry.addCluster(dialogContainer);
// 添加其他群
List<Cluster> subClusters = new ArrayList<Cluster>();
for(XCluster cluster : (List<XCluster>)group.getCluster()) {
Cluster c = ModelUtils.createCluster(cluster);
g.addCluster(c);
ModelRegistry.addCluster(c);
// 创建Cluster中的member
for(XUser user : (List<XUser>)cluster.getUser()) {
if(user.getQq() == 0)
continue;
User u = ModelUtils.createUser(user);
u.remark = main.getConfigHelper().getRemark(u.qq);
if(u.hasCardName())
u.displayName = u.cardName;
c.addMember(u);
}
if(c.isPermanent()) {
// 创建两个dummy,一个是群内组织,一个是讨论组
Dummy orgDummy = new Dummy();
orgDummy.dummyType = DummyType.CLUSTER_ORGANIZATION;
orgDummy.name = cluster_organization;
c.addDummy(orgDummy);
Dummy subDummy = new Dummy();
subDummy.dummyType = DummyType.SUBJECTS;
subDummy.name = cluster_subject;
c.addDummy(subDummy);
} else {
subClusters.add(c);
}
// 添加群中的组织
for(XOrganization org : (List<XOrganization>)cluster.getOrganization()) {
Organization o = ModelUtils.createOrganization(org);
c.addOrganization(o);
}
}
// 建立父子群关系,如果父群是null,则为多人对话
for(Cluster c : subClusters) {
Cluster parent = c.getParentCluster();
if(parent == null)
dialogContainer.addSubCluster(c);
else
parent.addSubCluster(c);
}
} else if(g == latestGroup) {
for(XUser user : (List<XUser>)group.getUser()) {
if(user.getQq() == 0)
continue;
User u = ModelUtils.createUser(user);
u.remark = main.getConfigHelper().getRemark(u.qq);
g.addUser(u);
}
for(XCluster cluster : (List<XCluster>)group.getCluster()) {
Cluster c = ModelUtils.createCluster(cluster);
g.addCluster(c);
}
} else {
// 创建用户
for(XUser user : (List<XUser>)group.getUser()) {
User u = ModelUtils.createUser(user);
u.remark = main.getConfigHelper().getRemark(u.qq);
g.addUser(u);
}
}
}
}
/**
* 重设blind显示模式
*/
private void resetMode() {
main.getBlind().removeAll();
viewers.clear();
OptionHelper options = main.getOptionHelper();
setShowSignature(options.isShowSignature());
setShowCustomHead(options.isShowCustomHead());
if(isTreeMode())
initTreeMode();
else
initTraditionalMode();
setShowOnlineOnly(options.isShowOnlineOnly());
setShowNick(options.isShowNick());
setShowSmallHead(options.isShowSmallHead());
setBackground(main.getGroupColor());
setLatestGroupVisible(options.isEnableLatest());
setBlacklistGroupVisible(options.isShowBlacklist());
}
/**
* 修改当前slat的文本
*/
public void editCurrentSlatText() {
Blind blind = main.getBlind();
Slat slat = blind.getCurrentSlat();
if(slat != null)
slat.editText();
}
/**
* @return
* 所有好友组列表
*/
public List<Group> getFriendGroupList() {
List<Group> ret = new ArrayList<Group>();
ret.add(myFriendGroup);
ret.addAll(normalGroups);
return ret;
}
/**
* @return
* 所有用户组列表,也就是除了群组之外的所有组
*/
public List<Group> getUserGroupList() {
List<Group> ret = new ArrayList<Group>();
ret.add(myFriendGroup);
ret.addAll(normalGroups);
ret.add(strangerGroup);
ret.add(blacklistGroup);
return ret;
}
/**
* @return
* 能够接收短消息的组
*/
public List<Group> getSMSReceivableGroupList() {
List<Group> ret = new ArrayList<Group>();
ret.add(myFriendGroup);
ret.addAll(normalGroups);
ret.add(strangerGroup);
ret.add(blacklistGroup);
return ret;
}
/**
* @return
* 所有需要导出记录的组列表
*/
public List<Group> getExportGroupList() {
List<Group> ret = new ArrayList<Group>();
ret.add(myFriendGroup);
ret.addAll(normalGroups);
ret.add(strangerGroup);
ret.add(clusterGroup);
return ret;
}
/**
* @return Returns the treeMode.
*/
public boolean isTreeMode() {
return main.getOptionHelper().isTreeMode();
}
/**
* @param treeMode The treeMode to set.
*/
public void setTreeMode(boolean treeMode) {
resetMode();
}
/**
* @return Returns the myFriendGroup.
*/
public Group getMyFriendGroup() {
return myFriendGroup;
}
/**
* @return Returns the clusterGroup.
*/
public Group getClusterGroup() {
return clusterGroup;
}
/**
* @return Returns the latestGroup.
*/
public Group getLatestGroup() {
return latestGroup;
}
/**
* @return Returns the normalGroups.
*/
public List<Group> getNormalGroups() {
return normalGroups;
}
/**
* @return Returns the blacklistGroup.
*/
public Group getBlacklistGroup() {
return blacklistGroup;
}
/**
* @return Returns the strangerGroup.
*/
public Group getStrangerGroup() {
return strangerGroup;
}
/**
* 添加一个XGroup元素
*
* @param groups
* XGroups
* @param g
* Group
*/
@SuppressWarnings("unchecked")
private void addXGroup(XGroups groups, Group g) {
XGroup group = ModelUtils.createXGroup(g);
groups.getGroup().add(group);
switch(g.groupType) {
case CLUSTER_GROUP:
for(Cluster c : g.clusters) {
// 不需要保存多人对话容器
if(c.clusterType != DIALOG_CONTAINER) {
XCluster cluster = ModelUtils.createXCluster(c);
group.getCluster().add(cluster);
for(User u : c.members.values()) {
XUser user = ModelUtils.createXUser(u);
cluster.getUser().add(user);
}
for(Organization o : c.organizations.values()) {
XOrganization org = ModelUtils.createXOrganization(o);
cluster.getOrganization().add(org);
}
}
}
break;
case LATEST_GROUP:
for(User u : g.users) {
XUser user = ModelUtils.createXUser(u);
group.getUser().add(user);
}
for(Cluster cluster : g.clusters) {
XCluster c = ModelUtils.createXCluster(cluster);
group.getCluster().add(c);
}
break;
case BLACKLIST_GROUP:
case DEFAULT_FRIEND_GROUP:
case FRIEND_GROUP:
case STRANGER_GROUP:
for(User u : g.users) {
XUser user = ModelUtils.createXUser(u);
group.getUser().add(user);
}
break;
default:
SWT.error(SWT.ERROR_INVALID_RANGE);
break;
}
}
/**
* 保存分组信息
*/
public void saveModel() {
if(myFriendGroup == null)
return;
XGroups groups = GroupFactory.eINSTANCE.createXGroups();
addXGroup(groups, myFriendGroup);
for(Group g : normalGroups)
addXGroup(groups, g);
addXGroup(groups, strangerGroup);
addXGroup(groups, blacklistGroup);
addXGroup(groups, clusterGroup);
addXGroup(groups, latestGroup);
// 写入到文件
GroupUtil.save(new File(LumaQQ.GROUPS), groups);
}
/**
* 刷新所有视图
*/
public void refreshAll() {
for(QTreeViewer<Model> viewer : viewers.values()) {
viewer.refresh();
main.getBlind().refreshSlat(viewer.getQTree());
}
}
/**
* 把一个组中的用户存到哈希表中
*
* @param hash
* @param g
*/
private void hashFriend(Map<Integer, User> hash, Group g) {
for(User u : g.users)
hash.put(u.qq, u);
}
/**
* @return
* 一个包含了所有好友的哈希表
*/
public Map<Integer, User> getFriendMap() {
Map<Integer, User> ret = new HashMap<Integer, User>();
hashFriend(ret, myFriendGroup);
for(Group g : normalGroups)
hashFriend(ret, g);
return ret;
}
/**
* 添加一个用户到某种组中。如果是添加到群组,则不操作。如果是自定义的
* 好友组,不操作。如果是最近联系人组,则添加一个link
*
* @param user
* User对象
* @param type
* 组类型
*/
public void addUser(User user, GroupType type) {
User u = user;
Group g = null;
switch(type) {
case BLACKLIST_GROUP:
g = blacklistGroup;
break;
case DEFAULT_FRIEND_GROUP:
g = myFriendGroup;
break;
case LATEST_GROUP:
g = latestGroup;
break;
case STRANGER_GROUP:
g = strangerGroup;
break;
case CLUSTER_GROUP:
case FRIEND_GROUP:
return;
default:
SWT.error(SWT.ERROR_INVALID_RANGE);
return;
}
g.addUser(u);
}
/**
* @return
* 需要上传的组的名称列表
*/
public List<String> getUploadGroupNameList() {
List<String> ret = new ArrayList<String>();
for(Group g : normalGroups)
ret.add(g.name);
return ret;
}
/**
* 根据索引得到组对象,默认的顺序是,好友是0,然后是自定义组,然后是陌生人,黑名单,
* 手机好友,群,最后是最近联系人。一般不应该用这个来的到组对象,因为自定义组个数
* 未知。
*
* @param index
* 索引
* @return
* Group对象, 如果索引超出范围,返回null
*/
public Group getGroup(int index) {
if(index < 0)
return null;
if(index == 0)
return myFriendGroup;
index--;
if(index < normalGroups.size())
return normalGroups.get(index);
index -= normalGroups.size();
switch(index) {
case 0:
return strangerGroup;
case 1:
return blacklistGroup;
case 2:
return clusterGroup;
case 3:
return latestGroup;
default:
return null;
}
}
/**
* 得到好友组,第0个好友组是我的好友组
*
* @param index
* 好友组索引
* @return
* Group
*/
public Group getFriendGroup(int index) {
if(index < 0)
return null;
if(index == 0)
return myFriendGroup;
return normalGroups.get(index - 1);
}
/**
* @return
* 需要上传的组数目
*/
public int getUploadGroupCount() {
return normalGroups.size() + 1;
}
/**
* @return
* 返回组总数
*/
public int getGroupCount() {
return normalGroups.size() + 6;
}
/**
* 设置最近联系人组的可见性
*
* @param b
* true表示可见
*/
public void setLatestGroupVisible(boolean b) {
Blind blind = main.getBlind();
QTreeViewer<Model> viewer = viewers.get(latestGroup);
if(b)
blind.showSlat(viewer.getQTree());
else
blind.hideSlat(viewer.getQTree());
}
/**
* 设置黑名单可见性
*
* @param b
* true表示可见
*/
public void setBlacklistGroupVisible(boolean b) {
Blind blind = main.getBlind();
QTreeViewer<Model> viewer = viewers.get(blacklistGroup);
if(isTreeMode())
viewers.get(myFriendGroup).refresh();
else {
if(b)
blind.showSlat(viewer.getQTree());
else
blind.hideSlat(viewer.getQTree());
}
}
/**
* 重设整个model
*
* @param groupNames
* 组名列表,不包括我的好友组
* @param friends
* 所有下载项
*/
public void resetModel(List<String> groupNames, List<DownloadFriendEntry> friends) {
// 清除旧的数据
ModelRegistry.clearGroup(myFriendGroup, false);
ModelRegistry.clearGroup(clusterGroup, false);
for(Group g : normalGroups)
ModelRegistry.clearGroup(g, true);
// 把旧的内容保存下来
Map<Integer, User> oldUsers = new HashMap<Integer, User>();
Map<Integer, Cluster> oldClusters = new HashMap<Integer, Cluster>();
for(User u : myFriendGroup.users)
oldUsers.put(u.qq, u);
int size = clusterGroup.clusters.size();
for(int i = size - 1; i >= 0; i--) {
Cluster c = clusterGroup.clusters.get(i);
if(c.clusterType == ClusterType.DIALOG_CONTAINER)
continue;
c.removeAllSubClusters();
oldClusters.put(c.clusterId, c);
}
for(Group g : normalGroups) {
for(User u : g.users)
oldUsers.put(u.qq, u);
g.removeAllUsers();
}
normalGroups.clear();
myFriendGroup.removeAllUsers();
clusterGroup.removeAllCluster();
// 创建新的组
for(String name : groupNames) {
Group g = new Group();
g.name = name;
g.expanded = false;
normalGroups.add(g);
ModelRegistry.addGroup(g);
}
// 添加新的组
boolean showNick = main.getOptionHelper().isShowNick();
size = getUploadGroupCount();
List<DownloadFriendEntry> needInfos = new ArrayList<DownloadFriendEntry>();
for(DownloadFriendEntry entry : friends) {
if(entry.isCluster()) {
// 如果这个组存在,使用老对象,如果不存在,新建一个Cluster对象
Cluster c = oldClusters.get(entry.qqNum);
if(c == null) {
needInfos.add(entry);
c = new Cluster();
c.clusterId = entry.qqNum;
c.name = String.valueOf(entry.qqNum);
c.headId = 1;
c.clusterType = ClusterType.NORMAL;
// 创建两个dummy,一个是群内组织,一个是讨论组
Dummy orgDummy = new Dummy();
orgDummy.dummyType = DummyType.CLUSTER_ORGANIZATION;
orgDummy.name = cluster_organization;
c.addDummy(orgDummy);
Dummy subDummy = new Dummy();
subDummy.dummyType = DummyType.SUBJECTS;
subDummy.name = cluster_subject;
c.addDummy(subDummy);
}
// 注册cluster
clusterGroup.addCluster(c);
ModelRegistry.addCluster(c);
} else {
if(entry.group >= size)
entry.group = 0;
User u = oldUsers.get(entry.qqNum);
if(u == null) {
needInfos.add(entry);
u = new User();
u.qq = entry.qqNum;
u.nick = String.valueOf(u.qq);
u.remark = main.getConfigHelper().getRemark(u.qq);
u.displayName = showNick ? u.nick : ((u.remark == null) ? u.nick : u.remark.getName());
} else {
u.status = Status.OFFLINE;
}
getFriendGroup(entry.group).addUser(u);
}
}
// 添加多人对话
Cluster dialogContainer = new Cluster();
dialogContainer.name = cluster_dialogs;
dialogContainer.clusterType = ClusterType.DIALOG_CONTAINER;
clusterGroup.addCluster(dialogContainer);
ModelRegistry.addCluster(dialogContainer);
// 刷新
main.getDisplay().syncExec(new Runnable() {
public void run() {
resetMode();
}
});
// 得到新的model的信息
for(DownloadFriendEntry dfe : needInfos) {
if(dfe.isCluster() && dfe.qqNum != 0) {
main.getClient().cluster_GetInfo(dfe.qqNum);
main.getClient().cluster_getSubjectList(dfe.qqNum);
} else
main.getClient().user_GetInfo(dfe.qqNum);
}
// 得到多人对话列表
main.getClient().cluster_getDialogList();
// 恢复图标的跳动和闪烁,然后关闭提示框
main.getDisplay().syncExec(new Runnable() {
public void run() {
resetAllImageEffect();
}
});
}
/**
* 设置是否显示昵称
*
* @param b
* true表示显示昵称
*/
public void setShowNick(boolean b) {
// 刷新所有用户的显示名称
for(Iterator<User> i = ModelRegistry.getUserIterator(); i.hasNext(); ) {
User u = i.next();
if(!u.group.isCluster())
u.displayName = b ? u.nick : (u.hasRemarkName() ? u.getRemarkName() : u.nick);
}
// 刷新群中所有成员的显示名称
for(Iterator<Cluster> i = ModelRegistry.getClustetIterator(); i.hasNext(); ) {
Cluster c = i.next();
for(User u : c.members.values()) {
User regUser = ModelRegistry.getUser(u.qq);
if(regUser == null)
regUser = u;
u.displayName = u.hasCardName() ? u.cardName :
(b ? regUser.nick :
((regUser.hasRemarkName() ? regUser.getRemarkName() : regUser.nick)));
}
}
}
/**
* 设置是否只显示在线用户
*
* @param b
* true表示只显示在线用户
*/
public void setShowOnlineOnly(boolean b) {
for(Group g : viewers.keySet()) {
if(!g.isLatest())
viewers.get(g).setFilter(b ? onlineFilter : null);
}
}
/**
* @return
* 当前的qtree viewer
*/
public QTreeViewer<Model> getCurrentViewer() {
return getViewer(getCurrentGroup());
}
/**
* 刷新model,同时刷新链接到这个model的model
*
* @param m
*/
public void refreshModel(Model m) {
QTreeViewer<Model> viewer = getViewer(m);
viewer.refresh(m);
}
/**
* 在当前组的后面添加一个组,如果处于树形模式,则处理有点不一样
*/
public void addGroup() {
Group g = new Group();
g.name = "Input Group Name";
g.groupType = GroupType.FRIEND_GROUP;
g.expanded = false;
ModelRegistry.addGroup(g);
if(isTreeMode()) {
normalGroups.add(g);
viewers.put(g, viewers.get(myFriendGroup));
refreshGroup(myFriendGroup);
viewers.get(myFriendGroup).editText(g);
} else {
Blind blind = main.getBlind();
int index = Math.min(normalGroups.size(), blind.getCurrentSlatIndex()) + 1;
normalGroups.add(index - 1, g);
OptionHelper options = main.getOptionHelper();
MouseListener itemMouseListener = new ItemMouseListener(main);
MouseTrackListener itemMouseTrackListener = new ItemMouseTrackListener(main);
DropTargetListener groupDropTargetListener = new GroupDropTargetListener(main);
DragSourceListener itemDragSourceListener = new ItemDragSourceListener();
IQTreeListener qtreeListener = new DefaultQTreeListener(main);
Transfer[] dummyTransfer = new Transfer[] { TextTransfer.getInstance() };
QTreeViewer<Model> viewer = new QTreeViewer<Model>(blind);
viewer.setContentProvider(new GroupContentProvider(g));
viewer.setLabelProvider(ModelLabelProvider.INSTANCE);
viewer.setSorter(ModelSorter.INSTANCE);
viewer.setInput(this);
viewer.addDragSupport(DND.DROP_MOVE, dummyTransfer, itemDragSourceListener);
viewer.getQTree().addMouseListener(itemMouseListener);
viewer.getQTree().addMouseTrackListener(itemMouseTrackListener);
viewer.getQTree().addQTreeListener(qtreeListener);
viewers.put(g, viewer);
blind.addSlat(index, viewer.getQTree());
blind.addSlatDropSupport(viewer.getQTree(), DND.DROP_MOVE, dummyTransfer, groupDropTargetListener);
changeViewerLayout(viewer, 0, options.isShowSmallHead() ? ItemLayout.HORIZONTAL : ItemLayout.VERTICAL);
Slat slat = blind.getSlat(index);
slat.addSlatListener(new GroupNameChangedListener(main));
slat.editText();
}
main.setGroupDirty(true);
}
/**
* 删除当前组
*
* @param g
* 要删除的组对象
*/
public void removeGroup(Group g) {
QTreeViewer<Model> viewer = viewers.remove(g);
if(viewer == null)
return;
ModelRegistry.clearGroup(g, true);
normalGroups.remove(g);
Blind blind = main.getBlind();
if(!isTreeMode())
blind.removeSlat(viewer.getQTree());
refreshAll();
main.setGroupDirty(true);
}
/**
* 添加一个Cluster对象
*
* @param clusterId
* id
* @param creator
* true表示我是这个群的创建者
* @return
* 创建的Cluster对象
*/
public Cluster addCluster(int clusterId, boolean creator) {
// 找到群组的索引
Cluster c = ModelRegistry.getCluster(clusterId);
if(c == null) {
// 新建一个群Model
c = new Cluster();
c.clusterId = clusterId;
c.headId = 1;
// 设置creator
if(creator)
c.creator = main.getMyModel().qq;
// 创建两个dummy,一个是群内组织,一个是讨论组
Dummy orgDummy = new Dummy();
orgDummy.dummyType = DummyType.CLUSTER_ORGANIZATION;
orgDummy.name = cluster_organization;
c.addDummy(orgDummy);
Dummy subDummy = new Dummy();
subDummy.dummyType = DummyType.SUBJECTS;
subDummy.name = cluster_subject;
c.addDummy(subDummy);
// 添加这个model
clusterGroup.addCluster(c);
ModelRegistry.addCluster(c);
refreshGroup(clusterGroup);
// 如果我是创建者,则激活群
if(creator)
main.getClient().cluster_Activate(clusterId);
// 请求得到这个群的信息和成员列表
main.getClient().cluster_GetInfo(clusterId);
main.getClient().cluster_getSubjectList(clusterId);
}
// 返回model
return c;
}
/**
* 添加一个临时群
*
* @param type
* @param clusterId
* @param parentClusterId
* @return
*/
public Cluster addTempCluster(byte type, int clusterId, int parentClusterId) {
// 查找父群
Cluster parent = ModelRegistry.getCluster(parentClusterId);
if(parent == null)
return null;
// 找到群组的索引
Cluster c = ModelRegistry.getCluster(clusterId);
if(c == null) {
// 新建一个群Model
c = new Cluster();
c.clusterId = clusterId;
c.headId = 4;
c.parentClusterId = parentClusterId;
c.creator = main.getMyModel().qq;
c.clusterType = ClusterType.valueOfTemp(type);
// 添加这个model
clusterGroup.addCluster(c);
parent.addSubCluster(c);
ModelRegistry.addCluster(c);
refreshGroup(clusterGroup);
// 请求得到这个群的信息和成员列表
main.getClient().cluster_AactivateTemp(type, clusterId, parentClusterId);
main.getClient().cluster_GetTempInfo(type, clusterId, parentClusterId);
}
// 返回model
return c;
}
/**
* 删除一个群的model,如果存在这个群的相关窗口,也将关闭他们
*
* @param clusterId
* 群的内部ID
* @return
* 成功则返回true
*/
public boolean removeCluster(int clusterId) {
ShellRegistry shellRegistry = main.getShellRegistry();
UIHelper uiHelper = main.getUIHelper();
// 找到群组
Cluster c = ModelRegistry.removeCluster(clusterId);
if(c == null || c.clusterType == DIALOG_CONTAINER)
return false;
// 删除群
clusterGroup.removeCluster(c);
if(c.clusterType != NORMAL) {
Cluster parent = ModelRegistry.getCluster(c.parentClusterId);
if(parent != null)
parent.removeSubCluster(c);
}
refreshGroup(clusterGroup);
// 关闭群相关窗口
if(shellRegistry.hasClusterInfoWindow(c)) {
shellRegistry.removeClusterInfoWindow(c).close();
}
if(shellRegistry.hasSendClusterIMWindow(c)) {
shellRegistry.removeSendClusterIMWindow(c).close();
}
// 把这个群的消息从队列中删除
main.getMessageQueue().removeMessage(clusterId);
// 调整动画状态
resetGroupImageEffect(clusterGroup);
uiHelper.resetTrayImageEffect();
// 返回true表示成功
return true;
}
/**
* 添加一个好友的View part到blind控件中
*
* @param qq
* 好友QQ号
*/
public void addFriend(int qq) {
// 首先查看是否已经有了这个好友,如果有了,返回
User f = ModelRegistry.getUser(qq);
if(f != null && f.isFriend())
return;
// 首先我们判断加入好友目的组的哈希表中是否有该项,如果有,则加入到指定的组
// 如果没有或者指定的组已经不存在,加入到第一个好友组中
if(addTo.containsKey(qq)) {
Group g = addTo.remove(qq);
addFriend(qq, g);
return;
}
// 出一个窗口要用户选择一个组,然后把这个好友添加到用户选择的组中
SelectGroupDialog sgd = new SelectGroupDialog(main.getShell());
sgd.setModel(getFriendGroupList());
Group g = sgd.open();
if(g != null)
addFriend(qq, g);
}
/**
* 添加一个好友
*
* @param qqNum
* 好友号码
* @param g
* 要添加到的好友组Group
*/
public void addFriend(int qq, Group g) {
boolean ani = false;
User f = ModelRegistry.getUser(qq);
if(f == null) {
/* 如果是null,那么还没有这个好友,添加之 */
f = new User();
f.qq = qq;
f.nick = String.valueOf(qq);
f.displayName = f.nick;
if(!main.getOptionHelper().isShowNick()) {
Remark remark = main.getConfigHelper().getRemark(qq);
if(remark != null)
f.remark = remark;
}
} else {
// 移动好友
Group srcGroup = f.group;
ani = hasAnimation(f);
if(ani)
stopAnimation(srcGroup, f);
srcGroup.removeUser(f);
refreshGroup(srcGroup);
resetGroupImageEffect(srcGroup);
}
// 添加好友到目的组并调整动画状态
g.addUser(f);
refreshGroup(g);
if(ani)
startBounce(g, f);
resetGroupImageEffect(g);
// 添加到组中,同时请求得到这个好友的信息和刷新在线好友列表
main.addOnline(f);
main.getClient().user_GetInfo(qq);
main.getClient().user_GetOnline();
// 分组信息已改变
main.setGroupDirty(true);
// 更新服务器端列表
// 这个功能不再使用,因为LumaQQ会允许不自动更新分组信息,所以,这里搞成自动的会带来问题
//client.addFriendToList(group, qqNum);
}
/**
* 停止某个组中某个model的动画
*
* @param g
* @param m
*/
public void stopAnimation(Group g, Model m) {
QTreeViewer<Model> viewer = getViewer(g);
if(viewer != null)
viewer.stopAnimation(m);
}
/**
* 开始跳动一个item
*
* @param g
* @param m
*/
public void startBounce(Group g, Model m) {
QTreeViewer<Model> viewer = getViewer(g);
if(viewer != null)
viewer.startAnimation(m, Animation.ICON_BOUNCE);
}
/**
* 停止Blind上所有的动画效果,如果有的话
*/
public void stopAllEffectOnBlind() {
main.getBlind().stopAllAnimation();
for(QTreeViewer<Model> viewer : viewers.values())
viewer.getQTree().stopAllAnimation();
}
/**
* @param g
* @return
* true表示组的Slat上有一个动画
*/
public boolean hasGroupAnimation(Group g) {
QTreeViewer<Model> viewer = viewers.get(g);
if(viewer == null)
return false;
int index = main.getBlind().indexOf(viewer.getQTree());
return main.getBlind().hasSlatAnimation(index);
}
/**
* 得到索引g指定的组,检查它目前是否需要闪烁图标,根据检查结果重置图标特效状态
*
* @param g
* 组索引
*/
public void resetGroupImageEffect(Group g) {
if(g == null)
return;
MessageQueue mq = main.getMessageQueue();
Resources res = Resources.getInstance();
// 如果是群组
if(g.isCluster()) {
stopBlinkGroupImage(g);
int sender = mq.nextClusterIMSender();
Cluster c = ModelRegistry.getCluster(sender);
if(c == null)
return;
switch(c.clusterType) {
case NORMAL:
startBlinkGroupImage(c.group, res.getClusterHead(c.headId));
startBounceImage(c);
break;
case SUBJECT:
startBlinkGroupImage(c.group, res.getImage(Resources.icoDialog));
startBlinkText(c.getParentCluster().getSubjectDummy());
startBounceImage(c.getParentCluster());
break;
case DIALOG:
startBlinkGroupImage(c.group, res.getImage(Resources.icoDialog));
startBlinkText(c.getParentCluster());
break;
}
return;
}
// 检查这个组还有没有消息,没有了就停止闪烁,有就闪烁下一个消息发送者的头像
// 如果是树形模式,处理有些不同,需要检查是否还有普通消息
stopBlinkGroupImage(g);
stopBlinkText(g);
if(isTreeMode()) {
int groupSender = mq.nextGroupSender(g);
User uGS = ModelRegistry.getUser(groupSender);
int sender = mq.nextBlinkableIMSender();
User uS = ModelRegistry.getUser(sender);
if(uS != null) {
if(uS.isTM())
startBlinkGroupImage(g, res.getImage(uS.female ? Resources.icoTMFemale16 : Resources.icoTMMale16));
else
startBlinkGroupImage(g, HeadFactory.getOnlineHead(uS));
}
if(uGS != null)
startBlinkText(uGS.group);
} else if(mq.hasGroupMessage(g)) {
int sender = mq.nextGroupSender(g);
User u = ModelRegistry.getUser(sender);
if(u != null) {
if(u.isTM())
startBlinkGroupImage(g, res.getImage(u.female ? Resources.icoTMFemale16 : Resources.icoTMMale16));
else
startBlinkGroupImage(g, HeadFactory.getOnlineHead(u));
}
}
}
/**
* 重设组内好友或者群的动画状态
*
* @param g
* Group
*/
public void resetUserClusterImageEffect(Group g) {
MessageQueue mq = main.getMessageQueue();
QTreeViewer<Model> viewer = null;
viewer = viewers.get(g);
if(viewer == null)
return;
switch(g.groupType) {
case CLUSTER_GROUP:
for(Cluster c : g.clusters) {
if(mq.hasMessage(c.clusterId))
viewer.startAnimation(c, Animation.ICON_BOUNCE);
}
break;
case DEFAULT_FRIEND_GROUP:
case FRIEND_GROUP:
case STRANGER_GROUP:
for(User u : g.users) {
if(mq.hasMessage(u.qq))
viewer.startAnimation(u, Animation.ICON_BOUNCE);
}
break;
default:
break;
}
}
/**
* 重置所有动画状态
*/
public void resetAllImageEffect() {
resetGroupImageEffect(myFriendGroup);
resetUserClusterImageEffect(myFriendGroup);
resetGroupImageEffect(strangerGroup);
resetUserClusterImageEffect(strangerGroup);
resetGroupImageEffect(clusterGroup);
resetUserClusterImageEffect(clusterGroup);
for(Group g : normalGroups) {
resetGroupImageEffect(g);
resetUserClusterImageEffect(g);
}
main.getUIHelper().resetTrayImageEffect();
}
/**
* 展开组
*
* @param g
*/
public void expandGroup(Group g) {
g.expanded = true;
QTreeViewer<Model> viewer = getViewer(g);
viewer.expandItem(g);
viewer.refresh();
}
/**
* 收起组
*
* @param g
*/
public void collapseGroup(Group g) {
g.expanded = false;
QTreeViewer<Model> viewer = getViewer(g);
viewer.collapseItem(g);
viewer.refresh();
}
/**
* 移动一个用户到一个组中
*
* @param user
* @param destGroup
*/
public void moveUser(User user, Group destGroup) {
/*
* 移动用户到这个组,判断各种情况
* 1. 好友组到好友组,简单移动
* 2. 好友组到陌生人组,删除
* 3. 好友组到黑名单组,删除且删除自己
* 4. 陌生人组到黑名单组,删除自己
* 5. 黑名单组到陌生人组,简单移动
*/
Group srcGroup = user.group;
if(srcGroup == destGroup)
return;
switch(srcGroup.groupType) {
case DEFAULT_FRIEND_GROUP:
case FRIEND_GROUP:
switch(destGroup.groupType) {
case DEFAULT_FRIEND_GROUP:
case FRIEND_GROUP:
simpleMove(user, srcGroup, destGroup);
break;
case STRANGER_GROUP:
remove(false, user, destGroup);
break;
case BLACKLIST_GROUP:
remove(true, user, destGroup);
break;
default:
break;
}
break;
case STRANGER_GROUP:
switch(destGroup.groupType) {
case DEFAULT_FRIEND_GROUP:
case FRIEND_GROUP:
main.getShellLauncher().openAddReceiveSystemMessageShell(user);
addTo.put(user.qq, destGroup);
main.getClient().user_Add(user.qq);
break;
case BLACKLIST_GROUP:
remove(true, user, destGroup);
break;
default:
break;
}
break;
case BLACKLIST_GROUP:
switch(destGroup.groupType) {
case DEFAULT_FRIEND_GROUP:
case FRIEND_GROUP:
main.getShellLauncher().openAddReceiveSystemMessageShell(user);
addTo.put(user.qq, destGroup);
main.getClient().user_Add(user.qq);
break;
case STRANGER_GROUP:
simpleMove(user, srcGroup, destGroup);
break;
default:
break;
}
break;
default:
break;
}
}
/**
* 简单移动
* @param user
* @param srcGroup
* @param destGroup
*/
public void simpleMove(User user, Group srcGroup, Group destGroup) {
boolean hasAnimation = hasAnimation(user);
if(hasAnimation)
stopAnimation(srcGroup, user);
srcGroup.removeUser(user);
refreshGroup(srcGroup);
resetGroupImageEffect(srcGroup);
if(destGroup != null) {
destGroup.addUser(user);
refreshGroup(destGroup);
if(hasAnimation)
startBounce(destGroup, user);
resetGroupImageEffect(destGroup);
}
if(srcGroup.isFriendly())
main.setGroupDirty(true);
}
/**
* 删除一个用户到指定组中
*
* @param destBlacklist
* 目的组是否是黑名单
* @param f
* @param destGroup
*/
private void remove(boolean destBlacklist, User f, Group destGroup) {
MessageBox box = new MessageBox(main.getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO);
box.setText(message_box_common_warning_title);
if(destBlacklist)
box.setMessage(NLS.bind(hint_delete_friend_and_remove_self, String.valueOf(f.qq)));
else
box.setMessage(NLS.bind(hint_delete_friend, String.valueOf(f.qq)));
if(box.open() == SWT.YES) {
ReceiveSystemMessageShell rsms = new ReceiveSystemMessageShell(main);
rsms.setFriendModel(f);
rsms.open(ReceiveSystemMessageShell.DELETE_MODE);
main.deleteFriendFromServer(f.qq, true, destBlacklist, destGroup);
}
}
/**
* 同步最近联系人中的信息
*
* @param f
* 需要同步的好友
*/
public void synchronizeLatest(User f) {
User u = latestGroup.getUser(f.qq);
if(u != null) {
u.infoCopy(f);
refreshGroup(latestGroup);
}
}
/**
* 同步最近联系人中的信息,不立刻刷新
*
* @param f
* 需要同步的好友
*/
public void synchronizeLatestDelayRefresh(User f) {
User u = latestGroup.getUser(f.qq);
if(u != null)
u.infoCopy(f);
}
/**
* 同步最近联系人中的群
*
* @param c
*/
public void synchronizeLatest(Cluster c) {
Cluster cInLatest = latestGroup.getCluster(c.clusterId);
if(cInLatest != null) {
cInLatest.infoCopy(c);
refreshGroup(latestGroup);
}
}
/**
* 更新最近联系人组,如果不存在这个用户,则添加
*
* @param f
*/
public void updateLatest(User f) {
f.lastMessageTime = System.currentTimeMillis();
// 得到最近联系人设定最大数量
int max = main.getOptionHelper().getLatestSize();
// 得到当前联系人数量
int num = latestGroup.users.size() + latestGroup.clusters.size();
// 删除多余的联系人
if(max > 0) {
while(num >= max) {
removeLRUModel();
num--;
}
// 如果没有这个人,添加
if(!latestGroup.hasUser(f.qq)) {
try {
latestGroup.addUser((User)f.clone());
} catch(CloneNotSupportedException e) {
}
}
}
main.getBlindHelper().synchronizeLatest(f);
}
/**
* 更新最近联系人组,如果不存在这个群,则添加
*
* @param c
*/
public void updateLatest(Cluster c) {
c.lastMessageTime = System.currentTimeMillis();
// 得到最近联系人设定最大数量
int max = main.getOptionHelper().getLatestSize();
// 得到当前联系人数量
int num = latestGroup.users.size() + latestGroup.clusters.size();
// 删除多余的联系人
if(max > 0) {
while(num >= max) {
removeLRUModel();
num--;
}
// 如果没有这个人,添加
if(!latestGroup.hasCluster(c.clusterId)) {
try {
latestGroup.addCluster((Cluster)c.clone());
} catch(CloneNotSupportedException e) {
}
}
}
main.getBlindHelper().synchronizeLatest(c);
}
/**
* 删除掉最近联系人中lastMessageTime最小的model
*/
private void removeLRUModel() {
User lruUser = null;
Cluster lruCluster = null;
long min = Long.MAX_VALUE;
for(User f : latestGroup.users) {
if(f.lastMessageTime < min) {
min = f.lastMessageTime;
lruUser = f;
}
}
for(Cluster c : latestGroup.clusters) {
if(c.lastMessageTime < min) {
min = c.lastMessageTime;
lruCluster = c;
}
}
if(lruCluster != null)
latestGroup.removeCluster(lruCluster);
else if(lruUser != null)
latestGroup.removeUser(lruUser);
}
/**
* 同步最近联系人中的状态
*
* @param f
* 需要同步的好友
* @param redraw
* true表示立刻刷新
*/
public void synchronizedLatestStatus(User f, boolean redraw) {
if(latestGroup.hasUser(f.qq)) {
User u = latestGroup.getUser(f.qq);
u.status = f.status;
if(redraw)
refreshGroup(latestGroup);
}
}
/**
* 设置是否显示个性签名
*
* @param b
*/
public void setShowSignature(boolean b) {
ModelLabelProvider.INSTANCE.setShowSignature(b);
}
/**
* 设置是否显示自定义头像
*
* @param b
*/
public void setShowCustomHead(boolean b) {
ModelLabelProvider.INSTANCE.setShowCustomHead(b);
}
}
|
package ru.otus.spring.dao;
import au.com.bytecode.opencsv.CSVReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Repository;
import ru.otus.spring.domain.Question;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
@Repository("daoCsv")
public class QuestionDaoCsvImpl implements QuestionDaoCsv {
private final Resource file;
private final ArrayList<Question> questions = new ArrayList<>();
public QuestionDaoCsvImpl(@Value("${csv.name}") Resource file) {
this.file = file;
}
public ArrayList<Question> getQuestionsDaoCsv(){
if (questions.isEmpty()) {
try {
List<String[]> allRows = new CSVReader(new InputStreamReader(file.getInputStream()), ',', '"', 1).readAll();
for (String[] row : allRows) {
this.questions.add(new Question(row));
}
} catch (IOException e) {
e.printStackTrace();
}
}
return questions;
}
}
|
package com.iuce.control;
public interface ILoginControl {
public boolean controlPassword(String password);
public boolean resetPassword(String password);
public boolean savePassword(String password);
public boolean controlFirstOpen();
public boolean changePassword(String currentPassword, String newPassword);
}
|
package utils;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.opencv_core.IplImage;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Converters {
/**
* Converts an iplImage to a ByteArray
*
* @param img
* @return
* @throws IOException
*/
public static byte[] iplImageToByteArray(IplImage img) throws IOException {
BufferedImage im = new Java2DFrameConverter().convert(new OpenCVFrameConverter.ToIplImage().convert(img));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] barr = null;
try {
ImageIO.write(im, "jpg", baos);
baos.flush();
barr = baos.toByteArray();
} finally {
baos.close();
}
return barr;
}
/**
* Converts an iplImage to a BufferedImage
*
* @param src
* @return
*/
public static BufferedImage convertIplImageToBuffImage(IplImage src) {
OpenCVFrameConverter.ToIplImage grabberConverter = new OpenCVFrameConverter.ToIplImage();
Java2DFrameConverter paintConverter = new Java2DFrameConverter();
Frame frame = grabberConverter.convert(src);
return paintConverter.getBufferedImage(frame, 1);
}
/**
* Converts a BufferedImage to an IplImage
*
* @param img
* @return
*/
public static IplImage convertBuffToIplImage(BufferedImage img) {
Java2DFrameConverter converter1 = new Java2DFrameConverter();
OpenCVFrameConverter.ToIplImage converter2 = new OpenCVFrameConverter.ToIplImage();
IplImage iploriginal = converter2.convert(converter1.convert(img));
return iploriginal.clone();
}
}
|
package com.tencent.mm.plugin.appbrand.game;
class d$2 implements Runnable {
final /* synthetic */ int doP;
final /* synthetic */ String fwv;
final /* synthetic */ d fzU;
d$2(d dVar, int i, String str) {
this.fzU = dVar;
this.doP = i;
this.fwv = str;
}
public final void run() {
d.a(this.fzU, this.doP, this.fwv);
}
}
|
// Sun Certified Java Programmer
// Chapter 2, P109
// Object Orientation
class Horse extends Animal {
//private void eat() { } // Access modifier is more restrictive
//public void eat() throws IOException { } // Declares a checked
// exception not defined by superclass version
//public void eat(String food) { } // A legal overload, not an override,
// because the argument list changed
public String eat() {
} // Not an override because of the return type,
// not an overload either because there's no change in the argument list
}
|
package intra;
import java.util.Scanner;
//Question ||.1
public class Main {
public static void main(String[] args) {
double a ,b ;
Scanner kb =new Scanner(System.in);
System.out.println("saisir le primére number ");
a = kb.nextDouble();
System.out.println("saisir le primére number ");
b = kb.nextDouble();
affichage(calculePuissance(a,b));
}
public static double calculePuissance(double a ,double b ){
double puissance = 1 ;
for (int i = 0 ; i <b;i++ ){
puissance = a*puissance ;
}return puissance ;
}
public static void affichage(double puissance){
System.out.println("le puissance va Etre : "+puissance);
}
}
|
package com.acms.jdbc;
public class Student {
private int student_id;
private String first_name;
private String last_name;
private String address;
private String email;
private String telephone;
private boolean isDeleted;
public Student(int student_id, String first_name, String last_name, String address, String email, String telephone, boolean isDeleted) {
this.student_id = student_id;
this.first_name = first_name;
this.last_name = last_name;
this.address = address;
this.email = email;
this.telephone = telephone;
this.isDeleted = isDeleted;
}
public Student(int student_id, String first_name, String last_name, String address, String email,
String telephone) {
super();
this.student_id = student_id;
this.first_name = first_name;
this.last_name = last_name;
this.address = address;
this.email = email;
this.telephone = telephone;
}
public Student(String first_name, String last_name, String address, String email,
String telephone) {
this.first_name = first_name;
this.last_name = last_name;
this.address = address;
this.email = email;
this.telephone = telephone;
}
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public String toString() {
return "Student [student_id=" + student_id + ", first_name=" + first_name + ", last_name=" + last_name
+ ", address=" + address + ", email=" + email + ", telephone=" + telephone + "]";
}
}
|
package ast.identifier;
import parser.*;
public class VariableFunctionIdentifier extends Identifier {
public VariableFunctionIdentifier(Token idToken) {
super(idToken);
}
}
|
package com.learn.learn.bassis.强软弱虚引用;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: LL
* @Description:
* @Date:Create:in 2020/12/17 11:01
*/
class Main {
public static void main(String[] args) {
//强引用
String strongReference = new String("abc");
//软引用 内存空间充足时,垃圾回收器就不会回收它
String str = new String("abc");
SoftReference<String> softReference = new SoftReference<>(str);
//弱引用 不管当前内存空间足够与否,都会回收它的内存
String str1 = new String("abc");
WeakReference<String> weakReference = new WeakReference<>(str1);
//虚引用
String str2 = new String("abc");
ReferenceQueue queue = new ReferenceQueue();
// 创建虚引用,要求必须与一个引用队列关联
PhantomReference pr = new PhantomReference(str2, queue);
List list = new ArrayList();
for (int i = 0; i < 10; i++) {
Object o = new Object();
list.add(o);
o = null;
}
System.out.println(list.get(1));
}
}
|
/*
* Copyright 2010-2011, CloudBees Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudbees.api;
/**
* @author Olivier Lamy
*/
public class BeesClientConfiguration {
private String serverApiUrl;
private String apiKey;
private String secret;
private String format;
private String version;
private String proxyHost;
private int proxyPort;
private String proxyUser;
private String proxyPassword;
public BeesClientConfiguration(String serverApiUrl, String apiKey, String secret, String format, String version) {
this.serverApiUrl = serverApiUrl;
this.apiKey = apiKey;
this.secret = secret;
this.format = format;
this.version = version;
}
public String getServerApiUrl()
{
return serverApiUrl;
}
public void setServerApiUrl( String serverApiUrl )
{
this.serverApiUrl = serverApiUrl;
}
public String getProxyHost()
{
return proxyHost;
}
public void setProxyHost( String proxyHost )
{
this.proxyHost = proxyHost;
}
public int getProxyPort()
{
return proxyPort;
}
public void setProxyPort( int proxyPort )
{
this.proxyPort = proxyPort;
}
public String getProxyUser()
{
return proxyUser;
}
public void setProxyUser( String proxyUser )
{
this.proxyUser = proxyUser;
}
public String getProxyPassword()
{
return proxyPassword;
}
public void setProxyPassword( String proxyPassword )
{
this.proxyPassword = proxyPassword;
}
public String getApiKey()
{
return apiKey;
}
public void setApiKey(String apiKey)
{
this.apiKey = apiKey;
}
public String getSecret()
{
return secret;
}
public void setSecret( String secret )
{
this.secret = secret;
}
public String getFormat()
{
return format;
}
public void setFormat( String format )
{
this.format = format;
}
public String getVersion()
{
return version;
}
public void setVersion( String version )
{
this.version = version;
}
}
|
package com.tencent.mm.plugin.wallet.balance.a;
import com.tencent.mm.plugin.wallet_core.model.ab;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.c.d;
import com.tencent.mm.wallet_core.tenpay.model.i;
import com.tencent.mm.wallet_core.ui.e;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public final class b extends i implements d {
public int bIH = 0;
public String bQa = null;
public String ced;
public String cee;
public String cef;
public String ceg;
public String ceh;
public double mxE = 0.0d;
public double mxP = 0.0d;
public String oYA = "";
public com.tencent.mm.plugin.wallet_core.model.b oYB;
public com.tencent.mm.plugin.wallet_core.model.b oYC;
public double oYD;
public boolean oYz = false;
public b(double d, String str, String str2, int i) {
Map hashMap = new HashMap();
this.oYD = (double) Math.round(100.0d * d);
hashMap.put("total_fee", e.c(String.valueOf(d), "100", RoundingMode.HALF_UP).toString());
hashMap.put("fee_type", str);
hashMap.put("bank_type", str2);
hashMap.put("operation", String.valueOf(i));
F(hashMap);
}
public final int aBO() {
return 75;
}
public final void a(int i, String str, JSONObject jSONObject) {
x.d("Micromsg.NetSceneTenpayBalanceFetch", "errCode " + i + " errMsg: " + str);
if (i == 0) {
this.bQa = jSONObject.optString("req_key");
this.oYz = "1".equals(jSONObject.optString("should_alert"));
this.oYA = jSONObject.optString("alert_msg");
this.mxE = jSONObject.optDouble("charge_fee", 0.0d) / 100.0d;
this.mxP = jSONObject.optDouble("total_fee", 0.0d) / 100.0d;
JSONObject optJSONObject = jSONObject.optJSONObject("first_fetch_info");
if (optJSONObject != null) {
x.i("Micromsg.NetSceneTenpayBalanceFetch", "getBalanceFetchInfo(), first_fetch_info is valid");
this.oYB = ab.a(optJSONObject, false);
} else {
x.e("Micromsg.NetSceneTenpayBalanceFetch", "getBalanceFetchInfo(), first_fetch_info is null");
}
optJSONObject = jSONObject.optJSONObject("need_charge_fee_info");
if (optJSONObject != null) {
x.i("Micromsg.NetSceneTenpayBalanceFetch", "getBalanceFetchInfo(), need_charge_fee_info is valid");
this.oYC = ab.a(optJSONObject, false);
} else {
x.e("Micromsg.NetSceneTenpayBalanceFetch", "getBalanceFetchInfo(), need_charge_fee_info is null");
}
this.bIH = jSONObject.optInt("operation", 0);
x.i("Micromsg.NetSceneTenpayBalanceFetch", "charge_fee:" + this.mxE + " total_fee:" + this.mxP + " operation:" + this.bIH);
if (jSONObject.has("real_name_info")) {
optJSONObject = jSONObject.optJSONObject("real_name_info");
x.i("Micromsg.NetSceneTenpayBalanceFetch", "get real_name_info %s", optJSONObject.toString());
this.ced = optJSONObject.optString("guide_flag");
this.cee = optJSONObject.optString("guide_wording");
this.cef = optJSONObject.optString("left_button_wording");
this.ceg = optJSONObject.optString("right_button_wording");
this.ceh = optJSONObject.optString("upload_credit_url");
}
}
}
public final int If() {
return 1503;
}
public final String getUri() {
return "/cgi-bin/mmpay-bin/tenpay/genprefetch";
}
}
|
/*
* Copyright 2008 University of California at Berkeley
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.rebioma.client.services;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.rebioma.client.DataSwitch;
import org.rebioma.client.OccurrenceCommentQuery;
import org.rebioma.client.OccurrenceQuery;
import org.rebioma.client.bean.Occurrence;
import org.rebioma.client.bean.OccurrenceComments;
import org.rebioma.client.bean.OccurrenceReview;
import org.rebioma.client.bean.SearchFieldNameValuePair;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* Service for fetching {@link Occurrence} objects from the server.
*
*/
@RemoteServiceRelativePath("occurrenceService")
public interface OccurrenceService extends RemoteService {
/**
* Custom exception for occurrence service errors.
*/
@SuppressWarnings("serial")
public class OccurrenceServiceException extends Exception implements
IsSerializable {
public OccurrenceServiceException() {
this(null);
}
public OccurrenceServiceException(final String msg) {
super(msg);
}
}
/**
* Provides a singleton proxy to {@link OccurrenceService}. Clients typically
* use the proxy as follows:
*
* OccurrenceService.Proxy.get();
*/
public static class Proxy {
/**
* The singleton proxy instance.
*/
private static OccurrenceServiceAsync service;
/**
* Returns the singleton proxy instance and creates it if needed.
*/
public static synchronized OccurrenceServiceAsync get() {
if (service == null) {
service = GWT.create(OccurrenceService.class);
}
return service;
}
}
/**
* Deletes all {@link Occurrence} that match the given query.
*
* @param sessionId the current user session id
* @param query the query use to delete these {@link Occurrence}
* @return number of records get deleted
* @throws OccurrenceServiceException TODO
*/
public int delete(String sessionId, OccurrenceQuery query)
throws OccurrenceServiceException;
/**
* Deletes a set of {@link Occurrence} objects.
*
* @param sessionId the session id
* @param occurrences the occurrences tod delete
*/
public String delete(String sessionId, Set<Occurrence> occurrences)
throws OccurrenceServiceException;
/**
* Deletes all {@link OccurrenceComments} that match the given query.
*
* @param sid the current user session id
* @param comments the set of {@link OccurrenceComments} to be deleted
* @return number of records get deleted
* @throws OccurrenceServiceException
*/
public Integer deleteComments(String sid, Set<OccurrenceComments> comments)
throws OccurrenceServiceException;
/**
* This method queries the server for {@link OccurrenceComments} objects
* according to specifications in the {@link OccurrenceCommentQuery} and
* returns the same {@link OccurrenceCommentQuery} (that contains the original
* query specification) along with the resulting set of
* {@link OccurrenceComments} objects.
*
* @param query the occurrence comment query
* @return the occurrence comment query as results
*/
public OccurrenceCommentQuery fetch(OccurrenceCommentQuery query)
throws OccurrenceServiceException;
/**
* This method queries the server for {@link Occurrence} objects according to
* specifications in the {@link OccurrenceQuery} and returns the same
* {@link OccurrenceQuery} (that contains the original query specification)
* along with the resulting set of {@link Occurrence} objects. It should fail
* if the session id is invalid.
*
* @param sessionId the session id
* @param query the occurrence query
* @return the occurrence query as results
*/
public OccurrenceQuery fetch(String sessionId, OccurrenceQuery query)
throws OccurrenceServiceException;
/**
* This method returns the last time an {@link Occurrence} was created,
* updated, or deleted from the database. This is useful because the
* {@link DataSwitch} cache should be cleared if updates have happened so that
* users can have a sychronized view of {@link Occurrence} data.
*
* @return the last occurrence create, update, or delete time
* @throws OccurrenceServiceException
*/
public Long lastUpdateInMilliseconds() throws OccurrenceServiceException;
public int reviewRecords(String sid, Boolean reviewed, OccurrenceQuery query, String comment, boolean notified)
throws OccurrenceServiceException;
public int reviewRecords(String sid, Boolean reviewed,
Set<Integer> occurrenceIds, String comment, boolean noified) throws OccurrenceServiceException;
/**
* Updates a set of {@link Occurrence} objects.
*
* @param sessionId the session id
* @param occurrences set of occurrences to update
* @return error message or null if no error
* @throws OccurrenceServiceException
*/
public Integer update(String sessionId, OccurrenceQuery query)
throws OccurrenceServiceException;
/**
* Updates a set of {@link Occurrence} objects.
*
* @param sessionId the session id
* @param occurrences set of occurrences to update
* @return error message or null if no error
* @throws OccurrenceServiceException
*/
public String update(String sessionId, Set<Occurrence> occurrences)
throws OccurrenceServiceException;
public String update(String sessionId, Set<Occurrence> occurrences, boolean resetReview)
throws OccurrenceServiceException;
int updateComments(String sessionId, Integer owner,
Set<OccurrenceComments> comments, boolean emailing) throws OccurrenceServiceException;
Map<Integer, Boolean> getMyReviewedOnRecords(String sid,
Map<Integer, Integer> rowOccIdsMap) throws OccurrenceServiceException;
List<OccurrenceReview> getOccurrenceReviewsOf(Integer occId)
throws OccurrenceServiceException;
public boolean editUpdate(List<Occurrence> occurrences, String sessionId);
int commentRecords(String sid, Set<Integer> occurrenceIds, String comment,
boolean notified);
}
|
package udf;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
public class SubString_Test {
public static void main(String[] args) {
EnvironmentSettings settings = EnvironmentSettings.newInstance()
.useBlinkPlanner()
.inStreamingMode()
.build();
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tenv = StreamTableEnvironment.create(env,settings);
tenv.createTemporarySystemFunction("substr", SubString.class);
try {
tenv.executeSql("create table scores " +
"(id INTEGER," +
"name String" +
") WITH ( " +
"'connector' = 'kafka-0.11'," +
"'topic'='r_source'," +
"'properties.bootstrap.servers' = '10.0.9.56:18108,10.0.9.57:18108,10.0.9.58:18108'," +
"'properties.group.id' = 'testGroup'," +
"'scan.startup.mode' = 'latest-offset'," +
"'format' = 'csv')");
tenv.executeSql("create table res_test " +
"(id INTEGER," +
"name String" +
// " WATERMARK FOR order_time AS order_time - INTERVAL '5' SECOND " +
") WITH ( " +
"'connector' = 'kafka-0.11'," +
"'topic'='r_sink'," +
"'properties.bootstrap.servers' = '10.0.9.56:18108,10.0.9.57:18108,10.0.9.58:18108'," +
"'properties.group.id' = 'testGroup'," +
"'scan.startup.mode' = 'latest-offset'," +
"'format' = 'csv')");
tenv.executeSql("insert into res_test select\n" +
"id,\n" +
"substr(name,0,1)\n" +
"from\n" +
"scores");
tenv.execute("hi");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package cn.bs.zjzc.model.impl;
import cn.bs.zjzc.App;
import cn.bs.zjzc.model.IRechargeModel;
import cn.bs.zjzc.model.callback.HttpTaskCallback;
import cn.bs.zjzc.model.response.RechargeResponse;
import cn.bs.zjzc.net.GsonCallback;
import cn.bs.zjzc.net.PostHttpTask;
import cn.bs.zjzc.net.RequestUrl;
/**
* Created by Ming on 2016/6/16.
*/
public class RechargeModel implements IRechargeModel {
@Override
public void recharge(String type, String money, final HttpTaskCallback<RechargeResponse.DataBean> callback) {
String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.recharge);
PostHttpTask<RechargeResponse> httpTask = new PostHttpTask<>(url);
httpTask.addParams("token", App.LOGIN_USER.getToken())
.addParams("type", type)
.addParams("money", money)
.execute(new GsonCallback<RechargeResponse>() {
@Override
public void onFailed(String errorInfo) {
callback.onTaskFailed(errorInfo);
}
@Override
public void onSuccess(RechargeResponse response) {
callback.onTaskSuccess(response.data);
}
});
}
}
|
package com.tencent.mm.plugin.appbrand.widget.sms;
public interface EditVerifyCodeView$a {
}
|
package com.workorder.activity.service.impl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.workorder.activity.service.ActivityService;
import com.workorder.ticket.model.TaskInfo;
@Service
public class ActivitiServiceImpl implements ActivityService {
private static final Logger LOGGER = LoggerFactory
.getLogger(ActivitiServiceImpl.class);
@Resource
public ProcessEngine processEngine;
@Resource
private RuntimeService runtimeService;
@Resource
private TaskService taskService;
@Resource
private HistoryService historyService;
@Resource
private RepositoryService repositoryService;
@Resource
private ProcessEngineConfigurationImpl processEngineConfiguration;
/**
* 启动流程
*
* @param bizId
* 业务id
*/
@Override
public String startProcesses(String processDefinitionId,
Map<String, Object> variables) {
ProcessInstance processInstance = runtimeService
.startProcessInstanceById(processDefinitionId, variables);
LOGGER.info("启动新流程,instanceId:{}", processInstance.getId());
return processInstance.getId();
}
/**
*
* <p>
* 描述: 根据用户id查询待办任务列表
* </p>
*
*/
@Override
public List<Task> findTasksByUserId(String processDefinitionId,
String processor) {
List<Task> resultTask = taskService.createTaskQuery()
.processDefinitionId(processDefinitionId)
.taskCandidateOrAssigned(processor).list();
return resultTask;
}
/**
* <p>
* 描述:获取当前任务
* </p>
*
*/
@Override
public Task getCurrentTask(String processInstanceId) {
return taskService.createTaskQuery()// 创建查询对象
.processInstanceId(processInstanceId)// 通过流程实例id来查询当前任务
.singleResult();
}
/**
*
* <p>
* 描述:任务审批 (通过/拒接)
* </p>
*
* @param taskId
* 任务id
* @param userId
* 用户id
* @param result
* false OR true
*/
@Override
public void completeTask(String taskId, String processor, Boolean result,
String comment) {
// 获取流程实例
taskService.claim(taskId, processor);
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("verify", result);
taskService.addComment(taskId, null, comment);
taskService.complete(taskId, vars);
}
/**
*
* <p>
* 描述: 查询历史任务列表
* </p>
*
*/
@Override
public List<TaskInfo> findHistoryTasks(String processInstanceId) {
List<HistoricActivityInstance> list = processEngine.getHistoryService()
.createHistoricActivityInstanceQuery()
.processInstanceId(processInstanceId).finished()
.orderByHistoricActivityInstanceEndTime().asc().list();
if (CollectionUtils.isEmpty(list)) {
return Collections.emptyList();
}
List<TaskInfo> result = new ArrayList<TaskInfo>();
for (HistoricActivityInstance hai : list) {
if ("exclusiveGateway".equals(hai.getActivityType())) {
// 过滤网关
continue;
}
List<Comment> comments = taskService.getTaskComments(hai
.getTaskId());
StringBuilder commentBuilder = new StringBuilder();
// 如果当前任务有批注
if (comments != null && comments.size() > 0) {
comments.forEach(item -> commentBuilder.append(item
.getFullMessage()));
}
result.add(new TaskInfo(hai.getTaskId(), hai.getActivityName(), hai
.getProcessInstanceId(), hai.getAssignee(), commentBuilder
.toString()));
}
return result;
}
/**
*
* <p>
* 描述:删除任务审批
* </p>
*
* @param processInstanceId
*/
@Override
public void deleteTask(String processInstanceId) {
runtimeService.deleteProcessInstance(processInstanceId, "删除任务");
}
/**
*
* <p>
* 描述: 生成流程图 首先启动流程,获取processInstanceId,替换即可生成
* </p>
*
* @param processInstanceId
* @throws Exception
*/
@Override
public void queryProImg(String processInstanceId) {
try {
// 获取历史流程实例
HistoricProcessInstance processInstance = historyService
.createHistoricProcessInstanceQuery()
.processInstanceId(processInstanceId).singleResult();
// 根据流程定义获取输入流
InputStream is = repositoryService
.getProcessDiagram(processInstance.getProcessDefinitionId());
BufferedImage bi = ImageIO.read(is);
File file = new File("demo2.png");
if (!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write(bi, "png", fos);
fos.close();
is.close();
System.out.println("图片生成成功");
List<Task> tasks = taskService.createTaskQuery()
.taskCandidateUser("userId").list();
for (Task t : tasks) {
System.out.println(t.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void getTaskHistory(String processInstanceId) {
List<HistoricActivityInstance> list = processEngine.getHistoryService()
.createHistoricActivityInstanceQuery()
.processInstanceId(processInstanceId).finished()
.orderByHistoricActivityInstanceId().asc().list();
for (HistoricActivityInstance hai : list) {
LOGGER.info("ID:{},活动名称:{}", hai.getId(), hai.getActivityName());
}
}
@Override
public String deploy(String bpmnKey) {
// 部署流程定义文件
RepositoryService repositoryService = processEngine
.getRepositoryService(); // 创建一个对流程编译库操作的Service
DeploymentBuilder deploymentBuilder = repositoryService
.createDeployment(); // 获取一个builder
deploymentBuilder.addClasspathResource("activiti/"+bpmnKey + ".bpmn20.xml"); // 这里写上流程编译路径
deploymentBuilder.key(bpmnKey);
Deployment deployment = deploymentBuilder.deploy(); // 部署
String deploymentId = deployment.getId(); // 获取deployment的ID
ProcessDefinition processDefinition = repositoryService
.createProcessDefinitionQuery().deploymentId(deploymentId)
.singleResult(); // 根据deploymentId来获取流程定义对象
LOGGER.info("流程定义文件 [{}] , 流程ID [{}], 部署ID[{}]",
processDefinition.getId(), processDefinition.getId(),
deploymentId);
return processDefinition.getId();
}
}
|
package com.mashibing;
import java.awt.*;
import java.util.function.Function;
/**
* @program: tank
* @author: hduprince
* @create: 2020-03-30 15:45
**/
public interface Movable {
default void move(Dir dir, Point point, Integer speed){
switch (dir) {
case LEFT:
point.x = point.x - speed;
break;
case RIGHT:
point.x = point.x + speed;
break;
case UP:
point.y = point.y - speed;
break;
case DOWN:
point.y = point.y + speed;
break;
}
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class m extends b {
public a bGA;
public m() {
this((byte) 0);
}
private m(byte b) {
this.bGA = new a();
this.sFm = false;
this.bJX = null;
}
}
|
package co.sptnk.service.impl.mapper;
import co.sptnk.service.impl.mapper.configure.BeanMappingConfigure;
import org.dozer.DozerBeanMapper;
/**
* Created by Владимир on 02.11.2016.
*
* Абстрактная имплемнентация маппера
*/
public abstract class AbstractDozerMapper<TO, FROM> implements DozerMapping<TO, FROM> {
private Class<FROM> fromClass;
private Class<TO> toClass;
private DozerBeanMapper beanMapper;
public AbstractDozerMapper(Class<FROM> fromClass, Class<TO> toClass){
this.fromClass = fromClass;
this.toClass = toClass;
this.beanMapper = getBeanMapper();
}
@Override
public TO map(FROM from) throws IllegalAccessException, InstantiationException {
TO destinations = toClass.newInstance();
beanMapper.map(from, destinations);
return destinations;
}
public TO map(FROM from, TO to) {
beanMapper.map(from, to);
return to;
}
private DozerBeanMapper getBeanMapper() {
DozerBeanMapper dozerBeanMapper = new DozerBeanMapper();
dozerBeanMapper.addMapping(new BeanMappingConfigure(fromClass, toClass));
return dozerBeanMapper;
}
}
|
package com.developpez.lmauzaize.java.concurrence.ch02_synchronisation.api_native;
import com.developpez.lmauzaize.java.concurrence.Logger;
public class WaitTempsAttente {
public static void main(String[] args) {
//////////////////////////////////////////
new Thread() {
public void run() {
Object verrou = new Object();
Logger.println("Synchronisation");
synchronized (verrou) {
Logger.println("Attente - début");
try {
verrou.wait(1_000);
Logger.println("Attente - fin");
} catch (InterruptedException e) {
Logger.printStackTrace(e);
}
}
}
}.start();
//////////////////////////////////////////
}
}
|
package model;
import exception.NoSuggestionsException;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
//Class to test Suggest University
public class SuggestUniversityTest {
@Test
public void SuggestNoUniversityTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming", "cs", "canada"));
dataList.add((new DataChoices("robotics", "math", "usa", "UC Berkley")));
dataList.add((new DataChoices("robotics", "Information Technology", "india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
try {
suggestion.suggestion();
} catch (NoSuggestionsException e) {
//pass
}
}
@Test
public void SuggestUniversityBasedOnMajorTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming","math","canada"));
dataList.add((new DataChoices("robotics","math","usa","UC Berkley")));
dataList.add((new DataChoices("robotics","Information Technology","india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
}
@Test
public void SuggestUniversityBasedOnInterestTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming","math","canada"));
dataList.add((new DataChoices("gaming","cs","usa","UC Berkley")));
dataList.add((new DataChoices("robotics","Information Technology","india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
try {
assertEquals("UC Berkley" ,suggestion.suggestion().get(0));
} catch (NoSuggestionsException e) {
fail();
}
}
@Test
public void SuggestUniversityBasedOnLocationTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming","math","usa"));
dataList.add((new DataChoices("robotics","cs","usa","UC Berkley")));
dataList.add((new DataChoices("robotics","Information Technology","india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
try {
assertEquals("UC Berkley" ,suggestion.suggestion().get(0));
} catch (NoSuggestionsException e) {
fail();
}
}
@Test
public void SuggestUniversityBasedOnMultipleTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming","math","canada"));
dataList.add((new DataChoices("gaming","math","usa","UC Berkley")));
dataList.add((new DataChoices("robotics","Information Technology","india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
try {
assertEquals("UC Berkley" ,suggestion.suggestion().get(0));
} catch (NoSuggestionsException e) {
fail();
}
}
@Test
public void SuggestUniversityBasedOnAllTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming","math","usa"));
dataList.add((new DataChoices("gaming","math","usa","UC Berkley")));
dataList.add((new DataChoices("robotics","Information Technology","india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
try {
assertEquals("UC Berkley" ,suggestion.suggestion().get(0));
} catch (NoSuggestionsException e) {
fail();
}
}
@Test
public void SuggestTwoUniversitiesTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming","math","canada"));
dataList.add((new DataChoices("gaming","math","usa","UC Berkley")));
dataList.add((new DataChoices("gaming","Information Technology","india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
try {
assertEquals("UC Berkley" + "IIT Bombay",
suggestion.suggestion().get(0)+suggestion.suggestion().get(1));
} catch (NoSuggestionsException e) {
fail();
}
}
@Test
public void SuggestMoreThanFiveUniversitiesTest() {
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
userList.add(new UserChoices("gaming","math","canada"));
dataList.add((new DataChoices("gaming","math","usa","UC Berkley")));
dataList.add((new DataChoices("gaming","math","usa","UCSD")));
dataList.add((new DataChoices("gaming","math","usa","NYU")));
dataList.add((new DataChoices("robotics","math","usa","NYU")));
dataList.add((new DataChoices("gaming","math","usa","Stanford")));
dataList.add((new DataChoices("gaming","math","usa","UofC")));
dataList.add((new DataChoices("gaming","Information Technology","india",
"IIT Bombay")));
SuggestUniversity suggestion = new SuggestUniversity(userList, dataList);
try {
assertEquals("UC Berkley" + "UCSD" + "NYU" + "Stanford" + "UofC"
,suggestion.suggestion().get(0)+suggestion.suggestion().get(1)
+suggestion.suggestion().get(2)+suggestion.suggestion().get(3)+suggestion.suggestion().get(4));
} catch (NoSuggestionsException e) {
fail();
}
}
}
|
package de.propra2.ausleiherino24.data;
import de.propra2.ausleiherino24.model.Case;
import de.propra2.ausleiherino24.model.CustomerReview;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@DataJpaTest
@ActiveProfiles(profiles = "test")
public class CustomerReviewRepoTest {
@Autowired
private CustomerReviewRepository customerReviews;
private List<CustomerReview> customerReviewList;
@BeforeEach
public void init() {
final CustomerReview customerReview1 = new CustomerReview();
final CustomerReview customerReview2 = new CustomerReview();
customerReviewList = new ArrayList<>();
customerReview1.setText("test1");
customerReview1.setTimestamp(10012019L);
customerReview1.setStars(3);
customerReview1.setAcase(new Case());
customerReview2.setText("test2");
customerReview2.setTimestamp(11012019L);
customerReview2.setStars(5);
customerReview2.setAcase(new Case());
customerReviewList.add(customerReview1);
customerReviewList.add(customerReview2);
}
@Test
public void databaseShouldSaveEntities() {
customerReviews.saveAll(customerReviewList);
final List<CustomerReview> crvws = customerReviews.findAll();
Assertions.assertThat(crvws.size()).isEqualTo(2);
Assert.assertTrue(crvws.contains(customerReviewList.get(0)));
Assert.assertTrue(crvws.contains(customerReviewList.get(1)));
}
}
|
package cn.joyfollow.k21smartplayer;
import android.content.Context;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
import io.flutter.plugin.common.StandardMessageCodec;
import static io.flutter.plugin.common.PluginRegistry.Registrar;
public class SmartPlayerViewFactory extends PlatformViewFactory {
private final Registrar mPluginRegistrar;
public SmartPlayerViewFactory(Registrar registrar) {
super(StandardMessageCodec.INSTANCE);
mPluginRegistrar = registrar;
}
@Override
public PlatformView create(Context context, int i, Object o) {
return new SmartPlayerViewController(context, mPluginRegistrar, i);
}
}
|
package instruments;
import interfaces.IPlayable;
import interfaces.ISellable;
public class Instrument extends Product implements IPlayable {
private String model;
private String brand;
private String type;
private double buyingPrice;
private double sellingPrice;
private String sound;
public Instrument (String model, String brand, String type, double buyingPrice, double sellingPrice, String sound) {
this.model = model;
this.brand = brand;
this.type = type;
this.buyingPrice = buyingPrice;
this.sellingPrice = sellingPrice;
this.sound = sound;
}
public String getModel() {
return this.model;
}
public String getBrand() {
return this.brand;
}
public String getType() {
return this.type;
}
public double getBuyingPrice() {
return this.buyingPrice;
}
public double getSellingPrice() {
return this.sellingPrice;
}
public double markup() {
double margin = this.getSellingPrice() - this.getBuyingPrice();
double markup = (margin / this.getBuyingPrice()) * 100;
double markupPercentage = Math.round(markup * 100.0) / 100.0;
return markupPercentage;
}
//
public double calculateMarkup() {
return markup();
}
public String play(){
return this.sound;
}
}
|
package com.gtfs.dao.impl;
import java.io.Serializable;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.hibernate.type.DateType;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.gtfs.dao.UserMstDao;
import com.gtfs.dto.UserMstDto;
import com.gtfs.pojo.UserMst;
@Repository
public class UserMstDaoImpl implements UserMstDao, Serializable {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<UserMstDto> findAll() {
Session session = null;
List<UserMstDto> list = null;
try {
session = sessionFactory.openSession();
SQLQuery query = (SQLQuery) session.createSQLQuery(
"SELECT "
+ "UM.ID as id, "
+ "UM.USER_NAME as userName, "
+ "UM.USER_TYPE as userType, "
+ "UM.LOGIN_ID as loginId, "
+ "UM.PASSWORD as password, "
+ "UM.CREATED_BY as createdBy, "
+ "UM.MODIFIED_BY as modifiedBy, "
+ "UM.DELETED_BY as deletedBy, "
+ "UM.CREATED_DATE as createdDate, "
+ "UM.MODIFIED_DATE as modifiedDate, "
+ "UM.DELETED_DATE as deletedDate, "
+ "UM.DELETE_FLAG as deleteFlag "
+ "FROM "
+ "USER_MST UM "
+ "WHERE "
+ "UM.DELETE_FLAG = 'N'");
query.addScalar("id", LongType.INSTANCE);
query.addScalar("userName", StringType.INSTANCE);
query.addScalar("userType", StringType.INSTANCE);
query.addScalar("loginId", StringType.INSTANCE);
query.addScalar("password", StringType.INSTANCE);
query.addScalar("createdBy", LongType.INSTANCE);
query.addScalar("modifiedBy", LongType.INSTANCE);
query.addScalar("deletedBy", LongType.INSTANCE);
query.addScalar("createdDate", DateType.INSTANCE);
query.addScalar("modifiedDate", DateType.INSTANCE);
query.addScalar("deletedDate", DateType.INSTANCE);
query.addScalar("deleteFlag", StringType.INSTANCE);
query.setResultTransformer(Transformers.aliasToBean(UserMstDto.class));
list = query.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return list;
}
@Override
public UserMst findById(Long id) {
UserMst userMst = null;
Session session = null;
try {
session = sessionFactory.openSession();
userMst = (UserMst) session.get(UserMst.class, id);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return userMst;
}
@Override
public Boolean saveOrUpdate(UserMst userMst) {
Boolean status = false;
Session session = null;
Transaction tx = null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
session.saveOrUpdate(userMst);
tx.commit();
status = true;
} catch (Exception e) {
if(tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return status;
}
}
|
package com.dreamcatcher.factory;
import com.dreamcatcher.action.Action;
import com.dreamcatcher.main.action.*;
public class MainActionFactory {
private static Action mainViewAction;
private static Action mainSiteArticleSortAction;
private static Action mainRouteArticleSortAction;
static{
mainViewAction = new MainViewAction();
mainSiteArticleSortAction = new MainSiteArticleSortAction();
mainRouteArticleSortAction = new MainRouteArticleSortAction();
}
public static Action getMainRouteArticleSortAction() {
return mainRouteArticleSortAction;
}
public static Action getMainSiteArticleSortAction() {
return mainSiteArticleSortAction;
}
public static Action getMainViewAction() {
return mainViewAction;
}
}
|
//TODO Work more on the sign in options
/*
Home screen class with signin, and home-screen options of new case,
all avail mishnayos, and user's mishnayos
*/
package com.example.mna.mishnapals;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import static com.example.mna.mishnapals.SignInOptions.googleApiClient;
public class HomeScreen extends AppCompatActivity {
Button searchCaseButton;
EditText caseSearch;
private FirebaseAuth fAuth;
//FirebaseDatabase fbdb;
//DatabaseReference ref;
FirebaseUser user;
@Override
public boolean onCreateOptionsMenu(Menu menu){
fAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient= new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
})
.addApiIfAvailable(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
MenuInflater inflator = getMenuInflater();
inflator.inflate(R.menu.mishna_pals_menu, menu);
return true;
}
/* Used before started using firebaseUI
@Override
public boolean onOptionsItemSelected(MenuItem item){
fAuth.signOut();
Auth.GoogleSignInApi.signOut(googleApiClient);
startActivity(new Intent(getBaseContext(), SignInOptions.class));
HomeScreen.this.finish();
return true;
}
*/
@Override
public boolean onOptionsItemSelected(MenuItem item){
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(@NonNull Task<Void> task) {
startActivity(new Intent(getBaseContext(), FirebaseUI_Auth.class));
HomeScreen.this.finish();
}
});
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null)
{
// startActivity(new Intent(getBaseContext(), EmailPassword.class));
startActivity(new Intent(getBaseContext(), FirebaseUI_Auth.class));
HomeScreen.this.finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
//setContentView(R.layout.home_screen_horizontal);
View layout = findViewById(R.id.backgroundLayoutHome);
Drawable background = layout.getBackground();
background.setAlpha(50);
Button newCase = (Button) findViewById(R.id.newCase);
newCase.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
newCaseClicked(v);
}
}
);
Button allAvail = (Button) findViewById(R.id.viewAllAvailButton);
allAvail.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
viewAllClicked(v);
}
}
);
final Button myMishnayos = (Button)findViewById(R.id.myMishnayosButton);
myMishnayos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myMishnayosClicked(v);
}
});
searchCaseButton = (Button) findViewById(R.id.searchCaseButton);
caseSearch = (EditText) findViewById(R.id.caseIdSearch);
searchCaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), SearchResult.class);
intent.putExtra("caseId", caseSearch.getText().toString());
startActivity(intent);
}
});
}
public void newCaseClicked(View view)
{
Intent intent = new Intent(getBaseContext(), NewCase.class);
startActivity(intent);
}
/*
Check db for the public cases, put them into an arraylist and package into Intent to
pass to "PublicCases' class
*/
public void viewAllClicked(View view)
{
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference();
Query publicCase = dbref.child("cases").orderByChild("privateCase").equalTo(false);
publicCase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<Case> publicCases = new ArrayList<Case>();
final ArrayList<String> publicCaseNames = new ArrayList<String>();
final ArrayList<String> publicCaseKeys = new ArrayList<String>();
for(DataSnapshot ds : dataSnapshot.getChildren())
{
publicCaseKeys.add(ds.getKey());
publicCases.add(ds.getValue(Case.class));
publicCaseNames.add(ds.getValue(Case.class).getFirstName());
Log.d("aaaaa", ""+ds.getValue(Case.class).firstName);
}
Bundle extras = new Bundle();
extras.putSerializable("Arraylist", publicCases);
Intent intent = new Intent(getBaseContext(), PublicCases.class);
intent.putExtra("caseNames", publicCaseNames).putExtra("cases", extras).putExtra("caseIds", publicCaseKeys);
startActivity(intent);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
/*FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Log.d("CURRENTUSERHome", user.getUid());
Intent intent = new Intent(getBaseContext(), MasechtosList.class);
startActivity(intent);*/
}
public void myMishnayosClicked(View view)
{
startActivity(new Intent(getBaseContext(), MyMishnayos.class));
}
}
|
package web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AreaServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String areaName = request.getParameter("areaName");
// 判断是否存在此区域
boolean isArea = true;//从数据库中查询
if (isArea) {
// 如果存在,则查出此区域的对象
request.getSession().setAttribute("area", areaName);//从数据库中获取
request.getSession().setAttribute("price", 200);//从数据库中获取
response.sendRedirect("seat.jsp");
} else {
// 如果不存在,则弹出提示窗并返回区域选择页面
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<script>alert('请先选择一个区域!');location.href='area.jsp'</script>");
out.flush();
out.close();
}
}
}
|
package com.lei.domain.response.test;
import com.lei.domain.response.Response;
import com.thoughtworks.xstream.XStream;
public class TestResponse extends Response {
/**
* 序列号
*/
private static final long serialVersionUID = 1L;
/**
* 性别
*/
private String sex;
/**
* 年龄
*/
private int age;
/**
* 身份证号
*/
private String idCard;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("TestResponse [sex=");
builder.append(sex);
builder.append(", age=");
builder.append(age);
builder.append(", idCard=");
builder.append(idCard);
builder.append("]");
return builder.toString();
}
@Override
public void setAlias(XStream xstream) {
xstream.alias("Response", TestResponse.class);
}
}
|
package com.hcl.dmu.demand.stream.dao;
import java.util.List;
import com.hcl.dmu.demand.entity.DemandStreamEntity;
import com.hcl.dmu.demand.vo.DemandStreamVo;
public interface StreamDao {
public List<DemandStreamVo> getAllStreamDetails();
DemandStreamEntity findById(Long id);
}
|
package com.tencent.mm.ui.chatting.b;
import android.content.Context;
import android.content.Intent;
import android.util.SparseBooleanArray;
import android.view.MenuItem;
import android.widget.Toast;
import com.tencent.mm.R;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.m;
import com.tencent.mm.model.q;
import com.tencent.mm.modelsfs.FileOp;
import com.tencent.mm.modelvideo.o;
import com.tencent.mm.modelvideo.r;
import com.tencent.mm.modelvideo.s;
import com.tencent.mm.modelvideo.t;
import com.tencent.mm.network.ab;
import com.tencent.mm.plugin.appbrand.s$l;
import com.tencent.mm.plugin.mmsight.SightCaptureResult;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.sight.decode.a.b;
import com.tencent.mm.pluginsdk.model.j;
import com.tencent.mm.pluginsdk.ui.tools.l;
import com.tencent.mm.protocal.c.aso;
import com.tencent.mm.sdk.f.e;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.b.a.a;
import com.tencent.mm.ui.chatting.b.b.af;
import com.tencent.mm.ui.chatting.gallery.ImageGalleryUI;
import com.tencent.mm.ui.transmit.MsgRetransmitUI;
import java.util.ArrayList;
@a(cwo = af.class)
public class an extends a implements af {
private long tTb = -1;
private SparseBooleanArray tTc = new SparseBooleanArray();
private void do(final String str, final int i) {
au.Em().H(new Runnable() {
public final void run() {
t.W(str, i);
}
});
}
public final boolean a(MenuItem menuItem, bd bdVar) {
int i;
switch (menuItem.getItemId()) {
case s$l.AppCompatTheme_ratingBarStyle /*106*/:
r nI = o.Ta().nI(bdVar.field_imgPath);
if (nI == null) {
x.e("MicroMsg.ChattingUI.VideoComponent", "save video but videoInfo is null!");
} else if (nI.status == 199) {
o.Ta();
String nK = s.nK(bdVar.field_imgPath);
if (nI != null) {
i = 0;
if (com.tencent.mm.model.s.fq(nI.Tj())) {
i = m.gK(nI.Tj());
}
h.mEJ.a(106, 215, 1, false);
h.mEJ.h(12084, new Object[]{Integer.valueOf(nI.dHI), Integer.valueOf(nI.enM * 1000), Integer.valueOf(0), Integer.valueOf(2), nI.Tj(), Integer.valueOf(i), r.nH(nI.Tm()), Long.valueOf(nI.createTime)});
}
String nX = t.nX(nK);
if (bi.oW(nX)) {
Toast.makeText(this.bAG.tTq.getContext(), this.bAG.tTq.getMMResources().getString(R.l.video_file_save_failed), 1).show();
} else {
Toast.makeText(this.bAG.tTq.getContext(), this.bAG.tTq.getMMResources().getString(R.l.video_file_saved, new Object[]{nX}), 1).show();
l.a(nX, this.bAG.tTq.getContext());
}
} else {
do(nI.getFileName(), 6);
Intent intent = new Intent(this.bAG.tTq.getContext(), ImageGalleryUI.class);
intent.putExtra("img_gallery_msg_id", bdVar.field_msgId);
intent.putExtra("img_gallery_msg_svr_id", bdVar.field_msgSvrId);
intent.putExtra("img_gallery_talker", bdVar.field_talker);
intent.putExtra("img_gallery_chatroom_name", bdVar.field_talker);
intent.putExtra("img_gallery_enter_video_opcode", t.e(bdVar.field_msgId, 2));
i.a(this.bAG, bdVar, intent);
this.bAG.tTq.startActivity(intent);
this.bAG.tTq.overridePendingTransition(0, 0);
}
return true;
case s$l.AppCompatTheme_ratingBarStyleIndicator /*107*/:
au.HU();
if (!c.isSDCardAvailable()) {
com.tencent.mm.ui.base.s.gH(this.bAG.tTq.getContext());
break;
}
r nW = t.nW(bdVar.field_imgPath);
if (nW != null) {
if (!bdVar.cmu()) {
o.Ta();
Intent intent2;
if (!i.e(bdVar, s.nK(bdVar.field_imgPath))) {
if (nW.status != 199) {
if (!bdVar.cmj() && !bdVar.cmk()) {
x.w("MicroMsg.ChattingUI.VideoComponent", "retranmist video unknow status.");
break;
}
do(nW.getFileName(), 3);
intent2 = new Intent(this.bAG.tTq.getContext(), ImageGalleryUI.class);
intent2.putExtra("img_gallery_msg_id", bdVar.field_msgId);
intent2.putExtra("img_gallery_msg_svr_id", bdVar.field_msgSvrId);
intent2.putExtra("img_gallery_talker", bdVar.field_talker);
intent2.putExtra("img_gallery_chatroom_name", bdVar.field_talker);
intent2.putExtra("img_gallery_enter_video_opcode", t.e(bdVar.field_msgId, 1));
i.a(this.bAG, bdVar, intent2);
this.bAG.tTq.startActivity(intent2);
this.bAG.tTq.overridePendingTransition(0, 0);
if (!nW.To()) {
x.i("MicroMsg.ChattingUI.VideoComponent", "start complete offline video");
t.nS(bdVar.field_imgPath);
break;
}
x.i("MicroMsg.ChattingUI.VideoComponent", "start complete online video");
t.oa(bdVar.field_imgPath);
break;
}
intent2 = new Intent(this.bAG.tTq.getContext(), MsgRetransmitUI.class);
intent2.putExtra("Retr_length", nW.enM);
intent2.putExtra("Retr_File_Name", bdVar.field_imgPath);
intent2.putExtra("Retr_video_isexport", nW.enQ);
intent2.putExtra("Retr_Msg_Id", bdVar.field_msgId);
intent2.putExtra("Retr_From", "chattingui");
x.d("MicroMsg.ChattingUI.VideoComponent", "dkvideo msg.getType():" + bdVar.getType());
if (bdVar.cmk()) {
intent2.putExtra("Retr_Msg_Type", 11);
} else {
intent2.putExtra("Retr_Msg_Type", 1);
}
this.bAG.tTq.startActivity(intent2);
break;
}
x.i("MicroMsg.ChattingUI.VideoComponent", "video is expired");
do(nW.getFileName(), 3);
intent2 = new Intent(this.bAG.tTq.getContext(), ImageGalleryUI.class);
intent2.putExtra("img_gallery_msg_id", bdVar.field_msgId);
intent2.putExtra("img_gallery_msg_svr_id", bdVar.field_msgSvrId);
intent2.putExtra("img_gallery_talker", bdVar.field_talker);
intent2.putExtra("img_gallery_chatroom_name", bdVar.field_talker);
intent2.putExtra("img_gallery_enter_video_opcode", t.e(bdVar.field_msgId, 1));
i.a(this.bAG, bdVar, intent2);
this.bAG.tTq.startActivity(intent2);
this.bAG.tTq.overridePendingTransition(0, 0);
if (!nW.To()) {
x.i("MicroMsg.ChattingUI.VideoComponent", "start complete offline video");
t.nS(bdVar.field_imgPath);
break;
}
x.i("MicroMsg.ChattingUI.VideoComponent", "start complete online video");
t.oa(bdVar.field_imgPath);
break;
}
x.i("MicroMsg.ChattingUI.VideoComponent", "video is clean!!!");
com.tencent.mm.ui.base.h.a(this.bAG.tTq.getContext(), this.bAG.tTq.getContext().getString(R.l.video_clean), this.bAG.tTq.getContext().getString(R.l.app_tip), new 2(this));
break;
}
x.e("MicroMsg.ChattingUI.VideoComponent", "retransmit video but videoInfo is null!");
break;
break;
case 130:
Intent intent3 = menuItem.getIntent();
int i2 = 0;
i = 0;
int[] iArr = new int[2];
if (intent3 == null) {
x.e("MicroMsg.ChattingUI.VideoComponent", "[LONGCLICK_MENU_MUTE_PLAY] intent is null!");
} else {
i2 = intent3.getIntExtra("img_gallery_width", 0);
i = intent3.getIntExtra("img_gallery_height", 0);
iArr[0] = intent3.getIntExtra("img_gallery_left", 0);
iArr[1] = intent3.getIntExtra("img_gallery_top", 0);
}
intent3 = new Intent(this.bAG.tTq.getContext(), ImageGalleryUI.class);
intent3.putExtra("img_gallery_msg_id", bdVar.field_msgId);
intent3.putExtra("img_gallery_msg_svr_id", bdVar.field_msgSvrId);
intent3.putExtra("img_gallery_talker", bdVar.field_talker);
intent3.putExtra("img_gallery_chatroom_name", bdVar.field_talker);
intent3.putExtra("img_gallery_left", iArr[0]);
intent3.putExtra("img_gallery_top", iArr[1]);
intent3.putExtra("img_gallery_width", i2);
intent3.putExtra("img_gallery_height", i);
intent3.putExtra("img_gallery_enter_video_opcode", t.e(bdVar.field_msgId, 3));
i.a(this.bAG, bdVar, intent3);
this.bAG.tTq.startActivity(intent3);
this.bAG.tTq.overridePendingTransition(0, 0);
return true;
}
return false;
}
public final boolean g(bd bdVar, boolean z) {
if (bdVar.cmj()) {
o.Ta();
if (FileOp.cn(s.nK(bdVar.field_imgPath))) {
return z;
}
return false;
} else if (!bdVar.cmk()) {
return z;
} else {
o.Ta();
if (FileOp.cn(s.nK(bdVar.field_imgPath))) {
return z;
}
return false;
}
}
public final void ax(Intent intent) {
if (intent != null) {
ArrayList stringArrayListExtra = intent.getStringArrayListExtra("key_select_video_list");
if (stringArrayListExtra == null || stringArrayListExtra.size() <= 0) {
x.e("MicroMsg.ChattingUI.VideoComponent", "send video list is null or nil");
} else if (ab.bU(this.bAG.tTq.getContext())) {
ag(stringArrayListExtra);
} else {
com.tencent.mm.ui.base.h.a(this.bAG.tTq.getContext(), R.l.video_export_file_warning, R.l.app_tip, new 3(this, stringArrayListExtra), null);
}
}
}
private void ag(ArrayList<String> arrayList) {
x.v("MicroMsg.ChattingUI.VideoComponent", "send video path: %s", new Object[]{arrayList.toString()});
j jVar = new j(this.bAG.tTq.getContext(), arrayList, null, this.bAG.getTalkerUserName(), 2, new 4(this));
com.tencent.mm.ui.chatting.c.a aVar = this.bAG;
Context context = this.bAG.tTq.getContext();
this.bAG.tTq.getMMResources().getString(R.l.app_tip);
aVar.d(context, this.bAG.tTq.getMMResources().getString(R.l.app_waiting), new 5(this, jVar));
e.post(jVar, "ChattingUI_importMultiVideo");
}
public final void T(Intent intent) {
x.d("MicroMsg.ChattingUI.VideoComponent", "sendVideo");
if (ab.bU(this.bAG.tTq.getContext())) {
U(intent);
} else {
com.tencent.mm.ui.base.h.a(this.bAG.tTq.getContext(), R.l.video_export_file_warning, R.l.app_tip, new 6(this, intent), null);
}
}
private void U(Intent intent) {
com.tencent.mm.modelvideo.c cVar = new com.tencent.mm.modelvideo.c();
cVar.a(this.bAG.tTq.getContext(), intent, new 7(this));
com.tencent.mm.ui.chatting.c.a aVar = this.bAG;
Context context = this.bAG.tTq.getContext();
this.bAG.tTq.getMMResources().getString(R.l.app_tip);
aVar.d(context, this.bAG.tTq.getMMResources().getString(R.l.app_waiting), new 8(this, cVar));
}
private void ay(Intent intent) {
x.d("MicroMsg.ChattingUI.VideoComponent", "sendVideoFromCustomRecord");
if (intent == null) {
x.e("MicroMsg.ChattingUI.VideoComponent", "data == null");
return;
}
String stringExtra = intent.getStringExtra("VideoRecorder_ToUser");
String stringExtra2 = intent.getStringExtra("VideoRecorder_FileName");
int intExtra = intent.getIntExtra("VideoRecorder_VideoLength", 0);
x.e("MicroMsg.ChattingUI.VideoComponent", "fileName " + stringExtra2 + " length " + intExtra + " user " + stringExtra);
if (!bi.oW(stringExtra) && !bi.oW(stringExtra2) && intExtra >= 0) {
if (stringExtra.equals("medianote") && (q.GJ() & 16384) == 0) {
r rVar = new r();
rVar.fileName = stringExtra2;
rVar.enM = intExtra;
rVar.bWJ = stringExtra;
rVar.enF = (String) g.Ei().DT().get(2, "");
rVar.createTime = bi.VE();
rVar.enK = bi.VE();
rVar.enH = intExtra;
rVar.emu = intExtra;
o.Ta();
int nM = s.nM(s.nK(stringExtra2));
if (nM <= 0) {
x.e("MicroMsg.VideoLogic", "get Video size failed :" + stringExtra2);
return;
}
rVar.dHI = nM;
o.Ta();
stringExtra = s.nL(stringExtra2);
intExtra = s.nM(stringExtra);
if (intExtra <= 0) {
x.e("MicroMsg.VideoLogic", "get Thumb size failed :" + stringExtra + " size:" + intExtra);
return;
}
rVar.enJ = intExtra;
x.d("MicroMsg.VideoLogic", "init record file:" + stringExtra2 + " thumbsize:" + rVar.enJ + " videosize:" + rVar.dHI);
rVar.status = 199;
bd bdVar = new bd();
bdVar.ep(rVar.Tj());
bdVar.setType(43);
bdVar.eX(1);
bdVar.eq(stringExtra2);
bdVar.setStatus(2);
bdVar.ay(com.tencent.mm.model.bd.iD(rVar.Tj()));
rVar.enN = (int) com.tencent.mm.model.bd.i(bdVar);
o.Ta().a(rVar);
return;
}
t.b(stringExtra2, intExtra, stringExtra, null);
t.nR(stringExtra2);
this.bAG.lT(true);
}
}
public final void onActivityResult(int i, int i2, Intent intent) {
super.onActivityResult(i, i2, intent);
switch (i) {
case 208:
T(intent);
return;
case 215:
T(intent);
return;
case 216:
ay(intent);
return;
case 218:
if (intent == null) {
return;
}
if (intent.getBooleanExtra("from_record", false)) {
ay(intent);
return;
} else {
T(intent);
return;
}
case 226:
if (intent == null) {
x.w("MicroMsg.ChattingUI.VideoComponent", "[dealWithRequestCode] REQUEST_SIGHT_CAPTURE! null == data");
return;
}
SightCaptureResult sightCaptureResult = (SightCaptureResult) intent.getParcelableExtra("key_req_result");
if (sightCaptureResult == null) {
x.w("MicroMsg.ChattingUI.VideoComponent", "[dealWithRequestCode] REQUEST_SIGHT_CAPTURE! null == captureResult");
return;
} else if (sightCaptureResult.lec) {
((com.tencent.mm.ui.chatting.b.b.x) this.bAG.O(com.tencent.mm.ui.chatting.b.b.x.class)).a(sightCaptureResult);
return;
} else {
boolean z;
x.i("MicroMsg.ChattingUI.VideoComponent", "video path %s thumb path ", new Object[]{sightCaptureResult.lee, sightCaptureResult.lef});
o.Ta();
String nK = s.nK(sightCaptureResult.leg);
if (!sightCaptureResult.lee.equals(nK)) {
x.i("MicroMsg.ChattingUI.VideoComponent", "filepath not videopath and move it %s %s", new Object[]{sightCaptureResult.lee, nK});
FileOp.av(sightCaptureResult.lee, nK);
}
String str = sightCaptureResult.leg;
int i3 = sightCaptureResult.lei;
String talkerUserName = this.bAG.getTalkerUserName();
aso aso = sightCaptureResult.lej;
r rVar = new r();
rVar.fileName = str;
rVar.enM = i3;
rVar.bWJ = talkerUserName;
rVar.enF = (String) g.Ei().DT().get(2, "");
rVar.createTime = bi.VE();
rVar.enK = bi.VE();
rVar.enW = aso;
rVar.enQ = 0;
rVar.enT = 1;
o.Ta();
i3 = s.nM(s.nK(str));
if (i3 <= 0) {
x.e("MicroMsg.VideoLogic", "get Video size failed :" + str);
z = false;
} else {
rVar.dHI = i3;
o.Ta();
nK = s.nL(str);
int nM = s.nM(nK);
if (nM <= 0) {
x.e("MicroMsg.VideoLogic", "get Thumb size failed :" + nK + " size:" + nM);
z = false;
} else {
rVar.enJ = nM;
x.i("MicroMsg.VideoLogic", "prepareMMSightRecord file:" + str + " thumbsize:" + rVar.enJ + " videosize:" + rVar.dHI);
rVar.status = s$l.AppCompatTheme_checkboxStyle;
bd bdVar = new bd();
bdVar.ep(rVar.Tj());
bdVar.setType(43);
bdVar.eX(1);
bdVar.eq(str);
bdVar.setStatus(1);
bdVar.ay(com.tencent.mm.model.bd.iD(rVar.Tj()));
rVar.enN = (int) com.tencent.mm.model.bd.i(bdVar);
z = o.Ta().a(rVar);
}
}
if (z) {
t.nR(sightCaptureResult.leg);
return;
} else {
x.e("MicroMsg.ChattingUI.VideoComponent", "prepareMMSightRecord failed");
return;
}
}
default:
return;
}
}
public final void cpI() {
x.i("MicroMsg.ChattingUI.VideoComponent", "[onChattingResume]");
o.Ta().a(((com.tencent.mm.ui.chatting.b.b.g) this.bAG.O(com.tencent.mm.ui.chatting.b.b.g.class)).ctQ(), au.Em().lnJ.getLooper());
}
public final void cpJ() {
x.i("MicroMsg.ChattingUI.VideoComponent", "[onChattingPause]");
o.Ta().a(((com.tencent.mm.ui.chatting.b.b.g) this.bAG.O(com.tencent.mm.ui.chatting.b.b.g.class)).ctQ());
}
public final void cpK() {
b.Fm();
this.tTc.clear();
}
}
|
package com.kush.lib.expressions.functions.samples;
import static com.kush.lib.expressions.types.Type.INTEGER;
import static com.kush.lib.expressions.types.factory.TypedValueFactory.newMutableValue;
import static com.kush.lib.expressions.types.factory.TypedValueFactory.value;
import com.kush.lib.expressions.functions.FunctionExecutor;
import com.kush.lib.expressions.types.TypedValue;
import com.kush.lib.expressions.types.factory.MutableTypedValue;
public class IntMultiplierExecutor implements FunctionExecutor {
private final MutableTypedValue returnValue;
public IntMultiplierExecutor() {
returnValue = newMutableValue(INTEGER);
}
@Override
public TypedValue execute(TypedValue... arguments) {
int value = arguments[0].getInt();
int multiplier = arguments[1].getInt();
return value(value * multiplier, returnValue);
}
}
|
package model;
public class PictureBean {
String email;
String file;
String file_rename;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getFile_rename() {
return file_rename;
}
public void setFile_rename(String file_rename) {
this.file_rename = file_rename;
}
}
|
/*
Даны два целых числа A и B (A < B). Найти сумму всех целых чисел от A до B включительно.
*/
public class Ex_29 {
public static void main(String[] args){
if (args.length < 2) {
System.err.println("You haven't entered arguments! The task requires entering two arguments.");
return;
}
if (args.length > 2) System.out.println("You entered more arguments, than programm needs. \nIt will use only first two.");
Integer A = Integer.parseInt(args[0]);
Integer B = Integer.parseInt(args[1]);
if (B < A){
System.err.println("One of entered digits doesn't satisfy condition. First digit must be less than second!");
return;
}
System.out.print("A = " + A + ", B = " + B + ". \nThe sum of all integers from A to B inclusive: ");
for(int i = A+1; i <= B; i++)
A += i;
System.out.println(A);
}
}
|
package org.kiirun.adventofcode.day2;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.Range;
import java.util.List;
import java.util.stream.Stream;
public class Day2 {
private static final String[] INPUT = {"2-4 r: prrmspx", "5-6 p: hpzplphxb", "5-8 t: ttttbtttttc", "1-6 k: kkkkkk",
"1-3 q: qqqq", "4-8 t: pctpfqtrtttmvptvfmws", "3-5 z: zznzslv", "12-14 h: hhhhhhhhhhhhhhhh",
"14-15 v: vvvvvvvvhvvvvdmvv", "8-17 x: xxxxxxdxxxxxxxckxx", "11-12 f: gkfjnffjfcmfwk",
"10-12 s: xsgsssshbmsbnss", "6-15 s: sssssnsssssssss", "2-8 d: qnqtrqdrnvq", "5-7 k: lhxkkkk", "4-5 k: xkkkk",
"10-16 v: vvvvvvvvvcvvvvvpvv", "1-6 f: ffffflfffffff", "4-5 x: fxdnq", "10-12 p: mkspmhlldqjh",
"10-12 r: rcvzzcbdgrcr", "4-7 r: rxbkrrrzrrrtrrr", "18-19 k: kkkkkkkkkkkkkkkkkkk", "1-2 f: sfffffffffffffffff",
"1-5 z: mhkzwdxklf", "2-3 r: qzbgrghkmlpxdvd", "2-3 q: mqqpcxbqdf", "7-8 r: rrrrfrrj", "1-9 x: vmxsmwhnxccf",
"9-10 t: ttttttttppt", "2-4 x: rxxqxx", "16-17 k: jkfmnwkkztnxvlkkw", "3-4 c: ccbpccccczpcccc",
"5-8 g: ggggjggg", "1-3 z: szzzzz", "8-9 l: xnllznclz", "4-10 m: pkmmptjvgsnwmxm", "1-2 r: mbrrtkrjdr",
"1-3 c: ccqscsxcnctwlvm", "4-6 p: ppppppppp", "3-5 d: wdddxvmnbdhvzdgqbdm", "5-7 n: nnwbsnqnnvn",
"2-11 j: sgbxjvqnbmq", "5-13 q: qqqkpqqqsqqqxqqqq", "2-12 m: kvwlwmmvhbpgmnzfddms",
"2-4 j: kjgcpgxgcphkqjjmbwd", "3-6 v: tdvlvv", "10-20 n: tnmhnlznnpnmnfnngnnn", "4-7 h: hhhhhhhh",
"9-11 m: mmmmmmmmrmm", "7-9 b: mbnbbbbqk", "9-10 z: fqzzzmzzzzj", "3-15 s: chdpzcpgsgrkhss", "3-4 k: kklz",
"1-5 q: ltqqqxcndqrq", "9-17 m: mmmmmmmmqdlmmxbmtmmm", "14-16 k: kkkkkkmkkkkkjtkkk", "8-9 k: kkkkkqkkxlk",
"2-6 n: kbhhjhdmgtn", "3-8 w: rcwwwkqwbwkwmdqtwmw", "10-11 x: snkbxmwqwxp", "2-5 m: pmhmp", "6-7 b: bbbbbbq",
"3-7 l: cfqmljq", "9-13 q: qzqqqqqqqlqdt", "2-10 w: kmwqwtwkssd", "4-13 t: ttblttttttttftt",
"14-17 l: llllllwllllllwllclll", "3-4 p: xzps", "10-14 b: bjbbbbbpbdbbbb", "5-7 v: jlvhjtvx",
"6-9 r: bscrrrrcrphffdw", "5-7 r: brrvjrxfrljwxp", "15-16 b: bbbbbbbbbbbbbbbb", "7-8 h: bchfxxshh",
"2-13 z: zzqzzzzzzzzzzzz", "1-5 b: bbbbrbbhbbbbbcb", "2-3 k: zkkzjld", "4-6 f: fnffffff",
"8-11 d: qdvdddddndphdndmgdkp", "17-18 q: qqqkqqqqqqcqqqqtqq", "11-16 m: mmmwmwxvmmmmmmmmmmm",
"12-13 v: vvvvfxvgblvvk", "4-6 v: vsvvvvv", "2-4 p: rqgm", "7-8 r: rrrrrfrf", "2-4 j: xpjjl",
"7-8 b: wdpbvwbb", "15-16 k: fkkkskkkmkkkkkkk", "10-14 s: shkscsqjszstssv", "3-4 l: lllw",
"2-4 n: gjbnlsxvqmvxgcwntvvs", "6-12 l: lclllgllllllll", "16-17 b: bbbbbbbbbbbbbbbbbbb", "7-8 q: pqqqqqwq",
"1-2 r: rrzsr", "1-3 r: rrfr", "16-17 f: fffcfffffjfmrzqffnr", "15-17 h: bhzhhfndwgdhlhhhjh",
"7-11 t: vtwnrwzczmtwn", "3-6 v: vvvvvmvvvvvv", "4-5 s: ssptsss", "1-3 t: ttntq", "5-9 g: ggggtgggcg",
"7-8 h: hcjdkphhb", "15-17 j: jjjjjmjjjjtjgvnxk", "3-4 q: qqqq", "5-7 g: lggsjqlg",
"11-18 m: mmmmmmmmmmqmmmmmmf", "1-14 x: xxxxcxxxxxxxxxxxxx", "7-8 f: ffffffbffff", "3-4 t: xmct",
"3-4 x: xxtcd", "1-11 x: xcnxxxxvxlxkmcrxn", "8-11 h: hgnhkhhshhnhhzdhllw", "8-10 z: zdzzzzzrpvvzzqz",
"6-7 r: lrbrrprrxr", "6-10 n: fnnwnpnnjnhmnntqn", "10-15 b: bbbbbbbbbwbbbbbbbbbb",
"13-16 z: zzzzzzzwzzzzvvzkztjz", "5-6 t: xntkwthxbdtlmxtpzz", "5-13 r: njrlghrrxfrfv",
"11-14 s: vssnzksspscrss", "7-10 c: gtrkbcxccccccchch", "6-11 v: vvsvvvvvvvvvvvvv",
"17-18 b: bbbbbbbqbbbsbbbbsnbb", "13-15 x: smxxxjxmmkxxxmxx", "10-11 h: hpqqwkxnfhd",
"15-16 j: jjjjjjjjjjjjzgjjwjjj", "3-5 f: cjcff", "3-4 z: hnfzzzmq", "11-14 c: cccccccccczcckc",
"2-7 t: tstmdtk", "2-3 f: wffkfm", "7-16 w: tvgdzjjqlwzknwvwgzh", "1-2 d: dzdqpn", "8-14 j: jjzqjxjjsjrngzfj",
"6-9 h: xknzmlzpbpzcth", "2-5 j: njmnj", "10-15 z: kfqlljdfzzczzmp", "7-12 g: gcqwnmgjhcrjnzwcmw",
"3-4 h: hhjhh", "5-16 d: ddddddvddddddddddd", "1-2 p: fwwtpllzbmjbwcnkbh", "10-18 p: vhpwpppxfppppvppdh",
"2-6 x: rqgqgx", "11-12 m: mhpmmmmmmmmmmm", "3-4 z: lzzf", "5-8 w: vfwwmlwfvwwwwlh", "3-10 t: ltgtztzlct",
"7-8 k: kkkkkkmk", "10-13 b: ndflbblbchkbq", "18-19 z: zzzzzzzzzzzzszzzzzzz", "2-5 n: nlzrmkhz",
"14-15 v: vwvvvvvvvvvjvmcvvv", "13-15 p: ppppppppwpppxph", "6-9 k: jvhxzwkkwkzv", "9-11 s: snspssslkss",
"13-18 j: jgjrjjjjjqjjjhjtjj", "5-7 v: vgvrhzvvv", "1-7 t: ttttttttttttt", "8-9 n: nnnnfnnnj",
"2-5 x: dxcrxhstqwldt", "6-12 s: dkshssdsltspgcb", "2-7 k: kkkkkkkk", "7-13 d: vbjsdddfstdhtdxl",
"12-17 r: nrrgrrsrrrrkrrrdt", "3-5 w: wwwjw", "5-8 l: mlfldllll", "4-5 m: mmmqm", "9-10 j: sjtmlxjrzl",
"2-14 h: hhhhhhhhhhhhrnhhwh", "3-4 b: bbbw", "12-13 g: gggggggggggzg", "13-14 t: tttgtttrztstltlhb",
"14-17 s: fhdxfshbglsvjsgbs", "9-13 x: xxxxlxxtxxxxxxx", "2-3 j: jjtn", "12-13 n: nnnnnsnwnnvmq",
"3-6 z: gzzzbzmzzzmz", "3-4 d: ddnt", "2-7 s: pswmrnsrgb", "8-9 q: qqqqqqqdv", "5-6 s: sdlcqs",
"6-10 f: jffwjfhfff", "4-5 p: pmpppps", "9-14 p: pppppppppppvpppppppc", "3-9 n: nsnpnmmnnwtnvb", "3-4 b: bhzh",
"7-9 g: ggggggggng", "10-11 x: xwxxxkxxxjxqxxxbbxx", "17-18 k: kkkkkkkkkkkckkkkkk", "3-4 v: vvrv",
"12-14 s: vdsrgdsghxcblflbwj", "8-13 h: gxzhhbkdgfdglfqqcls", "4-6 m: mmmvmfmmmmm", "2-13 b: lbtzwffqfrfhbwb",
"1-3 r: lrcr", "3-6 j: cjtcjj", "5-8 z: zzztzmzz", "4-12 t: wttrttvtgttztttdttst",
"6-7 n: zbfvmngknrzfzqpwhtx", "12-14 g: gggggggggggggbgg", "6-10 k: jkkkkkrkmbkdh",
"14-19 m: mmmmmmmmmmmmmmmmmmfm", "2-4 d: sdft", "4-10 g: bgtgsbjcqgt", "2-4 t: trtqt", "7-11 b: wjbbsqsvpkpb",
"12-14 z: zcfqlkxghjjpjzsc", "3-4 g: ggjt", "5-7 r: zdrrqrrrrrr", "15-16 p: brpvpplmhvnbxppc",
"15-16 b: bbxbbbbbbbbbbbbb", "8-11 c: hscggrpcpbxrxwgsv", "10-15 j: jjjjjjjjjnjjjjmjjjj", "4-6 g: bgkghgc",
"9-15 c: ccjcccsbcccspxc", "2-3 v: fjzb", "2-3 h: hhhxlchhwmjjzj", "4-11 x: xxxxlxxxxcxxxxk",
"6-11 d: dvpdmdddzch", "5-6 j: jjjjjjdjwj", "6-12 p: pppppxpppppbppp", "1-7 q: xqqqqqqqqqqqqq",
"5-6 w: xwwrtwjpwgsw", "11-13 k: kkkkkkkkkkckfkkk", "2-3 m: qbmnxlwmldmmc", "2-3 w: jqlwws", "6-8 k: kkkjbkmz",
"10-12 m: mmmmmmmmmvbm", "6-13 n: hqnkdmwnxnwndnxgl", "1-5 j: jjjjb", "16-17 x: gxxxxxsxxbxxxxxmp",
"3-10 s: ssrsssssss", "3-4 s: rslpsx", "1-10 g: qgggjgwqzggvzflmj", "8-9 g: gggbngqghg", "1-3 q: qqqfj",
"3-5 m: mmmmzmmmmm", "7-8 q: qqqxqqgqq", "1-2 j: rpdjrrt", "7-10 v: mdzpkvvdpv",
"12-14 m: xzmmjmhmmmmktmtmmmm", "6-9 m: mmvbmvmzm", "7-9 c: gcccqmlhc", "6-8 z: zzzzzznrz", "4-7 w: wwwmwwww",
"1-4 h: vhhhhh", "13-14 z: xzzzjzzzzzzfzz", "1-3 l: jlqml", "10-12 f: wdbfzsbwffgf", "4-8 p: vjpppfppxppjmctw",
"18-19 x: zkxbllxbtbzggncfxxx", "5-6 x: xxxxhxxx", "2-6 v: tvdprvvrvv", "5-14 k: jkdhkhdhjgmtkk",
"1-2 k: sskk", "5-12 w: mvqtkwwmcwwlkw", "2-6 v: gvmlvv", "12-13 p: ppppppppppppbp", "3-4 r: frrrr",
"13-15 r: qrrrrrrrrbrrrrr", "5-10 b: bxkbrbkdtwwrbkskjpc", "4-5 x: bxrcx", "12-15 f: ffffftjfffffffzfff",
"6-7 g: ggggggzgvxggg", "10-11 w: kgwhvwwwwtcwp", "9-10 j: jjjjjjjjpjj", "5-12 t: pnbsttwccrtvttm",
"2-8 c: wcccccxfccnkvrllg", "2-9 j: frddhfbkkj", "9-11 m: mmmmmmmmtmmm", "9-10 m: mmhmmmmmtm", "2-4 r: crtr",
"14-15 v: vvvvvvvvvvvvvlrv", "5-6 c: wccwctch", "1-13 c: lcccccccccccfccc", "12-15 x: zppxdwxtplfvzfxlwl",
"4-18 c: cccccccccccccccccc", "2-3 c: xcccc", "1-7 q: qvfbcfqx", "6-9 k: lkbkhkkmsjlk",
"7-15 w: wwwwwwwwwwwwrwwwwwww", "2-5 s: lscsssqsn", "16-17 n: nnnnnnnnnnnnnnnnznnn", "4-5 g: ggggggg",
"2-3 w: mfdw", "4-5 r: rfrqh", "3-7 f: vfpfbzf", "8-9 j: jjjjjjjcbj", "10-13 p: pppppzpppppppp",
"8-10 t: tntbgchftpttttttfttt", "4-7 r: rlrbsmhnrqrbxrnlrm", "13-17 m: vkmmmdhfkmtmgmxhk",
"9-11 t: ttttttttttt", "16-17 g: gggggmgggfgggggsggvg", "5-7 w: wpffgdw", "3-7 r: rrzklzbmrrr",
"2-3 l: tllcqnlwfvlfmcgssg", "3-4 q: qqqp", "3-7 x: xnxxxzcxrqwx", "7-18 s: shssssfwssssssksmss",
"1-4 r: rrrrmbc", "2-6 t: tttdmsmtg", "3-5 h: tmhbh", "4-15 c: ccccccccccccccccr", "8-10 v: vvvkvvvhvk",
"3-6 r: rsmzcrhqnxljrnnd", "2-3 s: msss", "10-18 w: wwwwwwwwwwwwwwwwwnw", "11-13 j: hmwdjqjhjbfdrhj",
"5-17 x: hxpnccxhwlsxxdmxxd", "4-5 t: ttznj", "6-7 l: llllllqll", "1-3 q: qsqnhqm", "4-6 t: tdtttthc",
"16-17 x: xxxxkxxxxxlmxxvxfx", "7-11 r: prtrxrprrrrr", "5-7 j: mjjqjjg", "3-8 l: rnllnklplllllllll",
"10-15 p: pppppppppdppppp", "2-6 g: grgggx", "3-4 s: ssqss", "1-4 t: tttq", "6-9 w: fxvvndkmwlskw",
"11-12 c: cccccccccccp", "4-9 b: bbblbbbbbbbbbb", "2-3 g: hggnbw", "17-20 x: xxxpxxxxxxhxxxxxfxxx",
"1-2 f: bpvf", "3-5 j: wjbfjw", "13-19 m: srmmmmmmmmfhmgmmmqs", "10-16 c: cccgcczcccccccbcfcct",
"11-15 b: bzpqpffbfqslknb", "2-5 t: stnztmvjg", "3-9 h: hqxhxxhhwh", "2-4 r: rvrz", "2-3 p: pppk",
"7-8 s: sskssjdss", "5-9 x: xzvjjkmqzthpht", "12-13 p: pstcvcjlnwsqphwnsr", "3-15 p: lnfhbvnpmfztbqppcf",
"14-18 l: lllljllllllllllgld", "4-5 g: gctggxhgpxkx", "7-8 q: qqqqqqrdq", "10-13 c: ccccccccccccc",
"4-9 s: sssnssskwsbfssssss", "10-12 g: zgpgghbggjqgggkggjg", "3-18 m: mmmmmmmmmmmmmmmmmkmm", "1-3 z: jzzzz",
"1-4 k: fqqwmd", "4-8 r: wzbrhxrw", "2-13 x: fzvhrqwcrjjzxprnxlk", "9-10 q: qqjqqqhqqr",
"4-10 g: mnlggbkdhrgtndk", "4-19 w: wksmppsqrpppfkdzlrg", "6-7 k: kkkkkxwkk", "15-18 t: tttttttttttttthtttt",
"8-13 k: kkkkzkkvkkkktkkk", "1-5 j: jjlqrwsjzkjbl", "6-9 m: gmmmdmmmbmmdxmg", "4-5 r: gdbfmxnrmc",
"3-4 h: rhhhh", "2-8 n: nnnnnnnln", "4-9 x: fxgwflwxblgnwxv", "3-6 x: xmkxxvxxs", "1-15 g: jgggggpgggggggpg",
"2-7 n: nwnnnnnn", "2-4 r: hrwcr", "5-8 x: tbbtxltxdsftztx", "3-11 r: rzrwrdbqkhrbldrgph",
"2-10 j: jljxrjjxjv", "17-18 b: bbbbbbwbbbbbbcbbtb", "10-11 w: wwwjwwwwwrw", "1-2 h: qbhh", "2-3 r: rvjr",
"10-13 b: bfbbbjxbbjbbwblc", "2-4 j: qjdt", "4-5 j: jjjjjjbfjj", "11-14 d: pssdgpplqjdzxr",
"4-8 x: zxgxfxjhjxgv", "6-7 g: gdnhggz", "3-14 f: fbfffsjffffffgfffff", "2-7 f: qtxmpvfscrbgxfq",
"6-8 w: wwwwwlqwwswww", "2-9 g: gbnwwncws", "1-4 t: ttbctt", "3-4 g: gggbl", "5-8 h: hhhhhhhhh",
"9-16 n: nnnnnnnnnnnnnnnnn", "3-4 x: xxxxxx", "3-4 l: psgl", "4-7 p: pppntst", "4-13 m: mvdmnfnnpxjtmgnwgc",
"9-15 p: pprtppppwnphlhf", "7-10 v: vlvvbvqtvp", "11-15 k: jmckdsmvzptdslkkjqf", "2-3 p: cwkf",
"8-9 r: rrrrmrrhhrr", "7-8 h: vhhhhhhjh", "4-5 z: zzhznzk", "10-13 n: qnnnksnsnvnnnnt", "1-4 m: jmmmmm",
"5-8 w: jpcmlxtwzvhww", "10-12 k: kkkkkkkkkkkkk", "11-14 g: ggggggrgmgggnhgggg", "1-5 z: zzzwz",
"2-4 x: xxxxxxx", "6-14 c: cccccvccccccckc", "11-12 z: zzzkzzbzzcvz", "13-18 p: pppppppppppppppppxpp",
"9-14 c: tcnphlfkczmcpc", "7-8 n: wnzmjcnn", "7-11 p: ppspppmdppp", "2-6 w: wdwwwww", "2-4 w: qzvw",
"8-9 j: njbvchssj", "2-7 b: fnbbbnp", "3-4 c: ccqv", "1-5 x: xxqxdxx", "3-9 w: wzwptwtwwwswbqmk",
"17-18 x: xxhplchxxxxxxxxxgm", "4-5 g: fsggvmg", "1-12 w: lwwwwwwwwwwwwwww", "3-4 b: kbnvg",
"2-7 t: ztttmfftttrtttt", "2-3 n: wqvnsn", "1-6 z: qfddndzzg", "15-17 z: nfzxdmgdvjzzpqdjt",
"1-5 g: mggglgggg", "5-13 x: xxxxgxxxxxxxrxxb", "12-13 x: xxxxxxxxxxxcx", "5-6 r: prrvrrrrh",
"13-14 h: hhhhhhhlhhhhmz", "8-10 j: jjjjjjnlbjhjzjljj", "1-7 w: wwwwvwkwwb", "4-5 h: hpshh",
"2-12 f: vhptghgvhqsf", "16-17 w: wwwwwwwwwwwwwswzww", "16-19 x: jltfxxfgkkxnnxjkrxz",
"3-13 s: ssfpvsssshssrxss", "4-9 q: qsqqrqqqqjkqqkqv", "9-11 h: djhvttnrjzh", "2-3 j: jjjz", "3-7 j: jtjqgmj",
"4-8 p: ppnpcpppspgpc", "9-13 s: sssskslspdsnss", "6-10 m: mxzlmmmpvgm", "10-11 c: cccccccccwnc",
"6-8 f: klkqkthgzfbb", "7-9 t: tttttttmx", "2-13 r: nrlmjrhxwnjsrwfx", "12-13 x: xthxxwpxsdxmj",
"3-11 r: nqgznrmqhcm", "3-4 c: rqcxmgc", "12-14 f: ffffffffrdfjffff", "14-15 d: vdddxdddddddddddd",
"4-8 m: mmmcmkmmmmmkh", "3-4 g: ggcggsm", "7-10 p: pppppphppw", "11-17 f: fffftfxbffffffffrff",
"1-18 f: ffffffffffffffffffff", "4-6 x: mxnxkx", "3-7 g: ggrlrmhggl", "1-2 b: pbblqxtlztwcbt", "4-5 c: ccccz",
"1-4 k: kqkhkkkk", "9-12 v: vtvvgvvxvvvvv", "3-4 g: ncgbnrvdbrm", "9-12 t: tttttttttttttttt",
"14-17 c: crncccqdsjcclcxcmdw", "8-10 h: hvhpghvhnfhhh", "4-12 p: ppplpppppplnpppp", "4-5 l: lrlllllnlllq",
"3-14 p: ppnppppppppppcpppppp", "2-5 v: vmvvbv", "6-7 v: vcvvvqvvvvvjvv", "4-5 l: llllhl",
"5-12 h: hjhphkxhkcqh", "6-7 f: fbskrlff", "4-5 k: rkfnrk", "1-4 q: tqqkqkqqcxq", "6-7 p: pppppxp",
"1-2 f: fnfffffffffw", "5-18 p: ppfpppppppppppppppp", "1-5 d: dwndd", "8-9 h: hhhhhhhhh", "3-6 l: llllllllll",
"9-10 r: gvhwsfbckr", "7-16 h: hhhhhhhhhhhhhhhhh", "1-2 j: tjjlj", "5-9 b: tsvwbmbvbk",
"1-8 r: vrrkbsrrrrkrrcrr", "1-5 b: hbbbbbs", "7-8 j: zgjwjcmnjjjljnvjjgj", "11-15 z: zqzzzxvzzdmzzzzz",
"2-13 q: tqqnzjjxvcsvqksl", "6-10 f: fqqczfhfmf", "2-14 v: vcvvvvvvvvvvvvvv", "1-5 c: kgcdcckbc",
"3-5 r: rrdrr", "15-16 f: ffffffffffffffmbf", "10-11 s: ssssssssssssxssnss", "9-10 j: jjwjjjjjtkj",
"4-5 v: vfdvv", "2-13 z: znkpztzzzzzzznlwzz", "3-4 r: lrrm", "15-16 n: nnnnnnnnnnnnnnsnn",
"6-12 n: nxnnxnnnpnnnnvn", "4-8 q: lqsqdcqq", "15-16 x: xxxxxxxxxmxxxxxtxrx", "6-17 h: hhhhhhhhhhhhpjhhh",
"11-15 c: cccccjccccpcccc", "11-12 r: rrmrhvzgrtrd", "3-7 b: bwmbbblb", "8-13 v: zlvhjhjhtwtkbxqqw",
"6-9 p: pppppfpppppk", "2-5 r: rcrrjr", "14-19 f: gfbrfsffprfffhrffzm", "3-6 r: rrsrrtr", "4-6 j: jjzjbz",
"1-4 l: jllnl", "6-7 z: zzzzzppzzzzzz", "17-18 h: xjvnmlhhnlxltrdltgr", "2-14 z: xhtwcgngdxlzhnv",
"3-5 v: xvvrvvv", "11-14 v: dnhpmxjvmwrknvvpr", "8-17 w: vnwpmbbpmcwwgpwlwh", "4-5 f: fffjl",
"13-16 v: vzvgvvvwvvvvvvvjvvgk", "8-9 n: nnnnnknnn", "18-19 g: gjgggkggggkxgpgdglh", "2-4 t: ptkzwltkr",
"17-18 q: qbmbqqlqqjqqhtqfqq", "3-6 r: rfkmhfd", "4-7 h: fghxhhhh", "4-5 s: spsxv", "3-5 k: dkpkzkl",
"7-10 n: nzpnnnlnnsnnn", "3-4 h: hhnh", "19-20 r: rsrkmcrhkqfrfdqmlvxq", "9-10 m: mmhmwmwmmvm",
"3-9 j: jdjjjjbjwjjjjjjjjjj", "1-2 s: mpsscts", "3-4 g: nghj", "6-10 x: xxxxxnxxxhxx",
"10-13 t: tttttttttqttvtttt", "12-13 s: nssssssnsjrss", "7-9 z: hjkzxlzrczhhmm",
"16-17 s: sssssssssssssssfpsss", "4-5 x: xxxxx", "2-4 c: bppcccfwqs", "4-11 w: wwwwwwwwwwwkw",
"6-8 m: hdxjhkpjdjmrql", "2-19 k: zkhcfxztkgltmqbdqxj", "1-3 n: gnqnnnnnrnnn", "11-13 f: ffffffffgfmfkf",
"1-5 z: lwzkxzjzv", "11-12 m: mhlxvjmrcffn", "2-7 z: cqhbjlbzh", "3-18 k: kdkkkfbkgwkdknkkkzjk",
"9-10 b: bbrbbbkcbbbbbzll", "5-6 l: llplkl", "9-15 c: vcgcngchvkvjsgcf", "3-6 q: qqqqqwq",
"9-11 k: kxkjrpkkckkkkkskk", "9-18 k: hbkrrwvctstksttkwrvf", "2-3 j: jtjj", "1-5 n: nnnnln",
"1-6 b: jpmbbbbqkd", "5-7 w: wwkwwws", "3-10 m: pxpwzblsvrlsxjpvpslt", "11-12 j: ljjjjkjjjcmc",
"10-11 q: qqqqqqqqqqq", "2-7 h: hqqhkbh", "7-9 l: lllclmfslldrlsl", "8-9 h: jhtvlvrhhhkhh", "3-6 k: kkjkkkk",
"1-5 l: vllllc", "1-2 q: vqqq", "5-6 q: mkqhjp", "7-14 l: lllllllrdlmlckll", "3-4 k: kxkkrjk",
"6-8 l: pslrqlbl", "1-8 t: gtzthtct", "5-7 d: lhxkdrddf", "2-3 h: hmhh", "7-9 p: ppppvppppvwp",
"9-11 q: jhzvqqbqfnql", "9-14 r: rrrrrrrrtrrrglrrz", "11-12 s: shsssssssssbs", "1-7 t: qtttttt",
"11-16 s: spgsmwbrshhldcsvvx", "5-6 l: lkmlll", "2-9 h: vdchgpmlhvxzjcp", "4-7 k: xfkkkkkckmkk", "1-3 w: wwww",
"13-14 c: cccccccgcwcccxdc", "12-15 w: wrlwwxwwwlwwwfwcw", "5-13 m: jmtjqmvkmpxdmt", "7-11 m: nxnkxfgzcpfm",
"8-10 m: mmmmbhmmmk", "11-13 z: khcksspxzwmznpl", "6-7 x: xkxxcxj", "8-11 s: sssrssssssss",
"6-12 h: wkzcnspbtjwchv", "8-9 b: bbbbbbbkb", "7-8 d: hxsjqfddxdb", "15-16 g: gggggwgggggggggg",
"8-10 q: gqqzqmltqqlkqwtzgfn", "11-16 j: kjsjjjjjjjckjjjj", "2-4 s: vbfqcmgssqb", "16-17 r: rrrrrrrrrrrrrrrrr",
"7-11 d: ddhdddrddtdd", "2-3 x: gvpcx", "4-10 t: mbftjndbttv", "13-14 j: zjjfmsgqtgwdhd",
"6-11 s: qlqhssgsbvnsts", "9-15 t: ttdttttvttttqttvs", "3-6 l: lcvlll", "3-5 x: mpdsxrhqlbcdx", "1-4 q: kjqz",
"2-3 p: pncmptpppgp", "2-6 l: tlbvnpllvxlgxhn", "14-17 q: lgdsvqxwmhdwzhjsq", "13-19 m: mmmmzmmsmmmmmmmmmmc",
"4-5 x: xxxxzl", "2-4 n: nnrn", "8-9 n: nnnnnnnns", "11-14 l: bpmrcbhslcmxxv", "7-12 p: ppmpvpppppkpfpp",
"4-10 k: kkkqkkkkkfkkkkk", "8-11 s: sssfssssnssssss", "8-16 l: xklrjlllrqlxhrkl", "2-12 r: rrcrqrprhcrrrvrph",
"14-15 h: jrhhjhhhhhhzhmp", "8-12 m: mmmmmcmmvwmmx", "2-9 f: ffdffffmfqpffffffff", "8-12 x: xxxxxxxgxxxr",
"5-6 z: zzzzzxz", "14-17 j: jjjjjjjjjjjjjzjjs", "1-3 f: qfjmrf", "6-7 t: ttbttdq", "8-9 x: xfxxxxxxxxbxxxq",
"4-6 q: qqpgwqbr", "5-12 l: lqzqrtgjmzml", "5-7 w: wwwnwjwwfw", "5-6 x: znxdtx", "4-5 x: qqxhvmxxxxz",
"1-5 n: nnnnnn", "2-5 s: gxsnj", "5-7 s: gssjssszst", "9-14 h: zjhrdpjwhkppdf", "2-8 t: ftgttpcttxtvnttntjs",
"1-4 t: lttl", "8-10 f: fffffffffrf", "3-6 q: qvqxrhd", "9-10 j: zrfxvmhgzcnkthzs", "5-7 q: rqtqxqq",
"2-4 j: jxnj", "7-8 c: fccccczkc", "1-2 x: xktx", "5-6 t: tttqkt", "3-4 m: crbhwmq", "5-7 d: ddddhdcd",
"3-4 w: wwcn", "2-7 d: dmdddcd", "6-7 l: llzllfg", "5-8 l: llxllllllf", "3-4 s: lspsb", "1-6 k: kkkkkdk",
"6-12 x: ztxxmxxqxrxxxcxx", "5-12 p: fpngpxprbqhprvj", "1-11 k: kvkkkkkkkkkkkkkkk",
"2-11 x: qxxnxxxxxxxmxfxjsg", "12-14 r: wzrrfztrbrrrztgrgrm", "1-4 r: rbrlrj", "14-16 d: dddddddddddddsddd",
"8-15 l: lzllmllclllljlll", "7-8 l: qkgqklzzllqclqlfjl", "1-4 g: vggggg", "12-13 c: krbpskrctrvtc",
"3-6 t: btttttmkt", "8-12 t: tttttttttttltttt", "10-16 k: kkkkkqkkkkkkkkkw", "5-6 d: ddldvkd",
"10-14 v: vvbrvvvkbvgvvr", "4-13 v: vvvcvvqcvflrph", "7-17 x: qxfxxxxvzslqzzbcx",
"9-10 g: ggggggggvjggggggggg", "3-4 p: hpppkp", "1-3 s: lstcssssv", "4-6 n: nnnsnmnnn", "2-6 k: kkkknkvkg",
"1-2 c: cccccc", "8-13 h: hhhhhhhhhzhhv", "10-13 h: hwvhhhhjhhthhhhlxh", "15-18 p: pzpgpppppgpxpppbppnp",
"10-11 n: nffrjnmbnxj", "5-9 l: lllldrllbzljsw", "4-8 j: jjmjjjrjsjjjjj", "2-9 v: vtzlvvdjv", "2-3 g: ggcf",
"9-15 b: psxgbbcjbbhbntb", "15-16 q: qqqqqqqqqqqqqqqz", "11-12 c: dvgckwdtcccc", "5-11 s: nskssssssfwb",
"2-7 p: pdfdnpqppzpp", "3-7 d: dcdwnmdgnstt", "13-14 w: hwdsrqmdmxhlkm", "5-7 l: lzzdzlvrtgzllcn",
"5-6 t: bttttvt", "6-8 c: crcczxckcc", "5-7 g: gmvgggg", "7-9 g: gggggglgqgg", "5-6 t: ttttrt",
"2-3 g: sntggpm", "4-6 m: flmmsm", "9-12 w: wwwwwwwwwwjw", "6-13 x: cfxrwlljbnzlb",
"13-16 v: wvfcgrgfvggjcbqv", "7-8 n: sdnrsnhn", "1-3 q: qqqrqmjfq", "4-6 s: bzdsslss", "1-5 f: rfffcf",
"4-5 s: sssss", "4-5 h: xhkhhh", "10-11 g: ggjdgpvggggx", "9-10 v: vvvvvvvvjvvvjvwvv",
"3-7 b: fbbmzbblqzvfgpnrl", "6-11 h: hhhhhlhhhhchhhhh", "3-4 l: llllstmhwlchzd", "3-7 t: xthsjgtcblcszn",
"2-17 f: kfjwdtmhzjzlvhpjf", "2-5 b: rbtbg", "9-15 z: mzzzcfzzzwvtzqgbzjzm", "6-12 f: qgtzmktjffmfn",
"11-17 f: flcffsqwlfjvbcffb", "5-6 r: gsdrrr", "13-14 b: bbbbbbnbbbnbbbbbsb", "2-9 b: bcbrvbvbbbzb",
"3-5 t: tkttft", "6-7 v: vcvlqvdcvdh", "7-13 w: wwwxwwwwhwwwlqwh", "5-6 z: zkhpzzjtnkjzf",
"7-9 p: pppppppppppkppppp", "4-7 p: spppfjmc", "8-9 k: sxnkplwfz", "4-5 r: clpgrr", "7-8 m: mmmntmmmpmmmmrmpk",
"4-5 j: jxbjnxj", "3-10 b: jwbclnqzdbnb", "5-6 r: rxbxlnsmrrfr", "3-4 f: fvfsbq", "2-4 x: sxxxd",
"7-8 p: qpppppprpp", "3-4 q: qqqq", "6-8 n: njwgnqntnnn", "6-10 z: zdzzgzzzzj", "6-9 d: rwdlfdrtd",
"5-6 l: skllpxslll", "5-7 d: dwdznhddttljdnvkdws", "1-3 d: dhdc", "1-11 s: sqgzsrrvgms",
"8-14 w: wvvwrwwlwwmwwwn", "11-12 t: ttbttttttttttttt", "17-18 f: lfffffmfffffffffkff",
"17-19 k: kkkmzkkkrkfspllkckb", "4-7 f: fxfjtdfcxff", "4-10 h: hhhrhhhhhhhhhh", "6-7 p: ppkpppppp",
"5-10 c: hccpcgbkbctctp", "5-11 l: llllvljllltlllplll", "5-6 c: kcntkj", "16-18 m: mmxmmmmmmmlmmmmwmmm",
"4-7 b: bbvbbrbb", "6-7 n: dbrqnnn", "3-4 h: hhhht", "11-13 s: sssssssssvlwxsfj", "3-9 g: zrsdrgrzgghxj",
"14-15 f: ffzgnqfrclzgxfffff", "7-8 c: cccccccbc", "5-8 s: ssssssssss", "8-15 k: klkkkppksvdrknd",
"4-6 h: hfhhjljh", "8-15 c: cxljcccvhpklxcr", "3-7 h: kpnttrczt", "14-16 p: tqxpdpddrwfxgjvc",
"12-15 j: cjjjmwjdbtpwjmjcg", "11-17 n: nnnnnnnnnnnnnnnnln", "1-8 s: sssswsms", "9-10 w: wwwwwwwwww",
"6-16 v: gvfjvvvvvqlsbrvvd", "3-8 q: rvfnrfvsmjk", "4-6 w: wvpwtww", "7-10 c: xcctfssplcdqrpqs",
"4-10 j: mjcjjwvjwjm", "7-11 w: qmwjfrjpjkqww", "6-18 r: qvvthtbxlkrnvqzvlf", "10-12 f: ffglffjffffctfffff",
"6-7 x: xxhxtfpqxxx", "9-10 t: tttttttxtt", "3-10 j: cpqxwljhgjldfns", "15-16 q: mqqnqfqjfqqqzqqt",
"4-12 f: fffffffffffvf", "4-10 s: ssssssszst", "1-6 x: xgxxxxxxkx", "2-4 z: zzzb", "11-13 j: jjjjjjjjjjjjv",
"1-2 j: hjjd", "4-12 h: hhljhhxhxnhr", "6-10 b: bbbbbkbbbv", "7-8 m: mmmmmmgvmm", "9-15 h: hhhhhhhhwhhhwhhh",
"1-2 g: gvglg", "4-10 v: gkbvgntvrvv", "9-10 p: mjpppbppnpjv", "1-3 w: wwwtww", "1-7 v: vmvsgjdfdpwtvqqfsh",
"10-12 c: ccccccccclmcccjc", "13-14 g: gggggglgrggqzgggvbgg", "1-6 p: mhptnp", "10-11 n: nnnnnnjnnpxxn",
"2-5 l: tllcc", "13-14 j: zbvlwljjgljwjj", "10-11 p: ppppppvpppjppvp", "12-18 c: cccccccccctdccccch",
"15-16 j: jjjjjjjjjjjjrjjj", "5-8 t: gjkttztjt", "5-9 k: kjkhwdvkk", "5-7 p: pjvpppp", "2-4 w: wwwhwlwwm",
"4-5 m: mmljm", "6-15 b: rbbncbrvmdvbbqb", "13-15 n: nnnrnnpdfnnqnnncnfnn", "2-11 r: srfhtxczprbx",
"3-6 n: nnnnnh", "15-16 v: vvvvvrvvvvvvvvvvr", "7-8 m: jphmmmmft", "4-6 p: pppjpvp", "1-4 g: dggkgg",
"1-2 p: zppsp", "6-7 b: bbbbbbbbbbb", "3-4 x: vxsv", "9-13 t: pqtqttttkxtghv", "10-19 v: vvvvvvvvvvvvvvvvvvxv",
"6-13 z: wnmzkzzqftzmc", "6-13 l: vklgsrjrkjpzlqll", "3-6 h: mwhllh", "1-8 l: blllllltl",
"3-9 v: glxlzpffvgvmb", "2-5 s: sssstss", "3-9 t: tfptcrhtlzqxcv", "9-10 t: ttttttttttjttt",
"9-14 h: ktwphtsnkmlzwd", "3-5 z: zzznz", "2-3 t: twtt", "3-5 f: ffffsf", "17-18 w: wwhwwwwwvwwwwwwwnsw",
"3-13 w: wwwwwwwvhwwwwpwww", "7-8 n: pjnxnnnntpwnbsjnnz", "2-4 v: vvvjhvv", "2-9 d: dmddwcpnqdddszpb",
"3-4 q: qqrqqh", "1-2 d: czdd", "1-4 d: xsdzrms", "1-3 n: znxnnn", "5-7 r: rrrrnrzrr", "2-5 c: ccccxcc",
"6-7 c: nccccdc", "1-4 s: bslsrvgjdfsgf", "10-11 j: jcjnjjpjlhh", "8-12 k: lzrvvhtkkpbkfwjzcmz",
"10-13 b: bbbbbbbrsnbbmb", "2-9 s: hswtzhlss", "6-7 j: cpnjjjf", "11-15 p: pgppqsfjcpbnmqp", "4-6 k: kkkfwq",
"10-11 c: rccccccccccccc", "5-14 d: bmfppdgvccmbdqpx", "7-8 v: vqnvvqvvvvjvv", "7-16 f: ffffffkfffffffffff",
"14-15 r: nbdlfkrbcrxbcts", "13-14 v: vvfvvvvvzgvvvvmvv", "1-12 l: glwdllllpllltll", "3-9 x: mnxpljmxnm",
"4-5 h: rjqhbxnvkc", "13-14 z: zzjzkzzlcbzpjzzz", "2-6 p: tnpppp", "8-12 n: kpjfjwpnwlzqhwbz",
"2-15 q: jqkjkbzcwvvqbxq", "2-3 l: llllll", "15-19 l: llllllllllfllllllll", "1-3 p: pkzkpsvdptz",
"1-8 f: fffffffvfrf", "1-11 j: prdqjlhjdvljjvjmhnm", "10-16 v: stshngzvzvvvnffv", "10-11 m: nmmtmqmmmmb",
"4-9 t: nzttkfcvrnd", "18-20 t: bbttltktrgtntgtzhtct", "4-6 p: pppglp", "7-13 g: vgrccggpbvxgl",
"5-7 l: lqllvld", "7-10 w: wswwwwqrww", "7-8 c: cncczcmlcmcx", "1-9 d: ggjtdddcqcmpd",
"4-7 q: vdkqwnqkbsdqxwwth", "5-6 s: ptjwxsz", "7-14 v: vvgbvtvvxvzvwvvc", "4-8 h: tmjhhrndwlh",
"6-7 w: wwjvswf", "2-9 v: vvvvvvvmv", "2-4 c: hcgc", "2-3 x: xxxx", "6-15 h: vnbhwhhwtzztrlh",
"13-16 k: kkknkkkkkkkkkkkrkk", "2-7 b: nbfxslbqblbbbbbbl", "9-11 k: kkrqkzkkkvkshqkbkkhk",
"9-13 j: qjjjjjjvmrjjjjjjjj", "7-15 h: zhqhhhjbhdhhmhfn", "3-5 t: vtvstkkttftttt",
"7-8 h: hdhhhqhhnnfqwhzhdlsx", "16-19 k: kkkkkkkkkkkkkkkfkkd", "3-4 f: qfjsxfnsfq",
"13-14 t: ttjftttcttttptttt", "8-9 f: gjmfffgrq", "9-10 m: mmpmmljmmmmmm", "9-10 k: skttkrjkkb", "3-4 k: kkgk",
"1-6 h: vhhhhvhh", "11-19 z: zzhzzzzzzzzvznzzzzgz", "9-11 z: mzzzzzzlzzbz", "7-16 c: tpcwtwcbljrnztwrsdd",
"13-15 b: hnrbfgqwqwqhpnc", "2-4 g: fgsdg", "2-3 k: kklkkqkhklkkqb", "8-9 g: tgrfdbvgfzqvsf",
"3-12 j: jmjvwqrpsjvc", "4-10 v: zvhjvtpjgvvd", "5-6 p: fgplzd", "9-13 r: csngrmrxrqvhdwfkvns",
"7-13 q: qqqqqqqqqqqqqqqqq", "11-16 l: cvlxgkdmltldzsplzz", "8-11 z: znmhzzcpbzz", "13-14 x: xxxxxxxxxxxxxhxx",
"11-20 c: qmhcvthqctdtscfcjcck", "14-15 l: lnllllslwjlllll", "5-7 p: qppptqm", "1-7 f: chffvqfrdffbcmqf",
"8-14 h: hhhbhhrshhphhl", "16-19 j: tgsjqjwjjjbcjtjjjjj", "3-4 p: jzppdrzpkgcxdljgm", "5-6 z: zzzzgzzz",
"3-8 t: nvzdttst", "4-6 x: qfkznxh", "9-18 d: ddddddddzddddddddl", "11-17 x: xcxrxxxxxqzrxxxxxxx",
"3-4 l: lmll", "10-13 f: fffffffffffffff", "7-9 v: mccgvfvlh", "9-10 m: ddmlmtmgmmgmprmbmpqm",
"5-10 v: vvvvjvvvvvvvvvx", "3-10 v: dwxdfjhxgsznhzqsqnd", "1-3 k: xkrkkkkkkmp", "2-5 c: dcrscf",
"1-10 p: ppwpwppppppljtppr", "3-7 r: rrrrrrbrdr", "5-9 t: ttttjtttttttttt", "4-5 w: wwwxr",
"6-11 f: rtwzsffhxplnwrzpwwj", "3-9 c: klcdzfchcnxcccnccpc", "3-4 g: mgnlg", "1-5 f: kffgpffft",
"3-4 l: qlsvllnl", "2-5 w: vwwwwwwrf", "11-12 n: qcgnnznfnmnt", "6-13 d: rbbzghqwwmrdkssgn",
"1-3 x: hdxnqxtphtmk", "10-13 w: xwwwxwcwrfcwm", "9-10 p: tpppfxvbppppgpnvfzcv", "8-13 h: nhqhqhthmpmnhlch",
"11-13 z: hjkftzgzlfhjjh", "9-10 t: tttthttpzt", "2-8 g: vghggdbfggrfggrgggrt", "11-16 g: gjzgfnggggsgggzh",
"6-10 r: srmjvrrrlrrrhrl", "2-11 d: ddddddddbddddd", "5-6 j: jjfjjjj", "8-11 s: ssssssssssqssmssss",
"4-5 v: vvvhp", "5-7 c: ccqxvklbc", "8-9 q: qnqfgqvqqqdwzqmcq", "3-5 q: zbqqq", "6-9 g: kkgzgwpvgt",
"1-14 h: hhhhhhhhhhhhhhh", "9-10 w: swwwwwwwjq", "1-13 j: xjwjjljjjjdjjjjmjj", "11-13 m: smmhmmcmmmkmdmmmmm",
"15-17 p: ppppppppppppppsps"};
public static void main(final String[] args) {
System.out.println(Stream.of(INPUT)
.map(PolicyAndPassword::new)
.filter(PolicyAndPassword::isValid)
.count());
System.out.println(Stream.of(INPUT)
.map(PolicyAndPassword::new)
.filter(PolicyAndPassword::isValidNewPolicy)
.count());
}
private static class PolicyAndPassword {
private final Range<Integer> allowedOccurrences;
private final Character character;
private final String password;
public PolicyAndPassword(final String rawData) {
final List<String> parts = Splitter.on(" ").splitToList(rawData);
final List<String> range = Splitter.on("-").splitToList(parts.get(0));
allowedOccurrences = Range.closed(Integer.parseInt(range.get(0)), Integer.parseInt(range.get(1)));
character = parts.get(1).charAt(0);
password = parts.get(2);
}
public boolean isValid() {
return allowedOccurrences.contains(CharMatcher.is(character).countIn(password));
}
public boolean isValidNewPolicy() {
return CharMatcher.is(character)
.countIn(String.valueOf(password.charAt(allowedOccurrences.lowerEndpoint() - 1)) +
String.valueOf(password.charAt(allowedOccurrences.upperEndpoint() - 1))) == 1;
}
}
}
|
package com.example.optexdatagatherandroid;
public class DataGatherResult {
public boolean HasError;
public String ErrorId;
public String ErrorMessage;
public DataGatherInfo DataGatherInformation;
}
|
package ru.kappers.service;
import ru.kappers.model.catalog.Team;
import java.util.List;
/**
* Интерфейс сервиса команды
*/
public interface TeamService {
/**
* Сохранить команду
* @param team сохраняемая команда
* @return сохраненная команда
*/
Team save(Team team);
/**
* Удалить команду
* @param team удаляемая команда
*/
void delete(Team team);
/**
* Получить команду по id
* @param id идентификатор команды
* @return найденная команда или {@literal null}
*/
Team getById(int id);
/**
* Получить команду по имени
* @param name имя команды
* @return найденная команда или {@literal null}
*/
Team getByName(String name);
/**
* Получить все команды со строкой в имени
* @param name строка в имени
* @return список команд
*/
List<Team> getAllWithNameContains(String name);
/**
* Получить все команды
* @return список команд
*/
List<Team> getAll();
/**
* Получить список команд по их id
* @param ids идентификаторы команд
* @return список команд
*/
List<Team> getAllById(Iterable<Integer> ids);
/**
* Получить список команд с id, не входящие в список указанных id
* @param ids исключаемые id
* @return список команд
*/
List<Team> getAllByIdIsNotIn(Iterable<Integer> ids);
}
|
package rx.operators;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import rx.Subscriber;
import rx.functions.Func1;
import rx.functions.Functions;
import rx.observers.TestSubscriber;
import java.util.concurrent.atomic.AtomicBoolean;
@RunWith(RobolectricTestRunner.class)
public class OperatorConditionalBindingTest {
private TestSubscriber<String> subscriber = new TestSubscriber<String>();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldReleaseBoundReferenceIfPredicateFailsToPass() {
final AtomicBoolean toggle = new AtomicBoolean(true);
OperatorConditionalBinding<String, Object> op = new OperatorConditionalBinding<String, Object>(
new Object(), new Func1<Object, Boolean>() {
@Override
public Boolean call(Object o) {
return toggle.get();
}
});
Subscriber<? super String> sub = op.call(subscriber);
sub.onNext("one");
toggle.set(false);
sub.onNext("two");
sub.onCompleted();
sub.onError(new Exception());
assertEquals(1, subscriber.getOnNextEvents().size());
assertEquals(0, subscriber.getOnCompletedEvents().size());
assertEquals(0, subscriber.getOnErrorEvents().size());
assertNull(op.getBoundRef());
}
@Test
public void shouldUnsubscribeFromSourceSequenceWhenPredicateFailsToPass() {
OperatorConditionalBinding<String, Object> op = new OperatorConditionalBinding<String, Object>(
new Object(), Functions.alwaysFalse());
Subscriber<? super String> sub = op.call(subscriber);
sub.onNext("one");
sub.onNext("two");
sub.onCompleted();
sub.onError(new Exception());
assertEquals(0, subscriber.getOnNextEvents().size());
assertEquals(0, subscriber.getOnCompletedEvents().size());
assertEquals(0, subscriber.getOnErrorEvents().size());
}
@Test
public void unsubscribeWillUnsubscribeFromWrappedSubscriber() {
OperatorConditionalBinding<String, Object> op = new OperatorConditionalBinding<String, Object>(new Object());
op.call(subscriber).unsubscribe();
subscriber.assertUnsubscribed();
}
}
|
package org.idea.plugin.atg.psi.reference;
import com.google.common.collect.Lists;
import com.intellij.lang.properties.PropertiesFileType;
import com.intellij.lang.properties.psi.impl.PropertiesFileImpl;
import com.intellij.lang.properties.psi.impl.PropertyValueImpl;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlText;
import com.intellij.psi.xml.XmlToken;
import org.idea.plugin.atg.index.AtgIndexService;
import org.idea.plugin.atg.util.AtgComponentUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Optional;
public class AtgComponentReference extends PsiPolyVariantReferenceBase<PsiElement> {
private final String componentName;
public AtgComponentReference(@NotNull PropertyValueImpl element, @NotNull TextRange textRange) {
super(element, textRange);
componentName = element.getText().substring(textRange.getStartOffset(), textRange.getEndOffset());
}
public AtgComponentReference(@NotNull XmlAttributeValue element) {
super(element);
componentName = element.getValue();
}
public AtgComponentReference(@NotNull XmlText element) {
super(element);
componentName = element.getValue().trim();
}
public AtgComponentReference(@NotNull XmlToken element) {
super(element);
componentName = ((XmlText)element.getParent()).getValue().trim();
}
public AtgComponentReference(@NotNull String componentName, @NotNull TextRange textRange, @NotNull PsiElement element) {
super(element, textRange);
this.componentName = componentName;
}
@Override
public ResolveResult @NotNull [] multiResolve(boolean incompleteCode) {
Project project = myElement.getProject();
AtgIndexService componentsService = ServiceManager.getService(project, AtgIndexService.class);
Collection<PsiFile> applicableComponents;
if (componentName.endsWith(".xml")) {
applicableComponents = Lists.newArrayList(componentsService.getXmlsByName(componentName));
} else {
applicableComponents = Lists.newArrayList(componentsService.getComponentsByName(componentName));
}
return applicableComponents.stream()
.map(element -> new PsiElementResolveResult(element, true))
.toArray(ResolveResult[]::new);
}
@Override
public Object @NotNull [] getVariants() {
return new String[0];
}
@Override
public PsiElement handleElementRename(final String newElementName) {
int endIndex = componentName.contains("/") ? componentName.lastIndexOf("/") + 1 : 0;
String newComponentName = componentName.substring(0, endIndex) + newElementName.replace(PropertiesFileType.DOT_DEFAULT_EXTENSION, "");
return super.handleElementRename(newComponentName);
}
@Override
@SuppressWarnings("OptionalIsPresent")
public PsiElement bindToElement(@NotNull PsiElement element) {
if (element instanceof PropertiesFileImpl) {
Optional<String> newComponentName = AtgComponentUtil.getComponentCanonicalName((PropertiesFileImpl) element);
if (newComponentName.isPresent()) {
return super.handleElementRename(newComponentName.get());
}
return null;
}
return super.bindToElement(element);
}
}
|
package com.gerray.fmsystem.ManagerModule.Profile;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.gerray.fmsystem.R;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.squareup.picasso.Picasso;
import java.util.Objects;
public class ProfilePopUp extends AppCompatActivity {
private TextInputEditText profAuth, profAddress, profEmail, profOcc;
private Spinner profActivity;
private ImageView profImage;
private static final int PICK_IMAGE_REQUEST = 1;
private Uri mImageUri;
DatabaseReference databaseReference;
StorageReference mStorageRef;
StorageTask mUploadTask;
FirebaseAuth auth;
ProgressDialog progressDialog;
FirebaseDatabase firebaseDatabase;
DatabaseReference firebaseDatabaseReference;
FirebaseUser firebaseUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_pop_up);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
getWindow().setLayout((int) (width * .9), (int) (height * .6));
Button btnUpdate = findViewById(R.id.btn_update_prof);
btnUpdate.setOnClickListener(v -> facilityCreate());
Button btnProfImage = findViewById(R.id.prof_image);
btnProfImage.setOnClickListener(v -> openFileChooser());
profImage = findViewById(R.id.prof_imageView);
profAuth = findViewById(R.id.facility_auth);
profAddress = findViewById(R.id.facility_postal);
profEmail = findViewById(R.id.facility_email);
profOcc = findViewById(R.id.facility_occ);
profActivity = findViewById(R.id.prof_spinner);
auth = FirebaseAuth.getInstance();
FirebaseUser currentUser = auth.getCurrentUser();
assert currentUser != null;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Facilities").child(currentUser.getUid());
mStorageRef = FirebaseStorage.getInstance().getReference().child("Facilities").child(currentUser.getUid());
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
if (auth.getCurrentUser() != null) {
databaseReference.child("Profile")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.child("authorityName").exists()) {
String authName = Objects.requireNonNull(snapshot.child("authorityName").getValue()).toString().trim();
profAuth.setText(authName);
}
if (snapshot.child("emailAddress").exists()) {
String emailAddress = Objects.requireNonNull(snapshot.child("emailAddress").getValue()).toString().trim();
profEmail.setText(emailAddress);
}
if (snapshot.child("occupancyNo").exists()) {
String occNo = Objects.requireNonNull(snapshot.child("occupancyNo").getValue()).toString().trim();
profOcc.setText(occNo);
}
if (snapshot.child("postalAddress").exists()) {
String postal = Objects.requireNonNull(snapshot.child("postalAddress").getValue()).toString().trim();
profAddress.setText(postal);
}
if (snapshot.child("facilityImageUrl").exists()) {
String imageUrl = Objects.requireNonNull(snapshot.child("facilityImageUrl").getValue()).toString().trim();
Picasso.with(ProfilePopUp.this).load(imageUrl).into(profImage);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.with(this).load(mImageUri).into(profImage);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void facilityCreate() {
progressDialog.setMessage("Updating");
progressDialog.show();
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabaseReference = firebaseDatabase.getReference();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
firebaseDatabaseReference.child("Facilities").child(firebaseUser.getUid())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String getName = null, getFacilityID = null;
if (snapshot.child("name").exists()) {
getName = Objects.requireNonNull(snapshot.child("name").getValue()).toString().trim();
}
if (snapshot.child("facilityID").exists()) {
getFacilityID = Objects.requireNonNull(snapshot.child("facilityID").getValue()).toString().trim();
}
final String name = getName;
final String facilityID = getFacilityID;
final String auth = Objects.requireNonNull(profAuth.getText()).toString().trim();
final String postal = Objects.requireNonNull(profAddress.getText()).toString().trim();
final String email = Objects.requireNonNull(profEmail.getText()).toString().trim();
final String activity = profActivity.getSelectedItem().toString().trim();
final int occupancy = Integer.parseInt(Objects.requireNonNull(profOcc.getText()).toString().trim());
if (TextUtils.isEmpty(name)) {
Toast.makeText(ProfilePopUp.this, "Enter Name", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(auth)) {
Toast.makeText(ProfilePopUp.this, "Enter Authority Name", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(postal)) {
Toast.makeText(ProfilePopUp.this, "Add Postal Address", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
Toast.makeText(ProfilePopUp.this, "Enter Email Address", Toast.LENGTH_SHORT).show();
return;
}
if (mImageUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(taskSnapshot -> {
fileReference.getDownloadUrl().addOnSuccessListener(uri -> {
final String downUri = uri.toString().trim();
FacProfile facProfile = new FacProfile(name, auth, activity, postal, email, occupancy, facilityID, downUri);
databaseReference.child("Profile").setValue(facProfile);
});
progressDialog.dismiss();
Toast.makeText(ProfilePopUp.this, "Saved", Toast.LENGTH_SHORT).show();
ProfilePopUp.this.finish();
})
.addOnFailureListener(e -> Toast.makeText(ProfilePopUp.this, e.getMessage(), Toast.LENGTH_SHORT).show())
.addOnProgressListener(taskSnapshot -> {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setProgress((int) progress);
});
} else {
Toast.makeText(ProfilePopUp.this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
|
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
public class OffsetDateTimeDemo
{
public static void main(String[] args)
{
/*
* Parameters:
*
* temporal - the temporal object to convert, not null
*
* Returns:the offset date-time, not null
*/
OffsetDateTime offsetDateTime = OffsetDateTime.from(ZonedDateTime.now());
System.out.println(offsetDateTime);
}
}
|
package cz.csas.atpcoolapp.rest;
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
/**
* Configuration object for REST Service API
*
* Here can be various RESTeasy services registered
*
*
*/
public class ServiceApplication extends Application {
HashSet<Object> singletons = new HashSet<Object>();
public ServiceApplication() {
// Services
singletons.add(new RestService());
CorsFilter corsFilter = new CorsFilter();
corsFilter.getAllowedOrigins().add("*");
corsFilter.setAllowedMethods("OPTIONS, GET, POST, DELETE, PUT, PATCH");
singletons.add(corsFilter);
ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
providerFactory.registerProvider(JacksonConfig.class);
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.09.03 at 09:19:50 PM EDT
//
package org.oasisopen.xliff;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:oasis:names:tc:xliff:document:1.2}header" minOccurs="0"/>
* <element ref="{urn:oasis:names:tc:xliff:document:1.2}body"/>
* </sequence>
* <attribute name="original" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="source-language" use="required" type="{http://www.w3.org/2001/XMLSchema}language" />
* <attribute name="datatype" use="required" type="{urn:oasis:names:tc:xliff:document:1.2}AttrType_datatype" />
* <attribute name="tool-id" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="tool" type="{http://www.w3.org/2001/XMLSchema}string" default="manual" />
* <attribute name="date" type="{http://www.w3.org/2001/XMLSchema}dateTime" />
* <attribute ref="{http://www.w3.org/XML/1998/namespace}space"/>
* <attribute name="ts" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="category" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="target-language" type="{http://www.w3.org/2001/XMLSchema}language" />
* <attribute name="product-name" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="product-version" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="build-num" type="{http://www.w3.org/2001/XMLSchema}string" />
* <anyAttribute processContents='skip'/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"header",
"body"
})
@XmlRootElement(name = "file")
public class File {
protected Header header;
@XmlElement(required = true)
protected Body body;
@XmlAttribute(name = "original", required = true)
protected String original;
@XmlAttribute(name = "source-language", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String sourceLanguage;
@XmlAttribute(name = "datatype", required = true)
protected String datatype;
@XmlAttribute(name = "tool-id")
protected String toolId;
@XmlAttribute(name = "tool")
protected String tool;
@XmlAttribute(name = "date")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar date;
@XmlAttribute(name = "space", namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String space;
@XmlAttribute(name = "ts")
protected String ts;
@XmlAttribute(name = "category")
protected String category;
@XmlAttribute(name = "target-language")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "language")
protected String targetLanguage;
@XmlAttribute(name = "product-name")
protected String productName;
@XmlAttribute(name = "product-version")
protected String productVersion;
@XmlAttribute(name = "build-num")
protected String buildNum;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the header property.
*
* @return
* possible object is
* {@link Header }
*
*/
public Header getHeader() {
return header;
}
/**
* Sets the value of the header property.
*
* @param value
* allowed object is
* {@link Header }
*
*/
public void setHeader(Header value) {
this.header = value;
}
/**
* Gets the value of the body property.
*
* @return
* possible object is
* {@link Body }
*
*/
public Body getBody() {
return body;
}
/**
* Sets the value of the body property.
*
* @param value
* allowed object is
* {@link Body }
*
*/
public void setBody(Body value) {
this.body = value;
}
/**
* Gets the value of the original property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOriginal() {
return original;
}
/**
* Sets the value of the original property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOriginal(String value) {
this.original = value;
}
/**
* Gets the value of the sourceLanguage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSourceLanguage() {
return sourceLanguage;
}
/**
* Sets the value of the sourceLanguage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSourceLanguage(String value) {
this.sourceLanguage = value;
}
/**
* Gets the value of the datatype property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDatatype() {
return datatype;
}
/**
* Sets the value of the datatype property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDatatype(String value) {
this.datatype = value;
}
/**
* Gets the value of the toolId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getToolId() {
return toolId;
}
/**
* Sets the value of the toolId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setToolId(String value) {
this.toolId = value;
}
/**
* Gets the value of the tool property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTool() {
if (tool == null) {
return "manual";
} else {
return tool;
}
}
/**
* Sets the value of the tool property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTool(String value) {
this.tool = value;
}
/**
* Gets the value of the date property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDate() {
return date;
}
/**
* Sets the value of the date property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDate(XMLGregorianCalendar value) {
this.date = value;
}
/**
* Gets the value of the space property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpace() {
return space;
}
/**
* Sets the value of the space property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpace(String value) {
this.space = value;
}
/**
* Gets the value of the ts property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTs() {
return ts;
}
/**
* Sets the value of the ts property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTs(String value) {
this.ts = value;
}
/**
* Gets the value of the category property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCategory() {
return category;
}
/**
* Sets the value of the category property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCategory(String value) {
this.category = value;
}
/**
* Gets the value of the targetLanguage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTargetLanguage() {
return targetLanguage;
}
/**
* Sets the value of the targetLanguage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTargetLanguage(String value) {
this.targetLanguage = value;
}
/**
* Gets the value of the productName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProductName() {
return productName;
}
/**
* Sets the value of the productName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProductName(String value) {
this.productName = value;
}
/**
* Gets the value of the productVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProductVersion() {
return productVersion;
}
/**
* Sets the value of the productVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProductVersion(String value) {
this.productVersion = value;
}
/**
* Gets the value of the buildNum property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBuildNum() {
return buildNum;
}
/**
* Sets the value of the buildNum property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBuildNum(String value) {
this.buildNum = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
|
package com.maoyan.day1;
/**
* Created by jiangdongyu on 2017/4/18.
*/
public class Prims {
/*
Guava提供了若干通用工具,包括原生类型数组与集合API的交互,原生类型和字节数组的相互转换,以及对某些原生类型的无符号形式的支持。
原生类型 Guava工具类(都在com.google.common.primitives包)
byte Bytes, SignedBytes, UnsignedBytes
short Shorts
int Ints, UnsignedInteger, UnsignedInts
long Longs, UnsignedLong, UnsignedLongs
float Floats
double Doubles
char Chars
boolean Booleans
List<Wrapper> asList(prim… backingArray) 把数组转为相应包装类的List
prim[] toArray(Collection<Wrapper> collection) 把集合拷贝为数组,和collection.toArray()一样线程安全
prim[] concat(prim[]… arrays) 串联多个原生类型数组
boolean contains(prim[] array, prim target) 判断原生类型数组是否包含给定值
int indexOf(prim[] array, prim target) 给定值在数组中首次出现处的索引,若不包含此值返回-1
int lastIndexOf(prim[] array, prim target) 给定值在数组最后出现的索引,若不包含此值返回-1
prim min(prim… array)数组中的最小值
prim max(prim… array)数组中的最大值
String join(String separator, prim… array) 把数组用给定分隔符连接为字符串
Comparator<prim[]> lexicographicalComparator() 按字典序比较原生类型数组的Comparator
int compare(prim a, prim b) 传统的Comparator.compare方法,但针对原生类型。JDK7的原生类型包装类也提供这样的方法 符号相关
prim checkedCast(long value) 把给定long值转为某一原生类型,若给定值不符合该原生类型,则抛出IllegalArgumentException 仅适用于符号相关的整型*
prim saturatedCast(long value) 把给定long值转为某一原生类型,若给定值不符合则使用最接近的原生类型值 仅适用于符号相关的整型
int BYTES 常量:表示该原生类型需要的字节数
prim fromByteArray(byte[] bytes) 使用字节数组的前Prims.BYTES个字节,按大字节序返回原生类型值;如果bytes.length <= Prims.BYTES,抛出IAE
prim fromBytes(byte b1, …, byte bk) 接受Prims.BYTES个字节参数,按大字节序返回原生类型值
byte[] toByteArray(prim value) 按大字节序返回value的字节数组
int/long UnsignedInts.parseUnsignedInt(String) 按无符号十进制解析字符串
int/long UnsignedInts.parseUnsignedInt(String string, int radix) 按无符号的特定进制解析字符串
String UnsignedInts.toString(long) 数字按无符号十进制转为字符串
String UnsignedInts.toString(long value, int radix) 数字按无符号特定进制转为字符串
UnsignedPrim add(UnsignedPrim), subtract, multiply, divide, remainder 简单算术运算
UnsignedPrim valueOf(BigInteger) 按给定BigInteger返回无符号对象,若BigInteger为负或不匹配,抛出IAE
UnsignedPrim valueOf(long) 按给定long返回无符号对象,若long为负或不匹配,抛出IAE
UnsignedPrim asUnsigned(prim value) 把给定的值当作无符号类型。例如,UnsignedInteger.asUnsigned(1<<31)的值为231,尽管1<<31当作int时是负的
BigInteger bigIntegerValue() 用BigInteger返回该无符号对象的值
toString(), toString(int radix) 返回无符号值的字符串表示
*/
}
|
package com.tianlang.DAO;
import java.sql.*;
public class JDBCUtil {
Connection conn = null;
// Statement stm = null;
PreparedStatement pstm = null;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConnection(){
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tianlang","root","Lance2497");
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/*
public Statement getStatement(){
try {
stm = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stm;
}
*/
public PreparedStatement getPrepareStatement(String sql){
try {
conn = getConnection();
pstm = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return pstm;
}
public void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void close(){
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
package com.ajith.beintouch;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import android.view.View;
import android.content.Intent;
import android.widget.ImageView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.UploadTask;
import android.app.ProgressDialog;
import android.widget.Toast;
import java.util.UUID;
public class Profile extends AppCompatActivity
{
private Button btnLogOut, btnUpload;
private ImageView imgProfile;
private Uri imagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
btnLogOut=findViewById(R.id.btnLogOut);
imgProfile=findViewById(R.id.profile_img);
btnUpload = findViewById(R.id.btnUploadImage);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
uploadImage();
}
});
btnLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(Profile.this,MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP));//to ensure that the goingback to old screen doesnot happen
finish();
}
});
imgProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent photoIntent = new Intent(Intent.ACTION_PICK);
photoIntent.setType("image/*");
startActivityForResult(photoIntent,1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data!=null){
imagePath = data.getData();
getImageInImageView();
}
}
private void getImageInImageView()
{
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imagePath);
} catch (IOException e) {
e.printStackTrace();
}
imgProfile.setImageBitmap(bitmap);
}
private void uploadImage(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
FirebaseStorage.getInstance().getReference("images/"+ UUID.randomUUID().toString()).putFile(imagePath)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
task.getResult().getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()){
updateProfilePicture(task.getResult().toString());
}
}
});
Toast.makeText(Profile.this, "Image Uploaded!", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(Profile.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
double progress = 100.0 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount();
progressDialog.setMessage(" Uploaded "+(int) progress + "%");
}
});
}
private void updateProfilePicture(String url)
{
FirebaseDatabase.getInstance()
.getReference("user/"+FirebaseAuth.getInstance().getCurrentUser().getUid() + "/profilePicture")
.setValue(url);
}
}
|
package org.rec.sample1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastIDSet;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.recommender.AbstractRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.IDRescorer;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
public class MyRecommender extends AbstractRecommender implements Recommender{
List<RecommendedItem> itemsRecommended;
DataModel model;
ItemSimilarity sim1;
protected MyRecommender(DataModel dataModel) throws TasteException {
super(dataModel);
// TODO Auto-generated constructor stub
model = dataModel;
//sim1 = new PearsonCorrelationSimilarity(model);
sim1 = new AdjustedCosineSimmilarity(model);
}
@Override
public void refresh(Collection<Refreshable> arg0) {
// TODO Auto-generated method stub
}
@Override
public float estimatePreference(long userid, long itemid) throws TasteException {
// TODO Auto-generated method stub
FastIDSet items = null;
if(model.getItemIDsFromUser(userid) != null)
items = model.getItemIDsFromUser(userid);
else
return (float) 0.0;
LongPrimitiveIterator iter = items.iterator();
float total=(float) 0.0,totalWeight = (float) 0.0;
double sim = 0.0;
while(iter.hasNext()){
long ratedItem = iter.nextLong();
float rating = model.getPreferenceValue(userid, ratedItem);
sim = sim1.itemSimilarity(itemid, ratedItem);
if(sim < 0.0 || Double.isNaN(sim))
sim = (float) 0.0;
total = (float) (total + sim * rating);
totalWeight = (float) (totalWeight + sim);
}
if(totalWeight > 0.0)
total = total / totalWeight;
else
total = (float) 0.0;
if(total > 5.0)
total = (float) 5.0;
return total;
}
List<MovieRecommended> movieList = new ArrayList<MovieRecommended>();
@Override
public List<RecommendedItem> recommend(long userid, int k)
throws TasteException {
// TODO Auto-generated method stub
List<RecommendedItem> recommendedList = new ArrayList<RecommendedItem>();
LongPrimitiveIterator iter = model.getItemIDs();
FastIDSet ratedItemSet = model.getItemIDsFromUser(userid);
int i = 0;
while(iter.hasNext()){
long item = iter.nextLong();
boolean ignore = false;
for(long ratedItem:ratedItemSet){
if(ratedItem == item){
ignore = true;
break;
}
}
if(ignore == true)
continue;
double rating = estimatePreference(userid, item);
MovieRecommended mv = new MovieRecommended();
mv.setItemID(item);
mv.setValue((float)rating);
movieList.add(mv);
}
Collections.sort(movieList);
int count = 0;
List<RecommendedItem> finalList = new ArrayList<RecommendedItem>();
for(MovieRecommended m:movieList){
if(count >= k)
break;
RecommendedItem item = m;
finalList.add(item);
count++;
}
return finalList;
}
@Override
public List<RecommendedItem> recommend(long arg0, int arg1, IDRescorer arg2)
throws TasteException {
// TODO Auto-generated method stub
return null;
}
}
|
public class CountArgs {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("You provided " + args.length + " args.");
}
else {
System.out.println("None supplied");
}
}
}
|
/*
* 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 age;
import java.util.Calendar;
/**
*
* @author xubo
*/
public class Main {
/**
* @param args the command line arguments
*/
private int year,month,day,age;
public Main(int y,int m,int d){
// TODO code application logic here
// private int year,month,day,age;
year=y;
month=(((m>=1)&(m<12))?m:1);
day=(((d>=1)&(d<31))?d:1);
// month=m;
// day=d;
age = Calendar.getInstance().get(Calendar.YEAR) - year;
}
public static void main(String[] args) {
Main main=new Main(1984,11,2);
// main.year
System.out.println("a" + main.year + "a" + main.month +"a"+ main.day + "a" + main.age + "a");
// sout
}
}
|
package conTest;
/*
* 目的: 演示构造法初始化对象 再演示set get初始化对象
*/
public class AnimalTest {
public static void main(String[] args) {
/*
* 使用无参构造
*/
Animal an = new Animal();
an.setName("神龟");
an.setAge(20000);
an.setGender("雄");
System.out.println(an.getName() + an.getAge() +an.getGender());
/*
* 有参构造
*/
Animal an1 = new Animal("饕鬄",30000,"公");
System.out.println(an1.getName() + an1.getAge() + an1.getGender());
}
}
class Animal {
private String name;
private int age ;
String gender; //性别
//无参构造
public Animal(){
}
//有参构造
public Animal(String name, int age ,String gender){
this.name = name;
this.age = age;
this.gender = gender;
}
//setter getter
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void setGender(String gender){
this.gender = gender;
}
public String getGender(){
return gender;
}
}
|
package com.shaoye.dbtest;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.shaoye.dto.TBUserDto;
import com.shaoye.pojo.User;
import com.shaoye.service.ITBUserService;
import com.shaoye.service.IUserService;
@RunWith(SpringJUnit4ClassRunner.class)
//表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class DatabaseTest {
private static Logger logger = LoggerFactory.getLogger(DatabaseTest.class);
@Resource
private IUserService userService = null;
@Resource
private ITBUserService tbUserService = null;
@Test
public void test1() {
User user = userService.getUserById(3);
if (user != null) {
logger.info("**********" + JSON.toJSONString(user));
} else {
logger.info("*****{}*****","noting get from db");
}
}
@Test
public void test2() {
User user = new User();
user.setUsername("angular");
user.setPassword("123456");
try {
userService.addUser(user);
} catch (Exception e) {
e.printStackTrace();
}
logger.info("**********" + JSON.toJSONString(user));
}
@Test
public void test3() {
List<TBUserDto> users = tbUserService.getAllTBUser();
for (TBUserDto user : users) {
logger.info("[" + JSON.toJSONString(user) + "]");
}
}
}
|
package com.dnomaid.iot.mqtt.device;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.dnomaid.iot.mqtt.global.Constants;
import com.dnomaid.iot.mqtt.topic.TopicJson;
import com.dnomaid.iot.mqtt.topic.TopicNoJson;
import com.dnomaid.iot.mqtt.topic.json.*;
import com.dnomaid.iot.mqtt.topic.noJson.*;
public class Devices implements Constants {
private ArrayList<DeviceConfig> DevicesConfig;
private ArrayList<Device> Devices;
private static Devices myGlobal = null;
public static synchronized Devices getInst() {
if (myGlobal==null) {
myGlobal=new Devices();
}
return myGlobal;
}
Devices(){
DevicesConfig = new ArrayList<>();
Devices = new ArrayList<>();
}
public void newDevice(TypeDevice typeDevice, String numberDevice){
DevicesConfig.add(new DeviceConfig(typeDevice, numberDevice));
selectDevice(typeDevice, numberDevice);
}
public void deleteDevice(DeviceConfig deviceConfig){
/*
IntStream.range(0, (getDevices().size()-1))
.forEach(index -> {
if (deviceConfig.toString().equals(getDevices().get(index).toString())){
getDevices().remove(index);
}
});
IntStream.range(0, (getDevicesConfig().size()-1))
.forEach(index -> {
if (deviceConfig.toString().equals(getDevicesConfig().get(index).toString())){
getDevicesConfig().remove(index);
}
});
*/
for (int i = 0; i < getDevices().size(); ++i) {
if (deviceConfig.toString().equals(getDevices().get(i).toString())){
getDevices().remove(i);
}
}
for (int i = 0; i < getDevicesConfig().size(); ++i) {
if (deviceConfig.toString().equals(getDevicesConfig().get(i).toString())){
getDevicesConfig().remove(i);
}
}
}
public ArrayList<DeviceConfig> getDevicesConfig() {return DevicesConfig;}
public ArrayList<Device> getDevices() {return Devices;}
public ArrayList<Device> getRelays() {
ArrayList<Device> filterList = (ArrayList<Device>) getDevices().stream()
.filter(c -> c.getGroupList().equals(GroupList.Relay)
|| c.getGroupList().equals(GroupList.RelaySensorClimate))
.collect(Collectors.toList());
return filterList;
}
public ArrayList<Device> getSensorsClimate() {
ArrayList<Device> filterList = (ArrayList<Device>) getDevices().stream()
.filter(c -> c.getGroupList().equals(GroupList.SensorClimate)
|| c.getGroupList().equals(GroupList.RelaySensorClimate))
.collect(Collectors.toList());
return filterList;
}
public String getPublishTopicRelay(Integer numberRelay) {
String PublishTopicRelay = "PublishTopic01Relay??";
if(numberRelay>0&getRelays().size()>=numberRelay) {
PublishTopicRelay = getRelays().get(numberRelay-1).getTopics().get(1).getName();
}
return PublishTopicRelay;
}
private void selectDevice (TypeDevice typeDevice, String numberDevice){
String nametopic01 = "";
String nametopic02 = "";
GroupList groupList;
TypeGateway typeGateway;
TopicNoJson topicNoJson01;
TopicNoJson topicNoJson02;
TopicJson topicJson01;
Device device;
switch (typeDevice) {
case SonoffS20:
typeGateway = TypeGateway.Router_1;
groupList = GroupList.Relay;
nametopic01 = groupList+"_1"+"/POWER";
nametopic02 = nametopic01;
topicNoJson01 = new TopicNoJson(STAT_PREFIX, nametopic01, new POWER());
topicNoJson02 = new TopicNoJson(CMND_PREFIX, nametopic02, new POWER());
device = createDevice(typeGateway, typeDevice, numberDevice, groupList, topicNoJson01, topicNoJson02);
Devices.add(device);
break;
case SonoffSNZB02:
typeGateway = TypeGateway.CC2531_1;
groupList = GroupList.SensorClimate;
nametopic01 = groupList+"_1";
topicJson01 = new TopicJson(STAT_PREFIX, nametopic01, new SonoffSNZB02Json());
device = createDevice(typeGateway, typeDevice, numberDevice, groupList, topicJson01);
Devices.add(device);
break;
case AqaraTemp:
typeGateway = TypeGateway.CC2531_1;
groupList = GroupList.SensorClimate;
nametopic01 = groupList+"_1";
topicJson01 = new TopicJson(STAT_PREFIX, nametopic01, new AqaraTempJson());
device = createDevice(typeGateway, typeDevice, numberDevice, groupList, topicJson01);
Devices.add(device);
break;
case TuyaZigBeeSensor:
typeGateway = TypeGateway.CC2531_1;
groupList = GroupList.SensorClimate;
nametopic01 = groupList+"_1";
topicJson01 = new TopicJson(STAT_PREFIX, nametopic01, new TuyaZigBeeSensorJson());
device = createDevice(typeGateway, typeDevice, numberDevice, groupList, topicJson01);
Devices.add(device);
break;
case XiaomiZNCZ04LM:
typeGateway = TypeGateway.CC2531_1;
groupList = GroupList.RelaySensorClimate;
nametopic01 = groupList+"_1";
nametopic02 = nametopic01+"/set";
topicJson01 = new TopicJson(MIX_PREFIX, nametopic01, new XiaomiZNCZ04LM());
topicNoJson02 = new TopicNoJson(MIX_PREFIX, nametopic02, new Set());
device = createDevice(typeGateway, typeDevice, numberDevice, groupList, topicJson01, topicNoJson02);
Devices.add(device);
break;
default:
break;
}
}
private Device createDevice(TypeGateway gateway, TypeDevice typeDevice, String numberDevice, GroupList groupList, TopicNoJson topic01, TopicNoJson topic02){
Device device = new Device(gateway,typeDevice,numberDevice,groupList);
device.addTopic(topic01);
device.addTopic(topic02);
return device;
}
private Device createDevice(TypeGateway gateway, TypeDevice typeDevice, String numberDevice, GroupList groupList, TopicJson topic01){
Device device = new Device(gateway,typeDevice,numberDevice,groupList);
device.addTopic(topic01);
return device;
}
private Device createDevice(TypeGateway gateway, TypeDevice typeDevice, String numberDevice, GroupList groupList, TopicJson topic01, TopicNoJson topic02){
Device device = new Device(gateway,typeDevice,numberDevice,groupList);
device.addTopic(topic01);
device.addTopic(topic02);
return device;
}
}
|
package com.geeks.shoppingcart.entity;
import java.io.Serializable;
public class Account implements Serializable {
public static final String ROLE_MANAGER = "MANAGER";
public static final String ROLE_EMPLOYEE = "EMPLOYEE";
private String userName;
private String encrytedPassword;
private Boolean active;
private String userRole;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEncrytedPassword() {
return encrytedPassword;
}
public void setEncrytedPassword(String encrytedPassword) {
this.encrytedPassword = encrytedPassword;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
@Override
public String toString() {
return "Account{" +
"userName='" + userName + '\'' +
", encrytedPassword='" + encrytedPassword + '\'' +
", active=" + active +
", userRole='" + userRole + '\'' +
'}';
}
}
|
package com.danielsandrutski.convert;
import com.danielsandrutski.convert.namedata.BigDigit;
import com.danielsandrutski.convert.namedata.NameData;
import com.danielsandrutski.convert.namedata.SmallDigit;
import java.text.DecimalFormat;
/**
* Создано DanielSand 03.11.2017
* Класс, позволяющий отобразить числа прописью
* @version 1.0
* @autor Daniel Sandrutski
*/
public class NumbersWordsConvert {
/** Разделитель в выходной строке */
private static final String SEPARATOR = " ";
/** Шаблон для преобразования исходного числа в строку, с дальнейшим разделением на цедую часть и дробную */
private static final DecimalFormat df = new DecimalFormat("#.################################################");
/** Исходное число */
private double baselineNumber;
/** Результат преобразования */
private String result;
/** Наименования разрядов больших тысячи */
private BigDigit[] bigDigits;
/** Наименование разрядов и необходимых чисел меньших тысячи */
private SmallDigit[] smallDigits;
/** Наименования разрядов после запятой */
private BigDigit[] fractionDigits;
/**
* Конструктор по умолчанию
*/
public NumbersWordsConvert(){
this.baselineNumber = 0;
NameData nameData = new NameData();
this.bigDigits = nameData.getBigDigits();
this.smallDigits = nameData.getSmallDigit();
this.fractionDigits = nameData.getFractionDigits();
}
/**
* Конструктор, принимающий исходные данные в числовом формате
* @param number Исходное число
*/
public NumbersWordsConvert(double number){
this.baselineNumber = number;
NameData nameData = new NameData();
this.bigDigits = nameData.getBigDigits();
this.smallDigits = nameData.getSmallDigit();
this.fractionDigits = nameData.getFractionDigits();
}
/**
* Конструктор, принимающий исходные данные в строковом формате
* @param number Исходное число в формате строки
*/
public NumbersWordsConvert(String number) throws NumberFormatException {
this.baselineNumber = Double.parseDouble(number);
NameData nameData = new NameData();
this.bigDigits = nameData.getBigDigits();
this.smallDigits = nameData.getSmallDigit();
this.fractionDigits = nameData.getFractionDigits();
}
/**
* Устанавливающий метод исходного числа
* @param baselineNumber Исходное число
*/
public void setBaselineNumber(double baselineNumber) {
this.baselineNumber = baselineNumber;
}
/**
* Метод, инициализирующий преобразование вещественного числа в строку
* @return Возвращает исходное число прописью
*/
public String ConvertDouble(){
if(baselineNumber == 0) return "ноль";
//Проверяем на отрицательное число
if(baselineNumber <= 0) {
result = "минус" + SEPARATOR;
baselineNumber *= -1;
} else {
result = "";
}
//Разбиваем исходное число на его целую и дробную часть
double integerPart = Math.floor(baselineNumber);
String[] stringParts = String.valueOf(df.format(baselineNumber)).split(","); //Разделяем число на целую и дробную части
if((int)Math.ceil(stringParts[0].length() / 3.0) > bigDigits.length) {
return "Слишком большое число!";
}
if(stringParts.length > 1) { //Если у числа имеется дробная часть
int fractionDigit = stringParts[1].length(); //Определяем количество разрядов в дробной части
if(fractionDigit > fractionDigits.length){
return "Слишком много знаков в дробной части числа!";
}
//Преобразовываем целую часть
if(integerPart == 0) {
result = "ноль целых ";
} else {
result += InitConvert(integerPart, (int)Math.ceil(stringParts[0].length() / 3.0), "целая ", "целые ", "целых ", 1);
}
double fractionalPart = Double.parseDouble(stringParts[1]);
if (fractionDigit > 0) {
//Преобразовываем дробную часть
result += InitConvert(fractionalPart, fractionDigit,
fractionDigits[fractionDigit - 1].getOne(),
fractionDigits[fractionDigit - 1].getTwoToFour(),
fractionDigits[fractionDigit - 1].getAnother(),
fractionDigits[fractionDigit - 1].getSex());
}
} else {
result += InitConvert(integerPart, (int)Math.ceil(stringParts[0].length() / 3.0),"", "", "", 0);
}
return result.trim();
}
/**
* Метод, инициализирующий преобразование целого числа в строку, с добавлением дополнительного наименования
* @param one Дополнительная надпись в единственном числе
* @param twoToFour Дополнительная надпись для чисел от 2 до 4
* @param another Дополнительная надпись для остального ряда чисел
* @param sex Род дополнительной надписи (0 - мужской, 1 - женский)
* @return Исходное число прописью
*/
public String ConvertIntegerPartWithLabel(String one, String twoToFour, String another, int sex){
if(baselineNumber == 0) return "ноль " + another;
//Проверяем на отрицательное число
if(baselineNumber <= 0) {
result = "минус" + SEPARATOR;
baselineNumber *= -1;
} else {
result = "";
}
//Выделяем целую часть
double integerPart = Math.floor(baselineNumber);
if((int)Math.ceil(String.valueOf(integerPart).length() / 3.0) > bigDigits.length) {
return "Слишком большое число!";
}
return (result + InitConvert(integerPart, -1, one, twoToFour, another, sex)).trim();
}
/**
* Метод основной инициализации процесса конвертации
* @param _baselineNumber Исходное число (целое)
* @param _digit Количество степеней тысячи в числе
* @param _one Дополнительная надпись в единственном числе
* @param _twoToFour Дополнительная надпись для чисел от 2 до 4
* @param _another Дополнительная надпись для остального ряда чисел
* @param _sex Род дополнительной надписи (0 - мужской, 1 - женский)
* @return Исходное число прописью, включая дополнительную надпись в конце
*/
private String InitConvert(double _baselineNumber, int _digit, String _one, String _twoToFour, String _another, int _sex){
double integerPart = Math.floor(_baselineNumber); //Определяем целую часть числа (с дробной не работаем, поэтому отметаем)
//Заносим дополнительную надпись в массив, чтобы она добавилась в конце преобразования
bigDigits[0].setSex(_sex);
bigDigits[0].setOne(_one);
bigDigits[0].setTwoToFour(_twoToFour);
bigDigits[0].setAnother(_another);
if(_digit >= 1) //Было ли принято количество степеней тысячи. Если нет вычисляем сами
return Converting(integerPart, _digit);
else
return Converting(integerPart, (int)Math.ceil(String.valueOf(df.format(_baselineNumber)).split(",")[0].length() / 3.0));
}
/**
* Основной метод конвертации
* @param _baselineNumber Исходное число для перевода в строку
* @param _digit Количество степеней тысячи в числе
* @return Строка, содержащая число прописью
*/
private String Converting (double _baselineNumber, int _digit)
{
StringBuilder bufString = new StringBuilder();
//Выделить группу, лежащую в крайней слева степени тысячи
double div = Math.pow(1000.0, _digit - 1);
int bufNumber = (int)(_baselineNumber / div);
if (bufNumber == 0) {
//Если число содержит еще разряды, то значит в данной степени одни нули, и необходимо продолжить конвертацию ничего не добавляя
if(_digit > 0)
return Converting(_baselineNumber % div, --_digit);
else
return ""; //Иначе заканчиваем конвертацию
} else {
//Определение вхождения сотен в число
if(bufNumber >= 100){
bufString.append(smallDigits[bufNumber / 100].getHun());
bufNumber %= 100;
}
//Определение вхождения десятков в число
if(bufNumber >= 20) {
bufString.append(smallDigits[bufNumber / 10].getDec());
bufNumber%=10;
}
//Определение вхождения чисел от 10 до 19
if(bufNumber >= 10) {
bufString.append(smallDigits[bufNumber - 10].getTwo());
} else if(bufNumber >= 1) { //Определение вхождения единиц в число
bufString.append(smallDigits[bufNumber].getOne()[bigDigits[_digit - 1].getSex()]);
}
//Добавление наименования степеней тысячи
switch(bufNumber){
case 1:
bufString.append(bigDigits[_digit - 1].getOne());
break;
case 2: case 3:
case 4:
bufString.append(bigDigits[_digit - 1].getTwoToFour());
break;
default:
bufString.append(bigDigits[_digit - 1].getAnother());
break;
}
}
return bufString + Converting(_baselineNumber % div, --_digit); //Продолжаем конвертацию
}
}
|
package com.lyq.model;
import javax.persistence.*;
//目录管理
@Entity
@Table(name="t_mu")
public class Mu {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer mid; //主键Id
private String mname;//目录名称
private Integer kid; //对应课程id
//
@Transient
private String kname;//课程名称
public String getKname() {
return kname;
}
public void setKname(String kname) {
this.kname = kname;
}
public Integer getMid() {
return mid;
}
public void setMid(Integer mid) {
this.mid = mid;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public Integer getKid() {
return kid;
}
public void setKid(Integer kid) {
this.kid = kid;
}
}
|
package com.research.robertodvp.audioanalyzer.DAO;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by robertov on 03/09/2017.
*/
public class EntityDAOHelper<T extends EntityDAOContract> extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "AudioAnalyzer.db";
private EntityDAOContract mEntity = null;
public EntityDAOHelper(Context context, T obj) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mEntity = obj;
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(mEntity.SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(mEntity.SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public long saveEntity() {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
return sqLiteDatabase.insert(
mEntity.TABLE_NAME,
null,
mEntity.getContentValues());
}
}
|
package edu.buffalo.cse.sql.index;
import java.awt.image.DataBuffer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import edu.buffalo.cse.sql.Schema;
import edu.buffalo.cse.sql.SqlException;
import edu.buffalo.cse.sql.data.Datum;
import edu.buffalo.cse.sql.data.Datum.CastError;
import edu.buffalo.cse.sql.data.DatumBuffer;
import edu.buffalo.cse.sql.data.DatumSerialization;
import edu.buffalo.cse.sql.data.ISAMDatum;
import edu.buffalo.cse.sql.data.InsufficientSpaceException;
import edu.buffalo.cse.sql.buffer.BufferManager;
import edu.buffalo.cse.sql.buffer.BufferException;
import edu.buffalo.cse.sql.buffer.ManagedFile;
import edu.buffalo.cse.sql.buffer.FileManager;
import edu.buffalo.cse.sql.test.TestDataStream;
public class ISAMIndex implements IndexFile,Iterator {
Schema.Type[] schema; //((TestDataStream)dataSource).getSchema();// for rowschema
Schema.Type[] keyschema={Schema.Type.INT};
int row;
ManagedFile file;
IndexKeySpec keyspec;
boolean notfound=false;
int iidx;
public ISAMIndex(ManagedFile file, IndexKeySpec keySpec)
throws IOException, SqlException
{
this.file=file;
this.keyspec=keySpec;
}
public ISAMIndex(ManagedFile file, IndexKeySpec keySpec,Schema.Type[] schema)
throws IOException, SqlException
{
this.file=file;
this.schema=schema;
this.keyspec=keySpec;
}
public static ISAMIndex create(FileManager fm,
File path,
Iterator<Datum[]> dataSource,
IndexKeySpec key)
throws Exception
{
System.out.println("please wait while index is being created!!");
int rows=0;
ManagedFile isamindex=fm.open(path);
Schema.Type[] schema=((TestDataStream)dataSource).getSchema();
Schema.Type[] keyschema=key.keySchema();
isamindex.resize(1);
int tempptr=0;
DatumBuffer datbuff=new DatumBuffer(isamindex.getBuffer(0),schema);
datbuff.initialize(40);
File datfile=new File("data.txt");
FileWriter fw = new FileWriter(datfile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while(dataSource.hasNext()){
if(new DatumBuffer(isamindex.getBuffer(tempptr),schema).remaining()-8>schema.length*4){
//System.out.println("writing on page: "+tempptr);
datbuff=new DatumBuffer(isamindex.getBuffer(tempptr),schema);
Datum[] temp=dataSource.next();
int idx=datbuff.write(temp);
bw.write(Datum.Int.stringOfRow(temp));bw.write(Integer.toString(tempptr));
bw.newLine();
rows++;
isamindex.getBuffer(tempptr).putInt(5, 1);
isamindex.getBuffer(tempptr).putInt(25, 0);
isamindex.getBuffer(tempptr).putInt(0, -1);
isamindex.getBuffer(tempptr).putInt(10, idx);
isamindex.dirty(tempptr);
}
else{
isamindex.getBuffer(tempptr).putInt(5, 0);
isamindex.getBuffer(tempptr).putInt(0, -1);
isamindex.dirty(tempptr);
tempptr++;
//System.out.println("writing on new page: "+tempptr);
DatumBuffer dat=new DatumBuffer(isamindex.safeGetBuffer(tempptr),schema);
dat.initialize(40);
Datum[] temp=dataSource.next();
int idx=dat.write(temp);
bw.write(Datum.Int.stringOfRow(temp));bw.write(Integer.toString(tempptr));
bw.newLine();
rows++;
isamindex.getBuffer(tempptr).putInt(5, 1);
isamindex.getBuffer(tempptr).putInt(25, 0);
isamindex.getBuffer(tempptr).putInt(10, idx);
isamindex.dirty(tempptr);
}
}
bw.close();
//System.out.println("Done Writting pages. no. of pages written = "+(tempptr+1));
//System.out.println("total rows written: "+rows);
int indxptr=tempptr+2;
int to=indxptr;
isamindex.getBuffer(0).putInt(15, indxptr);
isamindex.dirty(0);
ISAMDatum isam=new ISAMDatum(isamindex.safeGetBuffer(indxptr),keyschema);
isam.initialize(40);
isamindex.safeGetBuffer(indxptr).putInt(20, 0);
int count=0;
boolean last=false;
boolean boolhold=false;
int hold=count;
count++;
int skip=1;
while(last==false){
//System.out.println("flag of page: "+isamindex.getBuffer(count).getInt(5));
if((isamindex.getBuffer(hold).getInt(5)!=1)&&(boolhold==false)){
//System.out.println("inside while if for page: "+hold);
count=hold+skip;
int max=isamindex.getBuffer(hold).getInt(10);
DatumBuffer readbuff1=new DatumBuffer(isamindex.getBuffer(hold),schema);
Datum[] temp1=key.createKey(readbuff1.read(max));
DatumBuffer readbuff2=new DatumBuffer(isamindex.getBuffer(count),schema);
Datum[] temp2=key.createKey(readbuff2.read(0));
if(skip>1){
max=isamindex.getBuffer(count-1).getInt(10);
readbuff1=new DatumBuffer(isamindex.getBuffer(count-1),schema);
temp1=key.createKey(readbuff1.read(max));
}
if(Datum.compareRows(temp1, temp2)==0){
//System.out.println("page on hold: "+hold);
isamindex.getBuffer(hold).putInt(20, 1);
isamindex.dirty(hold);
if((isamindex.getBuffer(count).getInt(5)==1)){
boolhold=true;
}
//System.out.println("skipping page: "+count);
isamindex.getBuffer(count).putInt(25, 1);
isamindex.getBuffer(count).putInt(30, 1);
isamindex.getBuffer(count-1).putInt(30, 0);
isamindex.dirty(count);
isamindex.getBuffer(hold+skip-1).putInt(0, count);
isamindex.dirty(count);
isamindex.dirty(count-1);
isamindex.dirty(hold+skip-1);
skip++;
continue;
}
else{
if(skip>1){
max=isamindex.getBuffer(count-1).getInt(10);
readbuff1=new DatumBuffer(isamindex.getBuffer(count-1),schema);
temp1=key.createKey(readbuff1.read(max));
}
Datum[] mean=new Datum[keyschema.length];
for(int i=0;i<keyschema.length;i++){
mean[i]=new Datum.Flt((float)(temp1[i].toInt()+temp2[i].toInt())/2);
}
//System.out.println("mean"+Datum.stringOfRow(mean));
//System.out.println("space free= "+isam.remaining());
if(keyschema.length*4+20<=isam.remaining()){
if(isam.getNumRows()==0){
isamindex.safeGetBuffer(indxptr).putInt(20,hold);
}
isamindex.getBuffer(indxptr).putInt(0, 1);
isamindex.getBuffer(indxptr).putInt(5, 1);
//System.out.println("writing index on page: "+indxptr);
isam.createPointer(hold);
isam.putKey(mean);
isamindex.dirty(indxptr);
}
else{
isam.createPointer(hold);
if(skip>1){
isamindex.safeGetBuffer(indxptr).putInt(25,count-1);
}
else{
isamindex.safeGetBuffer(indxptr).putInt(25,hold);
}
//isam.showPage();
isamindex.getBuffer(indxptr).putInt(0, 0);
isamindex.dirty(indxptr);
indxptr++;
isam=new ISAMDatum(isamindex.safeGetBuffer(indxptr),keyschema);
isam.initialize(40);
//System.out.println("created idx page: "+indxptr);
isamindex.getBuffer(indxptr).putInt(0, 1);
isamindex.getBuffer(indxptr).putInt(5, 1);
isamindex.dirty(indxptr);
}
skip=1;
hold=count;
//System.out.println("next page: "+hold);
}}
else{
isam.createPointer(hold);
isamindex.safeGetBuffer(indxptr).putInt(25,to-2);
last=true;
}
//System.out.println("hold: "+hold+"count: "+count);
}
//isam.showPage();
int from=indxptr;
int breadth=from-to+1;
int level=2;
//System.out.println("before layering up index: "+"to: "+to+" from: "+from);
while(breadth!=1){
isam=new ISAMDatum(isamindex.getBuffer(to),keyschema);
ISAMDatum newisam=new ISAMDatum(isamindex.safeGetBuffer(from+1),keyschema);
newisam.initialize(40);
isamindex.safeGetBuffer(from+1).putInt(20, isamindex.safeGetBuffer(to).getInt(20));
for(int i=0;i<breadth;i++){
//System.out.println("index flag at 0: "+isamindex.getBuffer(to).getInt(0)
//+" for page: "+to);
if(isamindex.getBuffer(to).getInt(0) !=1){
Datum[] max=new Datum[keyschema.length];
int page1=isamindex.getBuffer(to).getInt(25);
DatumBuffer bufmax=new DatumBuffer(isamindex.getBuffer(page1),keyschema);
max=bufmax.read(isamindex.getBuffer(page1).getInt(10));
isam=new ISAMDatum(isamindex.getBuffer(to+1),keyschema);
Datum[] min=new Datum[keyschema.length];
int page2=isamindex.getBuffer(to+1).getInt(20);
DatumBuffer bufmin=new DatumBuffer(isamindex.getBuffer(page2),keyschema);
min=bufmin.read(0);
Datum[] mean=new Datum[keyschema.length];
for(int l=0;l<keyschema.length;l++){
mean[l]=new Datum.Flt((max[l].toFloat()+min[l].toFloat())/2);
}
if(keyschema.length*4+20<=newisam.remaining()){
if(newisam.getNumRows()==0){
isamindex.safeGetBuffer(from+1).putInt(20, isamindex.safeGetBuffer(to).getInt(20));
}
isamindex.getBuffer(from+1).putInt(0, 1);
isamindex.getBuffer(from+1).putInt(5, level);
//System.out.println("writing index on page: "+(from+1)+" for index at: "+to);
newisam.createPointer(to);
newisam.putKey(mean);
isamindex.dirty(from+1);
to++;
}
else{
//System.out.println("writing last ptr on page: "+(from+1)+" for index at: "+to);
newisam.createPointer(to);
isamindex.safeGetBuffer(from+1).putInt(25, isamindex.safeGetBuffer(to).getInt(25));
//newisam.showPage();
isamindex.getBuffer(from+1).putInt(0, 0);
isamindex.dirty(from+1);
from++;
to++;
newisam=new ISAMDatum(isamindex.safeGetBuffer(from+1),keyschema);
newisam.initialize(40);
//System.out.println("created idx page: "+(from+1));
isamindex.getBuffer(from+1).putInt(0, 1);
isamindex.getBuffer(from+1).putInt(5, level);
isamindex.dirty(from+1);
}
}
else{
//System.out.println("writing closing ptr at: "+(from+1)+" for index at: "+to);
newisam.createPointer(to);
isamindex.safeGetBuffer(from+1).putInt(25, isamindex.safeGetBuffer(to).getInt(25));
isamindex.dirty(from+1);
isamindex.dirty(to);
to++;
}
}
level++;
from++;
//System.out.println("to: "+to+" from: "+from+" for level"+(level-1));
breadth=from-to+1;
//System.out.println("breadth: "+breadth);
//newisam.showPage();
}
isamindex.getBuffer(0).putInt(35, from);
isamindex.dirty(0);
ISAMDatum whatever=new ISAMDatum(isamindex.getBuffer(from),keyschema);
//whatever.showPage();
System.out.println("index created successfuly!! ");
fm.close(path);
return null;
}
public IndexIterator scan()
throws SqlException, IOException
{
int endpage=file.getBuffer(0).getInt(15)-2;
int endrow=file.getBuffer(endpage).getInt(10);
//System.out.println("endpage: "+endpage+" endrow: "+endrow);
Iter iter=new Iter(file,0,0,endpage,endrow,schema);
return iter;
}
public IndexIterator rangeScanTo(Datum[] toKey)
throws SqlException, IOException
{
int[] pageandnum=getPageNum(toKey);
int endpage=pageandnum[0];
int endnum=pageandnum[1];
int endrow=endnum;
int page=endpage;
if(pageandnum[2]==1){
if(endrow!=0){
endrow=endrow-1;
}
else{
page--;
endrow=file.getBuffer(page).getInt(10);
}
}
else{
while(true){
if(endpage==file.getBuffer(0).getInt(15)-2){
if(endnum==file.getBuffer(endpage).getInt(10)){
break;
}
else{
endnum++;
}
}
else{
if(endnum==file.getBuffer(endpage).getInt(10)){
endpage++;
endnum=0;
}
else{
endnum++;
}
}
DatumBuffer datfind=new DatumBuffer(file.getBuffer(endpage),schema);
if(toKey[0].compareTo(datfind.read(endnum)[iidx])!=0){
break;
}
else{
endrow=endnum;
page=endpage;
}
}
}
// DatumBuffer fff=new DatumBuffer(file.getBuffer(167),keyspec.keySchema());
// System.out.println("test dat/////////"+Datum.stringOfRow(fff.read(23)));
Iter iter=new Iter(file,0,0,page,endrow,schema);
return iter;
}
public IndexIterator rangeScanFrom(Datum[] fromKey)
throws SqlException, IOException
{
int[] pageandnum=getPageNum(fromKey);
int pagenum=pageandnum[0];
int row=pageandnum[1];
int endpage=file.getBuffer(0).getInt(15)-2;
int endrow=file.getBuffer(endpage).getInt(10);
int startrow=row;
int startpage=pagenum;
if(row==-1){
}
else{
while(true){
if(pagenum==0){
if(row==0){
break;
}
else{
row--;
}
}
else{
if(row==0){
pagenum--;
row=file.getBuffer(pagenum).getInt(10);
}
else{
row--;
}
}
DatumBuffer datfind=new DatumBuffer(file.getBuffer(pagenum),schema);
if(fromKey[0].compareTo(datfind.read(row)[iidx])!=0){
break;
}
else{
startrow=row;
startpage=pagenum;
}
}
}
// new code ends here
Iter iter=new Iter(file,startpage,startrow,endpage,endrow,schema);
return iter;
}
public IndexIterator rangeScan(Datum[] start, Datum[] end)
throws SqlException, IOException
{
int[] pageandnum=getPageNum(start);
int pagenum=pageandnum[0];
int row=pageandnum[1];
int startrow=row;
int startpage=pagenum;
if(row==-1){
}
else{
while(true){
if(pagenum==0){
if(row==0){
break;
}
else{
row--;
}
}
else{
if(row==0){
pagenum--;
row=file.getBuffer(pagenum).getInt(10);
}
else{
row--;
}
}
DatumBuffer datfind=new DatumBuffer(file.getBuffer(pagenum),schema);
if(start[0].compareTo(datfind.read(row)[iidx])!=0){
break;
}
else{
startrow=row;
startpage=pagenum;
}
}
}
int[] pageandnum1=getPageNum(end);
int endpage=pageandnum1[0];
int endnum=pageandnum1[1];
int endrow=endnum;
int page=endpage;
if(pageandnum1[2]==1){
if(endrow!=0){
endrow=endrow-1;
}
else{
page--;
endrow=file.getBuffer(page).getInt(10);
}
}
else{
while(true){
if(endpage==file.getBuffer(0).getInt(15)-2){
if(endnum==file.getBuffer(endpage).getInt(10)){
break;
}
else{
endnum++;
}
}
else{
if(endnum==file.getBuffer(endpage).getInt(10)){
endpage++;
endnum=0;
}
else{
endnum++;
}
}
DatumBuffer datfind=new DatumBuffer(file.getBuffer(endpage),schema);
if(end[0].compareTo(datfind.read(endnum)[iidx])!=0){
break;
}
else{
endrow=endnum;
page=endpage;
}
}
}
Iter iter =new Iter(file,startpage,startrow,page,endrow,schema);
return iter;
}
public Datum[] get(Datum[] key)
throws SqlException, IOException
{
int page=getPage(key);
//System.out.println("found page: "+page);
Datum[] ret=null;
DatumBuffer find=new DatumBuffer(file.getBuffer(page),schema);
DatumBuffer find1=new DatumBuffer(file.getBuffer(page),schema);
//System.out.println(file.getBuffer(page).getInt(10)+" = high");
int found=find(file.getBuffer(page),key,file.getBuffer(page).getInt(10),0);
//System.out.println("found: "+found);
//System.out.println("skip flag on page: "+page+" is "+file.getBuffer(page).getInt(20));
if(found!=-1&&key[0].compareTo(find.read(found)[iidx])==0){
ret=find1.read(found);
}
else{
if(file.getBuffer(page).getInt(20)==0){
ret=null;
}
else{
//System.out.println("last flag on page: "+page+" is "+file.getBuffer(page).getInt(30));
while(file.getBuffer(page).getInt(30)!=1){
page=file.getBuffer(page).getInt(0);
//System.out.println("finding for page: "+page);
find=new DatumBuffer(file.getBuffer(page),schema);
find1=new DatumBuffer(file.getBuffer(page),schema);
found=find(file.getBuffer(page),key,file.getBuffer(page).getInt(10),0);
if(found!=-1&&key[0].compareTo(find.read(found)[iidx])==0){
ret=find1.read(found);
break;
}
}
}
}
return ret;
}
private int getPage(Datum[] key) throws BufferException, IOException, CastError{
Datum[] temp=new Datum[key.length];
for(int i=0;i<key.length;i++){
temp[i]=new Datum.Flt((float)key[i].toInt());
}
key=temp;
int root=file.getBuffer(0).getInt(35);
//System.out.println("root: "+root);
int numpages=file.getBuffer(0).getInt(15) - 1;
//System.out.println("number of data pages: "+numpages+" fileSize = "+file.size());
int page=-1;
int level=file.getBuffer(root).getInt(5);
//System.out.println(level);
ByteBuffer buff=file.getBuffer(root);
ISAMDatum isam=new ISAMDatum(buff,keyschema);
/*DatumBuffer d=new DatumBuffer(file.getBuffer(430),keyspec.keySchema());
for(int i=0;i<22;i++){
Datum[] a=d.read(i);
System.out.println("choose keys from: "+Datum.Int.stringOfRow(a));}*/
for(int i=0;i<level;i++){
isam=new ISAMDatum(file.getBuffer(root),keyschema);
//isam.showPage();
root=isam.pointer(key);
}
/*isam=new ISAMDatum(file.getBuffer(4548),keyspec.keySchema());
isam.showPage();*/
page=root;
return page;
}
protected int find(ByteBuffer dat,Datum[] key,int high,int low){
DatumBuffer datbuff=new DatumBuffer(dat,schema);
int mid=(high+low)/2;
if(high-low==1||high-low==0){
//System.out.println("high: "+high+" low: "+low);
System.out.println();
if(key[0].compareTo(datbuff.read(low)[iidx])==0){
return low;
}
else if(key[0].compareTo(datbuff.read(high)[iidx])==0){
return high;
}
else{
return -1;
}
}
else if(key[0].compareTo(datbuff.read(mid)[iidx])==0){
//System.out.println(mid);
return mid;
}
else if(key[0].compareTo(datbuff.read(mid)[iidx])==1){
//System.out.println(mid);
low=mid+1;
return find(dat,key,high,low);
}
else{
//System.out.println(mid);
high=mid-1;
return find(dat,key,high,low);
}
}
private int[] getPageNum(Datum[] key) throws BufferException, IOException, CastError{
int[] toRet=new int[3];
toRet[2]=0;
int page=getPage(key);
//System.out.println("@ getpagenum found page: "+page);
Datum[] ret=null;
DatumBuffer find=new DatumBuffer(file.getBuffer(page),schema);
DatumBuffer find1=new DatumBuffer(file.getBuffer(page),schema);
//System.out.println(file.getBuffer(page).getInt(10)+" = high");
int found=find(file.getBuffer(page),key,file.getBuffer(page).getInt(10),0);
//System.out.println("@ getpagenum found: "+found);
if(found==-1){
if(file.getBuffer(page).getInt(20)==0){
found=-1;
//page=-1;
}
else{
//System.out.println("last flag on page: "+page+" is "+file.getBuffer(page).getInt(30));
while(file.getBuffer(page).getInt(30)!=1){
page=file.getBuffer(page).getInt(0);
//System.out.println("finding for page: "+page);
find=new DatumBuffer(file.getBuffer(page),schema);
find1=new DatumBuffer(file.getBuffer(page),schema);
found=find(file.getBuffer(page),key,file.getBuffer(page).getInt(10),0);
if(key[0].compareTo(find.read(found)[iidx])==0){
ret=find1.read(found);
break;
}
}
}
}
if(found==-1){
int i=0;
page=getPage(key);
toRet[2]=1;
while(true){
DatumBuffer datbuff=new DatumBuffer(file.getBuffer(page),schema);
if(datbuff.read(i)[iidx].compareTo(key[0])>0){
toRet[0]=page;
toRet[1]=i;
return toRet;
}
else{
if(page==file.getBuffer(0).getInt(15)-2){
if(i!=file.getBuffer(page).getInt(10)){
i++;
}
else{
toRet[0]=page;
toRet[1]=i;
return toRet;
}
}
else{
if(i!=file.getBuffer(page).getInt(10)){
i++;
}
else{
page++;
i=0;
}
}
}
}
}
//System.out.println("test "+(find.read(found)==0));
//System.out.println("skip flag on page: "+page+" is "+file.getBuffer(page).getInt(20));
//System.out.println("found page: "+page);
//System.out.println("found row: "+found);
toRet[0]=page;
toRet[1]=found;
return toRet;
}
public ISAMIndex create(FileManager fm,
File path,
Iterator<Datum[]> dataSource,
int[] callkey
//IndexKeySpec key
)
throws Exception
{
this.iidx=callkey[0];
System.out.println("please wait while index is being created!!");
int rows=0;
ManagedFile isamindex=fm.open(path);
isamindex.resize(1);
int tempptr=0;
DatumBuffer datbuff=new DatumBuffer(isamindex.getBuffer(0),schema);
datbuff.initialize(40);
File datfile=new File("data.txt");
FileWriter fw = new FileWriter(datfile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while(dataSource.hasNext()){
Datum[] temp=dataSource.next();
int size=0;
for(int i=0;i<temp.length;i++){
if(temp[i].getType()==Schema.Type.INT||temp[i].getType()==Schema.Type.FLOAT||temp[i].getType()==Schema.Type.DATE){
size += 4;
}
else{
String s=((Datum.Str)temp[i]).toString();
s=s.substring(1,s.length()-1);
size += s.getBytes().length+4;
temp[i]=new Datum.Str(s);
}
}
if(new DatumBuffer(isamindex.getBuffer(tempptr),schema).remaining()-8>size){
//System.out.println("writing on page: "+tempptr);
datbuff=new DatumBuffer(isamindex.getBuffer(tempptr),schema);
int idx=datbuff.write(temp);
bw.write(Datum.stringOfRow(temp));bw.write(Integer.toString(tempptr));
bw.newLine();
rows++;
isamindex.getBuffer(tempptr).putInt(5, 1);
isamindex.getBuffer(tempptr).putInt(25, 0);
isamindex.getBuffer(tempptr).putInt(0, -1);
isamindex.getBuffer(tempptr).putInt(10, idx);
isamindex.dirty(tempptr);
}
else{
isamindex.getBuffer(tempptr).putInt(5, 0);
isamindex.getBuffer(tempptr).putInt(0, -1);
isamindex.dirty(tempptr);
tempptr++;
//System.out.println("writing on new page: "+tempptr);
DatumBuffer dat=new DatumBuffer(isamindex.safeGetBuffer(tempptr),schema);
dat.initialize(40);
int idx=dat.write(temp);
bw.write(Datum.stringOfRow(temp));bw.write(Integer.toString(tempptr));
bw.newLine();
rows++;
isamindex.getBuffer(tempptr).putInt(5, 1);
isamindex.getBuffer(tempptr).putInt(25, 0);
isamindex.getBuffer(tempptr).putInt(10, idx);
isamindex.dirty(tempptr);
}
}
bw.close();
//System.out.println("Done Writting pages. no. of pages written = "+(tempptr+1));
//System.out.println("total rows written: "+rows);
int indxptr=tempptr+2;
int to=indxptr;
isamindex.getBuffer(0).putInt(15, indxptr);
isamindex.dirty(0);
ISAMDatum isam=new ISAMDatum(isamindex.safeGetBuffer(indxptr),keyschema);
isam.initialize(40);
isamindex.safeGetBuffer(indxptr).putInt(20, 0);
int count=0;
boolean last=false;
boolean boolhold=false;
int hold=count;
count++;
int skip=1;
while(last==false){
//System.out.println("flag of page: "+isamindex.getBuffer(count).getInt(5));
if((isamindex.getBuffer(hold).getInt(5)!=1)&&(boolhold==false)){
//System.out.println("inside while if for page: "+hold);
count=hold+skip;
int max=isamindex.getBuffer(hold).getInt(10);
DatumBuffer readbuff1=new DatumBuffer(isamindex.getBuffer(hold),schema);
Datum[] temp1=new Datum[callkey.length];
Datum[] darray=readbuff1.read(max);
for(int z=0;z<callkey.length;z++){
temp1[z]= darray[callkey[z]];
}
DatumBuffer readbuff2=new DatumBuffer(isamindex.getBuffer(count),schema);
Datum[] temp2=new Datum[callkey.length];
Datum[] darray2=readbuff2.read(0);
for(int z=0;z<callkey.length;z++){
temp2[z]= darray2[callkey[z]];
}
if(skip>1){
max=isamindex.getBuffer(count-1).getInt(10);
readbuff1=new DatumBuffer(isamindex.getBuffer(count-1),schema);
darray=readbuff1.read(max);
for(int z=0;z<callkey.length;z++){
temp1[z]= darray[callkey[z]];
}
}
if(Datum.compareRows(temp1, temp2)==0){
//System.out.println("page on hold: "+hold);
isamindex.getBuffer(hold).putInt(20, 1);
isamindex.dirty(hold);
if((isamindex.getBuffer(count).getInt(5)==1)){
boolhold=true;
}
//System.out.println("skipping page: "+count);
isamindex.getBuffer(count).putInt(25, 1);
isamindex.getBuffer(count).putInt(30, 1);
isamindex.getBuffer(count-1).putInt(30, 0);
isamindex.dirty(count);
isamindex.getBuffer(hold+skip-1).putInt(0, count);
isamindex.dirty(count);
isamindex.dirty(count-1);
isamindex.dirty(hold+skip-1);
skip++;
continue;
}
else{
if(skip>1){
max=isamindex.getBuffer(count-1).getInt(10);
readbuff1=new DatumBuffer(isamindex.getBuffer(count-1),schema);
darray=readbuff1.read(max);
for(int z=0;z<callkey.length;z++){
temp1[z]= darray[callkey[z]];
}
}
Datum[] mean=new Datum[keyschema.length];
for(int i=0;i<keyschema.length;i++){
mean[i]=new Datum.Flt((float)(temp1[i].toInt()+temp2[i].toInt())/2);
}
//System.out.println("mean"+Datum.stringOfRow(mean));
//System.out.println("space free= "+isam.remaining());
if(keyschema.length*4+20<=isam.remaining()){
if(isam.getNumRows()==0){
isamindex.safeGetBuffer(indxptr).putInt(20,hold);
}
isamindex.getBuffer(indxptr).putInt(0, 1);
isamindex.getBuffer(indxptr).putInt(5, 1);
//System.out.println("writing index on page: "+indxptr);
isam.createPointer(hold);
isam.putKey(mean);
isamindex.dirty(indxptr);
}
else{
isam.createPointer(hold);
if(skip>1){
isamindex.safeGetBuffer(indxptr).putInt(25,count-1);
}
else{
isamindex.safeGetBuffer(indxptr).putInt(25,hold);
}
//isam.showPage();
isamindex.getBuffer(indxptr).putInt(0, 0);
isamindex.dirty(indxptr);
indxptr++;
isam=new ISAMDatum(isamindex.safeGetBuffer(indxptr),keyschema);
isam.initialize(40);
//System.out.println("created idx page: "+indxptr);
isamindex.getBuffer(indxptr).putInt(0, 1);
isamindex.getBuffer(indxptr).putInt(5, 1);
isamindex.dirty(indxptr);
}
skip=1;
hold=count;
//System.out.println("next page: "+hold);
}}
else{
isam.createPointer(hold);
isamindex.safeGetBuffer(indxptr).putInt(25,to-2);
last=true;
}
//System.out.println("hold: "+hold+"count: "+count);
}
//isam.showPage();
int from=indxptr;
int breadth=from-to+1;
int level=2;
//System.out.println("before layering up index: "+"to: "+to+" from: "+from);
while(breadth!=1){
isam=new ISAMDatum(isamindex.getBuffer(to),keyschema);
ISAMDatum newisam=new ISAMDatum(isamindex.safeGetBuffer(from+1),keyschema);
newisam.initialize(40);
isamindex.safeGetBuffer(from+1).putInt(20, isamindex.safeGetBuffer(to).getInt(20));
for(int i=0;i<breadth;i++){
//System.out.println("index flag at 0: "+isamindex.getBuffer(to).getInt(0)
//+" for page: "+to);
if(isamindex.getBuffer(to).getInt(0) !=1){
Datum[] max=new Datum[keyschema.length];
int page1=isamindex.getBuffer(to).getInt(25);
DatumBuffer bufmax=new DatumBuffer(isamindex.getBuffer(page1),schema);
max[0]=bufmax.read(isamindex.getBuffer(page1).getInt(10))[iidx];
isam=new ISAMDatum(isamindex.getBuffer(to+1),keyschema);
Datum[] min=new Datum[keyschema.length];
int page2=isamindex.getBuffer(to+1).getInt(20);
DatumBuffer bufmin=new DatumBuffer(isamindex.getBuffer(page2),schema);
min[0]=bufmin.read(0)[iidx];
Datum[] mean=new Datum[keyschema.length];
for(int l=0;l<keyschema.length;l++){
mean[l]=new Datum.Flt((max[l].toFloat()+min[l].toFloat())/2);
}
if(keyschema.length*4+20<=newisam.remaining()){
if(newisam.getNumRows()==0){
isamindex.safeGetBuffer(from+1).putInt(20, isamindex.safeGetBuffer(to).getInt(20));
}
isamindex.getBuffer(from+1).putInt(0, 1);
isamindex.getBuffer(from+1).putInt(5, level);
//System.out.println("writing index on page: "+(from+1)+" for index at: "+to);
newisam.createPointer(to);
newisam.putKey(mean);
isamindex.dirty(from+1);
to++;
}
else{
//System.out.println("writing last ptr on page: "+(from+1)+" for index at: "+to);
newisam.createPointer(to);
isamindex.safeGetBuffer(from+1).putInt(25, isamindex.safeGetBuffer(to).getInt(25));
//newisam.showPage();
isamindex.getBuffer(from+1).putInt(0, 0);
isamindex.dirty(from+1);
from++;
to++;
newisam=new ISAMDatum(isamindex.safeGetBuffer(from+1),keyschema);
newisam.initialize(40);
//System.out.println("created idx page: "+(from+1));
isamindex.getBuffer(from+1).putInt(0, 1);
isamindex.getBuffer(from+1).putInt(5, level);
isamindex.dirty(from+1);
}
}
else{
//System.out.println("writing closing ptr at: "+(from+1)+" for index at: "+to);
newisam.createPointer(to);
isamindex.safeGetBuffer(from+1).putInt(25, isamindex.safeGetBuffer(to).getInt(25));
isamindex.dirty(from+1);
isamindex.dirty(to);
to++;
}
}
level++;
from++;
//System.out.println("to: "+to+" from: "+from+" for level"+(level-1));
breadth=from-to+1;
//System.out.println("breadth: "+breadth);
//newisam.showPage();
}
isamindex.getBuffer(0).putInt(35, from);
isamindex.dirty(0);
ISAMDatum whatever=new ISAMDatum(isamindex.getBuffer(from),keyschema);
//whatever.showPage();
System.out.println("index created successfuly!! ");
fm.close(path);
return null;
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
@Override
public Object next() {
// TODO Auto-generated method stub
return null;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
|
package offer;
import java.awt.*;
import java.security.cert.PolicyNode;
import java.util.ArrayList;
import java.util.Arrays;
public class 矩阵中的路径 {
public static void main(String[] args) {
String str1 = "ABCEHJIGSFCSLOPQADEEMNOEADIDEJFMVCEIFGGS";
String str2 = "SLHECCEIDEJFGGFIE";
char[] matrix = str1.toCharArray();
char[] str = str2.toCharArray();
System.out.println(hasPath(matrix,5,8,str)); // false
}
static boolean q = false;
public static boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if(matrix==null || matrix.length < str.length) return false;
// 重构matrix,并且新建一个visited的矩阵
char[][] chs = new char[rows][cols];
boolean[][] visited = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
chs[i][j] = matrix[i*cols+j];
}
}
ArrayList<Character> tracks=new ArrayList<Character>();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if(chs[i][j] == str[0]){ // 起始点比较,helper是从起始点开始的上下左右
// chs-整个矩阵,visited,i,j-以i,j开头,tracks-走过的路径,str-想要的路径
tracks.add(str[0]);visited[i][j] = true;
helper(chs, cols, rows, visited, i, j, tracks, str);
tracks.remove(tracks.size()-1); //【可以出现两个开头的是符合要求的,不行的需要从tracks中去除】
visited[i][j] = false;
if(q) return true;
}
}
}
return false;
}
private static void helper(char[][] chs,int cols,int rows, boolean[][] visited, int i, int j, ArrayList<Character> tracks, char[] str) {
// 结束条件
if(q){
return;
}
if(tracks.size() == str.length){
q = true;return;
}
if(i==rows && j == cols){
return;
}
// 上下左右四个方向的坐标
ArrayList<Point> ls=new ArrayList<>();
ls.add(new Point(i,j-1)); // 左
ls.add(new Point(i,j+1)); // 右
ls.add(new Point(i-1,j)); // 上
ls.add(new Point(i+1,j)); // 下
int len = ls.size();
for (int k = 0; k < len; k++) {
Point p = ls.get(k);
// Point p = ls.remove(0);
if(p.x < 0 || p.x >= rows) continue;
if(p.y < 0 || p.y >= cols) continue;
if(visited[p.x][p.y]) continue;
if(chs[p.x][p.y] != str[tracks.size()])
continue;
tracks.add(chs[p.x][p.y]);
visited[p.x][p.y] = true;
helper(chs, cols, rows, visited, p.x, p.y, tracks, str);
tracks.remove(tracks.size()-1);
visited[p.x][p.y] = false;
}
}
}
|
package com.qunchuang.carmall.auth.phone;
import com.qunchuang.carmall.domain.Customer;
import com.qunchuang.carmall.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 处理用户信息
*
* @author Curtain
* @date 2018/11/8:35
*/
@Component
public class PhoneUserInfo {
@Autowired
private CustomerService customerService;
public Customer getCustomer(Map<String, String> data) {
boolean phone = customerService.existsByPhone(data.get("phone"));
if (phone) {
//已注册直接返回
return customerService.findByPhone(data.get("phone"));
} else {
Customer customer = new Customer();
customer.setPhone(data.get("phone"));
customer.setInvitedId(data.get("invitedId"));
return customerService.register(customer);
}
}
}
|
package org.fuserleer.ledger.atoms;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.fuserleer.Universe;
import org.fuserleer.crypto.Identity;
import org.fuserleer.crypto.Hash;
import org.fuserleer.exceptions.ValidationException;
import org.fuserleer.ledger.SearchResult;
import org.fuserleer.ledger.ShardMapper;
import org.fuserleer.ledger.StateAddress;
import org.fuserleer.ledger.StateMachine;
import org.fuserleer.ledger.StateOp;
import org.fuserleer.ledger.StateSearchQuery;
import org.fuserleer.ledger.StateOp.Instruction;
import org.fuserleer.serialization.DsonOutput;
import org.fuserleer.serialization.SerializerId2;
import org.fuserleer.utils.UInt256;
import org.fuserleer.serialization.DsonOutput.Output;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
@SerializerId2("ledger.particle.token.transfer")
public final class TokenParticle extends SignedParticle
{
public enum Action
{
MINT, TRANSFER, BURN;
@JsonValue
@Override
public String toString()
{
return this.name();
}
}
@JsonProperty("action")
@DsonOutput(Output.ALL)
private Action action;
@JsonProperty("quantity")
@DsonOutput(Output.ALL)
private UInt256 quantity;
@JsonProperty("token")
@DsonOutput(Output.ALL)
private Hash token;
TokenParticle()
{
super();
}
public TokenParticle(UInt256 quantity, Hash token, Action action, Spin spin, Identity owner)
{
super(spin, owner);
this.action = Objects.requireNonNull(action);
this.quantity = Objects.requireNonNull(quantity);
this.token = Objects.requireNonNull(token);
}
@Override
public boolean requiresSignature()
{
if (getSpin().equals(Spin.DOWN) == true || action.equals(Action.MINT) == true)
return true;
else
return false;
}
public Action getAction()
{
return this.action;
}
public UInt256 getQuantity()
{
return this.quantity;
}
public Hash getToken()
{
return this.token;
}
@Override
public void prepare(StateMachine stateMachine) throws ValidationException, IOException
{
if (this.action == null)
throw new ValidationException("Action is null");
if (this.action.equals(Action.MINT) == true && getSpin().equals(Spin.DOWN) == true)
throw new ValidationException("Action is MINT but spin is DOWN");
if (this.token == null)
throw new ValidationException("Token is null");
if (this.quantity == null)
throw new ValidationException("Quantity is null");
if (this.quantity.compareTo(UInt256.ZERO) == 0)
throw new ValidationException("Quantity is zero");
if (this.quantity.compareTo(UInt256.ZERO) < 0)
throw new ValidationException("Quantity is negative");
stateMachine.sop(new StateOp(new StateAddress(Particle.class, Spin.spin(this.token, Spin.UP)), Instruction.EXISTS), this);
stateMachine.sop(new StateOp(new StateAddress(Particle.class, Spin.spin(this.token, Spin.DOWN)), Instruction.NOT_EXISTS), this);
}
@Override
public void execute(StateMachine stateMachine) throws ValidationException, IOException
{
Hash token = stateMachine.get("token");
if (stateMachine.get("token") == null)
{
stateMachine.set("token", this.token);
token = this.token;
}
// Check all transfers within this state machine as using the same token
if (token != null && token.equals(this.token) == false)
throw new ValidationException("Transfer is not multi-token, expected token "+token+" but discovered "+this.token);
// Check that "out" quantity does not exceed "in" quantity
UInt256 spendable = stateMachine.get("spendable");
UInt256 spent = stateMachine.get("spent");
// FIXME take these out to produce an NPE that isn't caught correct / nor fails the unit test
if (spendable == null)
spendable = UInt256.ZERO;
if (spent == null)
spent = UInt256.ZERO;
if (this.action.equals(Action.TRANSFER) == true)
{
if (getSpin().equals(Spin.DOWN) == true)
spendable = spendable.add(this.quantity);
else
spent = spent.add(this.quantity);
}
else if (this.action.equals(Action.MINT) == true)
{
spendable = spendable.add(this.quantity);
// Check if token spec is embedded in atom
TokenSpecification tokenSpec = stateMachine.getPendingAtom().getAtom().getParticle(token);
if (tokenSpec == null)
{
// Not a packed TOKEN/MINT atom ... look for the token if local shard group is responsible for it
StateAddress tokenSpecStateAddress = new StateAddress(Particle.class, token);
long numShardGroups = stateMachine.getContext().getLedger().numShardGroups();
long localShardGroup = ShardMapper.toShardGroup(stateMachine.getContext().getNode().getIdentity(), numShardGroups);
long tokenSpecShardGroup = ShardMapper.toShardGroup(tokenSpecStateAddress.get(), numShardGroups);
// Search ... if not found or invalid, localShardGroup will respond with REJECT failing the MINT action
if (localShardGroup == tokenSpecShardGroup)
{
// TODO find a more efficient way to do this as it will block ... multi-thread and do in the prepare?
// TODO not ideal to have dependencies searches when executing ... temporary
Future<SearchResult> tokenSearchFuture = stateMachine.getContext().getLedger().get(new StateSearchQuery(new StateAddress(Particle.class, token), TokenSpecification.class));
SearchResult tokenSearchResult;
try
{
tokenSearchResult = tokenSearchFuture.get(10, TimeUnit.SECONDS);
}
catch (Exception ex)
{
throw new ValidationException("Search of token specification for mint of "+getQuantity()+" "+getToken()+" failed", ex);
}
if (tokenSearchResult == null || tokenSearchResult.getPrimitive() == null)
throw new ValidationException("Token specification for mint of "+getQuantity()+" "+getToken()+" not found");
tokenSpec = tokenSearchResult.getPrimitive();
}
}
if (tokenSpec != null && tokenSpec.getOwner().equals(getOwner()) == false)
throw new ValidationException("Token specification for mint of "+getQuantity()+" "+getToken()+" is not owned by "+getOwner());
}
else if (this.action.equals(Action.BURN) == true)
{
throw new UnsupportedOperationException("BURN token actions not yet supported");
}
if (Universe.getDefault().getGenesis().contains(this.getHash()) == false && spent.compareTo(spendable) > 0)
throw new ValidationException("Transfer is invalid, over spending available token "+getToken()+" by "+spent.subtract(spendable));
stateMachine.set("spendable", spendable);
stateMachine.set("spent", spent);
stateMachine.associate(getOwner().asHash(), this);
}
@Override
public boolean isConsumable()
{
return true;
}
}
|
package leet;
import edu.princeton.cs.algs4.In;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* Created by kreddy on 2/10/18.
*/
public class ReachingPoint {
public static boolean reachingPoints(int sx, int sy, int tx, int ty) {
return reachingPoints(sx, sy, tx, ty, new HashMap<>());
}
public static boolean reachingPoints(int sx, int sy, int tx, int ty, Map<String, Boolean> notReachable) {
if (sx == tx && sy == ty)
return true;
if (sx > tx || sy > ty)
return false;
if(notReachable.get(sx + "-" + sy) != null && notReachable.get(sx + "-" + sy))
return false;
if (reachingPoints(sx + sy, sy, tx, ty))
return true;
notReachable.put(sx + sy + "-" + sy, true);
if(reachingPoints(sx, sx + sy, tx, ty))
return true;
notReachable.put(sx + "-" + (sx + sy), true);
return false;
}
public static boolean reachingPointsNew(int sx, int sy, int tx, int ty) {
if (sx == tx && sy == ty)
return true;
if (sx > tx || sy > ty)
return false;
LinkedList<Integer> xQueue = new LinkedList<>();
LinkedList<Integer> yQueue = new LinkedList<>();
xQueue.add(sx);
yQueue.add(sy);
Integer qx = null;
Integer qy = null;
while (!xQueue.isEmpty()) {
qx = xQueue.removeFirst();
qy = yQueue.removeFirst();
if (qx == tx && qy == ty)
return true;
if (qx > tx || qy > ty)
continue;
xQueue.addLast(qx + qy);
yQueue.addLast(qy);
xQueue.addLast(qx);
yQueue.addLast(qx + qy);
}
return false;
}
public static void main(String[] args) {
System.out.println(reachingPointsNew(1, 1, 1, 1));
System.out.println(reachingPointsNew(1, 1, 2, 2));
System.out.println(reachingPointsNew(1, 1, 3, 5));
System.out.println(reachingPointsNew(35, 13, 455955547, 420098884));
}
}
|
package com.paisheng.instagme.common.pic;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.github.chrisbanes.photoview.PhotoView;
import com.paisheng.instagme.R;
import com.paisheng.instagme.common.arouter.PicExplorerRouterConstant;
import com.paisheng.instagme.utils.AnimationHelper;
import com.paisheng.lib.picture.loader.Monet;
/**
* @author: yuanbaining
* @Filename: PicExplorerActivity
* @Description:
* @Copyright: Copyright (c) 2017 Tuandai Inc. All rights reserved.
* @date: 2018/2/1 9:32
*/
@Route(path = PicExplorerRouterConstant.PIC_EXPLORER_PAGE)
public class PicExplorerActivity extends AppCompatActivity
implements View.OnClickListener, View.OnLongClickListener {
public static final String PICT_URL = "pict_url";
private PhotoView mPhotoView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picexplorer);
overridePendingTransition(R.anim.pic_in, android.R.anim.fade_out);
findViewById(R.id.root).setOnClickListener(this);
mPhotoView = (PhotoView) findViewById(R.id.photo_view);
mPhotoView.setOnClickListener(this);
mPhotoView.setOnLongClickListener(this);
loadPict();
}
private void loadPict() {
String pictUrl = getIntent().getStringExtra(PICT_URL);
if (!TextUtils.isEmpty(pictUrl)) {
Monet.get(this).load(pictUrl).into(mPhotoView);
}
}
@Override
public void onClick(View view) {
onBackPressed();
}
@Override
public void onBackPressed() {
super.onBackPressed();
AnimationHelper.setFadeTransition(this);
}
@Override
public boolean onLongClick(View view) {
// 先预留,后续保存图片
return false;
}
}
|
package rs.code9.taster.service.memory;
import org.springframework.stereotype.Service;
import rs.code9.taster.model.Category;
import rs.code9.taster.service.CategoryService;
/**
* In memory backed {@link CategoryService} implementation.
*
* @author d.gajic
*/
@Service
public class InMemoryCategoryService extends AbstractInMemoryService<Category>
implements CategoryService {
}
|
import java.math.*;
public class Tree {
public static int minimumTreedepth (TreeNode treeNodeRoot) {
if (treeNodeRoot == null) {return 0;} else { return (1+Math.min(minimumTreedepth(treeNodeRoot.leftTreennode),minimumTreedepth(treeNodeRoot.leftTreennode)));}
}
public static int maximumTreedepth (TreeNode treeNodeRoot) {
if (treeNodeRoot == null) {return 0;} else { return (1+Math.max(maximumTreedepth(treeNodeRoot.leftTreennode),maximumTreedepth(treeNodeRoot.leftTreennode)));}
}
public static boolean isTreeBalanced (TreeNode treeNodeRoot) {
return (maximumTreedepth(treeNodeRoot)-minimumTreedepth(treeNodeRoot) <= 1 );
}
}
|
package com.tencent.mm.modelmulti;
import com.tencent.mm.ab.j;
import com.tencent.mm.protocal.k.d;
import com.tencent.mm.protocal.k.e;
import com.tencent.mm.protocal.w.a;
import com.tencent.mm.protocal.w.b;
public class j$a extends j {
private final a dZH = new a();
private final b dZI = new b();
protected final d Ic() {
return this.dZH;
}
public final e Id() {
return this.dZI;
}
public final int getType() {
return 39;
}
public final String getUri() {
return null;
}
public final int KP() {
return 1;
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class RegSetInfoUI$32 implements OnMenuItemClickListener {
final /* synthetic */ RegSetInfoUI eWJ;
RegSetInfoUI$32(RegSetInfoUI regSetInfoUI) {
this.eWJ = regSetInfoUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
RegSetInfoUI.w(this.eWJ);
return true;
}
}
|
package cn.bs.zjzc.ui.view;
import cn.bs.zjzc.base.IBaseView;
/**
* Created by Ming on 2016/6/15.
*/
public interface IWithdrawView extends IBaseView {
}
|
package com.kh.member.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.kh.member.model.service.MemberService;
import com.kh.member.model.vo.Member;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet(name = "Login", urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String pw = request.getParameter("pw");
//3. 비지니스로직 처리
MemberService service = new MemberService();
Member m = service.login(id, pw);
//4. view처리
if(m!=null) {
HttpSession session = request.getSession(); /*session 생성(jsp에선 session이 내장객체라 자동으로 만들어지지만 servlet에선 session이 내장객체가 아니므로 만들어줘야됨)*/
session.setAttribute("member", m);
request.setAttribute("msg", "로그인 성공");
}else {
request.setAttribute("msg", "로그인 실패");
}
request.setAttribute("loc", "/"); //로그인 성공하던 실패하던 무조건 /index.jsp로 이동
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/views/common/msg.jsp"); //메세지 처리를 위해 이동할 페이지
rd.forward(request, response); //페이지 이동. request와 respnse를 들고 페이지 이동, response는 큰 의미는 모르겠는데 매개변수로 반드시 있어야함.
//주소창에서도 msg.jsp가 나오지 않고 requestDisatcher를 호출한 이곳의 주소만 나온다.
//WEB-INF 아래에 작성한 페이지들은 일반적인 방법(url을 통한 이동)으로는 접근할 수 없고, requestDispatcher나 include를 통해서만 가능하다.
//보안성을 위해 접근하지 못하게 자동으로 설정되어있다.
System.out.println("로그인 Servlet 끝");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package testCases;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class testCase2 {
public static void main(String[] args)throws Exception
{
System.setProperty("webdriver.chrome.driver", "E:\\Selenium Softwares\\chromedriver.exe");
ChromeDriver Driver=new ChromeDriver();
//TO maximize browser
Driver.manage().window().maximize();
//-------------------------------------
//wait object
WebDriverWait wait=new WebDriverWait(Driver, 60);
//Actions class object
Actions Act=new Actions(Driver);
//----------------------------------------------
//Open application
Driver.get("http://apps.qaplanet.in/hrm/login.php");
//Verify home page displayed or not
if(wait.until(ExpectedConditions.titleIs("OrangeHRM - New Level of HR Management")))
{
System.out.println("Home Page Displayed");
}
else
{
System.out.println("Failed to display home page");
return;
}
//-------------------------------------------------
//Create webelement for UN,PWD,Login and clear
WebElement objUN=wait.until(ExpectedConditions.presenceOfElementLocated(By.name("txtUserName")));
WebElement objPWD=wait.until(ExpectedConditions.presenceOfElementLocated(By.name("txtPassword")));
WebElement objLogin=Driver.findElement(By.name("Submit"));
WebElement objClear=Driver.findElement(By.name("clear"));
//------------------------------------------------
//Verify user name
if(objUN.isDisplayed())
{
System.out.println("User name displayed");
}
//Verify password
if(objPWD.isDisplayed())
{
System.out.println("Password displayed");
}
//Verify login and clear
if(objLogin.isDisplayed() && objClear.isDisplayed())
{
System.out.println("Login and clear displayed");
}
//---------------------------------------------------
String sUN="qaplanet1";
String sPWD="lab1";
//-----------------------------------------------------
//Clear user name text box and enter user name
objUN.clear();
objUN.sendKeys(sUN);
//Clear password and enter password
objPWD.clear();
objPWD.sendKeys(sPWD);
//Click on login
objLogin.click();
//Verify OrangeHRM
if(wait.until(ExpectedConditions.titleIs("OrangeHRM")))
{
System.out.println("OrangeHRM displayed");
}
else
{
System.out.println("Failed to login");
return;
}
//---------------Verify welcome text-------------------------------
//way 1
if(wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//ul[@id='option-menu']/li[1]"), "Welcome "+sUN)))
{
System.out.println("Welcome "+sUN+" displayed");
}
//Way 2
String WelText=Driver.findElement(By.xpath("//ul[@id='option-menu']/li[1]")).getText();
if(WelText.equals("Welcome "+sUN))
{
System.out.println("Welcome "+sUN+" displayed");
}
//Way 3: Verify only user name
String[] Arr=WelText.split(" ");
if(Arr[1].equals(sUN))
{
System.out.println(sUN+" displayed");
}
//-------------------------------------------------------
//Create webelemnt for chnage password and logout
WebElement objCP=Driver.findElement(By.linkText("Change Password"));
WebElement objLogout=Driver.findElement(By.linkText("Logout"));
//Veify Change Password & Logout
if(objCP.isDisplayed() && objLogout.isDisplayed())
{
System.out.println("Change Password & Logout are displayed");
}
//------------------------------------------------------
//Create webelement for PIM
WebElement objPIM=Driver.findElement(By.id("pim"));
//Mouse ove ron PIM
Act.moveToElement(objPIM).perform();
//Click on add employee
Driver.findElement(By.linkText("Add Employee")).click();
//wait 2 sec
Thread.sleep(2000);
//switch to frame
Driver.switchTo().frame("rightMenu");
//Verify PIM : Add Employee
if(Driver.findElement(By.xpath("//div[@class='mainHeading']/h2")).getText().equals("PIM : Add Employee"))
{
System.out.println("PIM : Add Employee displayed");
}
else
{
System.out.println("Failed to display PIM : Add Employee");
}
//----------------------------------------------------
String sFN="Mahesh";
String sLN="P";
//----------------------------------------------------
//Get employee code
String strEmpCode=Driver.findElement(By.name("txtEmployeeId")).getAttribute("value");
//create webelement for save
WebElement objSave=Driver.findElement(By.id("btnEdit"));
//Keep all fields as blank and click on save
objSave.click();
//wait for alert
Alert A=wait.until(ExpectedConditions.alertIsPresent());
//Verify alert message
if(A.getText().equals("Last Name Empty!"))
{
System.out.println("Last Name Empty! displayed");
A.accept();
}
//Enter last name
Driver.findElement(By.name("txtEmpLastName")).sendKeys(sLN);
//Click on save
objSave.click();
//wait for alert
Alert A1=wait.until(ExpectedConditions.alertIsPresent());
//Verify alert message
if(A1.getText().equals("First Name Empty!"))
{
System.out.println("First Name Empty! displayed");
A1.accept();
}
//Enter employee first name
Driver.findElement(By.name("txtEmpFirstName")).sendKeys(sFN);
//Click on save
objSave.click();
//wait for Personal Details text
if(wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@class='mainHeading']/h2"), "Personal Details")))
{
System.out.println("Personal Details displayed");
}
//switch to parent frame
Driver.switchTo().parentFrame();
//-------------------------------------------
//Mouse ove ron PIM
Act.moveToElement(objPIM).perform();
//Click on Employee List
Driver.findElement(By.linkText("Employee List")).click();
//wait 2 sec
Thread.sleep(2000);
//switch to frame
Driver.switchTo().frame("rightMenu");
//Verify Employee Information
if(Driver.findElement(By.xpath("//div[@class='mainHeading']/h2")).getText().equals("Employee Information"))
{
System.out.println("Employee Information displayed");
}
else
{
System.out.println("Failed to display Employee Information");
}
//-------------------------------------------
//Get row count
int rc=Driver.findElements(By.xpath("//table[@class='data-table']/tbody/tr")).size();
int i;
for(i=1;i<=rc;i++)
{
//Get emp id from second column
String sEmpID=Driver.findElement(By.xpath("//table[@class='data-table']/tbody/tr["+i+"]/td[2]")).getText();
//Get emp name from third column
String sEmpName=Driver.findElement(By.xpath("//table[@class='data-table']/tbody/tr["+i+"]/td[3]/a")).getText();
if(sEmpID.equals(strEmpCode) && sEmpName.equals(sFN+" "+sLN))
{
System.out.println(sEmpName+", "+sEmpID+", "+"displayed at: "+i);
break;
}
}
//switch to default page
Driver.switchTo().defaultContent();
//--------------------------------------------
//Click on Logout
Driver.findElement(By.linkText("Logout")).click();
//wait 2 sec
Thread.sleep(2000);
//Verify home page displayed or not
if(Driver.getTitle().equals("OrangeHRM - New Level of HR Management"))
{
System.out.println("Signoff sucessfull & Home Page Displayed");
}
else
{
System.out.println("Failed to Signoff");
return;
}
//----------------------------------------------
//Close browser
Driver.close();
//Quit object
Driver.quit();
}
}
|
package com.smartwerkz.bytecode.classfile;
import java.util.ArrayList;
import java.util.List;
import com.smartwerkz.bytecode.vm.VirtualMachine;
public class Descriptor {
/**
* <ol>
* <li>()V == 0</li
* <li>([Ljava/lang/String;)V == 1</li>
* <li>()Ljava/lang/String; == 0</li>
* <li>((IF)V) == 2</li>
* </ol>
*/
public static int countParameters(String str) {
int cnt = 0;
int beginIndex = str.indexOf('(');
int endIndex = str.indexOf(')');
for (int i = beginIndex + 1; i < endIndex; i++) {
char c = str.charAt(i);
switch (c) {
case 'I':
cnt++;
break;
case 'S':
cnt++;
break;
case 'B':
cnt++;
break;
case 'F':
cnt++;
break;
case 'D':
cnt++;
break;
case 'J':
cnt++;
break;
case 'C':
cnt++;
break;
case 'Z':
cnt++;
break;
case '[':
// cnt++; Ignore Arrays and only count them once, by their type
// def
// i++;
break;
case 'L':
cnt++;
while (c != ';') {
i++;
if (i < str.length()) {
c = str.charAt(i);
}
}
break;
default:
throw new IllegalStateException("Unknown type: '" + c + "' in " + str);
}
}
return cnt;
}
public static List<String> toClassNames(VirtualMachine vm, String str) {
List<String> classnames = new ArrayList<String>();
int cnt = 0;
int beginIndex = str.indexOf('(');
int endIndex = str.indexOf(')');
for (int i = beginIndex + 1; i < endIndex; i++) {
char c = str.charAt(i);
switch (c) {
case 'I':
classnames.add(vm.classes().primitives().intClass().getThisClassName());
break;
case 'S':
classnames.add(vm.classes().primitives().shortClass().getThisClassName());
break;
case 'B':
classnames.add(vm.classes().primitives().byteClass().getThisClassName());
break;
case 'F':
classnames.add(vm.classes().primitives().floatClass().getThisClassName());
break;
case 'D':
classnames.add(vm.classes().primitives().doubleClass().getThisClassName());
break;
case 'J':
classnames.add(vm.classes().primitives().longClass().getThisClassName());
break;
case 'C':
classnames.add(vm.classes().primitives().charClass().getThisClassName());
break;
case 'Z':
classnames.add(vm.classes().primitives().booleanClass().getThisClassName());
break;
case '[':
// cnt++; Ignore Arrays and only count them once, by their type
// def
// i++;
break;
case 'L':
cnt++;
StringBuilder clazzName = new StringBuilder();
while (c != ';') {
i++;
if (i < str.length()) {
c = str.charAt(i);
if (c != ';') {
clazzName.append(c);
}
}
}
classnames.add(clazzName.toString());
break;
default:
throw new IllegalStateException("Unknown type: '" + c + "' in " + str);
}
}
return classnames;
}
}
|
package cache.inmemorycache.server.internal.datastore;
import java.sql.Timestamp;
import cache.inmemorycache.server.internal.transaction.Transaction;
public interface IDataStore {
public void set(String key, String value) throws InterruptedException, CloneNotSupportedException;
CacheValue get(java.lang.String key);
public Transaction begin();
void set(String key, String value, String transactionId) throws CloneNotSupportedException;
CacheValue get(String key, String transactionId);
boolean containsKey(String key);
boolean isValidTransaction(String transactionId);
int getCount(String value);
void commit(Transaction transaction);
void commit(String transactionId);
void delete(String key) throws CloneNotSupportedException;
void delete(String key, String transactionId) throws CloneNotSupportedException;
void print();
Timestamp getTransactionTimestamp(String transactionId);
void rollback(String transactionId);
int getCount(String value, String transactionId);
}
|
/**
*/
package EpkDSL;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Node To Pp Connection</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link EpkDSL.NodeToPpConnection#getStart <em>Start</em>}</li>
* <li>{@link EpkDSL.NodeToPpConnection#getEnd <em>End</em>}</li>
* </ul>
* </p>
*
* @see EpkDSL.EpkDSLPackage#getNodeToPpConnection()
* @model
* @generated
*/
public interface NodeToPpConnection extends DefaultConnection {
/**
* Returns the value of the '<em><b>Start</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Start</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Start</em>' reference.
* @see #setStart(Node)
* @see EpkDSL.EpkDSLPackage#getNodeToPpConnection_Start()
* @model required="true"
* @generated
*/
Node getStart();
/**
* Sets the value of the '{@link EpkDSL.NodeToPpConnection#getStart <em>Start</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Start</em>' reference.
* @see #getStart()
* @generated
*/
void setStart(Node value);
/**
* Returns the value of the '<em><b>End</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>End</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>End</em>' reference.
* @see #setEnd(ProcPath)
* @see EpkDSL.EpkDSLPackage#getNodeToPpConnection_End()
* @model required="true"
* @generated
*/
ProcPath getEnd();
/**
* Sets the value of the '{@link EpkDSL.NodeToPpConnection#getEnd <em>End</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>End</em>' reference.
* @see #getEnd()
* @generated
*/
void setEnd(ProcPath value);
} // NodeToPpConnection
|
package com.ic.SysAgenda.resource;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.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.RestController;
import com.ic.SysAgenda.exception.NaoEncontradoException;
import com.ic.SysAgenda.model.Pessoa;
import com.ic.SysAgenda.service.PessoaService;
@RestController
@RequestMapping("/pessoa")
public class PessoaResource {
@Autowired
private PessoaService pessoaService;
public PessoaResource() {
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Pessoa> salvar(@RequestBody Pessoa pessoa) {
Pessoa p = this.pessoaService.salvar(pessoa);
return new ResponseEntity<Pessoa>(p, HttpStatus.OK);
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Pessoa>> listarTodos() {
List<Pessoa> pessoas = (List<Pessoa>) this.pessoaService.listarTodos();
return new ResponseEntity<List<Pessoa>>(pessoas, HttpStatus.OK);
}
@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Pessoa> atualizar(@RequestBody Pessoa pessoa) {
try {
Pessoa p = this.pessoaService.atualizar(pessoa);
return new ResponseEntity<Pessoa>(p, HttpStatus.OK);
} catch (NaoEncontradoException e) {
return new ResponseEntity<Pessoa>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> deletar(@PathVariable Long id) {
try {
return new ResponseEntity<String>(this.pessoaService.deletar(id), HttpStatus.OK);
} catch (NaoEncontradoException e) {
return new ResponseEntity<String>("Pessoa não encontrada", HttpStatus.NOT_FOUND);
}
}
}
|
package com.taikang.healthcare.cust.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taikang.healthcare.cust.model.Xindex;
import com.taikang.healthcare.cust.XindexService;
@Controller
@RequestMapping(value="cust")
public class XindexController {
@Autowired
private XindexService xindexService;
/**
* 绑定客户索引
* FIXME
* @param customerId
* @param xindex
* @return
*/
@RequestMapping(value="/api/v1/customers/{customerId}/xindexs",method=RequestMethod.POST)
@ResponseBody
public Map<String,Object> bind(@PathVariable("customerId") long customerId,Map<String,Object> xindex){
xindex.put("customerId",customerId);
return xindexService.bind(xindex);
}
/**
* 解除客户索引
* FIXME
* @param customerId
* @param id
* @param xindex
* @return
*/
@RequestMapping(value="/api/v1/customers/{customerId}/xindexs/{id}",method=RequestMethod.DELETE)
@ResponseBody
public Map<String,Object> unbind(@PathVariable("customerId") long customerId,@PathVariable("id") int id,Map<String,Object> xindex){
xindex.put("id",id);
xindex.put("customerId",customerId);
return xindexService.unbind(xindex);
}
/**
* 查询客户索引列表
* FIXME
* @param customerId
* @param xindex
* @return
*/
@RequestMapping(value="/api/v1/customers/{customerId}/xindexs",method=RequestMethod.GET)
@ResponseBody
public List<Map<String,Object>> search(@PathVariable("customerId") long customerId,Map<String,Object> xindex){
xindex.put("customerId",customerId);
return xindexService.search(xindex);
}
}
|
package com.example.borja.simplecalculator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CalculatorActivity extends ActionBarActivity implements ICalculatorView{
TextView screen;
CalculatorViewModel viewModel;
static final String BUNDLE_VIEWMODEL_STATE = "Calculator state";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
screen = (TextView) findViewById(R.id.calculatorScreen);
this.screen.setText("0");
viewModel = new CalculatorViewModel(new CalculatorModel(), this);
if(savedInstanceState != null) {
viewModel.setState(savedInstanceState.getString(BUNDLE_VIEWMODEL_STATE));
showScreen(viewModel.screen);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_calculator, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
String viewModelState = viewModel.getState();
outState.putString(BUNDLE_VIEWMODEL_STATE, viewModelState);
}
@Override
public void showScreen(String value) {
this.screen.setText(value);
}
public void numberPressed(View view){
Button button = (Button)view;
char key = button.getText().charAt(0);
viewModel.onNumericKeyPressed(key);
showScreen(viewModel.screen);
}
public void operatorPressed(View view){
Button button = (Button)view;
char key = button.getText().charAt(0);
viewModel.onOperatorKeyPressed(key);
}
public void pointPressed(View view){
viewModel.onDecimalPointPressed();
showScreen(viewModel.screen);
}
public void equalPressed(View view){
viewModel.onEqualKeyPressed();
showScreen(viewModel.screen);
}
}
|
/*
* Copyright (c) 2016. Universidad Politecnica de Madrid
*
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*
*/
package org.librairy.modeler.lda.functions;
import org.librairy.metrics.data.Ranking;
import org.librairy.metrics.distance.ExtendedKendallsTauDistance;
import org.librairy.modeler.lda.models.Comparison;
import org.librairy.modeler.lda.models.Field;
import org.librairy.modeler.lda.utils.LevenshteinSimilarity;
import java.io.Serializable;
/**
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*/
public class PairToComparison implements Serializable {
// public static void apply(){
// Comparison<Field> topicComparison = new Comparison<Field>();
//
// Field fieldOne = new Field();
// fieldOne.setContainerUri(pair._1.getDescription());
// fieldOne.setFieldUri(pair._1.getUri());
// topicComparison.setFieldOne(fieldOne);
//
// Field fieldTwo = new Field();
// fieldTwo.setContainerUri(pair._2.getDescription());
// fieldTwo.setFieldUri(pair._2.getUri());
// topicComparison.setFieldTwo(fieldTwo);
//
// Ranking<String> r1 = new Ranking<String>();
// Ranking<String> r2 = new Ranking<String>();
//
// for (int i = 0; i < maxWords; i++) {
// r1.add(pair._1.getElements().get(i), pair._1.getScores().get(i));
// r2.add(pair._2.getElements().get(i), pair._2.getScores().get(i));
// }
//
// Double score = new ExtendedKendallsTauDistance<String>().calculate(r1, r2, new
// LevenshteinSimilarity());
// topicComparison.setScore(score);
// return topicComparison;
// }
}
|
package ru.job4j;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import ru.job4j.tracker.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class StartUIConsoleTest {
private final PrintStream stdout = System.out;
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
@Before
public void loadOutput() {
System.setOut(new PrintStream(this.out));
}
@After
public void backOutput() {
System.setOut(this.stdout);
}
@Test
public void whenChooseShowAllItems() {
StringBuilder menu = new StringBuilder();
menu.append("0. Add new Item");
menu.append(System.lineSeparator());
menu.append("1. Show all items");
menu.append(System.lineSeparator());
menu.append("2. Edit item");
menu.append(System.lineSeparator());
menu.append("3. Delete item");
menu.append(System.lineSeparator());
menu.append("4. Find item by Id");
menu.append(System.lineSeparator());
menu.append("5. Find items by name");
menu.append(System.lineSeparator());
menu.append("6. Exit Program");
menu.append(System.lineSeparator());
menu.append(" ");
menu.append(System.lineSeparator());
Tracker tracker = new Tracker();
tracker.add(new Item("name item", "desk name", 567L));
Input input = new StubInput(new String[]{"1", "6"});
new StartUI(input, tracker).init();
StringBuilder str = new StringBuilder();
str.append(menu);
str.append("Список всех заявок: ");
str.append(System.lineSeparator());
str.append("name item");
str.append(System.lineSeparator());
str.append(menu);
assertThat(out.toString(), is(str.toString()));
}
@Test
public void whenChooseFindByID() {
StringBuilder menu = new StringBuilder();
menu.append("0. Add new Item");
menu.append(System.lineSeparator());
menu.append("1. Show all items");
menu.append(System.lineSeparator());
menu.append("2. Edit item");
menu.append(System.lineSeparator());
menu.append("3. Delete item");
menu.append(System.lineSeparator());
menu.append("4. Find item by Id");
menu.append(System.lineSeparator());
menu.append("5. Find items by name");
menu.append(System.lineSeparator());
menu.append("6. Exit Program");
menu.append(System.lineSeparator());
menu.append(" ");
menu.append(System.lineSeparator());
Tracker tracker = new Tracker();
tracker.add(new Item("name item", "desk name", 567L));
Input input = new StubInput(new String[]{"4", tracker.findAll()[0].getId(), "6"});
StartUI su = new StartUI(input, tracker);
su.init();
StringBuilder str = new StringBuilder();
str.append(menu);
str.append("name item");
str.append(System.lineSeparator());
str.append(menu);
assertThat(out.toString(), is(str.toString()));
}
@Test
public void whenChooseFindByName() {
StringBuilder menu = new StringBuilder();
menu.append("0. Add new Item");
menu.append(System.lineSeparator());
menu.append("1. Show all items");
menu.append(System.lineSeparator());
menu.append("2. Edit item");
menu.append(System.lineSeparator());
menu.append("3. Delete item");
menu.append(System.lineSeparator());
menu.append("4. Find item by Id");
menu.append(System.lineSeparator());
menu.append("5. Find items by name");
menu.append(System.lineSeparator());
menu.append("6. Exit Program");
menu.append(System.lineSeparator());
menu.append(" ");
menu.append(System.lineSeparator());
Tracker tracker = new Tracker();
tracker.add(new Item("name item", "desk name", 567L));
Input input = new StubInput(new String[]{"5", tracker.findAll()[0].getName(), "6"});
StartUI su = new StartUI(input, tracker);
su.init();
StringBuilder str = new StringBuilder();
str.append(menu);
str.append("name item");
str.append(System.lineSeparator());
str.append(menu);
assertThat(out.toString(), is(str.toString()));
}
}
|
package com.project.homes.app.common.attach.service;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.project.homes.app.common.attach.dto.AttachDto;
import com.project.homes.app.common.attach.mapper.AttachMapper;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Service
public class AttachService {
private final AttachMapper attachMapper;
//첨부파일 insert
@Transactional
public String insertAttach(@RequestParam("files")MultipartFile[] mfiles, @RequestParam("id") long id) {
try {
for(int i=0;i<mfiles.length;i++) {
if(!mfiles[i].isEmpty()) {
String filename = mfiles[i].getOriginalFilename();
long filesize = mfiles[i].getSize();
String filetype = mfiles[i].getContentType();
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("id", id);
map.put("filename", filename);
map.put("filesize", filesize);
map.put("filetype", filetype);
attachMapper.insertAttach(map);
//폴더에 저장
String uploadFolder = "C:\\javaWeb\\tjoeun-project-homes\\src\\main\\webapp\\WEB-INF\\upload";
File saveFile = new File(uploadFolder, filename);
mfiles[i].transferTo(saveFile);
}
}
return "true";
} catch (Exception e) {
e.printStackTrace();
return "파일 저장 실패";
}
}
//첨부파일 삭제
@Transactional
public long deleteAttach(@RequestParam("id") long id) {
return attachMapper.deleteAttach(id);
}
//해당 게시판 첨부파일 리스트
public List<AttachDto> getAttachById(@RequestParam("id") long id){
return attachMapper.getAttachById(id);
}
}
|
package in.yuchengl.scoutui;
/**
* Created by Yucheng on 10/3/15.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
class FriendListAdapter extends ArrayAdapter<FriendListItem> {
private Context mContext;
private int mLogoOnline;
private int mLogoOffline;
FriendListAdapter(Context context, ArrayList<FriendListItem> friendsList) {
super(context, R.layout.list_item_layout, friendsList);
mContext = context;
mLogoOnline = mContext.getResources().getIdentifier("scoutlogo",
"drawable", "in.yuchengl.scoutui");
mLogoOffline = mContext.getResources().getIdentifier("scoutlogo2",
"drawable", "in.yuchengl.scoutui");
}
@Override
public View getView(int position, View convertView, ViewGroup parent ){
LayoutInflater listInflater = LayoutInflater.from(getContext());
View customView = listInflater.inflate(R.layout.list_item_layout, parent, false);
String name = getItem(position).getName();
Boolean live = getItem(position).getLive();
TextView userName = (TextView) customView.findViewById(R.id.displayName);
ImageView avatar = (ImageView) customView.findViewById(R.id.avi);
userName.setText(name);
if (live) {
avatar.setImageResource(mLogoOnline);
} else {
avatar.setImageResource(mLogoOffline);
}
return customView;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.