blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
listlengths 1
1
| author
stringlengths 0
161
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11650e4ece0d7b208e3456dafb05ba9b3ae8001b
|
8fe60d9443395a9c6b5dbd5f5745464be8bf370c
|
/src/com/voterapp/exception/UnderAgeException.java
|
7d8442e6a2dad5e57991e551aca324d360fbabd9
|
[] |
no_license
|
UmangAror/VoterApp
|
b014ca805eb8f630ed8aef5e786930975c4b5aba
|
a2396024ad671d84413286d974e55c712c8dd8bc
|
refs/heads/master
| 2023-04-09T05:27:55.830052
| 2021-04-05T14:28:04
| 2021-04-05T14:28:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 198
|
java
|
package com.voterapp.exception;
public class UnderAgeException extends InvalidVoterException{
public UnderAgeException() {
}
public UnderAgeException(String message) {
super(message);
}
}
|
[
"aroraumang353@gmail.com"
] |
aroraumang353@gmail.com
|
a1a4aa11fd069c3a6a2db8dc97bb4ad59913546c
|
68109a800b4240867c5078d5c0ed473dd5d0a369
|
/src/java/BBL/ControladorCargaFechasViaje.java
|
3341724d2867770b61f3e0187de855d6d74de112
|
[] |
no_license
|
itsobbe/autobusHibernate
|
8473894962908cef69aa52c9447da9da8dec198e
|
32b48c4214ec6402d13af08b4f43d808d0abf7f2
|
refs/heads/master
| 2020-06-16T08:15:01.715752
| 2019-07-06T10:04:50
| 2019-07-06T10:04:50
| 195,521,009
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,455
|
java
|
/*
* 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 BBL;
import DAO.NewHibernateUtil;
import DAO.Operaciones;
import MODELO.ApplicationException;
import POJO.Viaje;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
/**
*
* @author owa_7
*/
public class ControladorCargaFechasViaje extends HttpServlet {
private SessionFactory SessionBuilder;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
public void init() {
SessionBuilder = NewHibernateUtil.getSessionFactory();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
try (PrintWriter out = response.getWriter()) {
//PARA EJERCICIO EXÁMEN
try {
int origen = 0;
int destino = 0;
int id = Integer.parseInt(request.getParameter("idAjax"));
if (request.getParameter("origen") != "") {
origen = Integer.parseInt(request.getParameter("origen"));
}
if (request.getParameter("destino") != "") {
destino = Integer.parseInt(request.getParameter("destino"));
}
List<Viaje> viajes = new Operaciones().devuelveFechasRuta(SessionBuilder, origen, destino);
if (id == 1) {
LocalDate anterior = null;
out.print("<option value='Elige' selected disabled>Elige</option >");
for (Viaje item : viajes) {
LocalDate actual = LocalDate.parse(item.getFechaViaje().toString());
if (anterior == null) {
out.print("<option value='" + item.getFechaViaje() + "'>" + item.getFechaViaje() + " </option >");
} else {
if (actual.isEqual(anterior) == false) {
out.print("<option value='" + item.getFechaViaje() + "'>" + item.getFechaViaje() + " </option >");
}
}
anterior = LocalDate.parse(item.getFechaViaje().toString());
}
} else {
LocalDate elegida = LocalDate.parse(request.getParameter("fecha"));
out.print("<option value='Elige' selected disabled>Elige</option >");
for (Viaje item : viajes) {
LocalDate a = LocalDate.parse(item.getFechaViaje().toString());
if (a.equals(elegida)) {
out.print("<option value='" + item.getId() + "'>" + new SimpleDateFormat("HH:mm").format(item.getHorario().getHoraSalida()) + " </option >");
}
}
}
} catch (ApplicationException e) {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("VISTAS/VistaError.jsp");
request.setAttribute("error", e);
requestDispatcher.forward(request, response);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
[
"oboujloud@gmail.com"
] |
oboujloud@gmail.com
|
6b132ec5267bf472a2d52bd845542206713b98e7
|
6c85ebbeae28a1d61a11955950b11c80c2f07a55
|
/WebService/src/system/com/webservice/system/systembackup/action/SystemBackupAction.java
|
cdb7c29a558d8049ca0e76e5198408301a346b9d
|
[] |
no_license
|
severinamrozinski/jbpm-project
|
71e38f8f8274923941f1aa9af7e816f18126a485
|
e8823aad3770670491e5b6b51899559ffdae476b
|
refs/heads/master
| 2023-03-23T10:38:00.702934
| 2014-08-17T08:52:37
| 2014-08-17T08:52:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 11,138
|
java
|
package com.webservice.system.systembackup.action;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import com.webservice.common.action.BaseAction;
import com.webservice.system.systembackup.bean.SystemBackSettingInfo;
import com.webservice.system.systembackup.bean.SystemBackupInfo;
import com.webservice.system.systembackup.service.ISystemBackupService;
import com.webservice.system.systembackup.service.ISystemBackupSettingService;
import com.webservice.system.util.StringUtils;
import com.webservice.system.util.Tools;
public class SystemBackupAction extends BaseAction {
private ISystemBackupService systemBackupService;
private ISystemBackupSettingService systemBackupSettingService;
private DataSourceTransactionManager transactionManager;
private String userName;
private String backType;
private String backFileId;
private String backValue;
private String backTime;
private SystemBackupInfo backInfo;
/**
* <p>Discription:[系统备份列表]</p>
* @return
* @author:[代超]
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public String backupList(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("userName", userName);
map.put("backType", backType);
List<SystemBackupInfo> list = this.systemBackupService.queryPageBackList(start, limit, map);
int listSize = this.systemBackupService.queryPageBackList(map);
PrintWriter out = null;
Map<String, Object> resultMap = new HashMap<String, Object>();
try{
out = super.getPrintWriter();
resultMap.put("success", true);
resultMap.put("totalCount", listSize);
resultMap.put("backinfo", list);
}catch(Exception e){
e.printStackTrace();
LOG.error(e.getMessage());
resultMap.put("success", false);
resultMap.put("msg", "系统错误,错误代码:"+e.getMessage());
}finally{
if(out != null){
out.print(getJsonString(resultMap));
out.flush();
out.close();
}
}
return null;
}
/**
* <p>Discription:[备份文件下载]</p>
* @return
* @author:[代超]
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public String backupDownload(){
PrintWriter out = null;
OutputStream os = null;
FileInputStream fis = null;
HttpServletResponse response = ServletActionContext.getResponse();
try{
if(backFileId == null || "".equals(backFileId.trim())){
throw new Exception("您没有选择要下载的备份文件!");
}else{
SystemBackupInfo backupInfo = this.systemBackupService.findById(backFileId);
if(backupInfo == null){
throw new Exception("您选择的备份文件不存在!");
}
response.setHeader("Content-Disposition",
"attachment; fileName="
+ new String(backupInfo.getFileName().getBytes("gb2312"),
"ISO-8859-1"));
//获得一个从服务器上的文件myFile中获得输入字节的输入流对象
fis = new FileInputStream(backupInfo.getFilePath());
byte bytes[]=new byte[1024];//设置缓冲区为1024个字节,即1KB
int len=0;
os = response.getOutputStream();
while((len=fis.read(bytes))!=-1){
//将指定 byte数组中从下标 0 开始的 len个字节写入此文件输出流,(即读了多少就写入多少)
os.write(bytes,0,len);
}
}
}catch(Exception e){
LOG.error(e.getMessage());
try{
if(os != null){
os.flush();
os.close();
os = null;
}
if(fis != null){
try {
fis.close();
}
catch (IOException e2) {
LOG.error(e2.getMessage());
}
}
//清空response的设置
response.reset();
out = getPrintWriter(ServletActionContext.getRequest(), response, "UTF-8", "text/html; charset=utf-8");
out = response.getWriter();
out.write("<script>alert('系统错误,错误原因:"+StringUtils.convertChar(e.getMessage())+"'); window.close();</script>");
out.flush();
out.close();
}catch(Exception e1){
LOG.error(e1.getMessage());
}
}finally{
if(os != null){
try {
os.flush();
os.close();
}
catch (IOException e) {
LOG.error(e.getMessage());
}
}
if(fis != null){
try {
fis.close();
}
catch (IOException e) {
LOG.error(e.getMessage());
}
}
}
return null;
}
/**
* <p>Discription:[系统备份设置]</p>
* @return
* @author:[代超]
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public String systemBackupSetting(){
PrintWriter out = null;
Map<String, Object> resultMap = new HashMap<String, Object>();
TransactionStatus status = super.getTransactionStatus(transactionManager);
String settingId = ServletActionContext.getRequest().getParameter("id");
try{
out = super.getPrintWriter();
if(this.backType == null || this.backValue == null){
throw new Exception("您输入的信息部完整!");
}
SystemBackSettingInfo settingInfo = new SystemBackSettingInfo();
settingInfo.setBackValue(backValue);
settingInfo.setBackType(backType);
settingInfo.setUserName(userName);
settingInfo.setBackTime(backTime);
settingInfo.setCronValue(Tools.getCronValue(backType, backValue, backTime));
if(settingId != null && !"".equals(settingId.trim())){
settingInfo.setId(settingId);
}
this.systemBackupSettingService.saveOrUpdate(settingInfo);
//更新定时任务
Map<String, String> jobDataMap = new HashMap<String, String>();
jobDataMap.put("userName", userName);
systemBackupService.executeJob(jobDataMap, "ACCOUNTBACKUPJOB", settingInfo.getCronValue());
resultMap.put("success", true);
resultMap.put("msg", "您的账目备份设置信息已经成功保存!");
}catch(Exception e){
status.setRollbackOnly();
LOG.error(e.getMessage());
resultMap.put("success", false);
resultMap.put("msg", "系统错误,错误代码:"+e.getMessage());
}finally{
this.transactionManager.commit(status);
if(out != null){
out.print(super.getJsonString(resultMap));
out.flush();
out.close();
}
}
return null;
}
/**
* <p>Discription:[获取数据备份设置]</p>
* @return
* @author:[代超]
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public String getBackupSettingList(){
SystemBackSettingInfo settingInfo = new SystemBackSettingInfo();
settingInfo.setUserName(userName);
List list = this.systemBackupSettingService.findByExample(settingInfo);
PrintWriter out = null;
Map<String, Object> resultMap = new HashMap<String, Object>();
try{
out = super.getPrintWriter();
resultMap.put("success", true);
resultMap.put("totalCount", list.size());
resultMap.put("backsetting", list);
}catch(Exception e){
e.printStackTrace();
LOG.error(e.getMessage());
resultMap.put("success", false);
resultMap.put("msg", "系统错误,错误代码:"+e.getMessage());
}finally{
if(out != null){
out.print(getJsonString(resultMap));
out.flush();
out.close();
}
}
return null;
}
public ISystemBackupService getSystemBackupService() {
return systemBackupService;
}
public void setSystemBackupService(ISystemBackupService systemBackupService) {
this.systemBackupService = systemBackupService;
}
public ISystemBackupSettingService getSystemBackupSettingService() {
return systemBackupSettingService;
}
public void setSystemBackupSettingService(ISystemBackupSettingService systemBackupSettingService) {
this.systemBackupSettingService = systemBackupSettingService;
}
public DataSourceTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(DataSourceTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public String getBackFileId() {
return backFileId;
}
public void setBackFileId(String backFileId) {
this.backFileId = backFileId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getBackType() {
return backType;
}
public void setBackType(String backType) {
this.backType = backType;
}
public String getBackValue() {
return backValue;
}
public void setBackValue(String backValue) {
this.backValue = backValue;
}
public String getBackTime() {
return backTime;
}
public void setBackTime(String backTime) {
this.backTime = backTime;
}
public SystemBackupInfo getBackInfo() {
return backInfo;
}
public void setBackInfo(SystemBackupInfo backInfo) {
this.backInfo = backInfo;
}
}
|
[
"swpigris81@gmail.com"
] |
swpigris81@gmail.com
|
737d9f85a1f17a153ce1093d6337e0ad84716f9b
|
211c0b1ff0c689082f10197469f78999918c5df2
|
/src/main/java/com/index/isa/dependency/config/SwaggerConfig.java
|
c54bf3699734b0ec0da4a28e8245348afc37c84f
|
[] |
no_license
|
masnasri-a/APIDownloadFiles
|
d136ebfff8a2af2f3b04b196821e773f3f9307e2
|
9aeb9534197cc23ebadd7aa3f4726f490d0a21c5
|
refs/heads/main
| 2023-03-07T03:30:46.303828
| 2021-02-16T03:03:30
| 2021-02-16T03:03:30
| 339,270,205
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 964
|
java
|
package com.index.isa.dependency.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.builders.PathSelectors;
import com.google.common.base.Predicates;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket cyberPatrolApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(getApiInfo()).select()
.paths(Predicates.not(PathSelectors.regex("/error"))).build();
}
private ApiInfo getApiInfo() {
// We do not use all info
@SuppressWarnings("deprecation")
ApiInfo info = new ApiInfo("Dependency API", "API Dependency", "1.0", "", "", "", "");
return info;
}
}
|
[
"nasri@jkt1.ebdesk.com"
] |
nasri@jkt1.ebdesk.com
|
04ddfa07c9c6bace6a790c06b67388b362982814
|
3232829a72a02c5f9fa467f065d6041e22c3fe19
|
/src/Main/Practise13/CommodityLengthComparator.java
|
3b5dcb3627e0335f4a4408605c921bcad10fb211
|
[] |
no_license
|
DimaMaksymiv19/java_core_homework
|
29941e7cbacac0fe44ea373d0e7f7ac6c0db00a7
|
28111643a7b18266ffb4ad6becb43a61bcdae398
|
refs/heads/master
| 2023-03-31T02:46:47.574709
| 2021-04-06T21:50:52
| 2021-04-06T21:50:52
| 337,157,267
| 0
| 0
| null | 2021-04-06T21:50:53
| 2021-02-08T17:37:50
|
Java
|
UTF-8
|
Java
| false
| false
| 419
|
java
|
package Main.Practise13;
import Main.Homework10.Main;
import java.util.Comparator;
public class CommodityLengthComparator implements Comparator<Commodity> {
@Override
public int compare(Commodity o1, Commodity o2) {
if (o1.getLen() > o2.getLen()) {
return 1;
} else if (o1.getLen() < o2.getLen()) {
return -1;
} else {
return 0;
}
}
}
|
[
"dimamaksymiv2001@gmail.com"
] |
dimamaksymiv2001@gmail.com
|
b424cbf6c798215da9a96627297dfcef553d1024
|
e13d9e0305234066694ba3c624018afcc5658e63
|
/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceImpl.java
|
e1ade6b6f107f8d08d5ba65059e67086ca8f4467
|
[
"Apache-2.0"
] |
permissive
|
yyobject/java-server-sdk
|
218bb3c8d34207d280ec4a32a9a7b4e189823735
|
fe3771bd180c700e5f35cca0460f77f7aa753cb3
|
refs/heads/master
| 2023-04-22T01:19:07.599141
| 2021-04-23T03:23:07
| 2021-04-23T03:23:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 11,366
|
java
|
package com.launchdarkly.sdk.server.integrations;
import com.google.common.collect.ImmutableList;
import com.launchdarkly.sdk.LDValue;
import com.launchdarkly.sdk.server.LDClient;
import com.launchdarkly.sdk.server.integrations.FileDataSourceBuilder.SourceInfo;
import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FlagFactory;
import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FlagFileParser;
import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FlagFileRep;
import com.launchdarkly.sdk.server.interfaces.DataSource;
import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider.ErrorInfo;
import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider.ErrorKind;
import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider.State;
import com.launchdarkly.sdk.server.interfaces.DataSourceUpdates;
import com.launchdarkly.sdk.server.interfaces.DataStoreTypes.DataKind;
import com.launchdarkly.sdk.server.interfaces.DataStoreTypes.FullDataSet;
import com.launchdarkly.sdk.server.interfaces.DataStoreTypes.ItemDescriptor;
import com.launchdarkly.sdk.server.interfaces.DataStoreTypes.KeyedItems;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.Watchable;
import java.time.Instant;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.launchdarkly.sdk.server.DataModel.FEATURES;
import static com.launchdarkly.sdk.server.DataModel.SEGMENTS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
/**
* Implements taking flag data from files and putting it into the data store, at startup time and
* optionally whenever files change.
*/
final class FileDataSourceImpl implements DataSource {
private static final Logger logger = LoggerFactory.getLogger(LDClient.class.getName() + ".DataSource");
private final DataSourceUpdates dataSourceUpdates;
private final DataLoader dataLoader;
private final FileData.DuplicateKeysHandling duplicateKeysHandling;
private final AtomicBoolean inited = new AtomicBoolean(false);
private final FileWatcher fileWatcher;
FileDataSourceImpl(
DataSourceUpdates dataSourceUpdates,
List<SourceInfo> sources,
boolean autoUpdate,
FileData.DuplicateKeysHandling duplicateKeysHandling
) {
this.dataSourceUpdates = dataSourceUpdates;
this.dataLoader = new DataLoader(sources);
this.duplicateKeysHandling = duplicateKeysHandling;
FileWatcher fw = null;
if (autoUpdate) {
try {
fw = FileWatcher.create(dataLoader.getSources());
} catch (IOException e) {
// COVERAGE: there is no way to simulate this condition in a unit test
logger.error("Unable to watch files for auto-updating: {}", e.toString());
logger.debug(e.toString(), e);
fw = null;
}
}
fileWatcher = fw;
}
@Override
public Future<Void> start() {
final Future<Void> initFuture = CompletableFuture.completedFuture(null);
reload();
// Note that if reload() finds any errors, it will not set our status to "initialized". But we
// will still do all the other startup steps, because we still might end up getting valid data
// if we are told to reload by the file watcher.
if (fileWatcher != null) {
fileWatcher.start(this::reload);
}
return initFuture;
}
private boolean reload() {
DataBuilder builder = new DataBuilder(duplicateKeysHandling);
try {
dataLoader.load(builder);
} catch (FileDataException e) {
logger.error(e.getDescription());
dataSourceUpdates.updateStatus(State.INTERRUPTED,
new ErrorInfo(ErrorKind.INVALID_DATA, 0, e.getDescription(), Instant.now()));
return false;
}
dataSourceUpdates.init(builder.build());
dataSourceUpdates.updateStatus(State.VALID, null);
inited.set(true);
return true;
}
@Override
public boolean isInitialized() {
return inited.get();
}
@Override
public void close() throws IOException {
if (fileWatcher != null) {
fileWatcher.stop();
}
}
/**
* If auto-updating is enabled, this component watches for file changes on a worker thread.
*/
private static final class FileWatcher implements Runnable {
private final WatchService watchService;
private final Set<Path> watchedFilePaths;
private Runnable fileModifiedAction;
private final Thread thread;
private volatile boolean stopped;
private static FileWatcher create(Iterable<SourceInfo> sources) throws IOException {
Set<Path> directoryPaths = new HashSet<>();
Set<Path> absoluteFilePaths = new HashSet<>();
FileSystem fs = FileSystems.getDefault();
WatchService ws = fs.newWatchService();
// In Java, you watch for filesystem changes at the directory level, not for individual files.
for (SourceInfo s: sources) {
Path p = s.toFilePath();
if (p != null) {
absoluteFilePaths.add(p);
directoryPaths.add(p.getParent());
}
}
for (Path d: directoryPaths) {
d.register(ws, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
}
return new FileWatcher(ws, absoluteFilePaths);
}
private FileWatcher(WatchService watchService, Set<Path> watchedFilePaths) {
this.watchService = watchService;
this.watchedFilePaths = watchedFilePaths;
thread = new Thread(this, FileDataSourceImpl.class.getName());
thread.setDaemon(true);
}
public void run() {
while (!stopped) {
try {
WatchKey key = watchService.take(); // blocks until a change is available or we are interrupted
boolean watchedFileWasChanged = false;
for (WatchEvent<?> event: key.pollEvents()) {
Watchable w = key.watchable();
Object context = event.context();
if (w instanceof Path && context instanceof Path) {
Path dirPath = (Path)w;
Path fileNamePath = (Path)context;
Path absolutePath = dirPath.resolve(fileNamePath);
if (watchedFilePaths.contains(absolutePath)) {
watchedFileWasChanged = true;
break;
}
}
}
if (watchedFileWasChanged) {
try {
fileModifiedAction.run();
} catch (Exception e) {
// COVERAGE: there is no way to simulate this condition in a unit test
logger.warn("Unexpected exception when reloading file data: " + e);
}
}
key.reset(); // if we don't do this, the watch on this key stops working
} catch (InterruptedException e) {
// if we've been stopped we will drop out at the top of the while loop
}
}
}
public void start(Runnable fileModifiedAction) {
this.fileModifiedAction = fileModifiedAction;
thread.start();
}
public void stop() {
stopped = true;
thread.interrupt();
}
}
/**
* Implements the loading of flag data from one or more files. Will throw an exception if any file can't
* be read or parsed, or if any flag or segment keys are duplicates.
*/
static final class DataLoader {
private final List<SourceInfo> sources;
private final AtomicInteger lastVersion;
public DataLoader(List<SourceInfo> sources) {
this.sources = new ArrayList<>(sources);
this.lastVersion = new AtomicInteger(0);
}
public Iterable<SourceInfo> getSources() {
return sources;
}
public void load(DataBuilder builder) throws FileDataException
{
int version = lastVersion.incrementAndGet();
for (SourceInfo s: sources) {
try {
byte[] data = s.readData();
FlagFileParser parser = FlagFileParser.selectForContent(data);
FlagFileRep fileContents = parser.parse(new ByteArrayInputStream(data));
if (fileContents.flags != null) {
for (Map.Entry<String, LDValue> e: fileContents.flags.entrySet()) {
builder.add(FEATURES, e.getKey(), FlagFactory.flagFromJson(e.getValue(), version));
}
}
if (fileContents.flagValues != null) {
for (Map.Entry<String, LDValue> e: fileContents.flagValues.entrySet()) {
builder.add(FEATURES, e.getKey(), FlagFactory.flagWithValue(e.getKey(), e.getValue(), version));
}
}
if (fileContents.segments != null) {
for (Map.Entry<String, LDValue> e: fileContents.segments.entrySet()) {
builder.add(SEGMENTS, e.getKey(), FlagFactory.segmentFromJson(e.getValue(), version));
}
}
} catch (FileDataException e) {
throw new FileDataException(e.getMessage(), e.getCause(), s);
} catch (IOException e) {
throw new FileDataException(null, e, s);
}
}
}
}
/**
* Internal data structure that organizes flag/segment data into the format that the feature store
* expects. Will throw an exception if we try to add the same flag or segment key more than once.
*/
static final class DataBuilder {
private final Map<DataKind, Map<String, ItemDescriptor>> allData = new HashMap<>();
private final FileData.DuplicateKeysHandling duplicateKeysHandling;
public DataBuilder(FileData.DuplicateKeysHandling duplicateKeysHandling) {
this.duplicateKeysHandling = duplicateKeysHandling;
}
public FullDataSet<ItemDescriptor> build() {
ImmutableList.Builder<Map.Entry<DataKind, KeyedItems<ItemDescriptor>>> allBuilder = ImmutableList.builder();
for (Map.Entry<DataKind, Map<String, ItemDescriptor>> e0: allData.entrySet()) {
allBuilder.add(new AbstractMap.SimpleEntry<>(e0.getKey(), new KeyedItems<>(e0.getValue().entrySet())));
}
return new FullDataSet<>(allBuilder.build());
}
public void add(DataKind kind, String key, ItemDescriptor item) throws FileDataException {
Map<String, ItemDescriptor> items = allData.get(kind);
if (items == null) {
items = new HashMap<String, ItemDescriptor>();
allData.put(kind, items);
}
if (items.containsKey(key)) {
if (duplicateKeysHandling == FileData.DuplicateKeysHandling.IGNORE) {
return;
}
throw new FileDataException("in " + kind.getName() + ", key \"" + key + "\" was already defined", null, null);
}
items.put(key, item);
}
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
9b1c8bbc8f5e971756c934844715f23cc9c5e32c
|
785f25bbd08c412d3fa44644618afd9489aa81a8
|
/src/com/example/demo/Register.java
|
18c008f4a0ca6c38abfa7dd87ad1124b0a8bf9ec
|
[] |
no_license
|
iYeHao/Design
|
fc62915c141e05e19457626c2bbe71b39e26349f
|
d3a7d86782968241dac2095172515da4c3e8cb54
|
refs/heads/master
| 2021-01-19T22:52:58.536158
| 2017-04-12T11:20:11
| 2017-04-12T11:20:11
| 83,781,137
| 0
| 2
| null | null | null | null |
GB18030
|
Java
| false
| false
| 2,984
|
java
|
package com.example.demo;
import java.util.HashMap;
import java.util.Map;
public class Register {
private String uname;
private String upassword;
private String cpassword;
private String uemail;
private String usex;
private int ulevel;
private int uage;
/**
* 存储校验不通过时给用户的错误提示信息
*/
private Map<String, String> errors = new HashMap<String, String>();
public Map<String, String> getErrors() {
return errors;
}
/*
* validate方法负责校验表单输入项
* 表单输入项校验规则:
* private String userName; 用户名不能为空,并且要是3-8的字母 abcdABcd
* private String userPwd; 密码不能为空,并且要是3-8的数字
* private String confirmPwd; 两次密码要一致
* private String email; 可以为空,不为空要是一个合法的邮箱
* private String birthday; 可以为空,不为空时,要是一个合法的日期
*/
public boolean validate() {
boolean isOk = true;
if (this.uname == null || this.uname.trim().equals("")) {
isOk = false;
errors.put("uname", "*用户名不为空");
} else {
if (!this.uname.matches("[a-zA-Z]{3,8}"))
{
isOk = false;
errors.put("uname", "*用户名为3-8位的字母");
}
}
if (this.upassword == null || this.upassword.trim().equals(" ")) {
isOk = false;
errors.put("upassword", "*密码不为空");
} else {
if (!this.upassword.matches("\\d{3,8}")) {
isOk = false;
errors.put("upassword", "*密码为3-8位数字");
}
}
// private String password2; 两次密码要一致
if (this.cpassword != null) {
if (!this.cpassword.equals(this.upassword)) {
isOk = false;
errors.put("cpassword", "*俩次密码不一致");
}
}
return isOk;
}
public void setErrors(Map<String, String> errors) {
this.errors = errors;
}
public String getCpassword() {
return cpassword;
}
public void setCpassword(String cpassword) {
this.cpassword = cpassword;
}
public void setUemail(String uemail){
this.uemail=uemail;
}
public String getUemail(){
return uemail;
}
public void setUname(String uname){
this.uname=uname;
}
public String getUname(){
return uname;
}
public void setUpassword(String upassword){
this.upassword=upassword;
}
public String getUpassword(){
return upassword;
}
public void setUage(int uage){
this.uage=uage;
}
public int getUage(){
return uage;
}
public void setUlevel(int ulevel){
this.ulevel=ulevel;
}
public int getUlevel(){
return ulevel;
}
public void setUsex(String usex){
this.usex=usex;
}
public String getUsex(){
return usex;
}
}
|
[
"1561269761@qq.com"
] |
1561269761@qq.com
|
9002b8bd5b51544af22665d31a82c180a69b84b9
|
b78d96a8660f90649035c7a6d6698cabb2946d62
|
/solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/impl/ScriptTableImpl.java
|
293a036462562817072705ee86f28b5fddac226f
|
[
"MIT"
] |
permissive
|
suchaoxiao/ttc2017smartGrids
|
d7b677ddb20a0adc74daed9e3ae815997cc86e1a
|
2997f1c202f5af628e50f5645c900f4d35f44bb7
|
refs/heads/master
| 2021-06-19T10:21:22.740676
| 2017-07-14T12:13:22
| 2017-07-14T12:13:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 24,876
|
java
|
/**
*/
package COSEM.COSEMObjects.impl;
import COSEM.COSEMObjects.ActivateNormalMode;
import COSEM.COSEMObjects.ActivateTestMode;
import COSEM.COSEMObjects.Broadcast;
import COSEM.COSEMObjects.COSEMObjectsPackage;
import COSEM.COSEMObjects.DisconnectControl;
import COSEM.COSEMObjects.GlobalMeterReset;
import COSEM.COSEMObjects.ImageActivation;
import COSEM.COSEMObjects.MDIReset;
import COSEM.COSEMObjects.PowerQualityMeasurementManagement;
import COSEM.COSEMObjects.Push;
import COSEM.COSEMObjects.ScriptTable;
import COSEM.COSEMObjects.SetOutputSignal;
import COSEM.COSEMObjects.SwitchOpticalTestOutput;
import COSEM.COSEMObjects.Tariffication;
import COSEM.InterfaceClasses.impl.ScripttableImpl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Script Table</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getGlobalMeterReset <em>Global Meter Reset</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getMDIReset <em>MDI Reset</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getTariffication <em>Tariffication</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getAcitvateTest <em>Acitvate Test</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getActivateNormal <em>Activate Normal</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getSetOutput <em>Set Output</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getSwitchOptical <em>Switch Optical</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getPowerQuality <em>Power Quality</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getDisconnect <em>Disconnect</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getImage <em>Image</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getPush <em>Push</em>}</li>
* <li>{@link COSEM.COSEMObjects.impl.ScriptTableImpl#getBroadcast <em>Broadcast</em>}</li>
* </ul>
*
* @generated
*/
public class ScriptTableImpl extends ScripttableImpl implements ScriptTable {
/**
* The cached value of the '{@link #getGlobalMeterReset() <em>Global Meter Reset</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getGlobalMeterReset()
* @generated
* @ordered
*/
protected GlobalMeterReset globalMeterReset;
/**
* The cached value of the '{@link #getMDIReset() <em>MDI Reset</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMDIReset()
* @generated
* @ordered
*/
protected MDIReset mdiReset;
/**
* The cached value of the '{@link #getTariffication() <em>Tariffication</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTariffication()
* @generated
* @ordered
*/
protected Tariffication tariffication;
/**
* The cached value of the '{@link #getAcitvateTest() <em>Acitvate Test</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAcitvateTest()
* @generated
* @ordered
*/
protected ActivateTestMode acitvateTest;
/**
* The cached value of the '{@link #getActivateNormal() <em>Activate Normal</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getActivateNormal()
* @generated
* @ordered
*/
protected ActivateNormalMode activateNormal;
/**
* The cached value of the '{@link #getSetOutput() <em>Set Output</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSetOutput()
* @generated
* @ordered
*/
protected SetOutputSignal setOutput;
/**
* The cached value of the '{@link #getSwitchOptical() <em>Switch Optical</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSwitchOptical()
* @generated
* @ordered
*/
protected SwitchOpticalTestOutput switchOptical;
/**
* The cached value of the '{@link #getPowerQuality() <em>Power Quality</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPowerQuality()
* @generated
* @ordered
*/
protected PowerQualityMeasurementManagement powerQuality;
/**
* The cached value of the '{@link #getDisconnect() <em>Disconnect</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDisconnect()
* @generated
* @ordered
*/
protected DisconnectControl disconnect;
/**
* The cached value of the '{@link #getImage() <em>Image</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImage()
* @generated
* @ordered
*/
protected ImageActivation image;
/**
* The cached value of the '{@link #getPush() <em>Push</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPush()
* @generated
* @ordered
*/
protected Push push;
/**
* The cached value of the '{@link #getBroadcast() <em>Broadcast</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBroadcast()
* @generated
* @ordered
*/
protected Broadcast broadcast;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ScriptTableImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return COSEMObjectsPackage.eINSTANCE.getScriptTable();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public GlobalMeterReset getGlobalMeterReset() {
if (globalMeterReset != null && globalMeterReset.eIsProxy()) {
InternalEObject oldGlobalMeterReset = (InternalEObject)globalMeterReset;
globalMeterReset = (GlobalMeterReset)eResolveProxy(oldGlobalMeterReset);
if (globalMeterReset != oldGlobalMeterReset) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__GLOBAL_METER_RESET, oldGlobalMeterReset, globalMeterReset));
}
}
return globalMeterReset;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public GlobalMeterReset basicGetGlobalMeterReset() {
return globalMeterReset;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setGlobalMeterReset(GlobalMeterReset newGlobalMeterReset) {
GlobalMeterReset oldGlobalMeterReset = globalMeterReset;
globalMeterReset = newGlobalMeterReset;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__GLOBAL_METER_RESET, oldGlobalMeterReset, globalMeterReset));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MDIReset getMDIReset() {
if (mdiReset != null && mdiReset.eIsProxy()) {
InternalEObject oldMDIReset = (InternalEObject)mdiReset;
mdiReset = (MDIReset)eResolveProxy(oldMDIReset);
if (mdiReset != oldMDIReset) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__MDI_RESET, oldMDIReset, mdiReset));
}
}
return mdiReset;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MDIReset basicGetMDIReset() {
return mdiReset;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMDIReset(MDIReset newMDIReset) {
MDIReset oldMDIReset = mdiReset;
mdiReset = newMDIReset;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__MDI_RESET, oldMDIReset, mdiReset));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Tariffication getTariffication() {
if (tariffication != null && tariffication.eIsProxy()) {
InternalEObject oldTariffication = (InternalEObject)tariffication;
tariffication = (Tariffication)eResolveProxy(oldTariffication);
if (tariffication != oldTariffication) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__TARIFFICATION, oldTariffication, tariffication));
}
}
return tariffication;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Tariffication basicGetTariffication() {
return tariffication;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTariffication(Tariffication newTariffication) {
Tariffication oldTariffication = tariffication;
tariffication = newTariffication;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__TARIFFICATION, oldTariffication, tariffication));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ActivateTestMode getAcitvateTest() {
if (acitvateTest != null && acitvateTest.eIsProxy()) {
InternalEObject oldAcitvateTest = (InternalEObject)acitvateTest;
acitvateTest = (ActivateTestMode)eResolveProxy(oldAcitvateTest);
if (acitvateTest != oldAcitvateTest) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__ACITVATE_TEST, oldAcitvateTest, acitvateTest));
}
}
return acitvateTest;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ActivateTestMode basicGetAcitvateTest() {
return acitvateTest;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAcitvateTest(ActivateTestMode newAcitvateTest) {
ActivateTestMode oldAcitvateTest = acitvateTest;
acitvateTest = newAcitvateTest;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__ACITVATE_TEST, oldAcitvateTest, acitvateTest));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ActivateNormalMode getActivateNormal() {
if (activateNormal != null && activateNormal.eIsProxy()) {
InternalEObject oldActivateNormal = (InternalEObject)activateNormal;
activateNormal = (ActivateNormalMode)eResolveProxy(oldActivateNormal);
if (activateNormal != oldActivateNormal) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__ACTIVATE_NORMAL, oldActivateNormal, activateNormal));
}
}
return activateNormal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ActivateNormalMode basicGetActivateNormal() {
return activateNormal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setActivateNormal(ActivateNormalMode newActivateNormal) {
ActivateNormalMode oldActivateNormal = activateNormal;
activateNormal = newActivateNormal;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__ACTIVATE_NORMAL, oldActivateNormal, activateNormal));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SetOutputSignal getSetOutput() {
if (setOutput != null && setOutput.eIsProxy()) {
InternalEObject oldSetOutput = (InternalEObject)setOutput;
setOutput = (SetOutputSignal)eResolveProxy(oldSetOutput);
if (setOutput != oldSetOutput) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__SET_OUTPUT, oldSetOutput, setOutput));
}
}
return setOutput;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SetOutputSignal basicGetSetOutput() {
return setOutput;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSetOutput(SetOutputSignal newSetOutput) {
SetOutputSignal oldSetOutput = setOutput;
setOutput = newSetOutput;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__SET_OUTPUT, oldSetOutput, setOutput));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SwitchOpticalTestOutput getSwitchOptical() {
if (switchOptical != null && switchOptical.eIsProxy()) {
InternalEObject oldSwitchOptical = (InternalEObject)switchOptical;
switchOptical = (SwitchOpticalTestOutput)eResolveProxy(oldSwitchOptical);
if (switchOptical != oldSwitchOptical) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__SWITCH_OPTICAL, oldSwitchOptical, switchOptical));
}
}
return switchOptical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SwitchOpticalTestOutput basicGetSwitchOptical() {
return switchOptical;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSwitchOptical(SwitchOpticalTestOutput newSwitchOptical) {
SwitchOpticalTestOutput oldSwitchOptical = switchOptical;
switchOptical = newSwitchOptical;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__SWITCH_OPTICAL, oldSwitchOptical, switchOptical));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PowerQualityMeasurementManagement getPowerQuality() {
if (powerQuality != null && powerQuality.eIsProxy()) {
InternalEObject oldPowerQuality = (InternalEObject)powerQuality;
powerQuality = (PowerQualityMeasurementManagement)eResolveProxy(oldPowerQuality);
if (powerQuality != oldPowerQuality) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__POWER_QUALITY, oldPowerQuality, powerQuality));
}
}
return powerQuality;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PowerQualityMeasurementManagement basicGetPowerQuality() {
return powerQuality;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPowerQuality(PowerQualityMeasurementManagement newPowerQuality) {
PowerQualityMeasurementManagement oldPowerQuality = powerQuality;
powerQuality = newPowerQuality;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__POWER_QUALITY, oldPowerQuality, powerQuality));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DisconnectControl getDisconnect() {
if (disconnect != null && disconnect.eIsProxy()) {
InternalEObject oldDisconnect = (InternalEObject)disconnect;
disconnect = (DisconnectControl)eResolveProxy(oldDisconnect);
if (disconnect != oldDisconnect) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__DISCONNECT, oldDisconnect, disconnect));
}
}
return disconnect;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DisconnectControl basicGetDisconnect() {
return disconnect;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDisconnect(DisconnectControl newDisconnect) {
DisconnectControl oldDisconnect = disconnect;
disconnect = newDisconnect;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__DISCONNECT, oldDisconnect, disconnect));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ImageActivation getImage() {
if (image != null && image.eIsProxy()) {
InternalEObject oldImage = (InternalEObject)image;
image = (ImageActivation)eResolveProxy(oldImage);
if (image != oldImage) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__IMAGE, oldImage, image));
}
}
return image;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ImageActivation basicGetImage() {
return image;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setImage(ImageActivation newImage) {
ImageActivation oldImage = image;
image = newImage;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__IMAGE, oldImage, image));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Push getPush() {
if (push != null && push.eIsProxy()) {
InternalEObject oldPush = (InternalEObject)push;
push = (Push)eResolveProxy(oldPush);
if (push != oldPush) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__PUSH, oldPush, push));
}
}
return push;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Push basicGetPush() {
return push;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPush(Push newPush) {
Push oldPush = push;
push = newPush;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__PUSH, oldPush, push));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Broadcast getBroadcast() {
if (broadcast != null && broadcast.eIsProxy()) {
InternalEObject oldBroadcast = (InternalEObject)broadcast;
broadcast = (Broadcast)eResolveProxy(oldBroadcast);
if (broadcast != oldBroadcast) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMObjectsPackage.SCRIPT_TABLE__BROADCAST, oldBroadcast, broadcast));
}
}
return broadcast;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Broadcast basicGetBroadcast() {
return broadcast;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBroadcast(Broadcast newBroadcast) {
Broadcast oldBroadcast = broadcast;
broadcast = newBroadcast;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, COSEMObjectsPackage.SCRIPT_TABLE__BROADCAST, oldBroadcast, broadcast));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case COSEMObjectsPackage.SCRIPT_TABLE__GLOBAL_METER_RESET:
if (resolve) return getGlobalMeterReset();
return basicGetGlobalMeterReset();
case COSEMObjectsPackage.SCRIPT_TABLE__MDI_RESET:
if (resolve) return getMDIReset();
return basicGetMDIReset();
case COSEMObjectsPackage.SCRIPT_TABLE__TARIFFICATION:
if (resolve) return getTariffication();
return basicGetTariffication();
case COSEMObjectsPackage.SCRIPT_TABLE__ACITVATE_TEST:
if (resolve) return getAcitvateTest();
return basicGetAcitvateTest();
case COSEMObjectsPackage.SCRIPT_TABLE__ACTIVATE_NORMAL:
if (resolve) return getActivateNormal();
return basicGetActivateNormal();
case COSEMObjectsPackage.SCRIPT_TABLE__SET_OUTPUT:
if (resolve) return getSetOutput();
return basicGetSetOutput();
case COSEMObjectsPackage.SCRIPT_TABLE__SWITCH_OPTICAL:
if (resolve) return getSwitchOptical();
return basicGetSwitchOptical();
case COSEMObjectsPackage.SCRIPT_TABLE__POWER_QUALITY:
if (resolve) return getPowerQuality();
return basicGetPowerQuality();
case COSEMObjectsPackage.SCRIPT_TABLE__DISCONNECT:
if (resolve) return getDisconnect();
return basicGetDisconnect();
case COSEMObjectsPackage.SCRIPT_TABLE__IMAGE:
if (resolve) return getImage();
return basicGetImage();
case COSEMObjectsPackage.SCRIPT_TABLE__PUSH:
if (resolve) return getPush();
return basicGetPush();
case COSEMObjectsPackage.SCRIPT_TABLE__BROADCAST:
if (resolve) return getBroadcast();
return basicGetBroadcast();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case COSEMObjectsPackage.SCRIPT_TABLE__GLOBAL_METER_RESET:
setGlobalMeterReset((GlobalMeterReset)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__MDI_RESET:
setMDIReset((MDIReset)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__TARIFFICATION:
setTariffication((Tariffication)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__ACITVATE_TEST:
setAcitvateTest((ActivateTestMode)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__ACTIVATE_NORMAL:
setActivateNormal((ActivateNormalMode)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__SET_OUTPUT:
setSetOutput((SetOutputSignal)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__SWITCH_OPTICAL:
setSwitchOptical((SwitchOpticalTestOutput)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__POWER_QUALITY:
setPowerQuality((PowerQualityMeasurementManagement)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__DISCONNECT:
setDisconnect((DisconnectControl)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__IMAGE:
setImage((ImageActivation)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__PUSH:
setPush((Push)newValue);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__BROADCAST:
setBroadcast((Broadcast)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case COSEMObjectsPackage.SCRIPT_TABLE__GLOBAL_METER_RESET:
setGlobalMeterReset((GlobalMeterReset)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__MDI_RESET:
setMDIReset((MDIReset)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__TARIFFICATION:
setTariffication((Tariffication)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__ACITVATE_TEST:
setAcitvateTest((ActivateTestMode)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__ACTIVATE_NORMAL:
setActivateNormal((ActivateNormalMode)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__SET_OUTPUT:
setSetOutput((SetOutputSignal)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__SWITCH_OPTICAL:
setSwitchOptical((SwitchOpticalTestOutput)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__POWER_QUALITY:
setPowerQuality((PowerQualityMeasurementManagement)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__DISCONNECT:
setDisconnect((DisconnectControl)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__IMAGE:
setImage((ImageActivation)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__PUSH:
setPush((Push)null);
return;
case COSEMObjectsPackage.SCRIPT_TABLE__BROADCAST:
setBroadcast((Broadcast)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case COSEMObjectsPackage.SCRIPT_TABLE__GLOBAL_METER_RESET:
return globalMeterReset != null;
case COSEMObjectsPackage.SCRIPT_TABLE__MDI_RESET:
return mdiReset != null;
case COSEMObjectsPackage.SCRIPT_TABLE__TARIFFICATION:
return tariffication != null;
case COSEMObjectsPackage.SCRIPT_TABLE__ACITVATE_TEST:
return acitvateTest != null;
case COSEMObjectsPackage.SCRIPT_TABLE__ACTIVATE_NORMAL:
return activateNormal != null;
case COSEMObjectsPackage.SCRIPT_TABLE__SET_OUTPUT:
return setOutput != null;
case COSEMObjectsPackage.SCRIPT_TABLE__SWITCH_OPTICAL:
return switchOptical != null;
case COSEMObjectsPackage.SCRIPT_TABLE__POWER_QUALITY:
return powerQuality != null;
case COSEMObjectsPackage.SCRIPT_TABLE__DISCONNECT:
return disconnect != null;
case COSEMObjectsPackage.SCRIPT_TABLE__IMAGE:
return image != null;
case COSEMObjectsPackage.SCRIPT_TABLE__PUSH:
return push != null;
case COSEMObjectsPackage.SCRIPT_TABLE__BROADCAST:
return broadcast != null;
}
return super.eIsSet(featureID);
}
} //ScriptTableImpl
|
[
"hinkel@fzi.de"
] |
hinkel@fzi.de
|
f6fa70764c7cc247437300b10b7cc8ffdb5741a4
|
0dbd183528185c66f188585c16141e7756401275
|
/viewitEE-distribApp-backEnd/viewitEE/viewitEE-ejb/src/main/java/enumerations/ProductSize.java
|
b8fcd39c084c14fa5f621d0b287533f27696595b
|
[] |
no_license
|
Patricia-NavarroMartin/distributed-application-ViewIt
|
c6dab02e6a7201d5fa233058ab84d2f2f99efda6
|
23d3ee6334705ce775cce26a5e5c4cae72fd14fc
|
refs/heads/master
| 2022-12-17T09:55:45.311723
| 2020-09-22T13:45:13
| 2020-09-22T13:45:13
| 297,651,193
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 834
|
java
|
package enumerations;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.HashMap;
import java.util.Map;
public enum ProductSize {
S,M,L;
private static final Map<String,ProductSize> productSizeMap = new HashMap<String,ProductSize>();
static{
productSizeMap.put("S",S);
productSizeMap.put("M",M);
productSizeMap.put("L",L);
productSizeMap.put("",null);
}
@JsonCreator
public static ProductSize forValue(String value){
return productSizeMap.get(value);
}
@JsonValue
public String toValue(){
for (Map.Entry<String, ProductSize> entry : productSizeMap.entrySet()){
if(entry.getValue()==this) return entry.getKey();
}
return null; //failed
}
}
|
[
"patricia.navarro@cascination.com"
] |
patricia.navarro@cascination.com
|
c09bfc95752d3eb824b8868f8de4f8f9bf1a8b48
|
9291dbce63b02cc3341b4b89ea9d5c3d0e34cfab
|
/Notebook/app/src/test/java/dev/mdb/notebook/ExampleUnitTest.java
|
8e137927b1b735efd3e3f00800317252b6db5287
|
[] |
no_license
|
mdbresources/Android-Lesson-Three-Demos
|
ae1f27c0bf45cd00755dc16bb903d782d8899687
|
32d1d1c60fc0799062a47afb273e156c95f3191f
|
refs/heads/master
| 2021-01-04T18:06:11.241315
| 2020-02-15T12:05:01
| 2020-02-15T12:05:01
| 240,701,819
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 377
|
java
|
package dev.mdb.notebook;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
|
[
"imran.khaliq@berkeley.edu"
] |
imran.khaliq@berkeley.edu
|
af731f2f9af6f4ab15b98c1cf382765b0efd52e0
|
91233c6f27a191c941e80ebbf6d78e192d223d4b
|
/dubbo-provider-demo/src/main/java/com/github/dubbo/demo/provider/filter/ParameterValidationFilter.java
|
57bfcb7c1828a1a6981cb352880ffb6aa13c5d71
|
[] |
no_license
|
tsfans/dubbo-demo
|
74276cebb52ebf39ee1c5533dccfa736dc33aeed
|
55d024865a17522554def037313702fb20ac7fa7
|
refs/heads/master
| 2022-07-06T04:08:48.941742
| 2019-09-07T04:16:21
| 2019-09-07T04:16:21
| 205,830,089
| 0
| 0
| null | 2022-06-10T19:59:28
| 2019-09-02T10:10:36
|
Java
|
UTF-8
|
Java
| false
| false
| 2,138
|
java
|
package com.github.dubbo.demo.provider.filter;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcResult;
import com.alibaba.dubbo.validation.Validation;
import com.alibaba.dubbo.validation.Validator;
import com.alibaba.dubbo.validation.support.jvalidation.JValidation;
import com.github.dubbo.demo.facade.bean.response.BaseResponse;
import com.github.dubbo.demo.facade.common.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Activate(group = {Constants.CONSUMER, Constants.PROVIDER}, order = Integer.MIN_VALUE)
public class ParameterValidationFilter implements Filter {
private final Validation validation = new JValidation();
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
log.info(">>>>>> ParameterValidationFilter has been invoked <<<<<<");
try {
Validator validator = validation.getValidator(invoker.getUrl());
if (validator != null) {
validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments());
}
} catch (RpcException e) {
throw e;
} catch (ConstraintViolationException ce) {
StringBuilder error = new StringBuilder();
for (ConstraintViolation<?> constraintViolation : ce.getConstraintViolations()) {
error.append(" " + constraintViolation.getMessageTemplate());
}
BaseResponse<String> errorResponse = BaseResponse.fail(ResponseCode.ILLEGAL_ARGUMENT.getCode(), error.toString());
return new RpcResult(errorResponse);
} catch (Throwable t) {
return new RpcResult(t);
}
return invoker.invoke(invocation);
}
}
|
[
"hu382018@outlook.com"
] |
hu382018@outlook.com
|
4024974f38ff840bcede3ee29a0678f78770fbf3
|
d15c518fecf372790e53b4246c3ef5aecf7ceb1d
|
/gpd/src/org/netbpm/gpd/view/ForkView.java
|
3b2a7bbd71ef52d98b240a09a28f70af687833d3
|
[
"Apache-2.0",
"DOC"
] |
permissive
|
qwinner/NetBPM
|
a6cf6f645380ae96ba8b362a4bcfa4b28b2215b3
|
5e6df7413dde1367699817a735bfdbd829d93d41
|
refs/heads/master
| 2021-01-10T04:50:44.836371
| 2016-01-08T02:55:46
| 2016-01-08T02:55:46
| 49,244,976
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,420
|
java
|
package org.netbpm.gpd.view;
import java.awt.BasicStroke;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import org.jgraph.JGraph;
import org.jgraph.graph.CellMapper;
import org.jgraph.graph.CellViewRenderer;
import org.jgraph.graph.GraphConstants;
import org.jgraph.graph.VertexRenderer;
import org.jgraph.graph.VertexView;
import java.awt.geom.*;
public class ForkView extends VertexView {
public static ForkRenderer renderer = new ForkRenderer();
public ForkView(Object cell, JGraph graph, CellMapper cm) {
super(cell, graph, cm);
}
public CellViewRenderer getRenderer() {
return renderer;
}
public static class ForkRenderer extends VertexRenderer {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Dimension d = getSize();
boolean tmp = selected;
if (super.isOpaque()) {
g.setColor(super.getBackground());
g2.draw(new Line2D.Double(0, 0, 0, d.height ));
}
try {
setBorder(null);
setOpaque(false);
selected = false;
super.paint(g);
} finally {
selected = tmp;
}
if (bordercolor != null) {
g.setColor(bordercolor);
g2.setStroke(new BasicStroke(4));
g2.draw(new Line2D.Double(0, 0, d.width, 0 ));
}
if (selected) {
g2.setStroke(GraphConstants.SELECTION_STROKE);
g.setColor(graph.getHighlightColor());
g2.draw(new Line2D.Double(0, 0, 0, d.height ));
}
}
}
}
|
[
"xiaoqiangaaa2007@163.com"
] |
xiaoqiangaaa2007@163.com
|
eb9d389f72ba9098329a7a334af5ec7cc5a2e6fa
|
dfe8412ef2fcb91d603a77b9ea743f72c018db7f
|
/app/src/main/java/com/shareshow/airpc/ftpserver/NormalDataSocketFactory.java
|
1cce202a61ff16b78accc0656deb2a84cac59f9b
|
[] |
no_license
|
afterxiong/qm
|
d89331625802c434af7aebe18391b51a73cb1920
|
5f62fda441d34187e01b1d8f7378d1d9c66085ac
|
refs/heads/master
| 2020-03-21T06:48:53.094115
| 2018-06-22T09:54:33
| 2018-06-22T09:54:33
| 138,243,579
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,123
|
java
|
/*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.shareshow.airpc.ftpserver;
import android.util.Log;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class NormalDataSocketFactory extends DataSocketFactory {
/**
* This class implements normal, traditional opening and closing of data sockets
* used for transmitting directory listings and file contents. PORT and PASV
* work according to the FTP specs. This is in contrast to a
* ProxyDataSocketFactory, which performs contortions to allow data sockets
* to be proxied through a server out in the cloud.
*
*/
// Listener socket used for PASV mode
ServerSocket server = null;
// Remote IP & port information used for PORT mode
InetAddress remoteAddr;
int remotePort;
boolean isPasvMode = true;
public NormalDataSocketFactory() {
clearState();
}
private void clearState() {
/**
* Clears the state of this object, as if no pasv() or port() had occurred.
* All sockets are closed.
*/
if(server != null) {
try {
server.close();
} catch (IOException e) {}
}
server = null;
remoteAddr = null;
remotePort = 0;
myLog.l(Log.DEBUG, "NormalDataSocketFactory state cleared");
}
public int onPasv() {
clearState();
try {
// Listen on any port (port parameter 0)
server = new ServerSocket(0, Defaults.tcpConnectionBacklog);
myLog.l(Log.DEBUG, "Data socket pasv() listen successful");
return server.getLocalPort();
} catch(IOException e) {
myLog.l(Log.ERROR, "Data socket creation error");
clearState();
return 0;
}
}
public boolean onPort(InetAddress remoteAddr, int remotePort) {
clearState();
this.remoteAddr = remoteAddr;
this.remotePort = remotePort;
return true;
}
public Socket onTransfer() {
if(server == null) {
// We're in PORT mode (not PASV)
if(remoteAddr == null || remotePort == 0) {
myLog.l(Log.INFO, "PORT mode but not initialized correctly");
clearState();
return null;
}
Socket socket;
try {
socket = new Socket(remoteAddr, remotePort);
} catch (IOException e) {
myLog.l(Log.INFO,
"Couldn't open PORT data socket to: " +
remoteAddr.toString() + ":" + remotePort);
clearState();
return null;
}
// Kill the socket if nothing happens for X milliseconds
try {
socket.setSoTimeout(Defaults.SO_TIMEOUT_MS);
} catch (Exception e) {
myLog.l(Log.ERROR, "Couldn't set SO_TIMEOUT");
clearState();
return null;
}
return socket;
} else {
// We're in PASV mode (not PORT)
Socket socket = null;
try {
socket = server.accept();
myLog.l(Log.DEBUG, "onTransfer pasv accept successful");
} catch (Exception e) {
myLog.l(Log.INFO, "Exception accepting PASV socket");
socket = null;
}
clearState();
return socket; // will be null if error occurred
}
}
/**
* Return the port number that the remote client should be informed of (in the body
* of the PASV response).
* @return The port number, or -1 if error.
*/
public int getPortNumber() {
if(server != null) {
return server.getLocalPort(); // returns -1 if serversocket is unbound
} else {
return -1;
}
}
public InetAddress getPasvIp() {
//String retVal = server.getInetAddress().getHostAddress();
return FTPServerService.getWifiIp();
}
public void reportTraffic(long bytes) {
// ignore, we don't care about how much traffic goes over wifi.
}
}
|
[
"xiongchengguang@taipuglobal.com"
] |
xiongchengguang@taipuglobal.com
|
29385c7496d52eb408dbe227e5a3848856c9615d
|
71a4923fd7e78ffc7859fed614bb8d00e8c2e634
|
/app/src/main/java/com/delta/smt/base/BaseCommonActivity.java
|
45dae979fea7b78503b2fc80429f6684271ef3a6
|
[] |
no_license
|
zhangfuxiang/Tea_Market
|
1ee325b7cd568855c53037ec91610d1c02394ec4
|
1ec994c34e7d3244381e843434f33eb0e1cb052c
|
refs/heads/master
| 2020-12-02T17:50:43.400572
| 2017-07-06T14:52:55
| 2017-07-06T14:52:55
| 96,438,251
| 8
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,062
|
java
|
package com.delta.smt.base;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.delta.smt.app.App;
import java.util.LinkedList;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* @description :不带Presenter的Activity
* @autHor : V.Wenju.Tian
* @date : 2016/12/14 11:24
*/
public abstract class BaseCommonActivity extends AppCompatActivity {
public static final String ACTION_RECEIVER_ACTIVITY = "com.delta.smt";
public static final String IS_NOT_ADD_ACTIVITY_LIST = "is_add_activity_list";//是否加入到activity的list,管理
private String TAG = getClass().getSimpleName();
private BroadcastReceiver mBroadcastReceiver;
private App application;
private Unbinder bind;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
application = ((App) getApplication());
boolean isNotAdd = getIntent().getBooleanExtra(IS_NOT_ADD_ACTIVITY_LIST, false);
synchronized (BaseCommonActivity.class) {
if (!isNotAdd)
application.getActivityList().add(this);
}
setContentView(getContentViewId());
bind = ButterKnife.bind(this);
initCData();
initCView();
}
protected abstract void initCView();
protected abstract void initCData();
public App getMApplication() {
return application;
}
@Override
protected void onResume() {
super.onResume();
registReceiver();//注册广播
}
@Override
protected void onPause() {
super.onPause();
unregistReceriver();
}
@Override
protected void onDestroy() {
synchronized (BaseCommonActivity.class) {
application.getActivityList().remove(this);
}
if (bind != Unbinder.EMPTY) {
bind.unbind();
}
super.onDestroy();
}
protected abstract int getContentViewId();
/**
* 注册广播
*/
public void registReceiver() {
try {
mBroadcastReceiver = new ActivityReceriver();
IntentFilter filter = new IntentFilter(ACTION_RECEIVER_ACTIVITY);
registerReceiver(mBroadcastReceiver, filter);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解除注册广播
*/
public void unregistReceriver() {
if (mBroadcastReceiver == null) return;
try {
unregisterReceiver(mBroadcastReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
public void FullScreencall() {
if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
View v = this.getWindow().getDecorView();
v.setSystemUiVisibility(View.GONE);
} else if (Build.VERSION.SDK_INT >= 19) {
//for new api versions.
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
decorView.setSystemUiVisibility(uiOptions);
}
}
/**
* 用于处理当前activity需要
*/
class ActivityReceriver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
switch (intent.getStringExtra("type")) {
case "startActivity"://启动activity
Intent content = intent.getExtras().getParcelable("content");
startActivity(content);
break;
case "showSnackbar"://显示snackbar
String text = intent.getStringExtra("content");
boolean isLong = intent.getBooleanExtra("long", false);
View view = BaseCommonActivity.this.getWindow().getDecorView().findViewById(android.R.id.content);
Snackbar.make(view, text, isLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
break;
case "killAll":
LinkedList<BaseCommonActivity> copy;
synchronized (BaseCommonActivity.class) {
copy = new LinkedList<BaseCommonActivity>(application.getActivityList());
}
for (BaseCommonActivity baseActivity : copy) {
baseActivity.finish();
}
// android.os.Process.killProcess(android.os.Process.myPid());
break;
}
}
}
}
}
|
[
"1010993490@qq.com"
] |
1010993490@qq.com
|
85577e2bc0432bbb5e4f4d5f1d27d07b054cfc84
|
fe49bebdae362679d8ea913d97e7a031e5849a97
|
/bqerpweb/src/power/web/manage/stat/action/StatItemRealtimeAction.java
|
f6640222af47a22550bc5f71acd6da150b5e19f2
|
[] |
no_license
|
loveyeah/BQMIS
|
1f87fad2c032e2ace7e452f13e6fe03d8d09ce0d
|
a3f44db24be0fcaa3cf560f9d985a6ed2df0b46b
|
refs/heads/master
| 2020-04-11T05:21:26.632644
| 2018-03-08T02:13:18
| 2018-03-08T02:13:18
| 124,322,652
| 0
| 2
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,290
|
java
|
package power.web.manage.stat.action;
import power.ear.comm.ejb.PageObject;
import power.ejb.manage.stat.BpCStatItemRealtime;
import power.ejb.manage.stat.BpCStatItemRealtimeFacadeRemote;
import power.ejb.manage.stat.form.StatItemFrom;
import power.web.comm.AbstractAction;
import power.web.comm.Constants;
import com.googlecode.jsonplugin.JSONException;
import com.googlecode.jsonplugin.JSONUtil;
@SuppressWarnings("serial")
public class StatItemRealtimeAction extends AbstractAction {
private BpCStatItemRealtimeFacadeRemote realtimeRemote;
public StatItemRealtimeAction() {
realtimeRemote = (BpCStatItemRealtimeFacadeRemote) factory.getFacadeRemote("BpCStatItemRealtimeFacade");
}
/**
* 查询指标对应数据
*
*/
public void getStatItemList() throws JSONException {
String argFuzzy = request.getParameter("argFuzzy");
PageObject obj = new PageObject();
int start = Integer.parseInt(request.getParameter("start"));
int limit = Integer.parseInt(request.getParameter("limit"));
obj = realtimeRemote.findStatItemForCorrespond(argFuzzy,start,limit);
String str = JSONUtil.serialize(obj);
if ("".equals(str)) {
str = "{\"list\":[],\"totalCount\":null}";
}
write(str);
}
// /**
// * 查询节点对应数据
// *
// */
// public void getDcsNodeList() throws JSONException {
// PageObject obj = new PageObject();
// int start = Integer.parseInt(request.getParameter("start"));
// int limit = Integer.parseInt(request.getParameter("limit"));
// String queryKey = request.getParameter("queryKey");
// obj = realtimeRemote.findDcsNodeForCorrespond(queryKey,start,limit);
// String str = JSONUtil.serialize(obj);
// if ("".equals(str)) {
// str = "{\"list\":[],\"totalCount\":null}";
// }
// write(str);
// }
/**
* 查询指标对应的采集点信息
* @throws JSONException
*/
public void findCorrespondByItem() throws JSONException{
String itemCode = request.getParameter("itemCode");
StatItemFrom model=realtimeRemote.findItemCorrespondInfo(itemCode);
write(JSONUtil.serialize(model));
}
/**
* 生成指标编码与节点的对应信息
*/
public void generateCorrespond() {
String itemCode = request.getParameter("itemCode");
String nodeCode = request.getParameter("nodeCode");
String apartCode = request.getParameter("apartCode");
BpCStatItemRealtime model = realtimeRemote.findById(itemCode);
if(model == null)
{
BpCStatItemRealtime entity=new BpCStatItemRealtime();
entity.setItemCode(itemCode);
entity.setNodeCode(nodeCode);
entity.setApartCode(apartCode);
realtimeRemote.save(entity);
}
else
{
model.setNodeCode(nodeCode);
model.setApartCode(apartCode);
realtimeRemote.update(model);
}
write(Constants.ADD_SUCCESS);
}
/**
* 删除指标编码与节点的对应信息
*/
public void cancelCorrespond() {
String itemCode = request.getParameter("itemCode");
BpCStatItemRealtime entity = new BpCStatItemRealtime();
entity.setItemCode(itemCode);
BpCStatItemRealtime returnEntity = realtimeRemote.delete(entity);
if(returnEntity != null ) {
write(Constants.DELETE_SUCCESS);
} else {
write(Constants.DELETE_FAILURE);
}
}
}
|
[
"yexinhua@rtdata.cn"
] |
yexinhua@rtdata.cn
|
eb298cc9f67fdff0194ca8c9f6beac8c36c1144a
|
dab2c866842dbdb550080d78ba4049f1b71a8b61
|
/mathml-converters/src/main/java/com/formulasearchengine/mathmltools/converters/mathoid/EnrichedMathMLTransformer.java
|
395d7295ed7cdc313288da86f106c3d147c1e953
|
[
"Apache-2.0"
] |
permissive
|
gipplab/MathMLTools
|
a71187c3776fe60e07aa56d7a32c93af4eb3d15c
|
1597c66c3d0655a2110015cace8215a103138318
|
refs/heads/master
| 2023-03-12T22:18:32.580375
| 2022-10-28T10:22:16
| 2022-10-28T10:22:16
| 85,396,484
| 4
| 2
|
Apache-2.0
| 2023-03-12T22:18:28
| 2017-03-18T11:32:06
|
Java
|
UTF-8
|
Java
| false
| false
| 4,759
|
java
|
package com.formulasearchengine.mathmltools.converters.mathoid;
import com.formulasearchengine.mathmltools.helper.XMLHelper;
import com.formulasearchengine.mathmltools.io.XmlDocumentReader;
import com.formulasearchengine.mathmltools.mml.CMMLInfo;
import com.formulasearchengine.mathmltools.xml.NonWhitespaceNodeList;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.xpath.XPath;
import java.io.IOException;
/**
* Transformer from Enriched Math to a well formed MathML that contains
* pMML and cMML semantics.
* <p>
* It is mainly used after the MathoidConverter was called. Mathoid delivers an
* enriched MathML format, which only contains pMML. This transformator
* adds the cMML semantics and combines them in a new document.
*
* @author Vincent Stange
*/
public class EnrichedMathMLTransformer {
private static Logger logger = LogManager.getLogger(EnrichedMathMLTransformer.class);
private static final String XSL = "com/formulasearchengine/mathmltools/converters/mathoid/EnrichedMathML2Cmml.xsl";
private final Document readDocument;
/**
* Takes enriched MathML and build a document out of it. This will be
* further used by the transformer.
*
* @param eMathML The MathML the transformer will use
*/
public EnrichedMathMLTransformer(String eMathML) throws SAXException, IOException {
readDocument = XmlDocumentReader.parse(eMathML, false);
}
/**
* Transformers the enriched MathML to a well formed MathML that contains
* pMML and cMML semantics into a new document and returns it as a string.
* <p>
* This method still has a lot of flaws.
*
* @return String of the new formed document or null, if transformation failed.
* @throws Exception a lot could go wrong here: parser or transformer error
*/
public String getFullMathML() throws Exception {
XPath xPath = XMLHelper.namespaceAwareXpath("m", CMMLInfo.NS_MATHML);
Element semanticRoot = (Element) XMLHelper.getElementB(readDocument, xPath.compile("*//m:semantics"));
boolean hasSemanticEle = semanticRoot != null;
// get the first mrow element
NonWhitespaceNodeList mrowNodes = new NonWhitespaceNodeList(XMLHelper.getElementsB(readDocument, xPath.compile("*//m:mrow")));
Element mrowNode = (Element) mrowNodes.getFirstElement();
// secure the id field
copyIdField(mrowNode);
try {
// create the cmml apply node and then
// adopt the new cmml structure onto the original enriched mathml
Node tmpChild = XMLHelper.xslTransform(mrowNode, XSL).getFirstChild();
Node applyNode = readDocument.adoptNode(tmpChild.cloneNode(true));
// create a new "annotation-xml" node and append the created cmml structure
Element cmmlSemanticNode = readDocument.createElementNS(CMMLInfo.NS_MATHML, "annotation-xml");
cmmlSemanticNode.setAttribute("encoding", "MathML-Content");
cmmlSemanticNode.appendChild(applyNode);
// add the new "annotation-xml" to the semantics root
if (hasSemanticEle) {
semanticRoot.appendChild(cmmlSemanticNode);
} else {
// switch nodes around to include a noew semantics element
Node mathRoot = readDocument.getFirstChild();
Node tmpMrowNode = mathRoot.removeChild(mrowNode);
Element newSemanticRoot = readDocument.createElementNS(CMMLInfo.NS_MATHML, "semantics");
newSemanticRoot.appendChild(tmpMrowNode);
newSemanticRoot.appendChild(cmmlSemanticNode);
mathRoot.appendChild(newSemanticRoot);
}
} catch (Exception e) {
logger.error("enriched mathml transformation failed", e);
return null;
}
return XMLHelper.printDocument(readDocument.getFirstChild());
}
/**
* Copy the "data-semantic-id" attribute to "id", if it does not exist.
* Will recursively go over every child.
*
* @param readNode element to change
*/
void copyIdField(Element readNode) {
String newId = readNode.getAttribute("data-semantic-id");
if (!StringUtils.isEmpty(newId)) {
readNode.setAttribute("id", "p" + newId);
}
for (Node child : new NonWhitespaceNodeList(readNode.getChildNodes())) {
if (child instanceof Element) {
copyIdField((Element) child);
}
}
}
}
|
[
"andre.greiner-petter@t-online.de"
] |
andre.greiner-petter@t-online.de
|
6cf7c888d10ebe5f4626f97449a535258d0dc7ed
|
ac585cce1e2b6e551ec08387119ad47dc307114d
|
/JiYuspringbootDeGaoXiaoKeYanGuanLiXiTong/src/main/java/com/mryao/gxkygl/project/service/impl/FundServiceImpl.java
|
214af8c07a2aa556921425f395ea1e02134cfe89
|
[
"MIT"
] |
permissive
|
DGVY/ScienceManageSystem
|
35938eeb507807a742a55dce90428591f660faca
|
f5cbc19db37935251e4abba2aa483ef78bdb4177
|
refs/heads/master
| 2021-08-23T15:27:19.140361
| 2017-12-05T12:04:29
| 2017-12-05T12:04:29
| 113,174,320
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 601
|
java
|
package com.mryao.gxkygl.project.service.impl;
import com.mryao.gxkygl.common.base.dao.BaseRepository;
import com.mryao.gxkygl.common.base.service.Impl.BaseServiceImpl;
import com.mryao.gxkygl.project.entity.Fund;
import com.mryao.gxkygl.project.service.IFundService;
import org.springframework.stereotype.Service;
/**
* @author: yaohuaiying
* @Date: 2017/10/30 10:53
* @Description:
* @Version: 1.0
*/
@Service
public class FundServiceImpl extends BaseServiceImpl<Fund> implements IFundService {
public FundServiceImpl(BaseRepository<Fund> repository) {
super(repository);
}
}
|
[
"dgvylk@gmail.com"
] |
dgvylk@gmail.com
|
b3b63af712a1bd22659d2561da9eeab20943af55
|
614d50b567c426046515e976a44a005814aa0580
|
/core/src/main/java/org/eigenbase/sql/validate/SqlValidatorImpl.java
|
8596d1376b1ec1cd932f3d80dcca0b17baebf135
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
guilhermejccavalcanti/optiq
|
76b7f117a582d1f3fa284047a4cda7b9ae396d3b
|
b8022e45c9ef6e8c3ac792511b247816c4d6e929
|
refs/heads/master
| 2020-03-25T05:47:53.781191
| 2018-08-07T03:40:16
| 2018-08-07T03:40:16
| 143,466,381
| 0
| 0
|
Apache-2.0
| 2018-08-03T19:36:32
| 2018-08-03T19:36:32
| null |
UTF-8
|
Java
| false
| false
| 161,445
|
java
|
/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
package org.eigenbase.sql.validate;
import java.math.*;
import java.util.*;
import java.util.logging.*;
import org.eigenbase.reltype.*;
import org.eigenbase.resgen.*;
import org.eigenbase.resource.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.sql.parser.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.sql.util.*;
import org.eigenbase.trace.*;
import org.eigenbase.util.*;
import net.hydromatic.linq4j.Linq4j;
/**
* Default implementation of {@link SqlValidator}.
*
* @author jhyde
* @version $Id$
* @since Mar 3, 2005
*/
public class SqlValidatorImpl
implements SqlValidatorWithHints
{
//~ Static fields/initializers ---------------------------------------------
public static final Logger tracer = EigenbaseTrace.parserTracer;
/**
* Alias generated for the source table when rewriting UPDATE to MERGE.
*/
public static final String UPDATE_SRC_ALIAS = "SYS$SRC";
/**
* Alias generated for the target table when rewriting UPDATE to MERGE if no
* alias was specified by the user.
*/
public static final String UPDATE_TGT_ALIAS = "SYS$TGT";
/**
* Alias prefix generated for source columns when rewriting UPDATE to MERGE.
*/
public static final String UPDATE_ANON_PREFIX = "SYS$ANON";
//~ Enums ------------------------------------------------------------------
/**
* Validation status.
*/
public enum Status
{
/**
* Validation has not started for this scope.
*/
Unvalidated,
/**
* Validation is in progress for this scope.
*/
InProgress,
/**
* Validation has completed (perhaps unsuccessfully).
*/
Valid
}
//~ Instance fields --------------------------------------------------------
private final SqlOperatorTable opTab;
final SqlValidatorCatalogReader catalogReader;
/**
* Maps ParsePosition strings to the {@link SqlIdentifier} identifier
* objects at these positions
*/
protected final Map<String, IdInfo> idPositions =
new HashMap<String, IdInfo>();
/**
* Maps {@link SqlNode query node} objects to the {@link SqlValidatorScope}
* scope created from them}.
*/
protected final Map<SqlNode, SqlValidatorScope> scopes =
new IdentityHashMap<SqlNode, SqlValidatorScope>();
/**
* Maps a {@link SqlSelect} node to the scope used by its WHERE and HAVING
* clauses.
*/
private final Map<SqlSelect, SqlValidatorScope> whereScopes =
new IdentityHashMap<SqlSelect, SqlValidatorScope>();
/**
* Maps a {@link SqlSelect} node to the scope used by its SELECT and HAVING
* clauses.
*/
private final Map<SqlSelect, SqlValidatorScope> selectScopes =
new IdentityHashMap<SqlSelect, SqlValidatorScope>();
/**
* Maps a {@link SqlSelect} node to the scope used by its ORDER BY clause.
*/
private final Map<SqlSelect, SqlValidatorScope> orderScopes =
new IdentityHashMap<SqlSelect, SqlValidatorScope>();
/**
* Maps a {@link SqlSelect} node that is the argument to a CURSOR
* constructor to the scope of the result of that select node
*/
private final Map<SqlSelect, SqlValidatorScope> cursorScopes =
new IdentityHashMap<SqlSelect, SqlValidatorScope>();
/**
* Maps a {@link SqlNode node} to the {@link SqlValidatorNamespace
* namespace} which describes what columns they contain.
*/
protected final Map<SqlNode, SqlValidatorNamespace> namespaces =
new IdentityHashMap<SqlNode, SqlValidatorNamespace>();
/**
* Set of select expressions used as cursor definitions. In standard SQL,
* only the top-level SELECT is a cursor; Eigenbase extends this with
* cursors as inputs to table functions.
*/
private final Set<SqlNode> cursorSet = new IdentityHashSet<SqlNode>();
/**
* Stack of objects that maintain information about function calls. A stack
* is needed to handle nested function calls. The function call currently
* being validated is at the top of the stack.
*/
protected final Stack<FunctionParamInfo> functionCallStack =
new Stack<FunctionParamInfo>();
private int nextGeneratedId;
protected final RelDataTypeFactory typeFactory;
protected final RelDataType unknownType;
private final RelDataType booleanType;
/**
* Map of derived RelDataType for each node. This is an IdentityHashMap
* since in some cases (such as null literals) we need to discriminate by
* instance.
*/
private final Map<SqlNode, RelDataType> nodeToTypeMap =
new IdentityHashMap<SqlNode, RelDataType>();
private final AggFinder aggFinder = new AggFinder(false);
private final AggFinder aggOrOverFinder = new AggFinder(true);
private final SqlConformance conformance;
private final Map<SqlNode, SqlNode> originalExprs =
new HashMap<SqlNode, SqlNode>();
// REVIEW jvs 30-June-2006: subclasses may override shouldExpandIdentifiers
// in a way that ignores this; we should probably get rid of the protected
// method and always use this variable (or better, move preferences like
// this to a separate "parameter" class)
protected boolean expandIdentifiers;
protected boolean expandColumnReferences;
private boolean rewriteCalls;
// TODO jvs 11-Dec-2008: make this local to performUnconditionalRewrites
// if it's OK to expand the signature of that method.
private boolean validatingSqlMerge;
//~ Constructors -----------------------------------------------------------
/**
* Creates a validator.
*
* @param opTab Operator table
* @param catalogReader Catalog reader
* @param typeFactory Type factory
* @param conformance Compatibility mode
*/
protected SqlValidatorImpl(
SqlOperatorTable opTab,
SqlValidatorCatalogReader catalogReader,
RelDataTypeFactory typeFactory,
SqlConformance conformance)
{
Linq4j.requireNonNull(opTab);
Linq4j.requireNonNull(catalogReader);
Linq4j.requireNonNull(typeFactory);
Linq4j.requireNonNull(conformance);
this.opTab = opTab;
this.catalogReader = catalogReader;
this.typeFactory = typeFactory;
this.conformance = conformance;
// NOTE jvs 23-Dec-2003: This is used as the type for dynamic
// parameters and null literals until a real type is imposed for them.
unknownType = typeFactory.createSqlType(SqlTypeName.NULL);
booleanType = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
rewriteCalls = true;
expandColumnReferences = true;
}
//~ Methods ----------------------------------------------------------------
public SqlConformance getConformance()
{
return conformance;
}
public SqlValidatorCatalogReader getCatalogReader()
{
return catalogReader;
}
public SqlOperatorTable getOperatorTable()
{
return opTab;
}
public RelDataTypeFactory getTypeFactory()
{
return typeFactory;
}
public RelDataType getUnknownType()
{
return unknownType;
}
public SqlNodeList expandStar(
SqlNodeList selectList,
SqlSelect select,
boolean includeSystemVars)
{
List<SqlNode> list = new ArrayList<SqlNode>();
List<Map.Entry<String, RelDataType>> types =
new ArrayList<Map.Entry<String, RelDataType>>();
for (int i = 0; i < selectList.size(); i++) {
final SqlNode selectItem = selectList.get(i);
expandSelectItem(
selectItem,
select,
list,
new LinkedHashSet<String>(),
types,
includeSystemVars);
}
getRawSelectScope(select).setExpandedSelectList(list);
return new SqlNodeList(list, SqlParserPos.ZERO);
}
// implement SqlValidator
public void declareCursor(SqlSelect select, SqlValidatorScope parentScope)
{
cursorSet.add(select);
// add the cursor to a map that maps the cursor to its select based on
// the position of the cursor relative to other cursors in that call
FunctionParamInfo funcParamInfo = functionCallStack.peek();
Map<Integer, SqlSelect> cursorMap = funcParamInfo.cursorPosToSelectMap;
int numCursors = cursorMap.size();
cursorMap.put(numCursors, select);
// create a namespace associated with the result of the select
// that is the argument to the cursor constructor; register it
// with a scope corresponding to the cursor
SelectScope cursorScope = new SelectScope(parentScope, null, select);
cursorScopes.put(select, cursorScope);
final SelectNamespace selectNs = createSelectNamespace(select, select);
String alias = deriveAlias(select, nextGeneratedId++);
registerNamespace(cursorScope, alias, selectNs, false);
}
// implement SqlValidator
public void pushFunctionCall()
{
FunctionParamInfo funcInfo = new FunctionParamInfo();
functionCallStack.push(funcInfo);
}
// implement SqlValidator
public void popFunctionCall()
{
functionCallStack.pop();
}
// implement SqlValidator
public String getParentCursor(String columnListParamName)
{
FunctionParamInfo funcParamInfo = functionCallStack.peek();
Map<String, String> parentCursorMap =
funcParamInfo.columnListParamToParentCursorMap;
return parentCursorMap.get(columnListParamName);
}
/**
* If <code>selectItem</code> is "*" or "TABLE.*", expands it and returns
* true; otherwise writes the unexpanded item.
*
* @param selectItem Select-list item
* @param select Containing select clause
* @param selectItems List that expanded items are written to
* @param aliases Set of aliases
* @param types List of data types in alias order
* @param includeSystemVars If true include system vars in lists
*
* @return Whether the node was expanded
*/
private boolean expandSelectItem(
final SqlNode selectItem,
SqlSelect select,
List<SqlNode> selectItems,
Set<String> aliases,
List<Map.Entry<String, RelDataType>> types,
final boolean includeSystemVars)
{
final SelectScope scope = (SelectScope) getWhereScope(select);
if (selectItem instanceof SqlIdentifier) {
SqlIdentifier identifier = (SqlIdentifier) selectItem;
if ((identifier.names.length == 1)
&& identifier.names[0].equals("*"))
{
SqlParserPos starPosition = identifier.getParserPosition();
for (Pair<String, SqlValidatorNamespace> p : scope.children) {
final SqlNode from = p.right.getNode();
final SqlValidatorNamespace fromNs = getNamespace(from);
assert fromNs != null;
final RelDataType rowType = fromNs.getRowType();
for (RelDataTypeField field : rowType.getFieldList()) {
String columnName = field.getName();
// TODO: do real implicit collation here
final SqlNode exp =
new SqlIdentifier(
new String[] { p.left, columnName },
starPosition);
addToSelectList(
selectItems,
aliases,
types,
exp,
scope,
includeSystemVars);
}
}
return true;
} else if (
(identifier.names.length == 2)
&& identifier.names[1].equals("*"))
{
final String tableName = identifier.names[0];
SqlParserPos starPosition = identifier.getParserPosition();
final SqlValidatorNamespace childNs = scope.getChild(tableName);
if (childNs == null) {
// e.g. "select r.* from e"
throw newValidationError(
identifier.getComponent(0),
EigenbaseResource.instance().UnknownIdentifier.ex(
tableName));
}
final SqlNode from = childNs.getNode();
final SqlValidatorNamespace fromNs = getNamespace(from);
assert fromNs != null;
final RelDataType rowType = fromNs.getRowType();
for (RelDataTypeField field : rowType.getFieldList()) {
String columnName = field.getName();
// TODO: do real implicit collation here
final SqlIdentifier exp =
new SqlIdentifier(
new String[] { tableName, columnName },
starPosition);
addToSelectList(
selectItems,
aliases,
types,
exp,
scope,
includeSystemVars);
}
return true;
}
}
// Expand the select item: fully-qualify columns, and convert
// parentheses-free functions such as LOCALTIME into explicit function
// calls.
SqlNode expanded = expand(selectItem, scope);
final String alias =
deriveAlias(
selectItem,
aliases.size());
// If expansion has altered the natural alias, supply an explicit 'AS'.
if (expanded != selectItem) {
String newAlias =
deriveAlias(
expanded,
aliases.size());
if (!newAlias.equals(alias)) {
expanded =
SqlStdOperatorTable.asOperator.createCall(
selectItem.getParserPosition(),
expanded,
new SqlIdentifier(alias, SqlParserPos.ZERO));
deriveTypeImpl(scope, expanded);
}
}
selectItems.add(expanded);
aliases.add(alias);
final RelDataType type = deriveType(scope, selectItem);
setValidatedNodeTypeImpl(selectItem, type);
types.add(Pair.of(alias, type));
return false;
}
public SqlNode validate(SqlNode topNode)
{
SqlValidatorScope scope = new EmptyScope(this);
final SqlNode topNode2 = validateScopedExpression(topNode, scope);
final RelDataType type = getValidatedNodeType(topNode2);
Util.discard(type);
return topNode2;
}
public List<SqlMoniker> lookupHints(SqlNode topNode, SqlParserPos pos)
{
SqlValidatorScope scope = new EmptyScope(this);
SqlNode outermostNode = performUnconditionalRewrites(topNode, false);
cursorSet.add(outermostNode);
if (outermostNode.isA(SqlKind.TOP_LEVEL)) {
registerQuery(
scope,
null,
outermostNode,
outermostNode,
null,
false);
}
final SqlValidatorNamespace ns = getNamespace(outermostNode);
if (ns == null) {
throw Util.newInternal("Not a query: " + outermostNode);
}
List<SqlMoniker> hintList = new ArrayList<SqlMoniker>();
lookupSelectHints(ns, pos, hintList);
return hintList;
}
public SqlMoniker lookupQualifiedName(SqlNode topNode, SqlParserPos pos)
{
final String posString = pos.toString();
IdInfo info = idPositions.get(posString);
if (info != null) {
return new SqlIdentifierMoniker(info.scope.fullyQualify(info.id));
} else {
return null;
}
}
/**
* Looks up completion hints for a syntactically correct select SQL that has
* been parsed into an expression tree.
*
* @param select the Select node of the parsed expression tree
* @param pos indicates the position in the sql statement we want to get
* completion hints for
* @param hintList list of {@link SqlMoniker} (sql identifiers) that can
* fill in at the indicated position
*/
void lookupSelectHints(
SqlSelect select,
SqlParserPos pos,
List<SqlMoniker> hintList)
{
IdInfo info = idPositions.get(pos.toString());
if ((info == null) || (info.scope == null)) {
SqlNode fromNode = select.getFrom();
final SqlValidatorScope fromScope = getFromScope(select);
lookupFromHints(fromNode, fromScope, pos, hintList);
} else {
lookupNameCompletionHints(
info.scope,
Arrays.asList(info.id.names),
info.id.getParserPosition(),
hintList);
}
}
private void lookupSelectHints(
SqlValidatorNamespace ns,
SqlParserPos pos,
List<SqlMoniker> hintList)
{
final SqlNode node = ns.getNode();
if (node instanceof SqlSelect) {
lookupSelectHints((SqlSelect) node, pos, hintList);
}
}
private void lookupFromHints(
SqlNode node,
SqlValidatorScope scope,
SqlParserPos pos,
List<SqlMoniker> hintList)
{
final SqlValidatorNamespace ns = getNamespace(node);
if (ns.isWrapperFor(IdentifierNamespace.class)) {
IdentifierNamespace idNs = ns.unwrap(IdentifierNamespace.class);
final SqlIdentifier id = idNs.getId();
for (int i = 0; i < id.names.length; i++) {
if (pos.toString().equals(
id.getComponent(i).getParserPosition().toString()))
{
List<SqlMoniker> objNames = new ArrayList<SqlMoniker>();
SqlValidatorUtil.getSchemaObjectMonikers(
getCatalogReader(),
Arrays.asList(id.names).subList(0, i + 1),
objNames);
for (SqlMoniker objName : objNames) {
if (objName.getType() != SqlMonikerType.Function) {
hintList.add(objName);
}
}
return;
}
}
}
switch (node.getKind()) {
case JOIN:
lookupJoinHints((SqlJoin) node, scope, pos, hintList);
break;
default:
lookupSelectHints(ns, pos, hintList);
break;
}
}
private void lookupJoinHints(
SqlJoin join,
SqlValidatorScope scope,
SqlParserPos pos,
List<SqlMoniker> hintList)
{
SqlNode left = join.getLeft();
SqlNode right = join.getRight();
SqlNode condition = join.getCondition();
lookupFromHints(left, scope, pos, hintList);
if (hintList.size() > 0) {
return;
}
lookupFromHints(right, scope, pos, hintList);
if (hintList.size() > 0) {
return;
}
SqlJoinOperator.ConditionType conditionType = join.getConditionType();
final SqlValidatorScope joinScope = scopes.get(join);
switch (conditionType) {
case On:
condition.findValidOptions(this, joinScope, pos, hintList);
return;
default:
// No suggestions.
// Not supporting hints for other types such as 'Using' yet.
return;
}
}
/**
* Populates a list of all the valid alternatives for an identifier.
*
* @param scope Validation scope
* @param names Components of the identifier
* @param pos position
* @param hintList a list of valid options
*/
public final void lookupNameCompletionHints(
SqlValidatorScope scope,
List<String> names,
SqlParserPos pos,
List<SqlMoniker> hintList)
{
// Remove the last part of name - it is a dummy
List<String> subNames = names.subList(0, names.size() - 1);
if (subNames.size() > 0) {
// If there's a prefix, resolve it to a namespace.
SqlValidatorNamespace ns = null;
for (String name : subNames) {
if (ns == null) {
ns = scope.resolve(name, null, null);
} else {
ns = ns.lookupChild(name);
}
if (ns == null) {
break;
}
}
if (ns != null) {
RelDataType rowType = ns.getRowType();
for (RelDataTypeField field : rowType.getFieldList()) {
hintList.add(
new SqlMonikerImpl(
field.getName(),
SqlMonikerType.Column));
}
}
// builtin function names are valid completion hints when the
// identifier has only 1 name part
findAllValidFunctionNames(names, this, hintList, pos);
} else {
// No prefix; use the children of the current scope (that is,
// the aliases in the FROM clause)
scope.findAliases(hintList);
// If there's only one alias, add all child columns
SelectScope selectScope =
SqlValidatorUtil.getEnclosingSelectScope(scope);
if ((selectScope != null)
&& (selectScope.getChildren().size() == 1))
{
RelDataType rowType =
selectScope.getChildren().get(0).getRowType();
for (RelDataTypeField field : rowType.getFieldList()) {
hintList.add(
new SqlMonikerImpl(
field.getName(),
SqlMonikerType.Column));
}
}
}
findAllValidUdfNames(names, this, hintList);
}
private static void findAllValidUdfNames(
List<String> names,
SqlValidator validator,
List<SqlMoniker> result)
{
List<SqlMoniker> objNames = new ArrayList<SqlMoniker>();
SqlValidatorUtil.getSchemaObjectMonikers(
validator.getCatalogReader(),
names,
objNames);
for (SqlMoniker objName : objNames) {
if (objName.getType() == SqlMonikerType.Function) {
result.add(objName);
}
}
}
private static void findAllValidFunctionNames(
List<String> names,
SqlValidator validator,
List<SqlMoniker> result,
SqlParserPos pos)
{
// a function name can only be 1 part
if (names.size() > 1) {
return;
}
for (SqlOperator op : validator.getOperatorTable().getOperatorList()) {
SqlIdentifier curOpId =
new SqlIdentifier(
op.getName(),
pos);
final SqlCall call =
SqlUtil.makeCall(
validator.getOperatorTable(),
curOpId);
if (call != null) {
result.add(
new SqlMonikerImpl(
op.getName(),
SqlMonikerType.Function));
} else {
if ((op.getSyntax() == SqlSyntax.Function)
|| (op.getSyntax() == SqlSyntax.Prefix))
{
if (op.getOperandTypeChecker() != null) {
String sig = op.getAllowedSignatures();
sig = sig.replaceAll("'", "");
result.add(
new SqlMonikerImpl(
sig,
SqlMonikerType.Function));
continue;
}
result.add(
new SqlMonikerImpl(
op.getName(),
SqlMonikerType.Function));
}
}
}
}
public SqlNode validateParameterizedExpression(
SqlNode topNode,
final Map<String, RelDataType> nameToTypeMap)
{
SqlValidatorScope scope = new ParameterScope(this, nameToTypeMap);
return validateScopedExpression(topNode, scope);
}
private SqlNode validateScopedExpression(
SqlNode topNode,
SqlValidatorScope scope)
{
SqlNode outermostNode = performUnconditionalRewrites(topNode, false);
cursorSet.add(outermostNode);
if (tracer.isLoggable(Level.FINER)) {
tracer.finer(
"After unconditional rewrite: "
+ outermostNode.toString());
}
if (outermostNode.isA(SqlKind.TOP_LEVEL)) {
registerQuery(
scope,
null,
outermostNode,
outermostNode,
null,
false);
}
outermostNode.validate(this, scope);
if (!outermostNode.isA(SqlKind.TOP_LEVEL)) {
// force type derivation so that we can provide it to the
// caller later without needing the scope
deriveType(scope, outermostNode);
}
if (tracer.isLoggable(Level.FINER)) {
tracer.finer("After validation: " + outermostNode.toString());
}
return outermostNode;
}
public void validateQuery(SqlNode node, SqlValidatorScope scope)
{
final SqlValidatorNamespace ns = getNamespace(node);
if (ns == null) {
throw Util.newInternal("Not a query: " + node);
}
if (node.getKind() == SqlKind.TABLESAMPLE) {
SqlNode [] operands = ((SqlCall) node).operands;
SqlSampleSpec sampleSpec = SqlLiteral.sampleValue(operands[1]);
if (sampleSpec instanceof SqlSampleSpec.SqlTableSampleSpec) {
validateFeature(
EigenbaseResource.instance().SQLFeature_T613,
node.getParserPosition());
} else if (
sampleSpec
instanceof SqlSampleSpec.SqlSubstitutionSampleSpec)
{
validateFeature(
EigenbaseResource.instance()
.SQLFeatureExt_T613_Substitution,
node.getParserPosition());
}
}
validateNamespace(ns);
validateAccess(
node,
ns.getTable(),
SqlAccessEnum.SELECT);
}
/**
* Validates a namespace.
*/
protected void validateNamespace(final SqlValidatorNamespace namespace)
{
namespace.validate();
setValidatedNodeType(
namespace.getNode(),
namespace.getRowType());
}
public SqlValidatorScope getCursorScope(SqlSelect select)
{
return cursorScopes.get(select);
}
public SqlValidatorScope getWhereScope(SqlSelect select)
{
return whereScopes.get(select);
}
public SqlValidatorScope getSelectScope(SqlSelect select)
{
return selectScopes.get(select);
}
public SelectScope getRawSelectScope(SqlSelect select)
{
SqlValidatorScope scope = getSelectScope(select);
if (scope instanceof AggregatingSelectScope) {
scope = ((AggregatingSelectScope) scope).getParent();
}
return (SelectScope) scope;
}
public SqlValidatorScope getHavingScope(SqlSelect select)
{
// Yes, it's the same as getSelectScope
return selectScopes.get(select);
}
public SqlValidatorScope getGroupScope(SqlSelect select)
{
// Yes, it's the same as getWhereScope
return whereScopes.get(select);
}
public SqlValidatorScope getFromScope(SqlSelect select)
{
return scopes.get(select);
}
public SqlValidatorScope getOrderScope(SqlSelect select)
{
return orderScopes.get(select);
}
public SqlValidatorScope getJoinScope(SqlNode node)
{
switch (node.getKind()) {
case AS:
return getJoinScope(((SqlCall) node).operands[0]);
default:
return scopes.get(node);
}
}
public SqlValidatorScope getOverScope(SqlNode node)
{
return scopes.get(node);
}
/**
* Returns the appropriate scope for validating a particular clause of a
* SELECT statement.
*
* <p>Consider SELECT * FROM foo WHERE EXISTS ( SELECT deptno AS x FROM emp,
* dept WHERE emp.deptno = 5 GROUP BY deptno ORDER BY x) In FROM, you can
* only see 'foo'. In WHERE, GROUP BY and SELECT, you can see 'emp', 'dept',
* and 'foo'. In ORDER BY, you can see the column alias 'x', 'emp', 'dept',
* and 'foo'.
*/
public SqlValidatorScope getScope(SqlSelect select, int operandType)
{
switch (operandType) {
case SqlSelect.FROM_OPERAND:
return scopes.get(select);
case SqlSelect.WHERE_OPERAND:
case SqlSelect.GROUP_OPERAND:
return whereScopes.get(select);
case SqlSelect.HAVING_OPERAND:
case SqlSelect.SELECT_OPERAND:
return selectScopes.get(select);
case SqlSelect.ORDER_OPERAND:
return orderScopes.get(select);
default:
throw Util.newInternal("Unexpected operandType " + operandType);
}
}
public SqlValidatorNamespace getNamespace(SqlNode node)
{
switch (node.getKind()) {
case AS:
// AS has a namespace if it has a column list 'AS t (c1, c2, ...)'
final SqlValidatorNamespace ns = namespaces.get(node);
if (ns != null) {
return ns;
}
// fall through
case OVER:
case COLLECTION_TABLE:
case ORDER_BY:
case TABLESAMPLE:
return getNamespace(((SqlCall) node).operands[0]);
default:
return namespaces.get(node);
}
}
/**
* Performs expression rewrites which are always used unconditionally. These
* rewrites massage the expression tree into a standard form so that the
* rest of the validation logic can be simpler.
*
* @param node expression to be rewritten
* @param underFrom whether node appears directly under a FROM clause
*
* @return rewritten expression
*/
protected SqlNode performUnconditionalRewrites(
SqlNode node,
boolean underFrom)
{
if (node == null) {
return node;
}
SqlNode newOperand;
// first transform operands and invoke generic call rewrite
if (node instanceof SqlCall) {
if (node instanceof SqlMerge) {
validatingSqlMerge = true;
}
SqlCall call = (SqlCall) node;
final SqlKind kind = call.getKind();
final SqlNode [] operands = call.getOperands();
for (int i = 0; i < operands.length; i++) {
SqlNode operand = operands[i];
boolean childUnderFrom;
if (kind == SqlKind.SELECT) {
childUnderFrom = (i == SqlSelect.FROM_OPERAND);
} else if (kind == SqlKind.AS && (i == 0)) {
// for an aliased expression, it is under FROM if
// the AS expression is under FROM
childUnderFrom = underFrom;
} else {
childUnderFrom = false;
}
newOperand =
performUnconditionalRewrites(operand, childUnderFrom);
if (newOperand != null) {
call.setOperand(i, newOperand);
}
}
if (call.getOperator() instanceof SqlFunction) {
SqlFunction function = (SqlFunction) call.getOperator();
if (function.getFunctionType() == null) {
// This function hasn't been resolved yet. Perform
// a half-hearted resolution now in case it's a
// builtin function requiring special casing. If it's
// not, we'll handle it later during overload
// resolution.
List<SqlOperator> overloads =
opTab.lookupOperatorOverloads(
function.getNameAsId(),
null,
SqlSyntax.Function);
if (overloads.size() == 1) {
call.setOperator(overloads.get(0));
}
}
}
if (rewriteCalls) {
node = call.getOperator().rewriteCall(this, call);
}
} else if (node instanceof SqlNodeList) {
SqlNodeList list = (SqlNodeList) node;
for (int i = 0, count = list.size(); i < count; i++) {
SqlNode operand = list.get(i);
newOperand =
performUnconditionalRewrites(
operand,
false);
if (newOperand != null) {
list.getList().set(i, newOperand);
}
}
}
// now transform node itself
final SqlKind kind = node.getKind();
switch (kind) {
case VALUES:
if (underFrom || true) {
// leave FROM (VALUES(...)) [ AS alias ] clauses alone,
// otherwise they grow cancerously if this rewrite is invoked
// over and over
return node;
} else {
final SqlNodeList selectList =
new SqlNodeList(SqlParserPos.ZERO);
selectList.add(new SqlIdentifier("*", SqlParserPos.ZERO));
return SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
node,
null,
null,
null,
null,
null,
null,
null,
node.getParserPosition());
}
case ORDER_BY:
{
SqlCall orderBy = (SqlCall) node;
final SqlNode[] operands = orderBy.getOperands();
SqlNode query = operands[SqlOrderByOperator.QUERY_OPERAND];
SqlNodeList orderList =
(SqlNodeList) operands[SqlOrderByOperator.ORDER_OPERAND];
SqlNode offset = operands[SqlOrderByOperator.OFFSET_OPERAND];
SqlNode fetch = operands[SqlOrderByOperator.FETCH_OPERAND];
if (query instanceof SqlSelect) {
SqlSelect select = (SqlSelect) query;
// Don't clobber existing ORDER BY. It may be needed for
// an order-sensitive function like RANK.
if (select.getOrderList() == null) {
// push ORDER BY into existing select
select.setOperand(SqlSelect.ORDER_OPERAND, orderList);
select.setOperand(SqlSelect.OFFSET_OPERAND, offset);
select.setOperand(SqlSelect.FETCH_OPERAND, fetch);
return select;
}
}
final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
selectList.add(new SqlIdentifier("*", SqlParserPos.ZERO));
return SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
query,
null,
null,
null,
null,
orderList,
offset,
fetch,
SqlParserPos.ZERO);
}
case EXPLICIT_TABLE:
{
// (TABLE t) is equivalent to (SELECT * FROM t)
SqlCall call = (SqlCall) node;
final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
selectList.add(new SqlIdentifier("*", SqlParserPos.ZERO));
return SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
call.getOperands()[0],
null,
null,
null,
null,
null,
null,
null,
SqlParserPos.ZERO);
}
case DELETE:
{
SqlDelete call = (SqlDelete) node;
SqlSelect select = createSourceSelectForDelete(call);
call.setOperand(SqlDelete.SOURCE_SELECT_OPERAND, select);
break;
}
case UPDATE:
{
SqlUpdate call = (SqlUpdate) node;
SqlSelect select = createSourceSelectForUpdate(call);
call.setOperand(SqlUpdate.SOURCE_SELECT_OPERAND, select);
// See if we're supposed to rewrite UPDATE to MERGE
// (unless this is the UPDATE clause of a MERGE,
// in which case leave it alone).
if (!validatingSqlMerge) {
SqlNode selfJoinSrcExpr =
getSelfJoinExprForUpdate(
call.getTargetTable(),
UPDATE_SRC_ALIAS);
if (selfJoinSrcExpr != null) {
node = rewriteUpdateToMerge(call, selfJoinSrcExpr);
}
}
break;
}
case MERGE:
{
SqlMerge call = (SqlMerge) node;
rewriteMerge(call);
break;
}
}
return node;
}
private void rewriteMerge(SqlMerge call)
{
SqlNodeList selectList;
SqlUpdate updateStmt = call.getUpdateCall();
if (updateStmt != null) {
// if we have an update statement, just clone the select list
// from the update statement's source since it's the same as
// what we want for the select list of the merge source -- '*'
// followed by the update set expressions
selectList =
(SqlNodeList) updateStmt.getSourceSelect().getSelectList()
.clone();
} else {
// otherwise, just use select *
selectList = new SqlNodeList(SqlParserPos.ZERO);
selectList.add(new SqlIdentifier("*", SqlParserPos.ZERO));
}
SqlNode targetTable = call.getTargetTable();
if (call.getAlias() != null) {
targetTable =
SqlValidatorUtil.addAlias(
targetTable,
call.getAlias().getSimple());
}
// Provided there is an insert substatement, the source select for
// the merge is a left outer join between the source in the USING
// clause and the target table; otherwise, the join is just an
// inner join. Need to clone the source table reference in order
// for validation to work
SqlNode sourceTableRef = call.getSourceTableRef();
SqlInsert insertCall = call.getInsertCall();
SqlJoinOperator.JoinType joinType =
(insertCall == null) ? SqlJoinOperator.JoinType.Inner
: SqlJoinOperator.JoinType.Left;
SqlNode leftJoinTerm = (SqlNode) sourceTableRef.clone();
SqlNode outerJoin =
SqlStdOperatorTable.joinOperator.createCall(
leftJoinTerm,
SqlLiteral.createBoolean(false, SqlParserPos.ZERO),
joinType.symbol(SqlParserPos.ZERO),
targetTable,
SqlJoinOperator.ConditionType.On.symbol(SqlParserPos.ZERO),
call.getCondition(),
SqlParserPos.ZERO);
SqlSelect select =
SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
outerJoin,
null,
null,
null,
null,
null,
null,
null,
SqlParserPos.ZERO);
call.setOperand(SqlMerge.SOURCE_SELECT_OPERAND, select);
// Source for the insert call is a select of the source table
// reference with the select list being the value expressions;
// note that the values clause has already been converted to a
// select on the values row constructor; so we need to extract
// that via the from clause on the select
if (insertCall != null) {
SqlSelect valuesSelect = (SqlSelect) insertCall.getSource();
SqlCall valuesCall = (SqlCall) valuesSelect.getFrom();
SqlCall rowCall = (SqlCall) valuesCall.getOperands()[0];
selectList =
new SqlNodeList(
Arrays.asList(rowCall.getOperands()),
SqlParserPos.ZERO);
SqlNode insertSource = (SqlNode) sourceTableRef.clone();
select =
SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
insertSource,
null,
null,
null,
null,
null,
null,
null,
SqlParserPos.ZERO);
insertCall.setOperand(SqlInsert.SOURCE_OPERAND, select);
}
}
private SqlNode rewriteUpdateToMerge(
SqlUpdate updateCall,
SqlNode selfJoinSrcExpr)
{
// Make sure target has an alias.
if (updateCall.getAlias() == null) {
updateCall.setOperand(
SqlUpdate.ALIAS_OPERAND,
new SqlIdentifier(UPDATE_TGT_ALIAS, SqlParserPos.ZERO));
}
SqlNode selfJoinTgtExpr =
getSelfJoinExprForUpdate(
updateCall.getTargetTable(),
updateCall.getAlias().getSimple());
assert (selfJoinTgtExpr != null);
// Create join condition between source and target exprs,
// creating a conjunction with the user-level WHERE
// clause if one was supplied
SqlNode condition = updateCall.getCondition();
SqlNode selfJoinCond =
SqlStdOperatorTable.equalsOperator.createCall(
SqlParserPos.ZERO,
selfJoinSrcExpr,
selfJoinTgtExpr);
if (condition == null) {
condition = selfJoinCond;
} else {
condition =
SqlStdOperatorTable.andOperator.createCall(
SqlParserPos.ZERO,
selfJoinCond,
condition);
}
SqlIdentifier target =
(SqlIdentifier) updateCall.getTargetTable().clone(
SqlParserPos.ZERO);
// For the source, we need to anonymize the fields, so
// that for a statement like UPDATE T SET I = I + 1,
// there's no ambiguity for the "I" in "I + 1";
// this is OK because the source and target have
// identical values due to the self-join.
// Note that we anonymize the source rather than the
// target because downstream, the optimizer rules
// don't want to see any projection on top of the target.
IdentifierNamespace ns =
new IdentifierNamespace(
this,
target,
null);
RelDataType rowType = ns.getRowType();
SqlNode source = updateCall.getTargetTable().clone(SqlParserPos.ZERO);
final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
int i = 1;
for (RelDataTypeField field : rowType.getFieldList()) {
SqlIdentifier col =
new SqlIdentifier(
field.getName(),
SqlParserPos.ZERO);
selectList.add(
SqlValidatorUtil.addAlias(col, UPDATE_ANON_PREFIX + i));
++i;
}
source =
SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
source,
null,
null,
null,
null,
null,
null,
null,
SqlParserPos.ZERO);
source = SqlValidatorUtil.addAlias(source, UPDATE_SRC_ALIAS);
SqlMerge mergeCall =
new SqlMerge(
SqlStdOperatorTable.mergeOperator,
target,
condition,
source,
updateCall,
null,
updateCall.getAlias(),
updateCall.getParserPosition());
rewriteMerge(mergeCall);
return mergeCall;
}
/**
* Allows a subclass to provide information about how to convert an UPDATE
* into a MERGE via self-join. If this method returns null, then no such
* conversion takes place. Otherwise, this method should return a suitable
* unique identifier expression for the given table.
*
* @param table identifier for table being updated
* @param alias alias to use for qualifying columns in expression, or null
* for unqualified references; if this is equal to {@value
* #UPDATE_SRC_ALIAS}, then column references have been anonymized to
* "SYS$ANONx", where x is the 1-based column number.
*
* @return expression for unique identifier, or null to prevent conversion
*/
protected SqlNode getSelfJoinExprForUpdate(
SqlIdentifier table,
String alias)
{
return null;
}
/**
* Creates the SELECT statement that putatively feeds rows into an UPDATE
* statement to be updated.
*
* @param call Call to the UPDATE operator
*
* @return select statement
*/
protected SqlSelect createSourceSelectForUpdate(SqlUpdate call)
{
final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
selectList.add(new SqlIdentifier("*", SqlParserPos.ZERO));
int ordinal = 0;
for (SqlNode exp : call.getSourceExpressionList()) {
// Force unique aliases to avoid a duplicate for Y with
// SET X=Y
String alias = SqlUtil.deriveAliasFromOrdinal(ordinal);
selectList.add(SqlValidatorUtil.addAlias(exp, alias));
++ordinal;
}
SqlNode sourceTable = call.getTargetTable();
if (call.getAlias() != null) {
sourceTable =
SqlValidatorUtil.addAlias(
sourceTable,
call.getAlias().getSimple());
}
return SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
sourceTable,
call.getCondition(),
null,
null,
null,
null,
null,
null,
SqlParserPos.ZERO);
}
/**
* Creates the SELECT statement that putatively feeds rows into a DELETE
* statement to be deleted.
*
* @param call Call to the DELETE operator
*
* @return select statement
*/
protected SqlSelect createSourceSelectForDelete(SqlDelete call)
{
final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO);
selectList.add(new SqlIdentifier("*", SqlParserPos.ZERO));
SqlNode sourceTable = call.getTargetTable();
if (call.getAlias() != null) {
sourceTable =
SqlValidatorUtil.addAlias(
sourceTable,
call.getAlias().getSimple());
}
return SqlStdOperatorTable.selectOperator.createCall(
null,
selectList,
sourceTable,
call.getCondition(),
null,
null,
null,
null,
null,
null,
SqlParserPos.ZERO);
}
/** Returns null if there is no common type. E.g. if the rows have a
* different number of columns. */
RelDataType getTableConstructorRowType(
SqlCall values,
SqlValidatorScope scope)
{
assert values.getOperands().length >= 1;
List<RelDataType> rowTypes = new ArrayList<RelDataType>();
for (int iRow = 0; iRow < values.getOperands().length; ++iRow) {
final SqlNode operand = values.getOperands()[iRow];
assert (operand.getKind() == SqlKind.ROW);
SqlCall rowConstructor = (SqlCall) operand;
// REVIEW jvs 10-Sept-2003: Once we support single-row queries as
// rows, need to infer aliases from there.
SqlNode [] operands = rowConstructor.getOperands();
final List<String> aliasList = new ArrayList<String>();
final List<RelDataType> typeList = new ArrayList<RelDataType>();
for (int iCol = 0; iCol < operands.length; ++iCol) {
final String alias = deriveAlias(operands[iCol], iCol);
aliasList.add(alias);
final RelDataType type = deriveType(scope, operands[iCol]);
typeList.add(type);
}
rowTypes.add(typeFactory.createStructType(typeList, aliasList));
}
if (values.getOperands().length == 1) {
// TODO jvs 10-Oct-2005: get rid of this workaround once
// leastRestrictive can handle all cases
return rowTypes.get(0);
}
return typeFactory.leastRestrictive(rowTypes);
}
public RelDataType getValidatedNodeType(SqlNode node)
{
RelDataType type = getValidatedNodeTypeIfKnown(node);
if (type == null) {
throw Util.needToImplement(node);
} else {
return type;
}
}
public RelDataType getValidatedNodeTypeIfKnown(SqlNode node)
{
final RelDataType type = nodeToTypeMap.get(node);
if (type != null) {
return type;
}
final SqlValidatorNamespace ns = getNamespace(node);
if (ns != null) {
return ns.getRowType();
}
final SqlNode original = originalExprs.get(node);
if (original != null) {
return getValidatedNodeType(original);
}
return null;
}
public void setValidatedNodeType(
SqlNode node,
RelDataType type)
{
setValidatedNodeTypeImpl(node, type);
}
public void removeValidatedNodeType(SqlNode node)
{
nodeToTypeMap.remove(node);
}
void setValidatedNodeTypeImpl(SqlNode node, RelDataType type)
{
Util.pre(type != null, "type != null");
Util.pre(node != null, "node != null");
if (type.equals(unknownType)) {
// don't set anything until we know what it is, and don't overwrite
// a known type with the unknown type
return;
}
nodeToTypeMap.put(node, type);
}
public RelDataType deriveType(
SqlValidatorScope scope,
SqlNode expr)
{
Util.pre(scope != null, "scope != null");
Util.pre(expr != null, "expr != null");
// if we already know the type, no need to re-derive
RelDataType type = nodeToTypeMap.get(expr);
if (type != null) {
return type;
}
final SqlValidatorNamespace ns = getNamespace(expr);
if (ns != null) {
return ns.getRowType();
}
type = deriveTypeImpl(scope, expr);
Util.permAssert(
type != null,
"SqlValidator.deriveTypeInternal returned null");
setValidatedNodeTypeImpl(expr, type);
return type;
}
/**
* Derives the type of a node.
*
* @post return != null
*/
RelDataType deriveTypeImpl(
SqlValidatorScope scope,
SqlNode operand)
{
DeriveTypeVisitor v = new DeriveTypeVisitor(scope);
return operand.accept(v);
}
public RelDataType deriveConstructorType(
SqlValidatorScope scope,
SqlCall call,
SqlFunction unresolvedConstructor,
SqlFunction resolvedConstructor,
RelDataType [] argTypes)
{
SqlIdentifier sqlIdentifier = unresolvedConstructor.getSqlIdentifier();
assert (sqlIdentifier != null);
RelDataType type = catalogReader.getNamedType(sqlIdentifier);
if (type == null) {
// TODO jvs 12-Feb-2005: proper type name formatting
throw newValidationError(
sqlIdentifier,
EigenbaseResource.instance().UnknownDatatypeName.ex(
sqlIdentifier.toString()));
}
if (resolvedConstructor == null) {
if (call.getOperands().length > 0) {
// This is not a default constructor invocation, and
// no user-defined constructor could be found
handleUnresolvedFunction(call, unresolvedConstructor, argTypes);
}
} else {
SqlCall testCall =
resolvedConstructor.createCall(
call.getParserPosition(),
call.getOperands());
RelDataType returnType =
resolvedConstructor.validateOperands(
this,
scope,
testCall);
assert (type == returnType);
}
if (shouldExpandIdentifiers()) {
if (resolvedConstructor != null) {
call.setOperator(resolvedConstructor);
} else {
// fake a fully-qualified call to the default constructor
SqlReturnTypeInference returnTypeInference =
new ExplicitReturnTypeInference(type);
call.setOperator(
new SqlFunction(
type.getSqlIdentifier(),
returnTypeInference,
null,
null,
null,
SqlFunctionCategory.UserDefinedConstructor));
}
}
return type;
}
public void handleUnresolvedFunction(
SqlCall call,
SqlFunction unresolvedFunction,
RelDataType [] argTypes)
{
// For builtins, we can give a better error message
List<SqlOperator> overloads =
opTab.lookupOperatorOverloads(
unresolvedFunction.getNameAsId(),
null,
SqlSyntax.Function);
if (overloads.size() == 1) {
SqlFunction fun = (SqlFunction) overloads.get(0);
if ((fun.getSqlIdentifier() == null)
&& (fun.getSyntax() != SqlSyntax.FunctionId))
{
final int expectedArgCount =
fun.getOperandCountRange().getMin();
throw newValidationError(
call,
EigenbaseResource.instance().InvalidArgCount.ex(
call.getOperator().getName(),
expectedArgCount));
}
}
AssignableOperandTypeChecker typeChecking =
new AssignableOperandTypeChecker(argTypes);
String signature =
typeChecking.getAllowedSignatures(
unresolvedFunction,
unresolvedFunction.getName());
throw newValidationError(
call,
EigenbaseResource.instance().ValidatorUnknownFunction.ex(
signature));
}
protected void inferUnknownTypes(
RelDataType inferredType,
SqlValidatorScope scope,
SqlNode node)
{
final SqlValidatorScope newScope = scopes.get(node);
if (newScope != null) {
scope = newScope;
}
boolean isNullLiteral = SqlUtil.isNullLiteral(node, false);
if ((node instanceof SqlDynamicParam) || isNullLiteral) {
if (inferredType.equals(unknownType)) {
if (isNullLiteral) {
throw newValidationError(
node,
EigenbaseResource.instance().NullIllegal.ex());
} else {
throw newValidationError(
node,
EigenbaseResource.instance().DynamicParamIllegal.ex());
}
}
// REVIEW: should dynamic parameter types always be nullable?
RelDataType newInferredType =
typeFactory.createTypeWithNullability(inferredType, true);
if (SqlTypeUtil.inCharFamily(inferredType)) {
newInferredType =
typeFactory.createTypeWithCharsetAndCollation(
newInferredType,
inferredType.getCharset(),
inferredType.getCollation());
}
setValidatedNodeTypeImpl(node, newInferredType);
} else if (node instanceof SqlNodeList) {
SqlNodeList nodeList = (SqlNodeList) node;
if (inferredType.isStruct()) {
if (inferredType.getFieldCount() != nodeList.size()) {
// this can happen when we're validating an INSERT
// where the source and target degrees are different;
// bust out, and the error will be detected higher up
return;
}
}
int i = 0;
for (SqlNode child : nodeList) {
RelDataType type;
if (inferredType.isStruct()) {
type = inferredType.getFieldList().get(i).getType();
++i;
} else {
type = inferredType;
}
inferUnknownTypes(type, scope, child);
}
} else if (node instanceof SqlCase) {
// REVIEW wael: can this be done in a paramtypeinference strategy
// object?
SqlCase caseCall = (SqlCase) node;
RelDataType returnType = deriveType(scope, node);
SqlNodeList whenList = caseCall.getWhenOperands();
for (int i = 0; i < whenList.size(); i++) {
SqlNode sqlNode = whenList.get(i);
inferUnknownTypes(unknownType, scope, sqlNode);
}
SqlNodeList thenList = caseCall.getThenOperands();
for (int i = 0; i < thenList.size(); i++) {
SqlNode sqlNode = thenList.get(i);
inferUnknownTypes(returnType, scope, sqlNode);
}
if (!SqlUtil.isNullLiteral(
caseCall.getElseOperand(),
false))
{
inferUnknownTypes(
returnType,
scope,
caseCall.getElseOperand());
} else {
setValidatedNodeTypeImpl(
caseCall.getElseOperand(),
returnType);
}
} else if (node instanceof SqlCall) {
SqlCall call = (SqlCall) node;
SqlOperandTypeInference operandTypeInference =
call.getOperator().getOperandTypeInference();
SqlNode [] operands = call.getOperands();
RelDataType [] operandTypes = new RelDataType[operands.length];
if (operandTypeInference == null) {
// TODO: eventually should assert(operandTypeInference != null)
// instead; for now just eat it
Arrays.fill(operandTypes, unknownType);
} else {
operandTypeInference.inferOperandTypes(
new SqlCallBinding(this, scope, call),
inferredType,
operandTypes);
}
for (int i = 0; i < operands.length; ++i) {
inferUnknownTypes(operandTypes[i], scope, operands[i]);
}
}
}
/**
* Adds an expression to a select list, ensuring that its alias does not
* clash with any existing expressions on the list.
*/
protected void addToSelectList(
List<SqlNode> list,
Set<String> aliases,
List<Map.Entry<String, RelDataType>> fieldList,
SqlNode exp,
SqlValidatorScope scope,
final boolean includeSystemVars)
{
String alias = SqlValidatorUtil.getAlias(exp, -1);
String uniqueAlias = SqlValidatorUtil.uniquify(alias, aliases);
if (!alias.equals(uniqueAlias)) {
exp = SqlValidatorUtil.addAlias(exp, uniqueAlias);
}
fieldList.add(Pair.of(uniqueAlias, deriveType(scope, exp)));
list.add(exp);
}
public String deriveAlias(
SqlNode node,
int ordinal)
{
return SqlValidatorUtil.getAlias(node, ordinal);
}
// implement SqlValidator
public void setIdentifierExpansion(boolean expandIdentifiers)
{
this.expandIdentifiers = expandIdentifiers;
}
// implement SqlValidator
public void setColumnReferenceExpansion(
boolean expandColumnReferences)
{
this.expandColumnReferences = expandColumnReferences;
}
// implement SqlValidator
public boolean getColumnReferenceExpansion()
{
return expandColumnReferences;
}
// implement SqlValidator
public void setCallRewrite(boolean rewriteCalls)
{
this.rewriteCalls = rewriteCalls;
}
public boolean shouldExpandIdentifiers()
{
return expandIdentifiers;
}
protected boolean shouldAllowIntermediateOrderBy()
{
return true;
}
/**
* Registers a new namespace, and adds it as a child of its parent scope.
* Derived class can override this method to tinker with namespaces as they
* are created.
*
* @param usingScope Parent scope (which will want to look for things in
* this namespace)
* @param alias Alias by which parent will refer to this namespace
* @param ns Namespace
* @param forceNullable Whether to force the type of namespace to be
*/
protected void registerNamespace(
SqlValidatorScope usingScope,
String alias,
SqlValidatorNamespace ns,
boolean forceNullable)
{
if (forceNullable) {
ns.makeNullable();
}
namespaces.put(
ns.getNode(),
ns);
if (usingScope != null) {
usingScope.addChild(ns, alias);
}
}
/**
* Registers scopes and namespaces implied a relational expression in the
* FROM clause.
*
* <p>{@code parentScope} and {@code usingScope} are often the same. They
* differ when the namespace are not visible within the parent. (Example
* needed.)
*
* <p>Likewise, {@code enclosingNode} and {@code node} are often the same.
* {@code enclosingNode} is the topmost node within the FROM clause, from
* which any decorations like an alias (<code>AS alias</code>) or a table
* sample clause are stripped away to get {@code node}. Both are recorded in
* the namespace.
*
* @param parentScope Parent scope which this scope turns to in order to
* resolve objects
* @param usingScope Scope whose child list this scope should add itself to
* @param node Node which namespace is based on
* @param enclosingNode Outermost node for namespace, including decorations
* such as alias and sample clause
* @param alias Alias
* @param forceNullable Whether to force the type of namespace to be
* nullable because it is in an outer join
*
* @return registered node, usually the same as {@code node}
*/
private SqlNode registerFrom(
SqlValidatorScope parentScope,
SqlValidatorScope usingScope,
final SqlNode node,
SqlNode enclosingNode,
String alias,
boolean forceNullable)
{
final SqlKind kind = node.getKind();
SqlNode expr;
SqlNode newExpr;
// Add an alias if necessary.
SqlNode newNode = node;
if (alias == null) {
switch (kind) {
case IDENTIFIER:
case OVER:
alias = deriveAlias(node, -1);
if (alias == null) {
alias = deriveAlias(node, nextGeneratedId++);
}
if (shouldExpandIdentifiers()) {
newNode = SqlValidatorUtil.addAlias(node, alias);
}
break;
case SELECT:
case UNION:
case INTERSECT:
case EXCEPT:
case VALUES:
case UNNEST:
case OTHER_FUNCTION:
case COLLECTION_TABLE:
// give this anonymous construct a name since later
// query processing stages rely on it
alias = deriveAlias(node, nextGeneratedId++);
if (shouldExpandIdentifiers()) {
// Since we're expanding identifiers, we should make the
// aliases explicit too, otherwise the expanded query
// will not be consistent if we convert back to SQL, e.g.
// "select EXPR$1.EXPR$2 from values (1)".
newNode = SqlValidatorUtil.addAlias(node, alias);
}
break;
}
}
SqlCall call;
SqlNode operand;
SqlNode newOperand;
switch (kind) {
case AS:
call = (SqlCall) node;
if (alias == null) {
alias = call.operands[1].toString();
}
SqlValidatorScope usingScope2 = usingScope;
if (call.getOperands().length > 2) {
usingScope2 = null;
}
expr = call.operands[0];
newExpr =
registerFrom(
parentScope,
usingScope2,
expr,
enclosingNode,
alias,
forceNullable);
if (newExpr != expr) {
call.setOperand(0, newExpr);
}
// If alias has a column list, introduce a namespace to translate
// column names.
if (call.getOperands().length > 2) {
registerNamespace(
usingScope,
alias,
new AliasNamespace(this, call, enclosingNode),
false);
}
return node;
case TABLESAMPLE:
call = (SqlCall) node;
expr = call.operands[0];
newExpr =
registerFrom(
parentScope,
usingScope,
expr,
enclosingNode,
alias,
forceNullable);
if (newExpr != expr) {
call.setOperand(0, newExpr);
}
return node;
case JOIN:
final SqlJoin join = (SqlJoin) node;
final JoinScope joinScope =
new JoinScope(parentScope, usingScope, join);
scopes.put(join, joinScope);
final SqlNode left = join.getLeft();
final SqlNode right = join.getRight();
boolean rightIsLateral = false;
if (right.getKind() == SqlKind.LATERAL
|| (right.getKind() == SqlKind.AS
&& ((SqlCall) right).operands[0].getKind()
== SqlKind.LATERAL))
{
rightIsLateral = true;
}
boolean forceLeftNullable = forceNullable;
boolean forceRightNullable = forceNullable;
if (join.getJoinType() == SqlJoinOperator.JoinType.Left) {
forceRightNullable = true;
}
if (join.getJoinType() == SqlJoinOperator.JoinType.Right) {
forceLeftNullable = true;
}
if (join.getJoinType() == SqlJoinOperator.JoinType.Full) {
forceLeftNullable = true;
forceRightNullable = true;
}
final SqlNode newLeft =
registerFrom(
parentScope,
joinScope,
left,
left,
null,
forceLeftNullable);
if (newLeft != left) {
join.setOperand(SqlJoin.LEFT_OPERAND, newLeft);
}
final SqlValidatorScope rightParentScope;
if (rightIsLateral) {
rightParentScope = joinScope;
} else {
rightParentScope = parentScope;
}
final SqlNode newRight =
registerFrom(
rightParentScope,
joinScope,
right,
right,
null,
forceRightNullable);
if (newRight != right) {
join.setOperand(SqlJoin.RIGHT_OPERAND, newRight);
}
final JoinNamespace joinNamespace = new JoinNamespace(this, join);
registerNamespace(null, null, joinNamespace, forceNullable);
return join;
case IDENTIFIER:
final SqlIdentifier id = (SqlIdentifier) node;
final IdentifierNamespace newNs =
new IdentifierNamespace(
this,
id,
enclosingNode);
registerNamespace(usingScope, alias, newNs, forceNullable);
return newNode;
case LATERAL:
return registerFrom(
parentScope,
usingScope,
((SqlCall) node).operands[0],
enclosingNode,
alias,
forceNullable);
case COLLECTION_TABLE:
call = (SqlCall) node;
operand = call.operands[0];
newOperand =
registerFrom(
parentScope,
usingScope,
operand,
enclosingNode,
alias,
forceNullable);
if (newOperand != operand) {
call.setOperand(0, newOperand);
}
return newNode;
case SELECT:
case UNION:
case INTERSECT:
case EXCEPT:
case VALUES:
case UNNEST:
case OTHER_FUNCTION:
registerQuery(
parentScope,
usingScope,
node,
enclosingNode,
alias,
forceNullable);
return newNode;
case OVER:
if (!shouldAllowOverRelation()) {
throw Util.unexpected(kind);
}
call = (SqlCall) node;
final OverScope overScope = new OverScope(usingScope, call);
scopes.put(call, overScope);
operand = call.operands[0];
newOperand =
registerFrom(
parentScope,
overScope,
operand,
enclosingNode,
alias,
forceNullable);
if (newOperand != operand) {
call.setOperand(0, newOperand);
}
for (Pair<String, SqlValidatorNamespace> p : overScope.children) {
registerNamespace(
usingScope,
p.left,
p.right,
forceNullable);
}
return newNode;
default:
throw Util.unexpected(kind);
}
}
protected boolean shouldAllowOverRelation()
{
return false;
}
/**
* Creates a namespace for a <code>SELECT</code> node. Derived class may
* override this factory method.
*
* @param select Select node
* @param enclosingNode Enclosing node
*
* @return Select namespace
*/
protected SelectNamespace createSelectNamespace(
SqlSelect select,
SqlNode enclosingNode)
{
return new SelectNamespace(this, select, enclosingNode);
}
/**
* Creates a namespace for a set operation (<code>UNION</code>, <code>
* INTERSECT</code>, or <code>EXCEPT</code>). Derived class may override
* this factory method.
*
* @param call Call to set operation
* @param enclosingNode Enclosing node
*
* @return Set operation namespace
*/
protected SetopNamespace createSetopNamespace(
SqlCall call,
SqlNode enclosingNode)
{
return new SetopNamespace(this, call, enclosingNode);
}
/**
* Registers a query in a parent scope.
*
* @param parentScope Parent scope which this scope turns to in order to
* resolve objects
* @param usingScope Scope whose child list this scope should add itself to
* @param node Query node
* @param alias Name of this query within its parent. Must be specified if
* usingScope != null
*
* @pre usingScope == null || alias != null
*/
private void registerQuery(
SqlValidatorScope parentScope,
SqlValidatorScope usingScope,
SqlNode node,
SqlNode enclosingNode,
String alias,
boolean forceNullable)
{
registerQuery(
parentScope,
usingScope,
node,
enclosingNode,
alias,
forceNullable,
true);
}
/**
* Registers a query in a parent scope.
*
* @param parentScope Parent scope which this scope turns to in order to
* resolve objects
* @param usingScope Scope whose child list this scope should add itself to
* @param node Query node
* @param alias Name of this query within its parent. Must be specified if
* usingScope != null
* @param checkUpdate if true, validate that the update feature is supported
* if validating the update statement
*
* @pre usingScope == null || alias != null
*/
private void registerQuery(
SqlValidatorScope parentScope,
SqlValidatorScope usingScope,
SqlNode node,
SqlNode enclosingNode,
String alias,
boolean forceNullable,
boolean checkUpdate)
{
assert node != null;
assert enclosingNode != null;
Util.pre(
(usingScope == null)
|| (alias != null),
"usingScope == null || alias != null");
SqlCall call;
SqlNode [] operands;
switch (node.getKind()) {
case SELECT:
final SqlSelect select = (SqlSelect) node;
final SelectNamespace selectNs =
createSelectNamespace(select, enclosingNode);
registerNamespace(usingScope, alias, selectNs, forceNullable);
final SqlValidatorScope windowParentScope =
(usingScope != null) ? usingScope : parentScope;
SelectScope selectScope =
new SelectScope(parentScope, windowParentScope, select);
scopes.put(select, selectScope);
// Start by registering the WHERE clause
whereScopes.put(select, selectScope);
registerOperandSubqueries(
selectScope,
select,
SqlSelect.WHERE_OPERAND);
// Register FROM with the inherited scope 'parentScope', not
// 'selectScope', otherwise tables in the FROM clause would be
// able to see each other.
final SqlNode from = select.getFrom();
final SqlNode newFrom =
registerFrom(
parentScope,
selectScope,
from,
from,
null,
false);
if (newFrom != from) {
select.setOperand(SqlSelect.FROM_OPERAND, newFrom);
}
// If this is an aggregating query, the SELECT list and HAVING
// clause use a different scope, where you can only reference
// columns which are in the GROUP BY clause.
SqlValidatorScope aggScope = selectScope;
if (isAggregate(select)) {
aggScope =
new AggregatingSelectScope(selectScope, select, false);
selectScopes.put(select, aggScope);
} else {
selectScopes.put(select, selectScope);
}
registerSubqueries(selectScope, select.getGroup());
registerOperandSubqueries(
aggScope,
select,
SqlSelect.HAVING_OPERAND);
registerSubqueries(aggScope, select.getSelectList());
final SqlNodeList orderList = select.getOrderList();
if (orderList != null) {
// If the query is 'SELECT DISTINCT', restrict the columns
// available to the ORDER BY clause.
if (select.isDistinct()) {
aggScope =
new AggregatingSelectScope(selectScope, select, true);
}
OrderByScope orderScope =
new OrderByScope(aggScope, orderList, select);
orderScopes.put(select, orderScope);
registerSubqueries(orderScope, orderList);
if (!isAggregate(select)) {
// Since this is not an aggregating query,
// there cannot be any aggregates in the ORDER BY clause.
SqlNode agg = aggFinder.findAgg(orderList);
if (agg != null) {
throw newValidationError(
agg,
EigenbaseResource.instance()
.AggregateIllegalInOrderBy.ex());
}
}
}
break;
case INTERSECT:
validateFeature(
EigenbaseResource.instance().SQLFeature_F302,
node.getParserPosition());
registerSetop(
parentScope,
usingScope,
node,
node,
alias,
forceNullable);
break;
case EXCEPT:
validateFeature(
EigenbaseResource.instance().SQLFeature_E071_03,
node.getParserPosition());
registerSetop(
parentScope,
usingScope,
node,
node,
alias,
forceNullable);
break;
case UNION:
registerSetop(
parentScope,
usingScope,
node,
node,
alias,
forceNullable);
break;
case VALUES:
call = (SqlCall) node;
scopes.put(call, parentScope);
final TableConstructorNamespace tableConstructorNamespace =
new TableConstructorNamespace(
this,
call,
parentScope,
enclosingNode);
registerNamespace(
usingScope,
alias,
tableConstructorNamespace,
forceNullable);
operands = call.getOperands();
for (int i = 0; i < operands.length; ++i) {
assert (operands[i].getKind() == SqlKind.ROW);
// FIXME jvs 9-Feb-2005: Correlation should
// be illegal in these subqueries. Same goes for
// any non-lateral SELECT in the FROM list.
registerOperandSubqueries(parentScope, call, i);
}
break;
case INSERT:
SqlInsert insertCall = (SqlInsert) node;
InsertNamespace insertNs =
new InsertNamespace(
this,
insertCall,
enclosingNode);
registerNamespace(usingScope, null, insertNs, forceNullable);
registerQuery(
parentScope,
usingScope,
insertCall.getSource(),
enclosingNode,
null,
false);
break;
case DELETE:
SqlDelete deleteCall = (SqlDelete) node;
DeleteNamespace deleteNs =
new DeleteNamespace(
this,
deleteCall,
enclosingNode);
registerNamespace(usingScope, null, deleteNs, forceNullable);
registerQuery(
parentScope,
usingScope,
deleteCall.getSourceSelect(),
enclosingNode,
null,
false);
break;
case UPDATE:
if (checkUpdate) {
validateFeature(
EigenbaseResource.instance().SQLFeature_E101_03,
node.getParserPosition());
}
SqlUpdate updateCall = (SqlUpdate) node;
UpdateNamespace updateNs =
new UpdateNamespace(
this,
updateCall,
enclosingNode);
registerNamespace(usingScope, null, updateNs, forceNullable);
registerQuery(
parentScope,
usingScope,
updateCall.getSourceSelect(),
enclosingNode,
null,
false);
break;
case MERGE:
validateFeature(
EigenbaseResource.instance().SQLFeature_F312,
node.getParserPosition());
SqlMerge mergeCall = (SqlMerge) node;
MergeNamespace mergeNs =
new MergeNamespace(
this,
mergeCall,
enclosingNode);
registerNamespace(usingScope, null, mergeNs, forceNullable);
registerQuery(
parentScope,
usingScope,
mergeCall.getSourceSelect(),
enclosingNode,
null,
false);
// update call can reference either the source table reference
// or the target table, so set its parent scope to the merge's
// source select; when validating the update, skip the feature
// validation check
if (mergeCall.getUpdateCall() != null) {
registerQuery(
whereScopes.get(mergeCall.getSourceSelect()),
null,
mergeCall.getUpdateCall(),
enclosingNode,
null,
false,
false);
}
if (mergeCall.getInsertCall() != null) {
registerQuery(
parentScope,
null,
mergeCall.getInsertCall(),
enclosingNode,
null,
false);
}
break;
case UNNEST:
call = (SqlCall) node;
final UnnestNamespace unnestNs =
new UnnestNamespace(this, call, usingScope, enclosingNode);
registerNamespace(
usingScope,
alias,
unnestNs,
forceNullable);
registerOperandSubqueries(usingScope, call, 0);
break;
case OTHER_FUNCTION:
call = (SqlCall) node;
ProcedureNamespace procNs =
new ProcedureNamespace(
this,
parentScope,
call,
enclosingNode);
registerNamespace(
usingScope,
alias,
procNs,
forceNullable);
registerSubqueries(parentScope, call);
break;
case MULTISET_QUERY_CONSTRUCTOR:
validateFeature(
EigenbaseResource.instance().SQLFeature_S271,
node.getParserPosition());
call = (SqlCall) node;
CollectScope cs = new CollectScope(parentScope, usingScope, call);
final CollectNamespace ttableConstructorNs =
new CollectNamespace(call, cs, enclosingNode);
final String alias2 = deriveAlias(node, nextGeneratedId++);
registerNamespace(
usingScope,
alias2,
ttableConstructorNs,
forceNullable);
operands = call.getOperands();
for (int i = 0; i < operands.length; i++) {
registerOperandSubqueries(parentScope, call, i);
}
break;
default:
throw Util.unexpected(node.getKind());
}
}
private void registerSetop(
SqlValidatorScope parentScope,
SqlValidatorScope usingScope,
SqlNode node,
SqlNode enclosingNode,
String alias,
boolean forceNullable)
{
SqlCall call = (SqlCall) node;
final SetopNamespace setopNamespace =
createSetopNamespace(call, enclosingNode);
registerNamespace(usingScope, alias, setopNamespace, forceNullable);
// A setop is in the same scope as its parent.
scopes.put(call, parentScope);
for (SqlNode operand : call.operands) {
registerQuery(
parentScope,
null,
operand,
operand,
null,
false);
}
}
public boolean isAggregate(SqlSelect select)
{
return (select.getGroup() != null) || (select.getHaving() != null)
|| (aggFinder.findAgg(select.getSelectList()) != null);
}
public boolean isAggregate(SqlNode selectNode)
{
return (aggFinder.findAgg(selectNode) != null);
}
private void validateNodeFeature(SqlNode node)
{
switch (node.getKind()) {
case MULTISET_VALUE_CONSTRUCTOR:
validateFeature(
EigenbaseResource.instance().SQLFeature_S271,
node.getParserPosition());
break;
}
}
private void registerSubqueries(
SqlValidatorScope parentScope,
SqlNode node)
{
if (node == null) {
return;
} else if (node.getKind().belongsTo(SqlKind.QUERY)) {
registerQuery(parentScope, null, node, node, null, false);
} else if (node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR) {
registerQuery(parentScope, null, node, node, null, false);
} else if (node instanceof SqlCall) {
validateNodeFeature(node);
SqlCall call = (SqlCall) node;
final SqlNode[] operands = call.getOperands();
for (int i = 0; i < operands.length; i++) {
registerOperandSubqueries(parentScope, call, i);
}
} else if (node instanceof SqlNodeList) {
SqlNodeList list = (SqlNodeList) node;
for (int i = 0, count = list.size(); i < count; i++) {
SqlNode listNode = list.get(i);
if (listNode.getKind().belongsTo(SqlKind.QUERY)) {
listNode =
SqlStdOperatorTable.scalarQueryOperator.createCall(
listNode.getParserPosition(),
listNode);
list.set(i, listNode);
}
registerSubqueries(parentScope, listNode);
}
} else {
// atomic node -- can be ignored
}
}
/**
* Registers any subqueries inside a given call operand, and converts the
* operand to a scalar subquery if the operator requires it.
*
* @param parentScope Parent scope
* @param call Call
* @param operandOrdinal Ordinal of operand within call
*
* @see SqlOperator#argumentMustBeScalar(int)
*/
private void registerOperandSubqueries(
SqlValidatorScope parentScope,
SqlCall call,
int operandOrdinal)
{
SqlNode operand = call.getOperands()[operandOrdinal];
if (operand == null) {
return;
}
if (operand.getKind().belongsTo(SqlKind.QUERY)
&& call.getOperator().argumentMustBeScalar(operandOrdinal))
{
operand =
SqlStdOperatorTable.scalarQueryOperator.createCall(
operand.getParserPosition(),
operand);
call.setOperand(operandOrdinal, operand);
}
registerSubqueries(parentScope, operand);
}
public void validateIdentifier(SqlIdentifier id, SqlValidatorScope scope)
{
final SqlIdentifier fqId = scope.fullyQualify(id);
if (expandColumnReferences) {
// NOTE jvs 9-Apr-2007: this doesn't cover ORDER BY, which has its
// own ideas about qualification.
id.assignNamesFrom(fqId);
} else {
Util.discard(fqId);
}
}
public void validateLiteral(SqlLiteral literal)
{
switch (literal.getTypeName()) {
case DECIMAL:
// Decimal and long have the same precision (as 64-bit integers), so
// the unscaled value of a decimal must fit into a long.
// REVIEW jvs 4-Aug-2004: This should probably be calling over to
// the available calculator implementations to see what they
// support. For now use ESP instead.
//
// jhyde 2006/12/21: I think the limits should be baked into the
// type system, not dependent on the calculator implementation.
BigDecimal bd = (BigDecimal) literal.getValue();
BigInteger unscaled = bd.unscaledValue();
long longValue = unscaled.longValue();
if (!BigInteger.valueOf(longValue).equals(unscaled)) {
// overflow
throw newValidationError(
literal,
EigenbaseResource.instance().NumberLiteralOutOfRange.ex(
bd.toString()));
}
break;
case DOUBLE:
validateLiteralAsDouble(literal);
break;
case BINARY:
final BitString bitString = (BitString) literal.getValue();
if ((bitString.getBitCount() % 8) != 0) {
throw newValidationError(
literal,
EigenbaseResource.instance().BinaryLiteralOdd.ex());
}
break;
case DATE:
case TIME:
case TIMESTAMP:
Calendar calendar = (Calendar) literal.getValue();
final int year = calendar.get(Calendar.YEAR);
final int era = calendar.get(Calendar.ERA);
if ((year < 1) || (era == GregorianCalendar.BC) || (year > 9999)) {
throw newValidationError(
literal,
EigenbaseResource.instance().DateLiteralOutOfRange.ex(
literal.toString()));
}
break;
case INTERVAL_YEAR_MONTH:
case INTERVAL_DAY_TIME:
if (literal instanceof SqlIntervalLiteral) {
SqlIntervalLiteral.IntervalValue interval =
(SqlIntervalLiteral.IntervalValue)
literal.getValue();
SqlIntervalQualifier intervalQualifier =
interval.getIntervalQualifier();
// ensure qualifier is good before attempting to validate
// literal
validateIntervalQualifier(intervalQualifier);
String intervalStr = interval.getIntervalLiteral();
try {
int [] values =
intervalQualifier.evaluateIntervalLiteral(intervalStr);
Util.discard(values);
} catch (SqlValidatorException e) {
throw newValidationError(literal, e);
}
}
break;
default:
// default is to do nothing
}
}
private void validateLiteralAsDouble(SqlLiteral literal)
{
BigDecimal bd = (BigDecimal) literal.getValue();
double d = bd.doubleValue();
if (Double.isInfinite(d) || Double.isNaN(d)) {
// overflow
throw newValidationError(
literal,
EigenbaseResource.instance().NumberLiteralOutOfRange.ex(
Util.toScientificNotation(bd)));
}
// REVIEW jvs 4-Aug-2004: what about underflow?
}
public void validateIntervalQualifier(SqlIntervalQualifier qualifier)
{
assert (qualifier != null);
boolean startPrecisionOutOfRange = false;
boolean fractionalSecondPrecisionOutOfRange = false;
if (qualifier.isYearMonth()) {
if ((qualifier.getStartPrecision()
< SqlTypeName.INTERVAL_YEAR_MONTH.getMinPrecision())
|| (qualifier.getStartPrecision()
> SqlTypeName.INTERVAL_YEAR_MONTH.getMaxPrecision()))
{
startPrecisionOutOfRange = true;
} else if (
(qualifier.getFractionalSecondPrecision()
< SqlTypeName.INTERVAL_YEAR_MONTH.getMinScale())
|| (qualifier.getFractionalSecondPrecision()
> SqlTypeName.INTERVAL_YEAR_MONTH.getMaxScale()))
{
fractionalSecondPrecisionOutOfRange = true;
}
} else {
if ((qualifier.getStartPrecision()
< SqlTypeName.INTERVAL_DAY_TIME.getMinPrecision())
|| (qualifier.getStartPrecision()
> SqlTypeName.INTERVAL_DAY_TIME.getMaxPrecision()))
{
startPrecisionOutOfRange = true;
} else if (
(qualifier.getFractionalSecondPrecision()
< SqlTypeName.INTERVAL_DAY_TIME.getMinScale())
|| (qualifier.getFractionalSecondPrecision()
> SqlTypeName.INTERVAL_DAY_TIME.getMaxScale()))
{
fractionalSecondPrecisionOutOfRange = true;
}
}
if (startPrecisionOutOfRange) {
throw newValidationError(
qualifier,
EigenbaseResource.instance().IntervalStartPrecisionOutOfRange
.ex(
Integer.toString(qualifier.getStartPrecision()),
"INTERVAL " + qualifier.toString()));
} else if (fractionalSecondPrecisionOutOfRange) {
throw newValidationError(
qualifier,
EigenbaseResource.instance()
.IntervalFractionalSecondPrecisionOutOfRange.ex(
Integer.toString(qualifier.getFractionalSecondPrecision()),
"INTERVAL " + qualifier.toString()));
}
}
/**
* Validates the FROM clause of a query, or (recursively) a child node of
* the FROM clause: AS, OVER, JOIN, VALUES, or subquery.
*
* @param node Node in FROM clause, typically a table or derived table
* @param targetRowType Desired row type of this expression, or {@link
* #unknownType} if not fussy. Must not be null.
* @param scope Scope
*/
protected void validateFrom(
SqlNode node,
RelDataType targetRowType,
SqlValidatorScope scope)
{
Util.pre(targetRowType != null, "targetRowType != null");
switch (node.getKind()) {
case AS:
validateFrom(
((SqlCall) node).getOperands()[0],
targetRowType,
scope);
break;
case VALUES:
validateValues((SqlCall) node, targetRowType, scope);
break;
case JOIN:
validateJoin((SqlJoin) node, scope);
break;
case OVER:
validateOver((SqlCall) node, scope);
break;
default:
validateQuery(node, scope);
break;
}
// Validate the namespace representation of the node, just in case the
// validation did not occur implicitly.
getNamespace(node).validate();
}
protected void validateOver(SqlCall call, SqlValidatorScope scope)
{
throw Util.newInternal("OVER unexpected in this context");
}
protected void validateJoin(SqlJoin join, SqlValidatorScope scope)
{
SqlNode left = join.getLeft();
SqlNode right = join.getRight();
SqlNode condition = join.getCondition();
boolean natural = join.isNatural();
SqlJoinOperator.JoinType joinType = join.getJoinType();
SqlJoinOperator.ConditionType conditionType = join.getConditionType();
final SqlValidatorScope joinScope = scopes.get(join);
validateFrom(left, unknownType, joinScope);
validateFrom(right, unknownType, joinScope);
// Validate condition.
switch (conditionType) {
case None:
Util.permAssert(condition == null, "condition == null");
break;
case On:
Util.permAssert(condition != null, "condition != null");
validateWhereOrOn(joinScope, condition, "ON");
break;
case Using:
SqlNodeList list = (SqlNodeList) condition;
// Parser ensures that using clause is not empty.
Util.permAssert(list.size() > 0, "Empty USING clause");
for (int i = 0; i < list.size(); i++) {
SqlIdentifier id = (SqlIdentifier) list.get(i);
final RelDataType leftColType = validateUsingCol(id, left);
final RelDataType rightColType = validateUsingCol(id, right);
if (!SqlTypeUtil.isComparable(leftColType, rightColType)) {
throw newValidationError(
id,
EigenbaseResource.instance()
.NaturalOrUsingColumnNotCompatible.ex(
id.getSimple(),
leftColType.toString(),
rightColType.toString()));
}
}
break;
default:
throw Util.unexpected(conditionType);
}
// Validate NATURAL.
if (natural) {
if (condition != null) {
throw newValidationError(
condition,
EigenbaseResource.instance().NaturalDisallowsOnOrUsing
.ex());
}
// Join on fields that occur exactly once on each side. Ignore
// fields that occur more than once on either side.
final RelDataType leftRowType = getNamespace(left).getRowType();
final RelDataType rightRowType = getNamespace(right).getRowType();
List<String> naturalColumnNames =
SqlValidatorUtil.deriveNaturalJoinColumnList(
leftRowType,
rightRowType);
// Check compatibility of the chosen columns.
for (String name : naturalColumnNames) {
final RelDataType leftColType =
leftRowType.getField(name).getType();
final RelDataType rightColType =
rightRowType.getField(name).getType();
if (!SqlTypeUtil.isComparable(leftColType, rightColType)) {
throw newValidationError(
join,
EigenbaseResource.instance()
.NaturalOrUsingColumnNotCompatible.ex(
name,
leftColType.toString(),
rightColType.toString()));
}
}
}
// Which join types require/allow a ON/USING condition, or allow
// a NATURAL keyword?
switch (joinType) {
case Inner:
case Left:
case Right:
case Full:
if ((condition == null) && !natural) {
throw newValidationError(
join,
EigenbaseResource.instance().JoinRequiresCondition.ex());
}
break;
case Comma:
case Cross:
if (condition != null) {
throw newValidationError(
join.operands[SqlJoin.CONDITION_TYPE_OPERAND],
EigenbaseResource.instance().CrossJoinDisallowsCondition
.ex());
}
if (natural) {
throw newValidationError(
join.operands[SqlJoin.CONDITION_TYPE_OPERAND],
EigenbaseResource.instance().CrossJoinDisallowsCondition
.ex());
}
break;
default:
throw Util.unexpected(joinType);
}
}
/**
* Throws an error if there is an aggregate or windowed aggregate in the
* given clause.
*
* @param condition Parse tree
* @param clause Name of clause: "WHERE", "GROUP BY", "ON"
*/
private void validateNoAggs(SqlNode condition, String clause)
{
final SqlNode agg = aggOrOverFinder.findAgg(condition);
if (agg != null) {
if (SqlUtil.isCallTo(agg, SqlStdOperatorTable.overOperator)) {
throw newValidationError(
agg,
EigenbaseResource.instance()
.WindowedAggregateIllegalInClause.ex(clause));
} else {
throw newValidationError(
agg,
EigenbaseResource.instance().AggregateIllegalInClause.ex(
clause));
}
}
}
private RelDataType validateUsingCol(SqlIdentifier id, SqlNode leftOrRight)
{
if (id.names.length == 1) {
String name = id.names[0];
final SqlValidatorNamespace namespace = getNamespace(leftOrRight);
final RelDataType rowType = namespace.getRowType();
final RelDataTypeField field = rowType.getField(name);
if (field != null) {
if (Collections.frequency(rowType.getFieldNames(), name) > 1) {
throw newValidationError(
id,
EigenbaseResource.instance().ColumnInUsingNotUnique.ex(
id.toString()));
}
return field.getType();
}
}
throw newValidationError(
id,
EigenbaseResource.instance().ColumnNotFound.ex(
id.toString()));
}
/**
* Validates a SELECT statement.
*
* @param select Select statement
* @param targetRowType Desired row type, must not be null, may be the data
* type 'unknown'.
*
* @pre targetRowType != null
*/
protected void validateSelect(
SqlSelect select,
RelDataType targetRowType)
{
assert targetRowType != null;
// Namespace is either a select namespace or a wrapper around one.
final SelectNamespace ns =
getNamespace(select).unwrap(SelectNamespace.class);
// Its rowtype is null, meaning it hasn't been validated yet.
// This is important, because we need to take the targetRowType into
// account.
assert ns.rowType == null;
if (select.isDistinct()) {
validateFeature(
EigenbaseResource.instance().SQLFeature_E051_01,
select.getModifierNode(
SqlSelectKeyword.Distinct).getParserPosition());
}
final SqlNodeList selectItems = select.getSelectList();
RelDataType fromType = unknownType;
if (selectItems.size() == 1) {
final SqlNode selectItem = selectItems.get(0);
if (selectItem instanceof SqlIdentifier) {
SqlIdentifier id = (SqlIdentifier) selectItem;
if (id.isStar() && (id.names.length == 1)) {
// Special case: for INSERT ... VALUES(?,?), the SQL
// standard says we're supposed to propagate the target
// types down. So iff the select list is an unqualified
// star (as it will be after an INSERT ... VALUES has been
// expanded), then propagate.
fromType = targetRowType;
}
}
}
// Make sure that items in FROM clause have distinct aliases.
final SqlValidatorScope fromScope = getFromScope(select);
final List<Pair<String, SqlValidatorNamespace>> children =
((SelectScope) fromScope).children;
int duplicateAliasOrdinal = firstDuplicate(Pair.left(children));
if (duplicateAliasOrdinal >= 0) {
final Pair<String, SqlValidatorNamespace> child =
children.get(duplicateAliasOrdinal);
throw newValidationError(
child.right.getEnclosingNode(),
EigenbaseResource.instance().FromAliasDuplicate.ex(child.left));
}
validateFrom(
select.getFrom(),
fromType,
fromScope);
validateWhereClause(select);
validateGroupClause(select);
validateHavingClause(select);
validateWindowClause(select);
// Validate the SELECT clause late, because a select item might
// depend on the GROUP BY list, or the window function might reference
// window name in the WINDOW clause etc.
final RelDataType rowType =
validateSelectList(selectItems, select, targetRowType);
ns.setRowType(rowType);
// Validate ORDER BY after we have set ns.rowType because in some
// dialects you can refer to columns of the select list, e.g.
// "SELECT empno AS x FROM emp ORDER BY x"
validateOrderList(select);
}
/**
* Returns the ordinal of the first element in the list which is equal to a
* previous element in the list.
*
* <p>For example, <code>firstDuplicate(Arrays.asList("a", "b", "c", "b",
* "a"))</code> returns 3, the ordinal of the 2nd "b".
*
* @param list List
*
* @return Ordinal of first duplicate, or -1 if not found
*/
private static <T> int firstDuplicate(List<T> list)
{
// For large lists, it's more efficient to build a set to do a quick
// check for duplicates before we do an O(n^2) search.
if (list.size() > 10 && Util.isDistinct(list)) {
return -1;
}
for (int i = 1; i < list.size(); i++) {
final T e0 = list.get(i);
for (int j = 0; j < i; j++) {
final T e1 = list.get(j);
if (e0.equals(e1)) {
return i; // ordinal of the later item
}
}
}
return -1;
}
protected void validateWindowClause(SqlSelect select)
{
final SqlNodeList windowList = select.getWindowList();
if ((windowList == null) || (windowList.size() == 0)) {
return;
}
final SelectScope windowScope = (SelectScope) getFromScope(select);
Util.permAssert(windowScope != null, "windowScope != null");
// 1. ensure window names are simple
// 2. ensure they are unique within this scope
for (SqlNode node : windowList) {
final SqlWindow child = (SqlWindow) node;
SqlIdentifier declName = child.getDeclName();
if (!declName.isSimple()) {
throw newValidationError(
declName,
EigenbaseResource.instance().WindowNameMustBeSimple.ex());
}
if (windowScope.existingWindowName(declName.toString())) {
throw newValidationError(
declName,
EigenbaseResource.instance().DuplicateWindowName.ex());
} else {
windowScope.addWindowName(declName.toString());
}
}
// 7.10 rule 2
// Check for pairs of windows which are equivalent.
for (int i = 0; i < windowList.size(); i++) {
SqlNode window1 = windowList.get(i);
for (int j = i + 1; j < windowList.size(); j++) {
SqlNode window2 = windowList.get(j);
if (window1.equalsDeep(window2, false)) {
throw newValidationError(
window2,
EigenbaseResource.instance().DupWindowSpec.ex());
}
}
}
// Hand off to validate window spec components
windowList.validate(this, windowScope);
}
/**
* Validates the ORDER BY clause of a SELECT statement.
*
* @param select Select statement
*/
protected void validateOrderList(SqlSelect select)
{
// ORDER BY is validated in a scope where aliases in the SELECT clause
// are visible. For example, "SELECT empno AS x FROM emp ORDER BY x"
// is valid.
SqlNodeList orderList = select.getOrderList();
if (orderList == null) {
return;
}
if (!shouldAllowIntermediateOrderBy()) {
if (!cursorSet.contains(select)) {
throw newValidationError(
select,
EigenbaseResource.instance().InvalidOrderByPos.ex());
}
}
final SqlValidatorScope orderScope = getOrderScope(select);
Util.permAssert(orderScope != null, "orderScope != null");
for (SqlNode orderItem : orderList) {
validateOrderItem(select, orderItem);
}
}
private void validateOrderItem(SqlSelect select, SqlNode orderItem)
{
if (SqlUtil.isCallTo(
orderItem,
SqlStdOperatorTable.descendingOperator))
{
validateFeature(
EigenbaseResource.instance().SQLConformance_OrderByDesc,
orderItem.getParserPosition());
validateOrderItem(
select,
((SqlCall) orderItem).operands[0]);
return;
}
final SqlValidatorScope orderScope = getOrderScope(select);
validateExpr(orderItem, orderScope);
}
public SqlNode expandOrderExpr(SqlSelect select, SqlNode orderExpr)
{
return new OrderExpressionExpander(select, orderExpr).go();
}
/**
* Validates the GROUP BY clause of a SELECT statement. This method is
* called even if no GROUP BY clause is present.
*/
protected void validateGroupClause(SqlSelect select)
{
SqlNodeList groupList = select.getGroup();
if (groupList == null) {
return;
}
validateNoAggs(groupList, "GROUP BY");
final SqlValidatorScope groupScope = getGroupScope(select);
inferUnknownTypes(unknownType, groupScope, groupList);
groupList.validate(this, groupScope);
// Derive the type of each GROUP BY item. We don't need the type, but
// it resolves functions, and that is necessary for deducing
// monotonicity.
final SqlValidatorScope selectScope = getSelectScope(select);
AggregatingSelectScope aggregatingScope = null;
if (selectScope instanceof AggregatingSelectScope) {
aggregatingScope = (AggregatingSelectScope) selectScope;
}
for (SqlNode groupItem : groupList) {
final RelDataType type = deriveType(groupScope, groupItem);
setValidatedNodeTypeImpl(groupItem, type);
if (aggregatingScope != null) {
aggregatingScope.addGroupExpr(groupItem);
}
}
SqlNode agg = aggFinder.findAgg(groupList);
if (agg != null) {
throw newValidationError(
agg,
EigenbaseResource.instance().AggregateIllegalInGroupBy.ex());
}
}
protected void validateWhereClause(SqlSelect select)
{
// validate WHERE clause
final SqlNode where = select.getWhere();
if (where == null) {
return;
}
final SqlValidatorScope whereScope = getWhereScope(select);
validateWhereOrOn(whereScope, where, "WHERE");
}
protected void validateWhereOrOn(
SqlValidatorScope scope,
SqlNode condition,
String keyword)
{
validateNoAggs(condition, keyword);
inferUnknownTypes(
booleanType,
scope,
condition);
condition.validate(this, scope);
final RelDataType type = deriveType(scope, condition);
if (!SqlTypeUtil.inBooleanFamily(type)) {
throw newValidationError(
condition,
EigenbaseResource.instance().CondMustBeBoolean.ex(keyword));
}
}
protected void validateHavingClause(SqlSelect select)
{
// HAVING is validated in the scope after groups have been created.
// For example, in "SELECT empno FROM emp WHERE empno = 10 GROUP BY
// deptno HAVING empno = 10", the reference to 'empno' in the HAVING
// clause is illegal.
final SqlNode having = select.getHaving();
if (having == null) {
return;
}
final AggregatingScope havingScope =
(AggregatingScope) getSelectScope(select);
havingScope.checkAggregateExpr(having, true);
inferUnknownTypes(
booleanType,
havingScope,
having);
having.validate(this, havingScope);
final RelDataType type = deriveType(havingScope, having);
if (!SqlTypeUtil.inBooleanFamily(type)) {
throw newValidationError(
having,
EigenbaseResource.instance().HavingMustBeBoolean.ex());
}
}
protected RelDataType validateSelectList(
final SqlNodeList selectItems,
SqlSelect select,
RelDataType targetRowType)
{
// First pass, ensure that aliases are unique. "*" and "TABLE.*" items
// are ignored.
// Validate SELECT list. Expand terms of the form "*" or "TABLE.*".
final SqlValidatorScope selectScope = getSelectScope(select);
final List<SqlNode> expandedSelectItems = new ArrayList<SqlNode>();
final Set<String> aliases = new HashSet<String>();
final List<Map.Entry<String, RelDataType>> fieldList =
new ArrayList<Map.Entry<String, RelDataType>>();
for (int i = 0; i < selectItems.size(); i++) {
SqlNode selectItem = selectItems.get(i);
if (selectItem instanceof SqlSelect) {
handleScalarSubQuery(
select,
(SqlSelect) selectItem,
expandedSelectItems,
aliases,
fieldList);
} else {
expandSelectItem(
selectItem,
select,
expandedSelectItems,
aliases,
fieldList,
false);
}
}
// Check expanded select list for aggregation.
if (selectScope instanceof AggregatingScope) {
AggregatingScope aggScope = (AggregatingScope) selectScope;
for (SqlNode selectItem : expandedSelectItems) {
boolean matches = aggScope.checkAggregateExpr(selectItem, true);
Util.discard(matches);
}
}
// Create the new select list with expanded items. Pass through
// the original parser position so that any overall failures can
// still reference the original input text.
SqlNodeList newSelectList =
new SqlNodeList(
expandedSelectItems,
selectItems.getParserPosition());
if (shouldExpandIdentifiers()) {
select.setOperand(SqlSelect.SELECT_OPERAND, newSelectList);
}
getRawSelectScope(select).setExpandedSelectList(expandedSelectItems);
// TODO: when SELECT appears as a value subquery, should be using
// something other than unknownType for targetRowType
inferUnknownTypes(targetRowType, selectScope, newSelectList);
for (SqlNode selectItem : expandedSelectItems) {
validateExpr(selectItem, selectScope);
}
assert fieldList.size() >= aliases.size();
return typeFactory.createStructType(fieldList);
}
/**
* Validates an expression.
*
* @param expr Expression
* @param scope Scope in which expression occurs
*/
private void validateExpr(SqlNode expr, SqlValidatorScope scope)
{
// Call on the expression to validate itself.
expr.validateExpr(this, scope);
// Perform any validation specific to the scope. For example, an
// aggregating scope requires that expressions are valid aggregations.
scope.validateExpr(expr);
}
/**
* Processes SubQuery found in Select list. Checks that is actually Scalar
* subquery and makes proper entries in each of the 3 lists used to create
* the final rowType entry.
*
* @param parentSelect base SqlSelect item
* @param selectItem child SqlSelect from select list
* @param expandedSelectItems Select items after processing
* @param aliasList built from user or system values
* @param fieldList Built up entries for each select list entry
*/
private void handleScalarSubQuery(
SqlSelect parentSelect,
SqlSelect selectItem,
List<SqlNode> expandedSelectItems,
Set<String> aliasList,
List<Map.Entry<String, RelDataType>> fieldList)
{
// A scalar subquery only has one output column.
if (1 != selectItem.getSelectList().size()) {
throw newValidationError(
selectItem,
EigenbaseResource.instance().OnlyScalarSubqueryAllowed.ex());
}
// No expansion in this routine just append to list.
expandedSelectItems.add(selectItem);
// Get or generate alias and add to list.
final String alias =
deriveAlias(
selectItem,
aliasList.size());
aliasList.add(alias);
final SelectScope scope = (SelectScope) getWhereScope(parentSelect);
final RelDataType type = deriveType(scope, selectItem);
setValidatedNodeTypeImpl(selectItem, type);
// we do not want to pass on the RelRecordType returned
// by the sub query. Just the type of the single expression
// in the subquery select list.
assert type instanceof RelRecordType;
RelRecordType rec = (RelRecordType) type;
RelDataType nodeType = rec.getFieldList().get(0).getType();
nodeType = typeFactory.createTypeWithNullability(nodeType, true);
fieldList.add(Pair.of(alias, nodeType));
}
/**
* Derives a row-type for INSERT and UPDATE operations.
*
* @param table Target table for INSERT/UPDATE
* @param targetColumnList List of target columns, or null if not specified
* @param append Whether to append fields to those in <code>
* baseRowType</code>
*
* @return Rowtype
*/
protected RelDataType createTargetRowType(
SqlValidatorTable table,
SqlNodeList targetColumnList,
boolean append)
{
RelDataType baseRowType = table.getRowType();
if (targetColumnList == null) {
return baseRowType;
}
List<RelDataTypeField> targetFields = baseRowType.getFieldList();
int targetColumnCount = targetColumnList.size();
if (append) {
targetColumnCount += baseRowType.getFieldCount();
}
RelDataType [] types = new RelDataType[targetColumnCount];
String [] fieldNames = new String[targetColumnCount];
int iTarget = 0;
if (append) {
iTarget += baseRowType.getFieldCount();
for (int i = 0; i < iTarget; ++i) {
types[i] = targetFields.get(i).getType();
fieldNames[i] = SqlUtil.deriveAliasFromOrdinal(i);
}
}
Set<String> assignedColumnNames = new HashSet<String>();
for (SqlNode node : targetColumnList) {
SqlIdentifier id = (SqlIdentifier) node;
int iColumn = baseRowType.getFieldOrdinal(id.getSimple());
if (!assignedColumnNames.add(id.getSimple())) {
throw newValidationError(
id,
EigenbaseResource.instance().DuplicateTargetColumn.ex(
id.getSimple()));
}
if (iColumn == -1) {
throw newValidationError(
id,
EigenbaseResource.instance().UnknownTargetColumn.ex(
id.getSimple()));
}
final RelDataTypeField targetField = targetFields.get(iColumn);
fieldNames[iTarget] = targetField.getName();
types[iTarget] = targetField.getType();
++iTarget;
}
return typeFactory.createStructType(types, fieldNames);
}
public void validateInsert(SqlInsert insert)
{
SqlValidatorNamespace targetNamespace = getNamespace(insert);
validateNamespace(targetNamespace);
SqlValidatorTable table = targetNamespace.getTable();
// INSERT has an optional column name list. If present then
// reduce the rowtype to the columns specified. If not present
// then the entire target rowtype is used.
RelDataType targetRowType =
createTargetRowType(
table,
insert.getTargetColumnList(),
false);
SqlNode source = insert.getSource();
if (source instanceof SqlSelect) {
SqlSelect sqlSelect = (SqlSelect) source;
validateSelect(sqlSelect, targetRowType);
} else {
SqlValidatorScope scope = scopes.get(source);
validateQuery(source, scope);
}
// REVIEW jvs 4-Dec-2008: In FRG-365, this namespace row type is
// discarding the type inferred by inferUnknownTypes (which was invoked
// from validateSelect above). It would be better if that information
// were used here so that we never saw any untyped nulls during
// checkTypeAssignment.
RelDataType sourceRowType = getNamespace(source).getRowType();
RelDataType logicalTargetRowType =
getLogicalTargetRowType(targetRowType, insert);
setValidatedNodeType(insert, logicalTargetRowType);
RelDataType logicalSourceRowType =
getLogicalSourceRowType(sourceRowType, insert);
checkFieldCount(insert, logicalSourceRowType, logicalTargetRowType);
checkTypeAssignment(logicalSourceRowType, logicalTargetRowType, insert);
validateAccess(insert.getTargetTable(), table, SqlAccessEnum.INSERT);
}
private void checkFieldCount(
SqlNode node,
RelDataType logicalSourceRowType,
RelDataType logicalTargetRowType)
{
final int sourceFieldCount = logicalSourceRowType.getFieldCount();
final int targetFieldCount = logicalTargetRowType.getFieldCount();
if (sourceFieldCount != targetFieldCount) {
throw newValidationError(
node,
EigenbaseResource.instance().UnmatchInsertColumn.ex(
targetFieldCount,
sourceFieldCount));
}
}
protected RelDataType getLogicalTargetRowType(
RelDataType targetRowType,
SqlInsert insert)
{
return targetRowType;
}
protected RelDataType getLogicalSourceRowType(
RelDataType sourceRowType,
SqlInsert insert)
{
return sourceRowType;
}
protected void checkTypeAssignment(
RelDataType sourceRowType,
RelDataType targetRowType,
final SqlNode query)
{
// NOTE jvs 23-Feb-2006: subclasses may allow for extra targets
// representing system-maintained columns, so stop after all sources
// matched
List<RelDataTypeField> sourceFields = sourceRowType.getFieldList();
List<RelDataTypeField> targetFields = targetRowType.getFieldList();
final int sourceCount = sourceFields.size();
for (int i = 0; i < sourceCount; ++i) {
RelDataType sourceType = sourceFields.get(i).getType();
RelDataType targetType = targetFields.get(i).getType();
if (!SqlTypeUtil.canAssignFrom(targetType, sourceType)) {
// FRG-255: account for UPDATE rewrite; there's
// probably a better way to do this.
int iAdjusted = i;
if (query instanceof SqlUpdate) {
int nUpdateColumns =
((SqlUpdate) query).getTargetColumnList().size();
assert (sourceFields.size() >= nUpdateColumns);
iAdjusted -= (sourceFields.size() - nUpdateColumns);
}
SqlNode node = getNthExpr(query, iAdjusted, sourceCount);
String targetTypeString;
String sourceTypeString;
if (SqlTypeUtil.areCharacterSetsMismatched(
sourceType,
targetType))
{
sourceTypeString = sourceType.getFullTypeString();
targetTypeString = targetType.getFullTypeString();
} else {
sourceTypeString = sourceType.toString();
targetTypeString = targetType.toString();
}
throw newValidationError(
node,
EigenbaseResource.instance().TypeNotAssignable.ex(
targetFields.get(i).getName(),
targetTypeString,
sourceFields.get(i).getName(),
sourceTypeString));
}
}
}
/**
* Locates the n'th expression in an INSERT or UPDATE query.
*
* @param query Query
* @param ordinal Ordinal of expression
* @param sourceCount Number of expressions
*
* @return Ordinal'th expression, never null
*/
private SqlNode getNthExpr(SqlNode query, int ordinal, int sourceCount)
{
if (query instanceof SqlInsert) {
SqlInsert insert = (SqlInsert) query;
if (insert.getTargetColumnList() != null) {
return insert.getTargetColumnList().get(ordinal);
} else {
return getNthExpr(
insert.getSource(),
ordinal,
sourceCount);
}
} else if (query instanceof SqlUpdate) {
SqlUpdate update = (SqlUpdate) query;
if (update.getTargetColumnList() != null) {
return update.getTargetColumnList().get(ordinal);
} else if (update.getSourceExpressionList() != null) {
return update.getSourceExpressionList().get(ordinal);
} else {
return getNthExpr(
update.getSourceSelect(),
ordinal,
sourceCount);
}
} else if (query instanceof SqlSelect) {
SqlSelect select = (SqlSelect) query;
if (select.getSelectList().size() == sourceCount) {
return select.getSelectList().get(ordinal);
} else {
return query; // give up
}
} else {
return query; // give up
}
}
public void validateDelete(SqlDelete call)
{
SqlSelect sqlSelect = call.getSourceSelect();
validateSelect(sqlSelect, unknownType);
IdentifierNamespace targetNamespace =
getNamespace(call.getTargetTable()).unwrap(
IdentifierNamespace.class);
validateNamespace(targetNamespace);
SqlValidatorTable table = targetNamespace.getTable();
validateAccess(call.getTargetTable(), table, SqlAccessEnum.DELETE);
}
public void validateUpdate(SqlUpdate call)
{
IdentifierNamespace targetNamespace =
getNamespace(call.getTargetTable()).unwrap(
IdentifierNamespace.class);
validateNamespace(targetNamespace);
SqlValidatorTable table = targetNamespace.getTable();
RelDataType targetRowType =
createTargetRowType(
table,
call.getTargetColumnList(),
true);
SqlSelect select = call.getSourceSelect();
validateSelect(select, targetRowType);
RelDataType sourceRowType = getNamespace(select).getRowType();
checkTypeAssignment(sourceRowType, targetRowType, call);
validateAccess(call.getTargetTable(), table, SqlAccessEnum.UPDATE);
}
public void validateMerge(SqlMerge call)
{
SqlSelect sqlSelect = call.getSourceSelect();
// REVIEW zfong 5/25/06 - Does an actual type have to be passed into
// validateSelect()?
// REVIEW jvs 6-June-2006: In general, passing unknownType like
// this means we won't be able to correctly infer the types
// for dynamic parameter markers (SET x = ?). But
// maybe validateUpdate and validateInsert below will do
// the job?
// REVIEW ksecretan 15-July-2011: They didn't get a chance to
// since validateSelect() would bail.
// Let's use the update/insert targetRowType when available.
IdentifierNamespace targetNamespace =
(IdentifierNamespace) getNamespace(call.getTargetTable());
validateNamespace(targetNamespace);
SqlValidatorTable table = targetNamespace.getTable();
validateAccess(call.getTargetTable(), table, SqlAccessEnum.UPDATE);
RelDataType targetRowType = unknownType;
if (call.getUpdateCall() != null) {
targetRowType = createTargetRowType(
table,
call.getUpdateCall().getTargetColumnList(),
true);
}
if (call.getInsertCall() != null) {
targetRowType = createTargetRowType(
table,
call.getInsertCall().getTargetColumnList(),
false);
}
validateSelect(sqlSelect, targetRowType);
if (call.getUpdateCall() != null) {
validateUpdate(call.getUpdateCall());
}
if (call.getInsertCall() != null) {
validateInsert(call.getInsertCall());
}
}
/**
* Validates access to a table.
*
* @param table Table
* @param requiredAccess Access requested on table
*/
private void validateAccess(
SqlNode node,
SqlValidatorTable table,
SqlAccessEnum requiredAccess)
{
if (table != null) {
SqlAccessType access = table.getAllowedAccess();
if (!access.allowsAccess(requiredAccess)) {
throw newValidationError(
node,
EigenbaseResource.instance().AccessNotAllowed.ex(
requiredAccess.name(),
table.getQualifiedName().toString()));
}
}
}
/**
* Validates a VALUES clause.
*
* @param node Values clause
* @param targetRowType Row type which expression must conform to
* @param scope Scope within which clause occurs
*/
protected void validateValues(
SqlCall node,
RelDataType targetRowType,
final SqlValidatorScope scope)
{
assert node.getKind() == SqlKind.VALUES;
final SqlNode [] operands = node.getOperands();
for (SqlNode operand : operands) {
if (!(operand.getKind() == SqlKind.ROW)) {
throw Util.needToImplement(
"Values function where operands are scalars");
}
SqlCall rowConstructor = (SqlCall) operand;
if (targetRowType.isStruct()
&& (rowConstructor.getOperands().length
!= targetRowType.getFieldCount()))
{
return;
}
inferUnknownTypes(
targetRowType,
scope,
rowConstructor);
}
for (SqlNode operand : operands) {
operand.validate(this, scope);
}
// validate that all row types have the same number of columns
// and that expressions in each column are compatible.
// A values expression is turned into something that looks like
// ROW(type00, type01,...), ROW(type11,...),...
final int rowCount = operands.length;
if (rowCount >= 2) {
SqlCall firstRow = (SqlCall) operands[0];
final int columnCount = firstRow.getOperands().length;
// 1. check that all rows have the same cols length
for (int row = 0; row < rowCount; row++) {
SqlCall thisRow = (SqlCall) operands[row];
if (columnCount != thisRow.operands.length) {
throw newValidationError(
node,
EigenbaseResource.instance().IncompatibleValueType.ex(
SqlStdOperatorTable.valuesOperator.getName()));
}
}
// 2. check if types at i:th position in each row are compatible
for (int col = 0; col < columnCount; col++) {
final int c = col;
final RelDataType type =
typeFactory.leastRestrictive(
new AbstractList<RelDataType>() {
public RelDataType get(int row) {
SqlCall thisRow = (SqlCall) operands[row];
return deriveType(scope, thisRow.operands[c]);
}
public int size() {
return rowCount;
}
}
);
if (null == type) {
throw newValidationError(
node,
EigenbaseResource.instance().IncompatibleValueType.ex(
SqlStdOperatorTable.valuesOperator.getName()));
}
}
}
}
public void validateDataType(SqlDataTypeSpec dataType)
{
}
public void validateDynamicParam(SqlDynamicParam dynamicParam)
{
}
public EigenbaseException newValidationError(
SqlNode node,
SqlValidatorException e)
{
assert node != null;
final SqlParserPos pos = node.getParserPosition();
return SqlUtil.newContextException(pos, e);
}
protected SqlWindow getWindowByName(
SqlIdentifier id,
SqlValidatorScope scope)
{
SqlWindow window = null;
if (id.isSimple()) {
final String name = id.getSimple();
window = scope.lookupWindow(name);
}
if (window == null) {
throw newValidationError(
id,
EigenbaseResource.instance().WindowNotFound.ex(
id.toString()));
}
return window;
}
public SqlWindow resolveWindow(
SqlNode windowOrRef,
SqlValidatorScope scope,
boolean populateBounds)
{
SqlWindow window;
if (windowOrRef instanceof SqlIdentifier) {
window = getWindowByName((SqlIdentifier) windowOrRef, scope);
} else {
window = (SqlWindow) windowOrRef;
}
while (true) {
final SqlIdentifier refId = window.getRefName();
if (refId == null) {
break;
}
final String refName = refId.getSimple();
SqlWindow refWindow = scope.lookupWindow(refName);
if (refWindow == null) {
throw newValidationError(
refId,
EigenbaseResource.instance().WindowNotFound.ex(refName));
}
window = window.overlay(refWindow, this);
}
// Fill in missing bounds.
if (populateBounds) {
if (window.getLowerBound() == null) {
window.setLowerBound(
SqlWindowOperator.createCurrentRow(SqlParserPos.ZERO));
}
if (window.getUpperBound() == null) {
window.setUpperBound(
SqlWindowOperator.createCurrentRow(SqlParserPos.ZERO));
}
}
return window;
}
public SqlNode getOriginal(SqlNode expr)
{
SqlNode original = originalExprs.get(expr);
if (original == null) {
original = expr;
}
return original;
}
public void setOriginal(SqlNode expr, SqlNode original)
{
// Don't overwrite the original original.
if (originalExprs.get(expr) == null) {
originalExprs.put(expr, original);
}
}
SqlValidatorNamespace lookupFieldNamespace(
RelDataType rowType,
String name)
{
final RelDataType dataType =
SqlValidatorUtil.lookupFieldType(rowType, name);
return new FieldNamespace(this, dataType);
}
public void validateWindow(
SqlNode windowOrId,
SqlValidatorScope scope,
SqlCall call)
{
final SqlWindow targetWindow;
switch (windowOrId.getKind()) {
case IDENTIFIER:
// Just verify the window exists in this query. It will validate
// when the definition is processed
targetWindow = getWindowByName((SqlIdentifier) windowOrId, scope);
break;
case WINDOW:
targetWindow = (SqlWindow) windowOrId;
break;
default:
throw Util.unexpected(windowOrId.getKind());
}
Util.pre(
null == targetWindow.getWindowCall(),
"(null == targetWindow.getWindowFunctionCall()");
targetWindow.setWindowCall(call);
targetWindow.validate(this, scope);
targetWindow.setWindowCall(null);
}
public void validateAggregateParams(
SqlCall aggFunction,
SqlValidatorScope scope)
{
// For agg(expr), expr cannot itself contain aggregate function
// invocations. For example, SUM(2*MAX(x)) is illegal; when
// we see it, we'll report the error for the SUM (not the MAX).
// For more than one level of nesting, the error which results
// depends on the traversal order for validation.
for (SqlNode param : aggFunction.getOperands()) {
final SqlNode agg = aggOrOverFinder.findAgg(param);
if (aggOrOverFinder.findAgg(param) != null) {
throw newValidationError(
aggFunction,
EigenbaseResource.instance().NestedAggIllegal.ex());
}
}
}
public void validateCall(
SqlCall call,
SqlValidatorScope scope)
{
final SqlOperator operator = call.getOperator();
if ((call.operands.length == 0)
&& (operator.getSyntax() == SqlSyntax.FunctionId)
&& !call.isExpanded())
{
// For example, "LOCALTIME()" is illegal. (It should be
// "LOCALTIME", which would have been handled as a
// SqlIdentifier.)
handleUnresolvedFunction(
call,
(SqlFunction) operator,
new RelDataType[0]);
}
SqlValidatorScope operandScope = scope.getOperandScope(call);
// Delegate validation to the operator.
operator.validateCall(call, this, scope, operandScope);
}
/**
* Validates that a particular feature is enabled. By default, all features
* are enabled; subclasses may override this method to be more
* discriminating.
*
* @param feature feature being used, represented as a resource definition
* from {@link EigenbaseResource}
* @param context parser position context for error reporting, or null if
* none available
*/
protected void validateFeature(
ResourceDefinition feature,
SqlParserPos context)
{
// By default, do nothing except to verify that the resource
// represents a real feature definition.
assert (feature.getProperties().get("FeatureDefinition") != null);
}
public SqlNode expand(SqlNode expr, SqlValidatorScope scope)
{
final Expander expander = new Expander(this, scope);
SqlNode newExpr = expr.accept(expander);
if (expr != newExpr) {
setOriginal(newExpr, expr);
}
return newExpr;
}
public boolean isSystemField(RelDataTypeField field)
{
return false;
}
public List<List<String>> getFieldOrigins(SqlNode sqlQuery)
{
if (sqlQuery instanceof SqlExplain) {
return Collections.emptyList();
}
final RelDataType rowType = getValidatedNodeType(sqlQuery);
final int fieldCount = rowType.getFieldCount();
if (!sqlQuery.isA(SqlKind.QUERY)) {
return Collections.nCopies(fieldCount, null);
}
final ArrayList<List<String>> list = new ArrayList<List<String>>();
for (int i = 0; i < fieldCount; i++) {
List<String> origin = getFieldOrigin(sqlQuery, i);
// assert origin == null || origin.size() >= 4 : origin;
list.add(origin);
}
return list;
}
private List<String> getFieldOrigin(SqlNode sqlQuery, int i)
{
if (sqlQuery instanceof SqlSelect) {
SqlSelect sqlSelect = (SqlSelect) sqlQuery;
final SelectScope scope = getRawSelectScope(sqlSelect);
final List<SqlNode> selectList = scope.getExpandedSelectList();
SqlNode selectItem = selectList.get(i);
if (SqlUtil.isCallTo(selectItem, SqlStdOperatorTable.asOperator)) {
selectItem = ((SqlCall) selectItem).getOperands()[0];
}
if (selectItem instanceof SqlIdentifier) {
SqlIdentifier id = (SqlIdentifier) selectItem;
SqlValidatorNamespace namespace = null;
List<String> origin = new ArrayList<String>();
for (String name : id.names) {
if (namespace == null) {
namespace = scope.resolve(name, null, null);
final SqlValidatorTable table = namespace.getTable();
if (table != null) {
origin.addAll(table.getQualifiedName());
} else {
return null;
}
} else {
namespace = namespace.lookupChild(name);
if (namespace != null) {
origin.add(name);
} else {
return null;
}
}
}
return origin;
}
}
return null;
}
public void validateColumnListParams(
SqlFunction function,
RelDataType [] argTypes,
SqlNode [] operands)
{
throw new UnsupportedOperationException();
}
//~ Inner Classes ----------------------------------------------------------
/**
* Common base class for DML statement namespaces.
*/
public static class DmlNamespace
extends IdentifierNamespace
{
protected DmlNamespace(
SqlValidatorImpl validator,
SqlIdentifier id,
SqlNode enclosingNode)
{
super(
validator,
id,
enclosingNode);
}
}
/**
* Namespace for an INSERT statement.
*/
private static class InsertNamespace
extends DmlNamespace
{
private final SqlInsert node;
public InsertNamespace(
SqlValidatorImpl validator,
SqlInsert node,
SqlNode enclosingNode)
{
super(
validator,
node.getTargetTable(),
enclosingNode);
this.node = node;
assert node != null;
}
public SqlInsert getNode()
{
return node;
}
}
/**
* Namespace for an UPDATE statement.
*/
private static class UpdateNamespace
extends DmlNamespace
{
private final SqlUpdate node;
public UpdateNamespace(
SqlValidatorImpl validator,
SqlUpdate node,
SqlNode enclosingNode)
{
super(
validator,
node.getTargetTable(),
enclosingNode);
this.node = node;
assert node != null;
}
public SqlUpdate getNode()
{
return node;
}
}
/**
* Namespace for a DELETE statement.
*/
private static class DeleteNamespace
extends DmlNamespace
{
private final SqlDelete node;
public DeleteNamespace(
SqlValidatorImpl validator,
SqlDelete node,
SqlNode enclosingNode)
{
super(
validator,
node.getTargetTable(),
enclosingNode);
this.node = node;
assert node != null;
}
public SqlDelete getNode()
{
return node;
}
}
/**
* Namespace for a MERGE statement.
*/
private static class MergeNamespace
extends DmlNamespace
{
private final SqlMerge node;
public MergeNamespace(
SqlValidatorImpl validator,
SqlMerge node,
SqlNode enclosingNode)
{
super(
validator,
node.getTargetTable(),
enclosingNode);
this.node = node;
assert node != null;
}
public SqlMerge getNode()
{
return node;
}
}
/**
* Visitor which derives the type of a given {@link SqlNode}.
*
* <p>Each method must return the derived type. This visitor is basically a
* single-use dispatcher; the visit is never recursive.
*/
private class DeriveTypeVisitor
implements SqlVisitor<RelDataType>
{
private final SqlValidatorScope scope;
public DeriveTypeVisitor(SqlValidatorScope scope)
{
this.scope = scope;
}
public RelDataType visit(SqlLiteral literal)
{
return literal.createSqlType(typeFactory);
}
public RelDataType visit(SqlCall call)
{
final SqlOperator operator = call.getOperator();
return operator.deriveType(SqlValidatorImpl.this, scope, call);
}
public RelDataType visit(SqlNodeList nodeList)
{
// Operand is of a type that we can't derive a type for. If the
// operand is of a peculiar type, such as a SqlNodeList, then you
// should override the operator's validateCall() method so that it
// doesn't try to validate that operand as an expression.
throw Util.needToImplement(nodeList);
}
public RelDataType visit(SqlIdentifier id)
{
// First check for builtin functions which don't have parentheses,
// like "LOCALTIME".
SqlCall call = SqlUtil.makeCall(opTab, id);
if (call != null) {
return call.getOperator().validateOperands(
SqlValidatorImpl.this,
scope,
call);
}
RelDataType type = null;
if (!(scope instanceof EmptyScope)) {
id = scope.fullyQualify(id);
}
for (int i = 0; i < id.names.length; i++) {
String name = id.names[i];
if (i == 0) {
// REVIEW jvs 9-June-2005: The name resolution rules used
// here are supposed to match SQL:2003 Part 2 Section 6.6
// (identifier chain), but we don't currently have enough
// information to get everything right. In particular,
// routine parameters are currently looked up via resolve;
// we could do a better job if they were looked up via
// resolveColumn.
// TODO jvs 9-June-2005: Support schema-qualified table
// names here (FRG-140). This was illegal in SQL-92, but
// became legal in SQL:1999. (SQL:2003 Part 2 Section
// 6.6 Syntax Rule 8.b.vi)
Util.discard(Bug.Frg140Fixed);
SqlValidatorNamespace resolvedNs =
scope.resolve(name, null, null);
if (resolvedNs != null) {
// There's a namespace with the name we seek.
type = resolvedNs.getRowType();
}
// Give precedence to namespace found, unless there
// are no more identifier components.
if ((type == null) || (id.names.length == 1)) {
// See if there's a column with the name we seek in
// precisely one of the namespaces in this scope.
RelDataType colType = scope.resolveColumn(name, id);
if (colType != null) {
type = colType;
}
}
if (type == null) {
throw newValidationError(
id.getComponent(i),
EigenbaseResource.instance().UnknownIdentifier.ex(
name));
}
} else {
RelDataType fieldType =
SqlValidatorUtil.lookupFieldType(type, name);
if (fieldType == null) {
throw newValidationError(
id.getComponent(i),
EigenbaseResource.instance().UnknownField.ex(name));
}
type = fieldType;
}
}
type =
SqlTypeUtil.addCharsetAndCollation(
type,
getTypeFactory());
return type;
}
public RelDataType visit(SqlDataTypeSpec dataType)
{
// Q. How can a data type have a type?
// A. When it appears in an expression. (Say as the 2nd arg to the
// CAST operator.)
validateDataType(dataType);
return dataType.deriveType(SqlValidatorImpl.this);
}
public RelDataType visit(SqlDynamicParam param)
{
return unknownType;
}
public RelDataType visit(SqlIntervalQualifier intervalQualifier)
{
return typeFactory.createSqlIntervalType(intervalQualifier);
}
}
/**
* Converts an expression into canonical form by fully-qualifying any
* identifiers.
*/
private static class Expander
extends SqlScopedShuttle
{
private final SqlValidatorImpl validator;
public Expander(
SqlValidatorImpl validator,
SqlValidatorScope scope)
{
super(scope);
this.validator = validator;
}
public SqlNode visit(SqlIdentifier id)
{
// First check for builtin functions which don't have
// parentheses, like "LOCALTIME".
SqlCall call =
SqlUtil.makeCall(
validator.getOperatorTable(),
id);
if (call != null) {
return call.accept(this);
}
final SqlIdentifier fqId = getScope().fullyQualify(id);
validator.setOriginal(fqId, id);
return fqId;
}
// implement SqlScopedShuttle
protected SqlNode visitScoped(SqlCall call)
{
// Only visits arguments which are expressions. We don't want to
// qualify non-expressions such as 'x' in 'empno * 5 AS x'.
ArgHandler<SqlNode> argHandler =
new CallCopyingArgHandler(call, false);
call.getOperator().acceptCall(this, call, true, argHandler);
final SqlNode result = argHandler.result();
validator.setOriginal(result, call);
return result;
}
}
/**
* Shuttle which walks over an expression in the ORDER BY clause, replacing
* usages of aliases with the underlying expression.
*/
class OrderExpressionExpander
extends SqlScopedShuttle
{
private final List<String> aliasList;
private final SqlSelect select;
private final SqlNode root;
OrderExpressionExpander(SqlSelect select, SqlNode root)
{
super(getOrderScope(select));
this.select = select;
this.root = root;
this.aliasList = getNamespace(select).getRowType().getFieldNames();
}
public SqlNode go()
{
return root.accept(this);
}
public SqlNode visit(SqlLiteral literal)
{
// Ordinal markers, e.g. 'select a, b from t order by 2'.
// Only recognize them if they are the whole expression,
// and if the dialect permits.
if ((literal == root)
&& getConformance().isSortByOrdinal())
{
if ((literal.getTypeName() == SqlTypeName.DECIMAL)
|| (literal.getTypeName() == SqlTypeName.DOUBLE))
{
final int intValue = literal.intValue(false);
if (intValue >= 0) {
if ((intValue < 1) || (intValue > aliasList.size())) {
throw newValidationError(
literal,
EigenbaseResource.instance()
.OrderByOrdinalOutOfRange.ex());
}
// SQL ordinals are 1-based, but SortRel's are 0-based
int ordinal = intValue - 1;
return nthSelectItem(
ordinal,
literal.getParserPosition());
}
}
}
return super.visit(literal);
}
/**
* Returns the <code>ordinal</code>th item in the select list.
*/
private SqlNode nthSelectItem(int ordinal, final SqlParserPos pos)
{
// TODO: Don't expand the list every time. Maybe keep an expanded
// version of each expression -- select lists and identifiers -- in
// the validator.
SqlNodeList expandedSelectList =
expandStar(
select.getSelectList(),
select,
false);
SqlNode expr = expandedSelectList.get(ordinal);
if (expr instanceof SqlCall) {
SqlCall call = (SqlCall) expr;
if (call.getOperator() == SqlStdOperatorTable.asOperator) {
expr = call.operands[0];
}
}
if (expr instanceof SqlIdentifier) {
expr = getScope().fullyQualify((SqlIdentifier) expr);
}
// Create a copy of the expression with the position of the order
// item.
return expr.clone(pos);
}
public SqlNode visit(SqlIdentifier id)
{
// Aliases, e.g. 'select a as x, b from t order by x'.
if (id.isSimple()
&& getConformance().isSortByAlias())
{
String alias = id.getSimple();
final SqlValidatorNamespace selectNs = getNamespace(select);
final RelDataType rowType =
selectNs.getRowTypeSansSystemColumns();
RelDataTypeField field =
SqlValidatorUtil.lookupField(rowType, alias);
if (field != null) {
return nthSelectItem(
field.getIndex(),
id.getParserPosition());
}
}
// No match. Return identifier unchanged.
return getScope().fullyQualify(id);
}
protected SqlNode visitScoped(SqlCall call)
{
// Don't attempt to expand sub-queries. We haven't implemented
// these yet.
if (call instanceof SqlSelect) {
return call;
}
return super.visitScoped(call);
}
}
protected static class IdInfo
{
public final SqlValidatorScope scope;
public final SqlIdentifier id;
public IdInfo(SqlValidatorScope scope, SqlIdentifier id)
{
this.scope = scope;
this.id = id;
}
}
/**
* Utility object used to maintain information about the parameters in a
* function call.
*/
protected static class FunctionParamInfo
{
/**
* Maps a cursor (based on its position relative to other cursor
* parameters within a function call) to the SELECT associated with the
* cursor.
*/
public final Map<Integer, SqlSelect> cursorPosToSelectMap;
/**
* Maps a column list parameter to the parent cursor parameter it
* references. The parameters are id'd by their names.
*/
public final Map<String, String> columnListParamToParentCursorMap;
public FunctionParamInfo()
{
cursorPosToSelectMap = new HashMap<Integer, SqlSelect>();
columnListParamToParentCursorMap = new HashMap<String, String>();
}
}
}
// End SqlValidatorImpl.java
|
[
"julianhyde@gmail.com"
] |
julianhyde@gmail.com
|
1784c3a9dc9ca85f1fca8b246f1facb43c0360f2
|
d856a198f368d0a1bb393f5083810576f5ae6c5d
|
/src/haven/Coord.java
|
e2d885c3397622ce83d6e5ab743c70476acb4356
|
[] |
no_license
|
PanAeon/Hearth-Haven-Groovy-Bot
|
5d04e4584401245dcadaca5f71a85b6a604d8e3e
|
3185fe077de183ce917768bf559f594b5357bfd2
|
refs/heads/master
| 2020-05-28T04:02:18.394783
| 2011-06-30T15:19:43
| 2011-06-30T15:19:43
| 1,977,691
| 1
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,856
|
java
|
package haven;
import java.awt.Dimension;
import java.io.Serializable;
public class Coord
implements Comparable<Coord>, Serializable
{
public int x;
public int y;
public static Coord z = new Coord(0, 0);
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
public Coord(Coord c) {
this(c.x, c.y);
}
public Coord() {
this(0, 0);
}
public Coord(Dimension d) {
this(d.width, d.height);
}
public static Coord sc(double a, double r) {
return new Coord((int)(Math.cos(a) * r), -(int)(Math.sin(a) * r));
}
public boolean equals(Object o) {
if (!(o instanceof Coord))
return false;
Coord c = (Coord)o;
return (c.x == this.x) && (c.y == this.y);
}
public int hashCode(){
int hash = 1;
hash = hash * 17 + x;
hash = hash * 31 + y;
return hash;
}
public int compareTo(Coord c) {
if (c.y != this.y)
return c.y - this.y;
if (c.x != this.x)
return c.x - this.x;
return 0;
}
public Coord add(int ax, int ay) {
return new Coord(this.x + ax, this.y + ay);
}
public Coord add(Coord b) {
return add(b.x, b.y);
}
public Coord sub(int ax, int ay) {
return new Coord(this.x - ax, this.y - ay);
}
public Coord sub(Coord b) {
return sub(b.x, b.y);
}
public Coord mul(int f) {
return new Coord(this.x * f, this.y * f);
}
public Coord mul(double f) {
return new Coord((int)(this.x * f), (int)(this.y * f));
}
public Coord inv() {
return new Coord(-this.x, -this.y);
}
public Coord mul(Coord f) {
return new Coord(this.x * f.x, this.y * f.y);
}
public Coord div(Coord d)
{
int v = (this.x < 0 ? this.x + 1 : this.x) / d.x;
int w = (this.y < 0 ? this.y + 1 : this.y) / d.y;
if (this.x < 0)
v--;
if (this.y < 0)
w--;
return new Coord(v, w);
}
public Coord div(int d) {
return div(new Coord(d, d));
}
public Coord mod(Coord d)
{
int v = this.x % d.x;
int w = this.y % d.y;
if (v < 0)
v += d.x;
if (w < 0)
w += d.y;
return new Coord(v, w);
}
public boolean isect(Coord c, Coord s) {
return (this.x >= c.x) && (this.y >= c.y) && (this.x < c.x + s.x) && (this.y < c.y + s.y);
}
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
public double angle(Coord o) {
Coord c = o.add(inv());
if (c.x == 0) {
if (c.y < 0) {
return -1.570796326794897D;
}
return 1.570796326794897D;
}
if (c.x < 0) {
if (c.y < 0) {
return -3.141592653589793D + Math.atan(c.y / c.x);
}
return 3.141592653589793D + Math.atan(c.y / c.x);
}
return Math.atan(c.y / c.x);
}
public double dist(Coord o)
{
long dx = o.x - this.x;
long dy = o.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
|
[
"PanAeon@rambler.ru"
] |
PanAeon@rambler.ru
|
e901f2dd358003e9b49fec33f27c3a7fb9c4e26d
|
c4d31d949d79b4bd974125b4546dbf0211cf4369
|
/src/review/effectivejava/chapter7/item48/ParallelMersennePrimes.java
|
a941ceaa22d1eaa9c320945fa67b6c3443ee0d2d
|
[] |
no_license
|
tuegum/JavaReview
|
0aa5ba70fc273e310d713bcb4827703cb31938d7
|
ea08a92f68ddcea06e0ebaed427307a6b33730b4
|
refs/heads/master
| 2022-12-15T14:32:30.796844
| 2020-09-07T02:23:43
| 2020-09-07T02:23:43
| 278,246,571
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 686
|
java
|
package review.effectivejava.chapter7.item48;
import java.math.BigInteger;
import java.util.stream.Stream;
import static java.math.BigInteger.*;
// Parallel stream-based program to generate the first 20 Mersenne primes - HANGS!!! (Page 222)
public class ParallelMersennePrimes {
public static void main(String[] args) {
primes().map(p -> TWO.pow(p.intValueExact()).subtract(ONE))
.parallel()
.filter(mersenne -> mersenne.isProbablePrime(50))
.limit(20)
.forEach(System.out::println);
}
static Stream<BigInteger> primes() {
return Stream.iterate(TWO, BigInteger::nextProbablePrime);
}
}
|
[
"3238927913@qq.com"
] |
3238927913@qq.com
|
59dedce1ff6f1bb4cecf685488b2677c5abd4eb5
|
df8b8d960c3e2d2ee3d1edc2a9d01c101dc7ed12
|
/src/main/java/com/gspe/employee/dto/EmployeeDto.java
|
26a0fa403f7dccfaa4e5d7ba6eb74ff9e774864d
|
[] |
no_license
|
alim-gspe/employee-dummy
|
2fe9159db8d032b3aa1bdb9fbb4b458a997092c3
|
61aa6cf4e8e10ee1d4e3e08cdab78cbe0e12ccb0
|
refs/heads/master
| 2023-06-06T22:05:41.100041
| 2021-07-05T02:26:30
| 2021-07-05T02:26:30
| 382,992,182
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 214
|
java
|
package com.gspe.employee.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class EmployeeDto {
private int id;
private String name;
private String division;
}
|
[
"alimulh@gspe.co.id"
] |
alimulh@gspe.co.id
|
258d56b58122bdce7f14f741a22cb2514a4c6278
|
10f4356ec61341dd76743d8002cd714d4364557d
|
/src/com/sera/android/lemmings/actions/BashAction.java
|
dad18d2a087b9f3f2b781b9d29ecd89a0898485a
|
[] |
no_license
|
serafinje/Lemmings
|
72333365cfb3d4ac0c43a81de388def690798b11
|
9b2a86bc670c22b372241276329468fb36c7ec16
|
refs/heads/master
| 2021-05-04T18:27:38.009942
| 2018-02-04T10:19:21
| 2018-02-04T10:19:21
| 120,171,425
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 135
|
java
|
package com.sera.android.lemmings.actions;
import android.graphics.Bitmap;
public class BashAction extends Animation {
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
b115f5ef482af5586a777762b9d3a188fc839862
|
6c93660ba09adebd6c15b48995a7bd801bb13fe6
|
/src/org/curvedrawer/util/RobotPath.java
|
82f5d9e10d2c29942eaa20f58169ef81bb198311
|
[] |
no_license
|
Marius-Juston/CurveDrawer
|
9a741fdfb3e83e91be72a07f458dac6f0d442e5a
|
e3f1387bf78976ec524470779d1b3a025a217c14
|
refs/heads/master
| 2021-09-07T13:47:07.225362
| 2018-02-23T19:33:42
| 2018-02-23T19:33:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 467
|
java
|
package org.curvedrawer.util;
import java.io.File;
import java.util.List;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Window;
public class RobotPath {
public static final List<File> retrieveCSVFile(Window owner) {
FileChooser fileChooser = new FileChooser();
fileChooser.setSelectedExtensionFilter(new ExtensionFilter("CVS Files", "*.cvs"));
return fileChooser.showOpenMultipleDialog(owner);
}
}
|
[
"Marius.juston@hotmail.fr"
] |
Marius.juston@hotmail.fr
|
8ec8896d6d3d9f7f791c0745504b04375539c773
|
4e2522c83c58ba8eb046c7f1ee7061ebf7ea3cea
|
/demo/src/demo/ax/client/GetMetricDataResponse.java
|
9c70c849779ef25e4d53c77c77887267308468a6
|
[] |
no_license
|
wangyafei233/demo
|
8ddb6a4fc467bb1a82ffd8bf00a63feb09abc57e
|
bb5f3036d5eeffe1e2546218704adad71a50c00a
|
refs/heads/master
| 2021-01-21T13:03:10.780727
| 2016-05-30T05:38:31
| 2016-05-30T05:38:31
| 53,640,093
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,497
|
java
|
package demo.ax.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getMetricDataResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getMetricDataResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="return" type="{http://wsdl.intf.dcm.intel.com/}enumerationData" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getMetricDataResponse", propOrder = {
"_return"
})
public class GetMetricDataResponse {
@XmlElement(name = "return")
protected EnumerationData _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link EnumerationData }
*
*/
public EnumerationData getReturn() {
return _return;
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link EnumerationData }
*
*/
public void setReturn(EnumerationData value) {
this._return = value;
}
}
|
[
"peter_wang@amaxchina.com"
] |
peter_wang@amaxchina.com
|
2d82871030264392581a548896d785c872022ea2
|
29ba6960b5c3ee7a2221c25e6f376026bf271233
|
/ProyectoSoldado/src/Muerto.java
|
90cfefbe2385883afc3f5cd20db11cecf0c513f3
|
[] |
no_license
|
marianog83/Soldado
|
023a3ac64ee9d41dcb2d55132a7efa8b53d8492b
|
40811da104ec40fd5b280d30f66c294a76378738
|
refs/heads/master
| 2022-08-31T00:29:02.096895
| 2020-05-15T22:08:26
| 2020-05-15T22:08:26
| 264,295,937
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 628
|
java
|
public class Muerto implements EstadoSalud {
private Soldado soldado;
public Muerto(Soldado soldado) {
this.soldado = soldado;
}
@Override
public void recibirDisparo() {
this.soldado.agregarAgujeros(1);
}
@Override
public void gritar() {
}
@Override
public void recibirCuracion() {
this.soldado.setEstado(new Saludable(soldado));
this.soldado.recuperarSangre(3000);
this.soldado.decrementarAgujeros(this.soldado.getAgujeros());
this.agradecer();
}
@Override
public void agradecer() {
System.out.println("He revivido!");
}
@Override
public String toString() {
return "Muerto";
}
}
|
[
"mariano.garcia@grupoesfera.com.ar"
] |
mariano.garcia@grupoesfera.com.ar
|
d480141ac112d40ae659c91083eedb44a0228978
|
5005c36dea502a8d5b4bf4f3a7705c03ff1c79e9
|
/plant/src/main/java/plant/model/Palm.java
|
811d693a0a5091aa34bb8366338ab94a46dc8b05
|
[] |
no_license
|
john-limkeman/WaterMyPlants
|
92d0cbd81192415716351c9ec4eb273338209be6
|
a43dd7c4c919b3cc35143935859e95a8b5a730a5
|
refs/heads/master
| 2022-12-10T14:16:02.510076
| 2020-09-12T23:39:21
| 2020-09-12T23:39:21
| 295,031,208
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,387
|
java
|
package plant.model;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Palm implements Plant{
private String type = "Palm";
private String name;
private boolean isThirsty;
private int daysUntilNextWater;
private int waterRate = 4;
private LocalDate nextWaterDate = LocalDate.now();
private LocalDate lastWaterDate = LocalDate.now().minusDays(waterRate);
public Palm(String plantName) {
this.name = plantName;
this.isThirsty = true;
}
public String record() {
String record = getType() + "," + getName() + "," + isThirsty() + "," + getNextWaterDate() + ","
+ getLastWaterDate() + "," + getWaterRate();
return record;
}
public void waterIt() {
setThirsty(false);
setLastWaterDate(LocalDate.now());
setNextWaterDate(LocalDate.now().plusDays(waterRate));
}
@Override // fix
public String toString() {
return getType() + " " + getName();
}
public int getDaysUntilNextWater() {
int daysRemaining = 0;
if (LocalDate.now().compareTo(getNextWaterDate()) > 0 || LocalDate.now().compareTo(getNextWaterDate()) == 0) {
return daysRemaining;
} else {
daysRemaining = (int) ChronoUnit.DAYS.between(LocalDate.now(), getNextWaterDate());
}
this.daysUntilNextWater = daysRemaining;
return daysUntilNextWater;
}
public boolean isThirsty() {
if (getDaysUntilNextWater() == 0) {
setThirsty(true);
}
return isThirsty;
}
public LocalDate getLastWaterDate() {
return lastWaterDate;
}
public void setLastWaterDate(LocalDate lastWaterDate) {
this.lastWaterDate = lastWaterDate;
}
public void setNextWaterDate(LocalDate nextWaterDate) {
this.nextWaterDate = nextWaterDate;
}
public LocalDate getNextWaterDate() {
return this.nextWaterDate;
}
public int getWaterRate() {
return waterRate;
}
public void setWaterRate(int waterRate) {
this.waterRate = waterRate;
}
public String getLightRecommendation() {
return "Part Sun (2-4 hours)";
}
public String getType() {
return type;
}
public String getName() {
return name;
}
public void setThirsty(boolean isThirsty) {
this.isThirsty = isThirsty;
}
public void setType(String type) {
this.type = type;
}
public void setName(String name) {
this.name = name;
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
a03e3c4e5f2c80a6c275caf65de6b572a12382f3
|
ee2f307f8942d414ba56e2c81ef107ee5daeac4c
|
/target/tomcat/work/localEngine/localhost/springsportscenter-mongo/org/apache/jsp/WEB_002dINF/views/hall/newHall_jsp.java
|
f3299a9992bab3abf93beb18d4d751771c0c3ae6
|
[] |
no_license
|
fanjun-wu/sportdomeforCloudBees
|
dc77352d5a96c6da38a0fc0995c8045f36a3f86a
|
0b96719220c8a5c4476d3282669ddad4229daf5c
|
refs/heads/master
| 2020-05-20T08:44:54.165222
| 2014-05-24T14:16:12
| 2014-05-24T14:16:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 12,738
|
java
|
package org.apache.jsp.WEB_002dINF.views.hall;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class newHall_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005fform_0026_005fname_005fmethod_005fcommandName_005faction;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fform_005fform_0026_005fname_005fmethod_005fcommandName_005faction = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fform_005fform_0026_005fname_005fmethod_005fcommandName_005faction.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
if (_jspx_meth_tiles_005finsertDefinition_005f0(_jspx_page_context))
return;
out.write('\r');
out.write('\n');
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_tiles_005finsertDefinition_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
HttpServletRequest request = (HttpServletRequest)_jspx_page_context.getRequest();
HttpServletResponse response = (HttpServletResponse)_jspx_page_context.getResponse();
// tiles:insertDefinition
org.apache.tiles.jsp.taglib.InsertDefinitionTag _jspx_th_tiles_005finsertDefinition_005f0 = new org.apache.tiles.jsp.taglib.InsertDefinitionTag();
org.apache.jasper.runtime.AnnotationHelper.postConstruct(_jsp_annotationprocessor, _jspx_th_tiles_005finsertDefinition_005f0);
_jspx_th_tiles_005finsertDefinition_005f0.setJspContext(_jspx_page_context);
// /WEB-INF/views/hall/newHall.jsp(8,0) name = name type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsertDefinition_005f0.setName("defaultTemplate");
_jspx_th_tiles_005finsertDefinition_005f0.setJspBody(new Helper( 0, _jspx_page_context, _jspx_th_tiles_005finsertDefinition_005f0, null));
_jspx_th_tiles_005finsertDefinition_005f0.doTag();
org.apache.jasper.runtime.AnnotationHelper.preDestroy(_jsp_annotationprocessor, _jspx_th_tiles_005finsertDefinition_005f0);
return false;
}
private boolean _jspx_meth_tiles_005fputAttribute_005f0(javax.servlet.jsp.tagext.JspTag _jspx_parent, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
HttpServletRequest request = (HttpServletRequest)_jspx_page_context.getRequest();
HttpServletResponse response = (HttpServletResponse)_jspx_page_context.getResponse();
// tiles:putAttribute
org.apache.tiles.jsp.taglib.PutAttributeTag _jspx_th_tiles_005fputAttribute_005f0 = new org.apache.tiles.jsp.taglib.PutAttributeTag();
org.apache.jasper.runtime.AnnotationHelper.postConstruct(_jsp_annotationprocessor, _jspx_th_tiles_005fputAttribute_005f0);
_jspx_th_tiles_005fputAttribute_005f0.setJspContext(_jspx_page_context);
_jspx_th_tiles_005fputAttribute_005f0.setParent(_jspx_parent);
// /WEB-INF/views/hall/newHall.jsp(9,1) name = name type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005fputAttribute_005f0.setName("body");
_jspx_th_tiles_005fputAttribute_005f0.setJspBody(new Helper( 1, _jspx_page_context, _jspx_th_tiles_005fputAttribute_005f0, null));
_jspx_th_tiles_005fputAttribute_005f0.doTag();
org.apache.jasper.runtime.AnnotationHelper.preDestroy(_jsp_annotationprocessor, _jspx_th_tiles_005fputAttribute_005f0);
return false;
}
private boolean _jspx_meth_form_005fform_005f0(javax.servlet.jsp.tagext.JspTag _jspx_parent, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
HttpServletRequest request = (HttpServletRequest)_jspx_page_context.getRequest();
HttpServletResponse response = (HttpServletResponse)_jspx_page_context.getResponse();
// form:form
org.springframework.web.servlet.tags.form.FormTag _jspx_th_form_005fform_005f0 = (org.springframework.web.servlet.tags.form.FormTag) _005fjspx_005ftagPool_005fform_005fform_0026_005fname_005fmethod_005fcommandName_005faction.get(org.springframework.web.servlet.tags.form.FormTag.class);
_jspx_th_form_005fform_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005fform_005f0.setParent(new javax.servlet.jsp.tagext.TagAdapter((javax.servlet.jsp.tagext.SimpleTag) _jspx_parent));
// /WEB-INF/views/hall/newHall.jsp(21,3) name = name type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setName("newHallForm");
// /WEB-INF/views/hall/newHall.jsp(21,3) name = commandName type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setCommandName("hall");
// /WEB-INF/views/hall/newHall.jsp(21,3) name = action type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setAction("saveHall");
// /WEB-INF/views/hall/newHall.jsp(21,3) name = method type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setMethod("post");
int[] _jspx_push_body_count_form_005fform_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005fform_005f0 = _jspx_th_form_005fform_005f0.doStartTag();
if (_jspx_eval_form_005fform_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write("\t\t\t\t");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/WEB-INF/views/includes/hall/hallDetails.jsp", out, false);
out.write("\r\n");
out.write("\t\t\t\t<br/>\r\n");
out.write("\t\t\t\t<a href=\"hallList\">Back to list</a> \r\n");
out.write("\t\t\t\t<a href=\"javascript: document.forms.newHallForm.submit();\">Create new hall</a> \r\n");
out.write("\t\t\t");
int evalDoAfterBody = _jspx_th_form_005fform_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_form_005fform_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
throw new SkipPageException();
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005fform_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005fform_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005fform_005f0.doFinally();
_005fjspx_005ftagPool_005fform_005fform_0026_005fname_005fmethod_005fcommandName_005faction.reuse(_jspx_th_form_005fform_005f0);
}
return false;
}
private class Helper
extends org.apache.jasper.runtime.JspFragmentHelper
{
private javax.servlet.jsp.tagext.JspTag _jspx_parent;
private int[] _jspx_push_body_count;
public Helper( int discriminator, JspContext jspContext, javax.servlet.jsp.tagext.JspTag _jspx_parent, int[] _jspx_push_body_count ) {
super( discriminator, jspContext, _jspx_parent );
this._jspx_parent = _jspx_parent;
this._jspx_push_body_count = _jspx_push_body_count;
}
public boolean invoke0( JspWriter out )
throws Throwable
{
HttpServletRequest request = (HttpServletRequest)_jspx_page_context.getRequest();
HttpServletResponse response = (HttpServletResponse)_jspx_page_context.getResponse();
out.write('\r');
out.write('\n');
out.write(' ');
if (_jspx_meth_tiles_005fputAttribute_005f0(_jspx_parent, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
return false;
}
public boolean invoke1( JspWriter out )
throws Throwable
{
HttpServletRequest request = (HttpServletRequest)_jspx_page_context.getRequest();
HttpServletResponse response = (HttpServletResponse)_jspx_page_context.getResponse();
out.write("\r\n");
out.write("\t\t<div class=\"body\">\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\t");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/WEB-INF/views/includes/header.jsp", out, false);
out.write("\r\n");
out.write("\r\n");
out.write("\t");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/WEB-INF/views/includes/logo.jsp", out, false);
out.write("\r\n");
out.write("\t\t<div>\r\n");
out.write("\t\t\r\n");
out.write("\t\t\t<h1>New Hall</h1>\r\n");
out.write("\t\t\t\r\n");
out.write("\t\t\t\r\n");
out.write("\t\t\t");
if (_jspx_meth_form_005fform_005f0(_jspx_parent, _jspx_page_context))
return true;
out.write("\r\n");
out.write("\t\t\t\r\n");
out.write("\t\t\t");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "/WEB-INF/views/includes/footer.jsp", out, false);
out.write("\r\n");
out.write("\t\t\r\n");
out.write("\t\t </div>\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("</div>\r\n");
out.write("\r\n");
out.write("\t");
return false;
}
public void invoke( java.io.Writer writer )
throws JspException
{
JspWriter out = null;
if( writer != null ) {
out = this.jspContext.pushBody(writer);
} else {
out = this.jspContext.getOut();
}
try {
this.jspContext.getELContext().putContext(JspContext.class,this.jspContext);
switch( this.discriminator ) {
case 0:
invoke0( out );
break;
case 1:
invoke1( out );
break;
}
}
catch( Throwable e ) {
if (e instanceof SkipPageException)
throw (SkipPageException) e;
throw new JspException( e );
}
finally {
if( writer != null ) {
this.jspContext.popBody();
}
}
}
}
}
|
[
"lihuachenchen2507@gmail.com"
] |
lihuachenchen2507@gmail.com
|
707935ee51854f05f662cc85aa2168f3fba18234
|
9fb5f944087a8b0ec8bd2d205098a01ad1a6d09c
|
/src/rs/ac/bg/etf/pp1/ast/MatchedIfError.java
|
e8b858a23b0ceea2b3f7f9c17bba7e46c5100493
|
[] |
no_license
|
Luka-Popovic/microjava-compiler
|
ce088c97bcadfba5ba7c9874730c8280452421dd
|
f399652b5e234357988d4d11de64a4acb8b8038c
|
refs/heads/master
| 2022-12-01T00:54:08.878438
| 2020-08-26T11:20:09
| 2020-08-26T11:20:09
| 290,476,692
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 809
|
java
|
// generated with ast extension for cup
// version 0.8
// 6/1/2018 13:54:6
package rs.ac.bg.etf.pp1.ast;
public class MatchedIfError extends Matched {
public MatchedIfError () {
}
public void accept(Visitor visitor) {
visitor.visit(this);
}
public void childrenAccept(Visitor visitor) {
}
public void traverseTopDown(Visitor visitor) {
accept(visitor);
}
public void traverseBottomUp(Visitor visitor) {
accept(visitor);
}
public String toString(String tab) {
StringBuffer buffer=new StringBuffer();
buffer.append(tab);
buffer.append("MatchedIfError(\n");
buffer.append(tab);
buffer.append(") [MatchedIfError]");
return buffer.toString();
}
}
|
[
"pol@sly.ch"
] |
pol@sly.ch
|
eb4deaa60006bfb4ced081e31ce3f9f2355f88c9
|
17a00e3e185a7c10d06225f8ab35cd5d34c9b046
|
/Server/src/org/rscdaemon/server/packethandler/client/org/client/ShopHandler.java
|
bf089af47e814d46b2e12c202316365af48b4e35
|
[] |
no_license
|
mikenike360/VenemScape
|
36bca6b2172a6b18628087a5f24e12244ec9195e
|
77aaf7571faed87b6abd9717b577dd01a3beb241
|
refs/heads/master
| 2020-05-05T11:36:50.724725
| 2019-04-07T17:20:07
| 2019-04-07T17:20:07
| 179,996,511
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,528
|
java
|
package org.rscdaemon.server.packethandler.client;
import org.rscdaemon.server.packethandler.PacketHandler;
import org.rscdaemon.server.model.*;
import org.rscdaemon.server.net.Packet;
import org.rscdaemon.server.net.RSCPacket;
import org.apache.mina.common.IoSession;
public class ShopHandler implements PacketHandler {
/**
* World instance
*/
public static final World world = World.getWorld();
public void handlePacket(Packet p, IoSession session) throws Exception {
Player player = (Player)session.getAttachment();
int pID = ((RSCPacket)p).getID();
if(player.isBusy()) {
player.resetShop();
return;
}
final Shop shop = player.getShop();
if(shop == null) {
player.setSuspiciousPlayer(true);
player.resetShop();
return;
}
int value;
InvItem item;
switch(pID) {
case 253: // Close shop
player.resetShop();
break;
case 128: // Buy item
item = new InvItem(p.readShort(), 1);
value = p.readInt();
if(value != ((shop.getBuyModifier() * item.getDef().getBasePrice()) / 100) || shop.countId(item.getID()) < 1) {
return;
}
if(player.getInventory().countId(10) < value) {
player.getActionSender().sendMessage("You don't have enough money to buy that!");
return;
}
if((Inventory.MAX_SIZE - player.getInventory().size()) + player.getInventory().getFreedSlots(new InvItem(10, value)) < player.getInventory().getRequiredSlots(item)) {
player.getActionSender().sendMessage("You don't have room for that in your inventory");
return;
}
if(player.getInventory().remove(10, value) > -1) {
shop.remove(item);
player.getInventory().add(item);
player.getActionSender().sendSound("coins");
player.getActionSender().sendInventory();
shop.updatePlayers();
}
break;
case 255: // Sell item
item = new InvItem(p.readShort(), 1);
value = p.readInt();
if(value != ((shop.getSellModifier() * item.getDef().getBasePrice()) / 100) || player.getInventory().countId(item.getID()) < 1) {
return;
}
if(!shop.shouldStock(item.getID())) {
return;
}
if(!shop.canHold(item)) {
player.getActionSender().sendMessage("The shop is currently full!");
return;
}
if(player.getInventory().remove(item) > -1) {
player.getInventory().add(new InvItem(10, value));
shop.add(item);
player.getActionSender().sendSound("coins");
player.getActionSender().sendInventory();
shop.updatePlayers();
}
break;
}
}
}
|
[
"michael.venema2010@gmail.com"
] |
michael.venema2010@gmail.com
|
df506948df46edcf952c0c3eb360d7621022328a
|
f016fa49f9e378e886eae935de41949f431aa6df
|
/Hominglauncher.java
|
8c232fa2b100187fe72e4d2048502662aad6f1a4
|
[] |
no_license
|
porterjamesf/Jned
|
832fdd87a4fb5ca05feee75299e92256da1aaf69
|
c6b090fb26987c89a1b6e8529cddc4dcd86706d1
|
refs/heads/master
| 2021-01-10T20:44:02.727197
| 2015-05-11T20:43:16
| 2015-05-11T20:43:16
| 23,001,942
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 692
|
java
|
/**
* A Homing launcher item in Jned.
* @author James Porter
*/
public class Hominglauncher extends Turret {
/**
* Constructs a new Hominglauncher with the given position.
* @param jned a reference to the enclosing Jned instance
* @param x this Hominglauncher's x position
* @param y this Hominglauncher's y position
*/
public Hominglauncher (Jned jned, int x, int y) {
super(jned, 1, x, y);
setImage(ImageBank.HOMING);
}
/**
* Returns a copy of this Hominglauncher.
* @return a new Hominglauncher with the same properties as this Hominglauncher
*/
public Hominglauncher duplicate() {
return new Hominglauncher(jned, getX(), getY());
}
}
|
[
"porterjamesf@gmail.com"
] |
porterjamesf@gmail.com
|
d3c9fe8f36915b9e90368627e1002df5f6e9f4a6
|
6c4df84cd0ea730a7a61c38d7830006dc6f7c84c
|
/src/main/java/pl/krysinski/weatherdb/model/openweatherApi/Clouds.java
|
1ea988603c1d92ba869e593bc32e10ba3ce50f8d
|
[] |
no_license
|
MarcinKrysinski/WeatherDB
|
a238877856695297bbeb8051007d22cb9f8139b6
|
d224df6f66aa24f569412560ffc02a238666f79a
|
refs/heads/master
| 2023-01-14T10:20:14.695702
| 2020-11-18T18:59:19
| 2020-11-18T18:59:19
| 313,623,809
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 855
|
java
|
package pl.krysinski.weatherdb.model.openweatherApi;
import com.fasterxml.jackson.annotation.*;
import java.util.HashMap;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"all"
})
public class Clouds {
@JsonProperty("all")
private Integer all;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("all")
public Integer getAll() {
return all;
}
@JsonProperty("all")
public void setAll(Integer all) {
this.all = all;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
[
"marcin.jakubkrysinski@gmail.com"
] |
marcin.jakubkrysinski@gmail.com
|
416f3e51a737b902947101504b3fcc2332e8859a
|
ed70c6341370399344c8e8bb543b47d9facff129
|
/src/test/java/MainPlacesTest.java
|
e6e26c192a26f90ecf4f2ad3724a8b496ac43ede
|
[] |
no_license
|
dimaVais/GmapApiTester
|
96e1ac2d68cc983a5c8ce12a24cf157a2e37d1c5
|
084395ecafd02a2b8488dabb2e09f37a29a9c841
|
refs/heads/master
| 2022-07-03T11:20:22.095357
| 2020-11-02T15:00:25
| 2020-11-02T15:00:25
| 177,672,451
| 0
| 0
| null | 2022-06-21T01:00:57
| 2019-03-25T22:12:10
|
Java
|
UTF-8
|
Java
| false
| false
| 3,704
|
java
|
import com.aventstack.extentreports.MediaEntityBuilder;
import org.apache.commons.lang3.tuple.Triple;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.ArrayList;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MainPlacesTest
{
private static WebDriver driver;
private static ArrayList<Triple<String,String,String>> allSqlData; //All the data from remote SQL server.
private static ArrayList<Float[]> allAPIData = new ArrayList<Float[]>(); //All the data of lat and lng from API.
private static ArrayList<String[]> allResultData = new ArrayList<String[]>();//All test result data.
//Before class, initialize report class
@BeforeClass
public static void setPlacesTest()
{
new Reports();
}
//Suite to test data extraction from remote SQL.
@Test
public void test01_GetDataFromSql()
{
SqlDataGetter getLoc = new SqlDataGetter();
getLoc.connectToDB();
getLoc.readDBTable();
allSqlData = getLoc.getAllDbData();
Reports.reporter.pass(Reports.TEST_SUIT_PASS_MESSAGE + new Throwable().getStackTrace()[0].getMethodName());
}
//Suite to test request to Google places API according to the SQL data, and extracting of wanted values from the API.
@Test
public void test02_GetGooglePlacesData()
{
for (int i=0; i<allSqlData.size(); i++) {
GetLatAndLngFromPlaces placeTofind = new GetLatAndLngFromPlaces(allSqlData.get(i).getLeft(), allSqlData.get(i).getMiddle());
placeTofind.getFromApiLatAndLng();
allAPIData.add(new Float[]{placeTofind.getLat(), placeTofind.getLng()});
}
Reports.reporter.pass(Reports.TEST_SUIT_PASS_MESSAGE + new Throwable().getStackTrace()[0].getMethodName());
}
//Suite to test finding the location which retrieved from the API on Google maps, using selenium web driver.
@Test
public void test03_TestLocOnGoogleMaps() throws IOException {
System.setProperty(Consts.DRIVER_TYPE,Consts.DRIVER_PATH);
driver = new ChromeDriver();
SnapShot snap = new SnapShot(driver);
for(int i=0;i<allAPIData.size();i++) {
GoogleMapsWebTest tester = new GoogleMapsWebTest(driver, allAPIData.get(i)[0], allAPIData.get(i)[1], allSqlData.get(i).getRight());
String location = tester.findLocationFromAPI();
String[] currResult = tester.testLocationSearchOnMap(location);
allResultData.add(currResult);
Reports.reporter.pass(Reports.PAGE_FINISH_MSG, MediaEntityBuilder.createScreenCaptureFromPath(snap.takeScreenShot(Consts.GENERAL_FILE_PATH)).build()); //Take a screenshot.
}
Reports.reporter.pass(Reports.TEST_SUIT_PASS_MESSAGE + new Throwable().getStackTrace()[0].getMethodName());
driver.close();
}
//Suit to test writing of the test status to a remote SQL DB table.
@Test
public void test04_WriteTestResultToDb()
{
SqlDataGetter setResult = new SqlDataGetter();
for (int i = 0; i< allResultData.size(); i++) {
setResult.connectToDB();
setResult.writeStatusToDb(allResultData.get(i)[0], allResultData.get(i)[1]);
}
Reports.reporter.pass(Reports.TEST_SUIT_PASS_MESSAGE + new Throwable().getStackTrace()[0].getMethodName());
}
//After class, flush of the reports.
@AfterClass
public static void closePlacesTest()
{
Reports.createReport();
}
}
|
[
"dimavais300@gmail.com"
] |
dimavais300@gmail.com
|
1b7706ab94f41ca2bf9352829c19bf891a229453
|
77099bed3ce32eab5298af75677e5f1a88e484ec
|
/src/main/java/com/jin/service/GreetingService.java
|
5885daf7cc75191603f4b186b7de961ba83b34e7
|
[] |
no_license
|
cicadasworld/spring-framework-in-depth
|
c841aa584392c05ca9af3e4e759727a8583f2be7
|
29f5efdffda3825f057f6ec3d062080f1c1afff4
|
refs/heads/master
| 2022-04-16T06:18:25.022363
| 2020-04-19T04:15:16
| 2020-04-19T04:15:16
| 256,908,759
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 272
|
java
|
package com.jin.service;
public class GreetingService {
private final String greeting;
public GreetingService(String greeting) {
this.greeting = greeting;
}
public String getGreeting(String name) {
return greeting + " " + name;
}
}
|
[
"flyterren@163.com"
] |
flyterren@163.com
|
0c4ecb6bfe672ef15f279ff4a5faff7044a02454
|
ef4e192935fc79ff9e3865de38e2171ac7c41439
|
/app/src/androidTest/java/com/top/greenbeans/ExampleInstrumentedTest.java
|
88331b5a9f6883cdaae1cda91d4d416b0de5b97e
|
[] |
no_license
|
topdevelopment/GreenBeans
|
7195da15636462066c2e93beaec9153135560067
|
c22ec4254ba736d9e60921e35e3e30b9f01aa9a4
|
refs/heads/master
| 2023-05-07T17:53:36.299227
| 2021-05-30T13:42:56
| 2021-05-30T13:42:56
| 372,198,011
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 752
|
java
|
package com.top.greenbeans;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.top.greenbeans", appContext.getPackageName());
}
}
|
[
"thatoneprogrammer@Austins-MacBook-Air.local"
] |
thatoneprogrammer@Austins-MacBook-Air.local
|
2031ae46eadd73e61802f9586b8490c3db413ed3
|
53d677a55e4ece8883526738f1c9d00fa6560ff7
|
/com/tencent/mm/plugin/topstory/ui/video/fs/b.java
|
d31b645d55c3b8a3cad494842992e94f85681492
|
[] |
no_license
|
0jinxing/wechat-apk-source
|
544c2d79bfc10261eb36389c1edfdf553d8f312a
|
f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d
|
refs/heads/master
| 2020-06-07T20:06:03.580028
| 2019-06-21T09:17:26
| 2019-06-21T09:17:26
| 193,069,132
| 9
| 4
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,949
|
java
|
package com.tencent.mm.plugin.topstory.ui.video.fs;
import android.graphics.PointF;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.i;
import android.support.v7.widget.RecyclerView.r.b;
import android.support.v7.widget.ah;
import android.support.v7.widget.am;
import android.view.View;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.plugin.topstory.ui.widget.g;
public final class b extends g
{
private am amf;
private am amg;
private static int a(RecyclerView.i parami, View paramView, am paramam)
{
AppMethodBeat.i(1866);
int i = paramam.bf(paramView);
int j = paramam.bj(paramView) / 2;
if (parami.getClipToPadding());
for (int k = paramam.je() + paramam.jg() / 2; ; k = paramam.getEnd() / 2)
{
AppMethodBeat.o(1866);
return j + i - k;
}
}
private static View a(RecyclerView.i parami, am paramam)
{
View localView1 = null;
View localView2 = null;
AppMethodBeat.i(1867);
int i = parami.getChildCount();
if (i == 0)
{
AppMethodBeat.o(1867);
return localView2;
}
int j;
label49: int m;
if (parami.getClipToPadding())
{
j = paramam.je() + paramam.jg() / 2;
int k = 2147483647;
m = 0;
localView2 = localView1;
label58: if (m >= i)
break label123;
localView1 = parami.getChildAt(m);
int n = Math.abs(paramam.bf(localView1) + paramam.bj(localView1) / 2 - j);
if (n >= k)
break label132;
localView2 = localView1;
k = n;
}
label132:
while (true)
{
m++;
break label58;
j = paramam.getEnd() / 2;
break label49;
label123: AppMethodBeat.o(1867);
break;
}
}
private am b(RecyclerView.i parami)
{
AppMethodBeat.i(1869);
if ((this.amf == null) || (this.amf.getLayoutManager() != parami))
this.amf = am.e(parami);
parami = this.amf;
AppMethodBeat.o(1869);
return parami;
}
private am c(RecyclerView.i parami)
{
AppMethodBeat.i(1870);
if ((this.amg == null) || (this.amg.getLayoutManager() != parami))
this.amg = am.d(parami);
parami = this.amg;
AppMethodBeat.o(1870);
return parami;
}
private static View c(RecyclerView.i parami, am paramam)
{
View localView1 = null;
View localView2 = null;
AppMethodBeat.i(1868);
int i = parami.getChildCount();
if (i == 0)
{
AppMethodBeat.o(1868);
return localView2;
}
int j = 2147483647;
int k = 0;
localView2 = localView1;
label38: if (k < i)
{
localView1 = parami.getChildAt(k);
int m = paramam.bf(localView1);
if (m >= j)
break label87;
localView2 = localView1;
j = m;
}
label87:
while (true)
{
k++;
break label38;
AppMethodBeat.o(1868);
break;
}
}
public final int a(RecyclerView.i parami, int paramInt1, int paramInt2)
{
int i = 0;
int j = -1;
AppMethodBeat.i(1864);
if ((Math.abs(paramInt2) <= 500) || (Math.abs(paramInt1) >= Math.abs(paramInt2)))
{
AppMethodBeat.o(1864);
paramInt1 = j;
}
while (true)
{
return paramInt1;
int k = parami.getItemCount();
if (k == 0)
{
AppMethodBeat.o(1864);
paramInt1 = j;
}
else
{
View localView = null;
if (parami.iH())
localView = c(parami, b(parami));
while (true)
{
if (localView != null)
break label126;
AppMethodBeat.o(1864);
paramInt1 = j;
break;
if (parami.iG())
localView = c(parami, c(parami));
}
label126: int m = RecyclerView.i.bt(localView);
if (m == -1)
{
AppMethodBeat.o(1864);
paramInt1 = j;
}
else
{
if (parami.iG())
if (paramInt1 > 0)
paramInt1 = 1;
while (true)
{
paramInt2 = i;
if ((parami instanceof RecyclerView.r.b))
{
parami = ((RecyclerView.r.b)parami).bX(k - 1);
paramInt2 = i;
if (parami != null)
if (parami.x >= 0.0F)
{
paramInt2 = i;
if (parami.y >= 0.0F);
}
else
{
paramInt2 = 1;
}
}
if (paramInt2 == 0)
break label271;
if (paramInt1 == 0)
break label259;
paramInt1 = m - 1;
AppMethodBeat.o(1864);
break;
paramInt1 = 0;
continue;
if (paramInt2 > 0)
paramInt1 = 1;
else
paramInt1 = 0;
}
label259: AppMethodBeat.o(1864);
paramInt1 = m;
continue;
label271: if (paramInt1 != 0)
{
paramInt1 = m + 1;
AppMethodBeat.o(1864);
}
else
{
AppMethodBeat.o(1864);
paramInt1 = m;
}
}
}
}
}
public final View a(RecyclerView.i parami)
{
AppMethodBeat.i(1863);
if (parami.iH())
{
parami = a(parami, b(parami));
AppMethodBeat.o(1863);
}
while (true)
{
return parami;
if (parami.iG())
{
parami = a(parami, c(parami));
AppMethodBeat.o(1863);
}
else
{
parami = null;
AppMethodBeat.o(1863);
}
}
}
public final int[] a(RecyclerView.i parami, View paramView)
{
AppMethodBeat.i(1862);
int[] arrayOfInt = new int[2];
if (parami.iG())
{
arrayOfInt[0] = a(parami, paramView, c(parami));
if (!parami.iH())
break label65;
arrayOfInt[1] = a(parami, paramView, b(parami));
}
while (true)
{
AppMethodBeat.o(1862);
return arrayOfInt;
arrayOfInt[0] = 0;
break;
label65: arrayOfInt[1] = 0;
}
}
public final ah f(RecyclerView.i parami)
{
AppMethodBeat.i(1865);
if (!(parami instanceof RecyclerView.r.b))
{
parami = null;
AppMethodBeat.o(1865);
}
while (true)
{
return parami;
parami = new b.1(this, this.aiB.getContext());
AppMethodBeat.o(1865);
}
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes7-dex2jar.jar
* Qualified Name: com.tencent.mm.plugin.topstory.ui.video.fs.b
* JD-Core Version: 0.6.2
*/
|
[
"172601673@qq.com"
] |
172601673@qq.com
|
e984fc4574ed4f538bc070ac907a411af99caae3
|
9a922e239d4d41925363d7c744324e9827a59570
|
/5o/is/bet-o-matic/tags/it-2/src/test/java/es/udc/betomatic/test/model/commonservice/CommonServiceTest.java
|
ab649a1c53ec44d04c7e6c02e2e75301f34d1032
|
[] |
no_license
|
fpozzas/fic
|
e655426604ca12dc6f9c0be6e8f9081852f42aaa
|
b4a9b930f64f928858e7991798c46741a59b70fd
|
refs/heads/master
| 2021-01-20T11:14:16.927171
| 2013-04-08T09:28:30
| 2013-04-08T09:28:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,496
|
java
|
package es.udc.betomatic.test.model.commonservice;
import static es.udc.betomatic.model.util.GlobalNames.SPRING_CONFIG_FILE;
import static es.udc.betomatic.test.util.GlobalNames.SPRING_CONFIG_TEST_FILE;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import es.udc.betomatic.test.model.util.DbUtil;
import es.udc.pojo.modelutil.exceptions.DuplicateInstanceException;
import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;
import es.udc.betomatic.model.category.Category;
import es.udc.betomatic.model.commonservice.CommonService;
import es.udc.betomatic.model.commonservice.IncorrectPasswordException;
import es.udc.betomatic.model.user.User;
import es.udc.betomatic.model.user.UserDao;
import es.udc.betomatic.model.user.UserDetails;
import es.udc.betomatic.model.util.PasswordEncrypter;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { SPRING_CONFIG_FILE, SPRING_CONFIG_TEST_FILE })
@Transactional
public class CommonServiceTest {
@Autowired
private UserDao userDao;
@Autowired
private CommonService commonService;
@BeforeClass
public static void populateDb() throws Throwable {
DbUtil.populateDb();
}
@AfterClass
public static void cleanDb() throws Throwable {
DbUtil.cleanDb();
}
@Test
public void testUserAuthentication() throws InstanceNotFoundException, IncorrectPasswordException {
User user2 = userDao.find(DbUtil.getTestUserId());
boolean passwdIsEncrypted = true;
User user = commonService.authenticate(user2.getLogin(),user2.getPasswd(),passwdIsEncrypted);
assertEquals(user, user2);
}
@Test
public void testCreateAuthenticate()
throws DuplicateInstanceException,InstanceNotFoundException, IncorrectPasswordException {
String login = "infdfn01";
String clearPasswd = "rqe3wf2zs";
User user = commonService.registerUser(login, "Perico", "Pardo", "ppardo@lol.com", clearPasswd);
boolean passwdIsEncrypted = false;
User user2 = commonService.authenticate(login, clearPasswd, passwdIsEncrypted);
assertEquals(user,user2);
}
@Test
public void testChangeUserDetails() throws InstanceNotFoundException{
User user = userDao.find(DbUtil.getTestUserId());
String newName = "Petete";
commonService.updateUserDetails(user.getId(), newName, user.getLastName(), user.getEmail());
User userMod = userDao.find(DbUtil.getTestUserId());
assertEquals(newName,userMod.getName());
}
@Test
public void testChanguePassword()
throws InstanceNotFoundException, IncorrectPasswordException, DuplicateInstanceException{
String login = "pepa";
String clearPasswd = "rqe3wf2zs";
User user = commonService.registerUser("pepa", "Perico", "Pardo", "ppardo@lol.com", clearPasswd);
String newPasswd = "ccccc";
commonService.changePassword(user.getId(), clearPasswd, newPasswd);
boolean passwdIsEncrypted = false;
User userMod = commonService.authenticate(login, newPasswd, passwdIsEncrypted);
assertEquals(user,userMod);
assertTrue(PasswordEncrypter.isClearPasswordCorrect(newPasswd,userMod.getPasswd()));
}
@Test
public void testGetUserDetails() throws InstanceNotFoundException{
User user = userDao.find(DbUtil.getTestUserId());
UserDetails userDetails = commonService.getUserDetails(DbUtil.getTestUserId());
assertEquals(user.getName(), userDetails.getName());
assertEquals(user.getLastName(), userDetails.getLastName());
assertEquals(user.getEmail(), userDetails.getEmail());
}
@Test
public void testGetAllCategories(){
List<Category> result = commonService.getAllCategories();
assertEquals(4, result.size());
assertEquals("Cricket", result.get(0).getName());
assertEquals("Petanca", result.get(1).getName());
assertEquals("Mus", result.get(2).getName());
}
@Test
public void testAdminUserId() throws DuplicateInstanceException, InstanceNotFoundException{
String login = "admin";
String clearPasswd = "rqe3wf2zs";
User admin = commonService.registerUser(login, "Perico", "Pardo", "admin@lol.com", clearPasswd);
assertEquals(admin.getId(),commonService.getAdminUserId());
}
}
|
[
"github.dfn@mail"
] |
github.dfn@mail
|
3b96ffdeffdc2dfb5ca284ca868d14864f116312
|
d020e212602018d8df4d710e8b00c2eff938f8c6
|
/src/me/jupdyke01/AcronymQuiz/AQuiz.java
|
393dba1ba2de3b674c532b4f05afda2ef342d08c
|
[] |
no_license
|
NiveryIGN/AcronymQuiz
|
8b62a42fa7e72ae85457d47b36b02a8228941cc1
|
fe944d7192e85db1b3189e88dc1350ec00822b20
|
refs/heads/master
| 2020-03-23T08:36:59.654542
| 2017-09-04T22:48:07
| 2017-09-04T22:48:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,595
|
java
|
package me.jupdyke01.AcronymQuiz;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.md_5.bungee.api.ChatColor;
public class AQuiz implements CommandExecutor{
public static String PluginTag = Main.PluginTag;
public static String NoPerm = Main.NoPerm;
public static String ConsoleUse = Main.ConsoleUse;
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(!(sender instanceof Player)) {
sender.sendMessage(ConsoleUse);
return true;
}
Player p = (Player) sender;
if (args.length == 0) {
p.sendMessage(PluginTag + ChatColor.GRAY + " You must enter an argument, Try /aquiz help");
return true;
} else if (args.length == 1) {
if (args[0].equals("start")) {
if (!(p.hasPermission("aquiz.start"))) {
p.sendMessage(NoPerm);
return true;
}
if (Main.QuizEnabled == false) {
QuizStart.Chooser();
String name = QuizStart.name;
QuizStart.timeleft = QuizStart.Delay;
QuizStart.TimeUp = QuizStart.Delay2;
Utils.Broadcast(ChatColor.DARK_GRAY + "-=-=-=-=-=" + ChatColor.AQUA + PluginTag + ChatColor.DARK_GRAY + "=-=-=-=-=-");
Utils.Broadcast(ChatColor.GRAY + " A Quiz Has" + ChatColor.BLUE + " " + ChatColor.BOLD + "Begun!");
Utils.Broadcast(ChatColor.GRAY + " The Acronym Is " + ChatColor.WHITE + "" + ChatColor.BOLD + "" + name);
Utils.Broadcast(ChatColor.DARK_GRAY + "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
Main.QuizEnabled = true;
return true;
} else {
p.sendMessage(PluginTag + ChatColor.GRAY + "" + ChatColor.BOLD + " There is a quiz currently " + ChatColor.GREEN + "" + ChatColor.BOLD + "" + ChatColor.UNDERLINE + "active!");
return true;
}
} else if (args[0].equals("stop")) {
if (!(p.hasPermission("aquiz.stop"))) {
p.sendMessage(NoPerm);
return true;
}
if (Main.QuizEnabled != true) {
p.sendMessage(PluginTag + ChatColor.GRAY + " No current active acronym quizzes!");
return true;
} else {
String Answer = QuizStart.answer;
Utils.Broadcast(PluginTag + ChatColor.GRAY + " The quiz has been stopped!");
Utils.Broadcast(ChatColor.GRAY + "The answer was" + ChatColor.DARK_GRAY + " -> " + ChatColor.BLUE + Answer);
QuizStart.timeleft = QuizStart.Delay;
QuizStart.TimeUp = QuizStart.Delay2;
Main.QuizEnabled = false;
return true;
}
} else if (args[0].equals("check")) {
if (!(p.hasPermission("aquiz.check"))) {
p.sendMessage(NoPerm);
return true;
}
if (Main.QuizEnabled == true) {
p.sendMessage(PluginTag + ChatColor.GRAY + "" + ChatColor.BOLD + " There is a quiz currently " + ChatColor.GREEN + "" + ChatColor.BOLD + "" + ChatColor.UNDERLINE + "active!");
p.sendMessage(PluginTag + ChatColor.GRAY + " The acronmy is -> " + ChatColor.AQUA + "" + ChatColor.BOLD + "" + ChatColor.ITALIC + QuizStart.name);
return true;
} else {
p.sendMessage(PluginTag + ChatColor.GRAY + " No current active acronym quizzes!");
return true;
}
} else if (args[0].equals("pause")) {
if (!(p.hasPermission("aquiz.pause"))) {
p.sendMessage(NoPerm);
return true;
}
if (Main.Paused == false) {
Main.Paused = true;
p.sendMessage(PluginTag + ChatColor.GRAY + " The quizzes have been paused.");
return true;
} else {
p.sendMessage(PluginTag + ChatColor.GRAY + " The quizzes are already paused!");
return true;
}
} else if (args[0].equals("unpause")) {
if (!(p.hasPermission("aquiz.unpause"))) {
p.sendMessage(NoPerm);
return true;
}
if (Main.Paused == true) {
Main.Paused = false;
p.sendMessage(PluginTag + ChatColor.GRAY + " The quizzes have been unpaused.");
return true;
} else {
p.sendMessage(PluginTag + ChatColor.GRAY + " The quizzes are not paused!");
return true;
}
} else if (args[0].equals("info")) {
if (!(p.hasPermission("aquiz.info"))) {
p.sendMessage(NoPerm);
return true;
}
p.sendMessage(ChatColor.DARK_GRAY + "-=-=-=-=-=" + ChatColor.AQUA + PluginTag + ChatColor.DARK_GRAY + "=-=-=-=-=-");
p.sendMessage(ChatColor.GRAY + "Version: " + ChatColor.DARK_AQUA + Main.getPlugin(Main.class).getDescription().getVersion());
p.sendMessage(ChatColor.GRAY + "Author: " + ChatColor.DARK_AQUA + "Jupdyke01");
p.sendMessage(ChatColor.GRAY + "PluginName: " + ChatColor.DARK_AQUA + Main.getPlugin(Main.class).getDescription().getName());
return true;
} else if (args[0].equals("help")) {
if (!(p.hasPermission("aquiz.help"))) {
return true;
}
p.sendMessage(ChatColor.DARK_GRAY + "-=-=-=-=-=" + ChatColor.AQUA + PluginTag + ChatColor.DARK_GRAY + "=-=-=-=-=-");
p.sendMessage(ChatColor.GRAY + "/aquiz");
p.sendMessage(ChatColor.GRAY + "/aquiz" + ChatColor.DARK_AQUA + " start");
p.sendMessage(ChatColor.GRAY + "/aquiz" + ChatColor.DARK_AQUA + " stop");
p.sendMessage(ChatColor.GRAY + "/aquiz" + ChatColor.DARK_AQUA + " pause");
p.sendMessage(ChatColor.GRAY + "/aquiz" + ChatColor.DARK_AQUA + " unpause");
p.sendMessage(ChatColor.GRAY + "/aquiz" + ChatColor.DARK_AQUA + " check");
p.sendMessage(ChatColor.GRAY + "/aquiz" + ChatColor.DARK_AQUA + " help");
p.sendMessage(ChatColor.GRAY + "/aquiz" + ChatColor.DARK_AQUA + " info");
return true;
} else {
p.sendMessage(PluginTag + ChatColor.GRAY + " Unknown Command, Try /aquiz help");
}
}
return true;
}
}
|
[
"jupdyke01@hotmail.com"
] |
jupdyke01@hotmail.com
|
ab01d8f066905a276b26949c977f46b1079b8b9f
|
300fbb73db6ee077b4ae77bab1d03fd063525e3b
|
/src/main/java/se/ifmo/ru/Main.java
|
83ddeeea8c5f4293f4d9de5a49234cc9755d9b2a
|
[] |
no_license
|
mishkamashka/cm-lab1
|
2d64c34accb706d2e3a5b924eda3afa057fb38dc
|
1cea400abad673ee71cb149cd29971c3a088d979
|
refs/heads/master
| 2020-03-28T00:33:34.101290
| 2018-09-27T12:43:03
| 2018-09-27T12:43:03
| 147,428,742
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,637
|
java
|
package se.ifmo.ru;
import java.util.Scanner;
public class Main {
//TODO: less than 20 check
private static Input input = null;
private static Scanner scanner = new Scanner(System.in);;
private static double[][] matrix = null;
private static double[] vectorB = null;
public static void main(String[] args) {
while (true) {
while (matrix == null || vectorB == null) {
InputType type = null;
while (true) {
System.out.println("Choose input type:\n0 - cmd\n1 - from file\n2 - random");
while (type == null) {
type = InputType.getByValue(scanner.nextLine());
}
break;
}
switch (type) {
case CMD_INPUT:
input = new CMDInput(scanner);
break;
case FILE_INPUT:
input = new FileInput(scanner);
break;
case RND_INPUT:
input = new RandomInput();
break;
}
switch (input.createInput()) {
case 1:
System.out.println("Error getting from CMD");
break;
case 2:
System.out.println("Error getting from file");
break;
case 3:
System.out.println("Going back...");
break;
default:
matrix = input.getMatrixInput();
vectorB = input.getVectorBInput();
}
}
System.out.println("Initial matrix:");
MatrixPrinter.print(matrix, vectorB);
try {
GaussSolver solver = new GaussSolver(matrix, vectorB);
System.out.println("Triangular matrix:");
MatrixPrinter.print(solver.getTriangularMatrix(), solver.getModifiedVectorB());
System.out.println("Determinant: " + solver.getDeterminant());
System.out.println();
System.out.println("Solution vector:");
MatrixPrinter.print(solver.solve());
System.out.println("Discrepancy vector:");
MatrixPrinter.printAccurate(solver.getDiscrepancy());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
break;
}
}
}
|
[
"just-another-log-in@yandex.ru"
] |
just-another-log-in@yandex.ru
|
a200cb0de88ca4b0c75c23607d2139c21c38e032
|
95c40ad614762e4246b4c85d30961e33e7ad9bde
|
/src/main/java/com/suis/logistics/repository/person/PersonDaoImpl.java
|
30099002ad935a55cc1ab86429e53871510fe0e8
|
[] |
no_license
|
iswarjava9/logistics
|
df6e876a7b1253e5e4457cdf325ca196f073b8b8
|
f2359375f0ba52a9b1bdae617e76a3779a4f0f94
|
refs/heads/master
| 2021-03-27T13:45:57.051829
| 2018-03-17T14:57:30
| 2018-03-17T14:57:30
| 99,665,625
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,125
|
java
|
package com.suis.logistics.repository.person;
import java.util.List;
import org.hibernate.Query;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import com.suis.logistics.model.Person;
import com.suis.logistics.repository.BaseDao;
@Repository
public class PersonDaoImpl extends BaseDao implements PersonDao {
@Override
public Integer createPerson(Person person) {
getCurrentSession().save(person);
clearCache("personByName");
return person.getId();
}
@Override
public Person findById(int id) {
Person person;
try {
person = getCurrentSession().load(Person.class, id);
person.getId();
} catch (Exception e) {
throw new PersonNotFoundException(e);
}
return person;
}
@SuppressWarnings("unchecked")
@Override
@Cacheable(value = "personByName", key = "#name")
public List<Person> getPersonsByName(String name) {
Query query = getCurrentSession().getNamedQuery("Person.findByName").setParameter("name", name + "%");
List<Person> personList = query.list();
return personList;
}
}
|
[
"iswar.java9@gmail.com"
] |
iswar.java9@gmail.com
|
0d60907277c3c82d75fdf117c6563c235e024081
|
d8b726a3c0378d7630ba1174fa077de47cb924f8
|
/src/main/java/com/foodhub/services/HubRestaurantService.java
|
89c0bda5966f71c2ca80f91ed10e2f63f6f3b761
|
[] |
no_license
|
Jayakrishnantu/foodhub
|
810ff912ea937ea8e235e807f310d89fd324431d
|
7e7097463af3efbdda95b6dec362d4e77999351a
|
refs/heads/main
| 2023-02-18T06:06:09.465446
| 2021-01-18T01:42:18
| 2021-01-18T01:42:18
| 329,494,117
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 820
|
java
|
package com.foodhub.services;
import com.foodhub.entity.Restaurant;
import com.foodhub.payload.RestaurantRequest;
import com.foodhub.repository.RestaurantRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HubRestaurantService implements RestaurantService {
@Autowired
RestaurantRepository restaurantRepository;
@Override
public Restaurant createRestaurant(RestaurantRequest request) {
Restaurant restaurant = new Restaurant();
restaurant.setRestaurantName(request.getName());
restaurant.setRestaurantAddress(request.getAddress());
restaurant.setRestaurantContactInfo(request.getContact());
restaurantRepository.save(restaurant);
return restaurant;
}
}
|
[
"jayakrishnantu.007@gmail.com"
] |
jayakrishnantu.007@gmail.com
|
0c775849e5f1a35ac9bd21ef4ee2a3601cf0f8eb
|
d2a85ca45a7e497e2f4ed939a576b1b59c0c9635
|
/src/main/java/com/humanup/matrix/qcm/bs/ChoiceBS.java
|
978bf45787a02647a504da1cf02e14ec64e1f57c
|
[] |
no_license
|
bellouki/qcm-matrix
|
910c54810601fbe316562f4883766376b33d9623
|
c7a9c57b0ef54f686bc130496ac25ef82aa3f9bb
|
refs/heads/master
| 2020-12-09T12:14:46.767699
| 2020-04-25T13:48:04
| 2020-04-25T13:48:04
| 233,300,341
| 0
| 0
| null | 2020-01-11T21:34:09
| 2020-01-11T21:34:08
| null |
UTF-8
|
Java
| false
| false
| 274
|
java
|
package com.humanup.matrix.qcm.bs;
import com.humanup.matrix.qcm.vo.ChoiceVO;
import java.util.List;
public interface ChoiceBS {
boolean createChoice(ChoiceVO choice);
List<ChoiceVO> findListChoice();
List<ChoiceVO> findChoiceByQuestionId(Long questionId);
}
|
[
"khalil.kouiss@gmail.com"
] |
khalil.kouiss@gmail.com
|
144635a51ced56ed96715ff11db47069f48e3609
|
8615446cfa47a86a905363037c02ad339b618bc4
|
/services/order/order-client/src/main/java/ninja/cero/ecommerce/order/client/OrderClient.java
|
ab796cd0dae010601a7e50413b9c819e99500604
|
[
"Apache-2.0"
] |
permissive
|
cero-t/spring-cloud-kinoko-2017
|
510e54b56a240c8b8b286840f1389a2e23e334ff
|
eec447e169a85fca8680d0459954117dca034c6a
|
refs/heads/master
| 2021-05-13T17:21:35.024683
| 2018-04-18T15:04:48
| 2018-04-18T15:04:48
| 116,819,582
| 1
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 883
|
java
|
package ninja.cero.ecommerce.order.client;
import java.util.List;
import org.springframework.web.reactive.function.client.WebClient;
import ninja.cero.ecommerce.order.domain.OrderEvent;
import ninja.cero.ecommerce.order.domain.OrderInfo;
public class OrderClient {
private static final String ORDER_URL = "http://order-service";
WebClient webClient;
public OrderClient(WebClient webClient) {
this.webClient = webClient;
}
public void createOrder(OrderInfo order) {
webClient.post().uri(ORDER_URL).syncBody(order).exchange().block();
}
public void createEvent(OrderEvent orderEvent) {
webClient.post().uri(ORDER_URL + "/" + orderEvent.orderId + "/event").syncBody(orderEvent).exchange().block();
}
public List<OrderEvent> findAllEvents() {
return webClient.get().uri(ORDER_URL + "/events").retrieve().bodyToFlux(OrderEvent.class).collectList().block();
}
}
|
[
"cel@pos.to"
] |
cel@pos.to
|
d741907059e01069e7592316187ae13adca3b1d8
|
f458dc768b285e2c36d873c8fc8d790aadbd5743
|
/entity/src/main/java/com/alonelaval/cornerstone/entity/constants/State.java
|
0908bda66c84fc88271962e3d7ed0d9991eac294
|
[] |
no_license
|
miraclehjt/cornerstone
|
faaf3601eec6c0602c8a05613e83e95bc4a7af90
|
e9c6d0b77aefa6cfd12813013fa3136741872a0c
|
refs/heads/master
| 2022-12-27T08:45:35.384218
| 2020-04-09T04:31:06
| 2020-04-09T04:31:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,012
|
java
|
package com.alonelaval.cornerstone.entity.constants;
import com.alonelaval.common.entity.IEnum;
/***
*
* @author huawei
* @create 2018-07-07
**/
public enum State implements IEnum {
ENABLED(0,"正常"),
DISABLED(1,"禁用"),
DELETE(2,"删除");
private final int value;
private final String desc;
@Override
public int value() {
return value;
}
@Override
public String desc() {
return this.desc;
}
State(int value, String desc) {
this.value = value;
this.desc = desc;
}
public static String typeName() {
return "状态";
}
public static State valueOf(Integer value) {
if(State.ENABLED.value() ==value) {
return ENABLED;
}
else
if(State.DISABLED.value() ==value) {
return DISABLED;
}
else{
return DELETE;
}
}
@Override
public IEnum value(int value) {
return valueOf(value);
}
}
|
[
"huawei@bit-s.cn"
] |
huawei@bit-s.cn
|
5779ccd7287f35f250d466d4843835fa3423239a
|
b8c566b9bb4773e07021e539c7e90b47399aeeec
|
/YouTuber.java
|
40802853a61f64332307de3ab6a85e69503a8889
|
[
"MIT"
] |
permissive
|
nifx28/JavaCodex
|
83296321e5479a094c40df19eb1a148f9babec95
|
00f40100038995b12cfdd4f4efe0d14163c62a3d
|
refs/heads/main
| 2023-01-31T14:11:54.327828
| 2020-12-10T15:15:35
| 2020-12-10T15:15:35
| 320,307,729
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,831
|
java
|
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.Collections;
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.Scanner;
import java.util.NoSuchElementException;
/**
* https://zerojudge.tw/ShowProblem?problemid=e800
* e800. p7. 影片推薦 - 高中生程式解題系統
*/
class YouTuber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Integer> rank = new HashMap<>();
try {
List<Object> list = new ArrayList<Object>();
int i = 0, j = 0, n = 0;
while (true) {
String str = "";
int val = 0;
switch (i) {
case 1:
str = scanner.next();
list.add("\"" + str + "\"");
break;
default:
val = scanner.nextInt();
list.add(val);
}
if (i == 0) {
n = val;
}
i++;
if (i > 5) {
i = 1;
}
if (i == 1) {
if (j <= n) {
String result = list.stream()
.map(x -> String.valueOf(x))
.collect(Collectors.joining(", ", "{", "}"));
if (j > 0) {
int factor = (int)list.get(1) / (int)list.get(2) * (int)list.get(3) * (int)list.get(4);
rank.put((String)list.get(0), factor);
System.out.printf("%d: %s = %d%n", j, result, factor);
}
else
{
System.out.printf("%d: %s%n", j, result);
}
list.clear();
}
j++;
}
}
} catch (NoSuchElementException ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
scanner.close();
List<Map.Entry<String, Integer>> rankList = new ArrayList<Map.Entry<String, Integer>>(rank.entrySet());
Collections.sort(rankList, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
for (Map.Entry<String, Integer> ranking : rankList) {
System.out.printf("%s: %d%n", ranking.getKey(), ranking.getValue());
}
}
}
|
[
"vessalius1018@gmail.com"
] |
vessalius1018@gmail.com
|
16550a2b99bf618b518c875e4b65dbc77ece6c7d
|
db6e498dd76a6ce78d83e1e7801674783230a90d
|
/thirdlib/base-protocol/protocol/src/main/java/pb4client/LvUpEquipRtOrBuilder.java
|
d9a4118ba3be7eea701bd537d8fc2f1e1c3a59b3
|
[] |
no_license
|
daxingyou/game-4
|
3d78fb460c4b18f711be0bb9b9520d3e8baf8349
|
2baef6cebf5eb0991b1f5c632c500b522c41ab20
|
refs/heads/master
| 2023-03-19T15:57:56.834881
| 2018-10-10T06:35:57
| 2018-10-10T06:35:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| true
| 2,147
|
java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: client2server.proto
package pb4client;
public interface LvUpEquipRtOrBuilder extends
// @@protoc_insertion_point(interface_extends:client2server.LvUpEquipRt)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* 返回值
* </pre>
*
* <code>required int32 rt = 1;</code>
*/
boolean hasRt();
/**
* <pre>
* 返回值
* </pre>
*
* <code>required int32 rt = 1;</code>
*/
int getRt();
/**
* <pre>
* 要强化的装备
* </pre>
*
* <code>optional int64 equipId = 2;</code>
*/
boolean hasEquipId();
/**
* <pre>
* 要强化的装备
* </pre>
*
* <code>optional int64 equipId = 2;</code>
*/
long getEquipId();
/**
* <pre>
* 强化后等级
* </pre>
*
* <code>optional int32 lv = 3;</code>
*/
boolean hasLv();
/**
* <pre>
* 强化后等级
* </pre>
*
* <code>optional int32 lv = 3;</code>
*/
int getLv();
/**
* <pre>
*装备属性
* </pre>
*
* <code>repeated .client2server.EquipProps props = 4;</code>
*/
java.util.List<pb4client.EquipProps>
getPropsList();
/**
* <pre>
*装备属性
* </pre>
*
* <code>repeated .client2server.EquipProps props = 4;</code>
*/
pb4client.EquipProps getProps(int index);
/**
* <pre>
*装备属性
* </pre>
*
* <code>repeated .client2server.EquipProps props = 4;</code>
*/
int getPropsCount();
/**
* <pre>
*装备属性
* </pre>
*
* <code>repeated .client2server.EquipProps props = 4;</code>
*/
java.util.List<? extends pb4client.EquipPropsOrBuilder>
getPropsOrBuilderList();
/**
* <pre>
*装备属性
* </pre>
*
* <code>repeated .client2server.EquipProps props = 4;</code>
*/
pb4client.EquipPropsOrBuilder getPropsOrBuilder(
int index);
/**
* <pre>
*强化后经验
* </pre>
*
* <code>optional int32 exp = 5;</code>
*/
boolean hasExp();
/**
* <pre>
*强化后经验
* </pre>
*
* <code>optional int32 exp = 5;</code>
*/
int getExp();
}
|
[
"weiwei.witch@gmail.com"
] |
weiwei.witch@gmail.com
|
c792f303940951427241e63058ec25b8bdc1d0e6
|
ac596748b94a39e2f538ac948851af28fa1d03c1
|
/ActivityMaximizer-Android/activityMaximizer-master/app/src/main/java/model/UserData.java
|
28e393044096dc9ddda89cbaa20cbb0d21d52057
|
[] |
no_license
|
daniel-reich/activityMaximizer
|
f228a30b61e95e5148e4f3bf3a16f169b505f686
|
6373c4c9144629b6c0c525673c77a0d9474f66ab
|
refs/heads/master
| 2021-01-23T06:25:48.312222
| 2017-04-03T18:39:21
| 2017-04-03T18:39:21
| 86,368,071
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 226
|
java
|
package model;
import java.util.Collection;
/**
* Created by LucianVictor on 4/3/2017.
*/
public class UserData {
public User user;
public Collection<Event> events;
public Collection<UserContact> contacts;
}
|
[
"tepes.lucian.victor@gmail.com"
] |
tepes.lucian.victor@gmail.com
|
5f306daef3c3b3268fc6ca829eba5f5dbecfab7f
|
2d9664ad5db3fdbf2dd1f5f7d892fb7160e0db04
|
/store/entity/Product.java
|
95d5289ffaba36d350a02c3a76c91e1759b4710f
|
[] |
no_license
|
13935619154/sichenhui-store
|
eabc9f8666592332714079c1f788b618a0b45442
|
fb19aaca3baadec659c36a9c9aba99d7071f063d
|
refs/heads/master
| 2022-10-25T07:00:34.160545
| 2020-06-20T18:47:43
| 2020-06-20T18:47:43
| 273,749,839
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,592
|
java
|
package cn.tedu.store.entity;
/**
* 商品数据的实体类
*/
public class Product extends BaseEntity {
private static final long serialVersionUID = -199568590252555336L;
private Integer id;
private Integer categoryId;
private String itemType;
private String title;
private String sellPoint;
private Long price;
private Integer num;
private String image;
private Integer status;
private Integer priority;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSellPoint() {
return sellPoint;
}
public void setSellPoint(String sellPoint) {
this.sellPoint = sellPoint;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Product [id=" + id + ", categoryId=" + categoryId + ", itemType=" + itemType + ", title=" + title
+ ", sellPoint=" + sellPoint + ", price=" + price + ", num=" + num + ", image=" + image + ", status="
+ status + ", priority=" + priority + ", toString()=" + super.toString() + "]";
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
44be9e3fae8e71f947808dc31b97a5ee43f1a259
|
03d44f97f31ecebb726cbdb4e00129848cdc9129
|
/prime.java
|
c8bb3c3accff2f8896478198b7fa04141ce5b8a8
|
[] |
no_license
|
cjsanjeev16/JavaPrograms
|
a13c96c7a0cbf128beff2797b07daee24440b8ff
|
4c47dce019052416c663ad29e28683582bba6612
|
refs/heads/master
| 2023-06-09T20:02:39.192005
| 2021-06-29T19:10:12
| 2021-06-29T19:10:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 478
|
java
|
/**
* write a program to accept a number and check
whether the number is prime or not.
A prime number is divisible only by 1 and number
itself */
import java.util.Scanner;
public class prime
{
public static void main()
{
Scanner in = new Scanner(System.in);
int a,n,c=0;
System.out.println("Enter a number");
n = in.nextInt();
for(a=1;a<=n;a++)
{
if(n % a==0)
c=c+1;
}
if(c==2)
System.out.println("It is a prime number");
else
System.out.println("It is a not prime number");
}
}
|
[
"RAKESH@192.168.0.2"
] |
RAKESH@192.168.0.2
|
38fe9dd19f154330b0eb994b1d912c973038ba72
|
42cc9b7cc758620bf379c0a00b554c53fb4ca0c6
|
/src/main/java/com/sample/domain/SampleDomain.java
|
3145119ebb8ce007f54313d0a05afbd5449a68f3
|
[] |
no_license
|
espkishore98/exceltodb
|
3502cd60d63223d23cc2f4baa9716c412dbcaddd
|
59116e369c6db5ab6143536929e969f0154c7426
|
refs/heads/master
| 2022-12-22T06:25:43.708403
| 2020-09-25T14:53:14
| 2020-09-25T14:53:14
| 298,602,247
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,338
|
java
|
package com.sample.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name="sample")
public class SampleDomain {
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="business_services")
private String businessName;
@Column(name="fullapplication_name")
private String fullApplicationName;
@Column(name="abap_java")
private String abapOrJava;
@Column(name="sid")
private String sid;
@Column(name="aka")
private String aka;
@Column(name="environment_role")
private String environmentRole;
@Column(name="physicalserver_names")
private String physicalServerName;
@Column(name="db_ci_app")
private String dbOrCiOrApp;
@Column(name="sap_nw_bi_version")
private String sapOrBi;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getFullApplicationName() {
return fullApplicationName;
}
public void setFullApplicationName(String fullApplicationName) {
this.fullApplicationName = fullApplicationName;
}
public String getAbapOrJava() {
return abapOrJava;
}
public void setAbapOrJava(String abapOrJava) {
this.abapOrJava = abapOrJava;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getAka() {
return aka;
}
public void setAka(String aka) {
this.aka = aka;
}
public String getEnvironmentRole() {
return environmentRole;
}
public void setEnvironmentRole(String environmentRole) {
this.environmentRole = environmentRole;
}
public String getPhysicalServerName() {
return physicalServerName;
}
public void setPhysicalServerName(String physicalServerName) {
this.physicalServerName = physicalServerName;
}
public String getDbOrCiOrApp() {
return dbOrCiOrApp;
}
public void setDbOrCiOrApp(String dbOrCiOrApp) {
this.dbOrCiOrApp = dbOrCiOrApp;
}
public String getSapOrBi() {
return sapOrBi;
}
public void setSapOrBi(String sapOrBi) {
this.sapOrBi = sapOrBi;
}
public SampleDomain(String businessName, String fullApplicationName, String abapOrJava, String sid, String aka,
String environmentRole, String physicalServerName, String dbOrCiOrApp, String sapOrBi) {
super();
this.businessName = businessName;
this.fullApplicationName = fullApplicationName;
this.abapOrJava = abapOrJava;
this.sid = sid;
this.aka = aka;
this.environmentRole = environmentRole;
this.physicalServerName = physicalServerName;
this.dbOrCiOrApp = dbOrCiOrApp;
this.sapOrBi = sapOrBi;
}
public SampleDomain() {
super();
}
@Override
public String toString() {
return "SampleDomain [id=" + id + ", businessName=" + businessName + ", fullApplicationName="
+ fullApplicationName + ", abapOrJava=" + abapOrJava + ", sid=" + sid + ", aka=" + aka
+ ", environmentRole=" + environmentRole + ", physicalServerName=" + physicalServerName
+ ", dbOrCiOrApp=" + dbOrCiOrApp + ", sapOrBi=" + sapOrBi + "]";
}
}
|
[
"espkishore@gmail.com"
] |
espkishore@gmail.com
|
fab8e056dc72c901cc9ff1018cafd4297a5edc98
|
79595075622ded0bf43023f716389f61d8e96e94
|
/app/src/main/java/com/android/internal/telephony/cat/CallSetupParams.java
|
4216ad9d19270d3ade0f7b86d1e833811d5e92d4
|
[] |
no_license
|
dstmath/OppoR15
|
96f1f7bb4d9cfad47609316debc55095edcd6b56
|
b9a4da845af251213d7b4c1b35db3e2415290c96
|
refs/heads/master
| 2020-03-24T16:52:14.198588
| 2019-05-27T02:24:53
| 2019-05-27T02:24:53
| 142,840,716
| 7
| 4
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 845
|
java
|
package com.android.internal.telephony.cat;
import android.graphics.Bitmap;
/* compiled from: CommandParams */
class CallSetupParams extends CommandParams {
TextMessage mCallMsg;
TextMessage mConfirmMsg;
CallSetupParams(CommandDetails cmdDet, TextMessage confirmMsg, TextMessage callMsg) {
super(cmdDet);
this.mConfirmMsg = confirmMsg;
this.mCallMsg = callMsg;
}
boolean setIcon(Bitmap icon) {
if (icon == null) {
return false;
}
if (this.mConfirmMsg != null && this.mConfirmMsg.icon == null) {
this.mConfirmMsg.icon = icon;
return true;
} else if (this.mCallMsg == null || this.mCallMsg.icon != null) {
return false;
} else {
this.mCallMsg.icon = icon;
return true;
}
}
}
|
[
"toor@debian.toor"
] |
toor@debian.toor
|
41789a8ced1d8ca67259b074f3261d83803bbe88
|
ac32e49cf88c0f18cfacc20fdeca58c71705acc2
|
/src/main/java/com/job/designpattern/templatemethod/TestPaperB.java
|
811ab0b6eda4578063a5d26ec1632ff67eb970a3
|
[] |
no_license
|
gitter-badger/design-pattern
|
35d420a110cac8a3673221f3201f0b64fd48c8bc
|
3ced2793509d0f005183e9dcb23be12c19249d5f
|
refs/heads/master
| 2020-03-16T16:36:30.349899
| 2018-05-09T17:24:33
| 2018-05-09T17:24:33
| 132,795,507
| 0
| 0
| null | 2018-05-09T18:08:20
| 2018-05-09T18:08:20
| null |
UTF-8
|
Java
| false
| false
| 445
|
java
|
package com.job.designpattern.templatemethod;
public class TestPaperB extends TestPaper {
public static final String ANSWER_ONE = "B";
public static final String ANSWER_TWO = "C";
public static final String ANSWER_THREE = "D";
public String answerOne() {
return ANSWER_ONE;
}
public String answerTwo() {
return ANSWER_TWO;
}
public String answerThree() {
return ANSWER_THREE;
}
}
|
[
"522617505@qq.com"
] |
522617505@qq.com
|
27a3f2bc42cf865f271d4fceb17629b10093df3e
|
386a90a489c282bfe3f8063136f47c0cf9ed1e3e
|
/OpenMRSSubmissions/05072013/Group-1/src/api/src/main/java/org/openmrs/module/basicmodule/dsscompiler/interpreter/node/FieldRefInterpreter.java
|
93b093eb3afa08a641106402ff0d8fb1a6612d15
|
[] |
no_license
|
darthyoshi/sp2013-csc668-868-group1
|
08e4be2b5618d7a1431c5b2f6d26dd4bbadb6ba9
|
9747eea07e89380926a62df443c941c02b1a980a
|
refs/heads/master
| 2020-05-17T07:07:17.738001
| 2013-05-16T17:16:41
| 2013-05-16T17:16:41
| 32,191,471
| 1
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 990
|
java
|
package org.openmrs.module.basicmodule.dsscompiler.interpreter.node;
import org.openmrs.module.basicmodule.dsscompiler.ast.FieldRefTree;
import org.openmrs.module.basicmodule.dsscompiler.ast.IdTree;
import org.openmrs.module.basicmodule.dsscompiler.interpreter.ASTInterpreter;
import org.openmrs.module.basicmodule.dsscompiler.value.DSSValue;
import org.openmrs.module.basicmodule.dsscompiler.interpreter.ExecutionContext;
import org.openmrs.module.basicmodule.dsscompiler.interpreter.NamingContext;
import org.openmrs.module.basicmodule.dsscompiler.visitor.ASTVisitor;
/**
*
* @author woeltjen
*/
public class FieldRefInterpreter implements ASTInterpreter<FieldRefTree> {
public Object interpret(FieldRefTree tree, ExecutionContext context, ASTVisitor visitor) {
return context.getEvaluator().castTo(NamingContext.class,
(DSSValue) tree.getKid(1).accept(visitor)).get(
((IdTree) tree.getKid(2)).getSymbol().toString());
}
}
|
[
"vwoeltjen@gmail.com@8f292820-0a9e-4756-579c-e4d96cb42ef5"
] |
vwoeltjen@gmail.com@8f292820-0a9e-4756-579c-e4d96cb42ef5
|
2421c62f5bf62ebf19572b7bfa35be229a74f915
|
465af6d9208410970c94aa0fb7602a1615e8d533
|
/app/src/main/java/com/example/giovankabisano/androidpresencesystem/MapTracking.java
|
b132dd738f90af558ea8f7fb7d7cc0d8404e9a98
|
[] |
no_license
|
giovankabisano/AndroidPresenceSystem
|
3824f9685dba2711f9b14d73a0e4f0fc9a1b4478
|
c84e5750125e47ee9044db97ad41d301b476538e
|
refs/heads/master
| 2020-03-17T09:24:05.466086
| 2019-01-24T08:21:51
| 2019-01-24T08:21:51
| 133,473,533
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,963
|
java
|
package com.example.giovankabisano.androidpresencesystem;
import android.graphics.Bitmap;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.text.TextUtils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
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.text.DecimalFormat;
import java.util.function.DoubleUnaryOperator;
public class MapTracking extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private String email;
DatabaseReference locations;
Double lat, lng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_tracking);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locations = FirebaseDatabase.getInstance().getReference("Locations");
if(getIntent() != null){
email = getIntent().getStringExtra("email");
lat = getIntent().getDoubleExtra("lat", 0);
lng = getIntent().getDoubleExtra("lng", 0);
}
if(!TextUtils.isEmpty(email)){
loadLocationForThisUser(email);
}
}
private void loadLocationForThisUser(String email) {
Query user_location = locations.orderByChild("email").equalTo(email);
user_location.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapShot:dataSnapshot.getChildren()){
Tracking tracking = postSnapShot.getValue(Tracking.class);
LatLng friendLocation = new LatLng(Double.parseDouble(tracking.getLat()),
Double.parseDouble(tracking.getLng()));
Location currentUser = new Location("");
currentUser.setLatitude(lat);
currentUser.setLongitude(lng);
Location friend = new Location("");
friend.setLatitude(Double.parseDouble(tracking.getLat()));
friend.setLongitude(Double.parseDouble(tracking.getLng()));
distance(currentUser,friend);
mMap.clear();
mMap.addMarker(new MarkerOptions()
.position(friendLocation)
.title(tracking.getEmail())
.snippet("Distance " + new DecimalFormat("#.#").format((currentUser.distanceTo(friend)) / 1000d)+" km")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat,lng),12.0f));
}
//Create Marker for Current user
LatLng current = new LatLng(lat,lng);
mMap.addMarker(new MarkerOptions().position(current).title(FirebaseAuth.getInstance().getCurrentUser().getEmail()));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private double distance(Location currentUser, Location friend) {
double theta = currentUser.getLongitude() - friend.getLongitude();
double dist = Math.sin(deg2rad(currentUser.getLatitude()))
* Math.sin(deg2rad(friend.getLatitude()))
* Math.cos(deg2rad(currentUser.getLatitude()))
* Math.cos(deg2rad(friend.getLatitude()))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}
|
[
"gbisano@gmail.com"
] |
gbisano@gmail.com
|
ab9d6ce24a69fa7479bc3f4e1f138f5ec400eb82
|
a7a5d9a1f431fc0af85804c2620572cfce2c7436
|
/app/src/main/java/de/applicatum/shoprouter/utils/StringUtil.java
|
c12463d7825be9e22b487433d531694d986809f8
|
[] |
no_license
|
Tumanin/ShopRouterTUM
|
56f55359c80e59fb93e2c4bd0f74cb78f9a1be23
|
dc47da12ea9430dd7830f46a49ca7a2bd175344a
|
refs/heads/master
| 2020-07-27T03:43:42.924284
| 2016-12-14T17:22:27
| 2016-12-14T17:22:27
| 73,705,009
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 797
|
java
|
package de.applicatum.shoprouter.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class StringUtil {
public static String MD5(String string) {
if (string == null)
return null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] inputBytes = string.getBytes();
byte[] hashBytes = digest.digest(inputBytes);
return byteArrayToHex(hashBytes);
} catch (NoSuchAlgorithmException e) { }
return null;
}
private static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for(byte b: a)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
}
|
[
"atumanin@appmagnetics.de"
] |
atumanin@appmagnetics.de
|
d27cba701be9a87d6e9be37353ef8b9ddcb96888
|
3fca161aa76b05e863cfcb7caf2daf400b830f40
|
/src/GamePackage/GameObjects/AttributeStringObject.java
|
e23e7986ea532a6e5d5a6460ec9d5cfd34091d0c
|
[
"MIT"
] |
permissive
|
11BelowStudio/Muffin-Mania
|
1b763f5deb15f13495425818edab8b46b5459156
|
3ca677bb2e716d4cf0825a2c1c2b079df821e27e
|
refs/heads/master
| 2022-12-11T14:29:43.796531
| 2020-09-02T18:22:37
| 2020-09-02T18:22:37
| 291,774,382
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,236
|
java
|
package GamePackage.GameObjects;
import utilities.AttributeString;
import utilities.Vector2D;
import java.awt.*;
public class AttributeStringObject<T> extends StringObject {
private AttributeString<T> attributeString;
public AttributeStringObject(Vector2D p, Vector2D v, String attribute, T value, String suffix, int a){
super(p,v,a);
makeAttributeString(attribute,value,suffix);
}
public AttributeStringObject(Vector2D p, Vector2D v, String attribute, T value, int a){
this(p,v,attribute,value,"",a);
}
public AttributeStringObject(Vector2D p, Vector2D v, String attribute, T value, String suffix, int a, Font f){
this(p,v,attribute,value,suffix,a);
this.setTheFont(f);
}
public AttributeStringObject(Vector2D p, Vector2D v, String attribute, T value, int a, Font f){
this(p,v,attribute,value,"",a,f);
}
/*
public AttributeStringObject(Vector2D p, Vector2D v, String attribute, T value){
super(p,v);
makeAttributeString(attribute,value,"");
}*/
public AttributeStringObject<T> revive(T value){
super.revive();
return (this.setValue(value));
}
public AttributeStringObject<T> setAttribute(String attributeName){ attributeString.rename(attributeName); updateText(); return this;}
public AttributeStringObject<T> setValue(T value){
attributeString.showValue(value);
updateText();
return this;
}
public AttributeStringObject<T> setSuffix(String suffix){ attributeString.changeSuffix(suffix); updateText(); return this;}
public String getAttributeName(){ return attributeString.getAttributeName(); }
public T getValue(){ return attributeString.getValue();}
public String getSuffix() { return attributeString.getSuffix(); }
private void updateText(){ setText(attributeString.toString()); }
public AttributeStringObject<T> kill(){ super.kill(); return this; }
public void update(){
updateText();
super.update();
}
private void makeAttributeString(String att, T val, String suf){
attributeString = new AttributeString<>(att,val, suf);
setText(attributeString.toString());
}
}
|
[
"richard_lowe@outlook.com"
] |
richard_lowe@outlook.com
|
fccbfda0e319ed39d3bdce567ee65c42bfe587dc
|
7d06a4fdf6543ad059aafff66ddc3539935c0230
|
/src/main/java/kz/iitu/productservice/ProductServiceApplication.java
|
a80eb0b1568ef14e680c87da1020ff65f15391a3
|
[] |
no_license
|
aruyelemes/product-service
|
c6b5f61291143578f16bdc94dbd4046100b77206
|
3bdb58cc8221a5a3cb8594ea02a1d01fd44b9177
|
refs/heads/main
| 2022-12-29T14:04:19.955756
| 2020-10-12T04:22:50
| 2020-10-12T04:22:50
| 303,276,103
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 905
|
java
|
package kz.iitu.productservice;
import kz.iitu.productservice.Models.Product;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import java.util.ArrayList;
import java.util.List;
@EnableEurekaClient
@SpringBootApplication
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
public static List<Product> list;
public static List<Product> getProducts() {
if (list == null) {
list = new ArrayList<>();
Product p1 = new Product(1L, "Milk", "2.99", "10");
Product p2 = new Product(2L, "Ice Cream", "0.99", "15");
list.add(p1);
list.add(p2);
}
return list;
}
}
|
[
"aru.yelemes23@gmail.com"
] |
aru.yelemes23@gmail.com
|
e07f2342480a7ab371348a4f5ed023e608af87c6
|
e19aced5d34776e2379a26e57f9f59fb80206ddf
|
/ViewPagerTest/src/com/isme/viewpager/MainActivity.java
|
0e76670a5f1de133545c9686383290607afb463d
|
[
"MIT"
] |
permissive
|
heyugtan/viewpager
|
2d8f394abfc48164e225697fbe4ffc25d3be93b8
|
6afff7867f5f4d0a8f2479f9c98ca4831b02d979
|
refs/heads/master
| 2020-03-29T21:18:39.180181
| 2015-04-09T03:25:31
| 2015-04-09T03:25:31
| 33,646,215
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,157
|
java
|
package com.isme.viewpager;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity implements OnPageChangeListener{
// 控件
private ViewPager viewPager;
private TextView tvTitle;
private LinearLayout layoutDots;
// 图片
private int[] imgId;;
private List<ImageView> imageList;
// 文字
private List<String> titleList;
// 小点
private List<View> dotsList;
private View dot;
private int oldPosition;
private int currentPosition;
private ViewPagerAdapter adapter;
private Runnable runnable;
private int autoChangeTime = 1500;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 轮播图片
viewPager = (ViewPager) findViewById(R.id.vp_ad);
viewPager.setOnPageChangeListener(this);
// 文字
tvTitle = (TextView) findViewById(R.id.tv_title);
// 小点
layoutDots = (LinearLayout) findViewById(R.id.layout_dots);
initData();
pagerPlay();
}
/**
* -------------------自动播放 pager
*/
private void pagerPlay() {
runnable = new Runnable() {
@Override
public void run() {
oldPosition = viewPager.getCurrentItem();
int next = (oldPosition) +1;
if(next >= adapter.getCount())
{
next = 0;
}
handlerPager.sendEmptyMessage(next);
}
};
handlerPager.postDelayed(runnable, autoChangeTime);
}
private void initData() {
initImage();
initTitle();
initDots();
tvTitle.setText(titleList.get(0));
adapter = new ViewPagerAdapter();
viewPager.setAdapter(adapter);
}
/**
* ------------------------------------初始化 小点
*/
private void initDots() {
dotsList = new ArrayList<View>();
LinearLayout.LayoutParams dotsParams = new LinearLayout.LayoutParams(40, 12);
dotsParams.setMargins(12, 3, 12, 3);
for(int i=0; i<imgId.length; i++)
{
dot = new View(this);
dot.setLayoutParams(dotsParams);
if(0 == i)
{
dot.setBackgroundResource(R.drawable.dot_focus);
}
else{
dot.setBackgroundResource(R.drawable.dot_normal);
}
dotsList.add(dot);
// 给小点设点击事件
dotsList.get(i).setId(i);
dotsList.get(i).setOnClickListener(new DotClickListener());
layoutDots.addView(dotsList.get(i));
}
}
/**
* ----------------------------------初始化 轮播 标题
*/
private void initTitle() {
titleList = new ArrayList<String>();
for(int i=0; i<imgId.length; i++)
{
titleList.add("第"+i+"张");
}
}
/**
* --------------------------------初始化 轮播图片
*/
private void initImage() {
imgId = new int[] { R.drawable.order, R.drawable.tran, R.drawable.yue,
R.drawable.intro };
imageList = new ArrayList<ImageView>();
for (int i = 0; i < imgId.length; i++) {
ImageView img = new ImageView(this);
img.setImageResource(imgId[i]);
imageList.add(img);
}
// 最后单个图片的点击事件
ImageView image = imageList.get(imageList.size() - 1);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, JumpActivity.class));
}
});
}
/**
* viewPager的适配器
*
* @author Administrator
*
*/
class ViewPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return imageList.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(imageList.get(position));
return imageList.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(imageList.get(position));
}
}
/**
* ----------------------------小点 的点击事件
* 点击哪一个点 跳转到那个图片
*/
class DotClickListener implements OnClickListener{
@Override
public void onClick(View v) {
int position = v.getId();
Log.i("isme", String.valueOf(position));
setCurrentView(position);
}
}
/**
* -----------------------------viewPager 轮播的监听
*/
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
setCurrentPage(position);
handlerPager.removeCallbacks(runnable);
handlerPager.postDelayed(runnable, autoChangeTime);
}
/**
* --------------------------设置当前界面
* @param position
*/
private void setCurrentView(int position) {
if(position < 0)
{
return ;
}
viewPager.setCurrentItem(position);
}
/**
* -------------------------改变Pager页面 标题 小点
* @param position
*/
private void setCurrentPage(int position) {
currentPosition = position;
for(int i=0; i<imageList.size(); i++)
{
if(currentPosition == i)
{
tvTitle.setText(titleList.get(currentPosition));
dotsList.get(i).setBackgroundResource(R.drawable.dot_focus);
}
else{
dotsList.get(i).setBackgroundResource(R.drawable.dot_normal);
}
}
}
@SuppressLint("HandlerLeak")
private Handler handlerPager = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
setCurrentPage(msg.what);
viewPager.setCurrentItem(msg.what);
}
};
@Override
protected void onDestroy() {
if(runnable != null){
handlerPager.removeCallbacks(runnable);
}
super.onDestroy();
};
}
|
[
"tyzdhaha@163.com"
] |
tyzdhaha@163.com
|
40eb567eb9816e057e649a5e484fb4a81437da6b
|
fca163472c002db3c780e8d866779132ddb78606
|
/src/com/clearfaun/playing/around/AnimalCharmer.java
|
00dc3bd87a390ee0fbf456eda81580e868ad0b58
|
[] |
no_license
|
SpencerDepas/IteratorPattern_HW
|
d5113a654905372a4cf652235f7dda2931b609bc
|
d03fc012e0fc6e5289fe57fc90f91b7177ec1832
|
refs/heads/master
| 2016-09-12T19:59:04.629201
| 2016-05-06T01:50:16
| 2016-05-06T01:50:16
| 58,172,579
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,161
|
java
|
package com.clearfaun.playing.around;
import java.util.Iterator;
/**
* Created by SpencerDepas on 5/5/16.
*/
public class AnimalCharmer {
private AnimalIterator brooklynAnimals;
private AnimalIterator cambridgeAnimals;
public AnimalCharmer(AnimalIterator brooklynAnimals, AnimalIterator cambridgeAnimals){
this.brooklynAnimals = brooklynAnimals;
this.cambridgeAnimals = cambridgeAnimals;
}
public void showTheAnimals(){
Iterator brooklynAnimalsIterator = brooklynAnimals.createIterator();
Iterator cambridgeAnimalsIterator = cambridgeAnimals.createIterator();
System.out.println("Animals from Brooklyn\n");
printTheSongs(brooklynAnimalsIterator);
System.out.println("Animals from Cambridge\n");
printTheSongs(cambridgeAnimalsIterator);
}
private void printTheSongs(Iterator iterator){
while(iterator.hasNext()){
Animal animal = (Animal) iterator.next();
System.out.println(animal.getName());
System.out.println(animal.getType());
System.out.println(animal.getAge() + "\n");
}
}
}
|
[
"spencerdepas@gmail.com"
] |
spencerdepas@gmail.com
|
acd0de56ffb8280d7442f4f1636ce381a9aeffc9
|
9ef4aaf2036c1b00d5a4f218e39febbce9f6c75b
|
/spring-cloud-eureka-server/src/main/java/com/neusoft/springcloudeurekaserver/SpringCloudEurekaServerApplication.java
|
d0014f85ad9f13d274f321fbd7490adeffb11db3
|
[] |
no_license
|
yubaoqi/springcloud
|
264b16374382c7fa51e46f949f07a4c0a9ae78b2
|
10f4fdad6ac7cf3b1c69ee09b8eb51d95002fc44
|
refs/heads/master
| 2020-05-17T05:41:42.801094
| 2019-04-26T02:24:26
| 2019-04-26T02:24:26
| 183,541,637
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 469
|
java
|
package com.neusoft.springcloudeurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class SpringCloudEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaServerApplication.class, args);
}
}
|
[
"1657899428@qq.com"
] |
1657899428@qq.com
|
87e04bb5b9fe2b74f9dc7267fced61d7c8440eec
|
082e26b011e30dc62a62fae95f375e4f87d9e99c
|
/docs/weixin_7.0.4_source/反编译源码/未反混淆/src/main/java/com/tencent/mm/plugin/fts/ui/widget/FTSLocalPageRelevantView.java
|
91ff818cd9a7796795c877fb0fd538f48e7395a2
|
[] |
no_license
|
xsren/AndroidReverseNotes
|
9631a5aabc031006e795a112b7ac756a8edd4385
|
9202c276fe9f04a978e4e08b08e42645d97ca94b
|
refs/heads/master
| 2021-04-07T22:50:51.072197
| 2019-07-16T02:24:43
| 2019-07-16T02:24:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,253
|
java
|
package com.tencent.mm.plugin.fts.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.R;
import com.tencent.mm.protocal.protobuf.btf;
import com.tencent.mm.sdk.platformtools.bo;
import java.util.LinkedList;
import java.util.List;
public class FTSLocalPageRelevantView extends LinearLayout implements OnClickListener {
public String hlm = null;
public LinearLayout jbJ;
private b mMb = null;
public List<btf> mMc = null;
public String query = null;
class a {
public btf mMe;
public int position;
public a(btf btf, int i) {
this.mMe = btf;
this.position = i;
}
}
public interface b {
void a(btf btf, String str, int i);
}
public FTSLocalPageRelevantView(Context context) {
super(context);
AppMethodBeat.i(62138);
post(new Runnable() {
public final void run() {
AppMethodBeat.i(62136);
FTSLocalPageRelevantView.a(FTSLocalPageRelevantView.this);
AppMethodBeat.o(62136);
}
});
AppMethodBeat.o(62138);
}
public FTSLocalPageRelevantView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public FTSLocalPageRelevantView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
}
public void setOnRelevantClickListener(b bVar) {
this.mMb = bVar;
}
public void onClick(View view) {
AppMethodBeat.i(62139);
if (!(this.mMb == null || view.getTag() == null || !(view.getTag() instanceof a))) {
a aVar = (a) view.getTag();
this.mMb.a(aVar.mMe, this.hlm, aVar.position);
}
AppMethodBeat.o(62139);
}
public final void b(List<btf> list, LinearLayout linearLayout) {
AppMethodBeat.i(62140);
linearLayout.removeAllViews();
for (btf btf : list) {
if (btf != null) {
Object obj;
View inflate = LayoutInflater.from(linearLayout.getContext()).inflate(R.layout.a22, linearLayout, false);
TextView textView = (TextView) inflate.findViewById(R.id.m5);
inflate.setOnClickListener(new OnClickListener() {
public final void onClick(View view) {
AppMethodBeat.i(62137);
FTSLocalPageRelevantView.this.onClick(view);
AppMethodBeat.o(62137);
}
});
textView.setText(btf.wVl);
int indexOf = list.indexOf(btf);
if (list == null || indexOf >= list.size()) {
obj = null;
} else {
obj = new a((btf) list.get(indexOf), indexOf + 1);
}
inflate.setTag(obj);
linearLayout.addView(inflate);
}
}
AppMethodBeat.o(62140);
}
public static List<btf> ca(List<btf> list) {
AppMethodBeat.i(62141);
LinkedList linkedList = new LinkedList();
for (btf btf : list) {
if (!bo.isNullOrNil(btf.wVl)) {
linkedList.add(btf);
}
}
AppMethodBeat.o(62141);
return linkedList;
}
public String getSearchId() {
return this.hlm != null ? this.hlm : "";
}
public String getWordList() {
AppMethodBeat.i(62142);
StringBuilder stringBuilder = new StringBuilder("");
if (this.mMc != null) {
for (btf btf : this.mMc) {
if (stringBuilder.length() > 0) {
stringBuilder.append("|");
}
stringBuilder.append(btf.wVl);
}
}
String stringBuilder2 = stringBuilder.toString();
AppMethodBeat.o(62142);
return stringBuilder2;
}
public String getQuery() {
return this.query != null ? this.query : "";
}
static /* synthetic */ void a(FTSLocalPageRelevantView fTSLocalPageRelevantView) {
int dimensionPixelSize;
AppMethodBeat.i(62143);
fTSLocalPageRelevantView.setOrientation(1);
fTSLocalPageRelevantView.setGravity(16);
fTSLocalPageRelevantView.setVisibility(8);
try {
dimensionPixelSize = fTSLocalPageRelevantView.getResources().getDimensionPixelSize(R.dimen.ho);
} catch (Exception e) {
dimensionPixelSize = com.tencent.mm.bz.a.fromDPToPix(fTSLocalPageRelevantView.getContext(), 48);
}
fTSLocalPageRelevantView.setMinimumHeight(dimensionPixelSize);
LayoutParams layoutParams = (LayoutParams) fTSLocalPageRelevantView.getLayoutParams();
layoutParams.width = -1;
layoutParams.height = -2;
fTSLocalPageRelevantView.setLayoutParams(layoutParams);
AppMethodBeat.o(62143);
}
}
|
[
"alwangsisi@163.com"
] |
alwangsisi@163.com
|
1cf16f35f5415367d0c2319ce408a0c475c45b12
|
be0dedb286e329f2eef585357dfe2ed10631875d
|
/app/src/main/java/com/example/android/tourofleesburg/MarshallHouse.java
|
1d4cf0c03538d0bc2f1cbc8b66c429d3c19d5eb9
|
[] |
no_license
|
rreay724/TourofLeesburg
|
ec3fbf2073bad2ec63766aa0724dc1de3f01c04f
|
5f9afe35cc80ddea83e553be845d462b69b475ba
|
refs/heads/master
| 2020-04-02T11:50:42.856835
| 2018-10-29T23:52:49
| 2018-10-29T23:52:49
| 154,409,044
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 788
|
java
|
package com.example.android.tourofleesburg;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
public class MarshallHouse extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView titleHeader = findViewById(R.id.historyTitleTextView);
titleHeader.setText(R.string.marshall_house_title);
ImageView imageView = findViewById(R.id.tourImage);
imageView.setImageResource(R.drawable.marshall_image1);
TextView description = findViewById(R.id.contentDescription);
description.setText(R.string.marshall_house_info);
}
}
|
[
"rreay724@gmail.com"
] |
rreay724@gmail.com
|
a70f6751bddd1fd44b7d3e314454a0ff22912f9b
|
eff8420c9530e25de8da07e61e2b0d6b2efed309
|
/pinot-plugins/pinot-batch-ingestion/pinot-batch-ingestion-common/src/test/java/org/apache/pinot/plugin/ingestion/batch/common/SegmentGenerationUtilsTest.java
|
1753c959c9328769d96ceac0fe88399cb5a77df8
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"BSD-2-Clause",
"EPL-2.0",
"CDDL-1.0",
"EPL-1.0",
"CDDL-1.1",
"CPL-1.0",
"LicenseRef-scancode-public-domain",
"CC-PDDC",
"bzip2-1.0.6",
"CC-BY-SA-3.0",
"LGPL-2.0-or-later",
"CC-BY-2.5",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"NAIST-2003"
] |
permissive
|
mik-laj/incubator-pinot
|
5631f11e5f4a9c6bebe5c5cdbe8c45e2ab302bea
|
a5c4ed27f36b88dbce061f636fb6cc2b4270084b
|
refs/heads/master
| 2021-07-06T04:09:54.251138
| 2021-01-08T20:19:47
| 2021-01-08T20:19:47
| 218,931,646
| 0
| 0
|
Apache-2.0
| 2019-11-01T07:04:55
| 2019-11-01T07:04:55
| null |
UTF-8
|
Java
| false
| false
| 2,394
|
java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.plugin.ingestion.batch.common;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.net.URI;
import java.net.URISyntaxException;
public class SegmentGenerationUtilsTest {
@Test
public void testExtractFileNameFromURI() {
Assert.assertEquals(SegmentGenerationUtils.getFileName(URI.create("file:/var/data/myTable/2020/04/06/input.data")),
"input.data");
Assert.assertEquals(SegmentGenerationUtils.getFileName(URI.create("/var/data/myTable/2020/04/06/input.data")),
"input.data");
Assert.assertEquals(SegmentGenerationUtils
.getFileName(URI.create("dbfs:/mnt/mydb/mytable/pt_year=2020/pt_month=4/pt_date=2020-04-01/input.data")),
"input.data");
Assert.assertEquals(SegmentGenerationUtils.getFileName(URI.create("hdfs://var/data/myTable/2020/04/06/input.data")),
"input.data");
}
// Confirm output path generation works with URIs that have authority/userInfo.
@Test
public void testRelativeURIs() throws URISyntaxException {
URI inputDirURI = new URI("hdfs://namenode1:9999/path/to/");
URI inputFileURI = new URI("hdfs://namenode1:9999/path/to/subdir/file");
URI outputDirURI = new URI("hdfs://namenode2/output/dir/");
URI segmentTarFileName = new URI("file.tar.gz");
URI outputSegmentTarURI = SegmentGenerationUtils
.getRelativeOutputPath(inputDirURI, inputFileURI, outputDirURI).resolve(segmentTarFileName);
Assert.assertEquals(outputSegmentTarURI.toString(),
"hdfs://namenode2/output/dir/subdir/file.tar.gz");
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
604a490aab330041a541aeab87034951317c27eb
|
1a38b7f1c62e88fdd58457b4bd8fd53cc61d4680
|
/src/main/java/com/silverpeas/tags/searchEngine/getSearchEngineTag.java
|
acd82366e741caf847b82542f60505199988e517
|
[] |
no_license
|
Silverpeas/taglibs
|
d98e2f6ee7e17d02864e7ac3661f3b9b6e723e0f
|
4178b7e228fb276e1deddc04789f5edae0fd354d
|
refs/heads/master
| 2020-06-03T10:55:37.388294
| 2015-12-03T13:59:39
| 2015-12-03T13:59:39
| 9,592,899
| 0
| 1
| null | 2015-07-08T07:28:25
| 2013-04-22T07:01:36
|
Java
|
UTF-8
|
Java
| false
| false
| 5,341
|
java
|
/**
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/legal/licensing"
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.tags.searchEngine;
import java.util.Hashtable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import com.silverpeas.tags.authentication.AuthenticationManager;
import com.stratelia.silverpeas.pdc.model.SearchContext;
public class getSearchEngineTag extends TagSupport {
public static final String PAGE_ID = "page";
public static final String REQUEST_ID = "request";
public static final String SESSION_ID = "session";
public static final String APPLICATION_ID = "application";
private String scope = REQUEST_ID;
private String name;
private String query;
private String spaceId;
private String componentId;
private String authorId;
private String afterDate;
private String beforeDate;
private SearchContext pdcContext;
private Hashtable xmlQuery;
private String xmlTitle;
private String xmlTemplate;
private String publicationEnabled = "true";
private String forumEnabled = "false";
public getSearchEngineTag() {
super();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setQuery(String query) {
this.query = query;
}
public String getQuery() {
return query;
}
public void setSpaceId(String spaceId) {
this.spaceId = spaceId;
}
public String getSpaceId() {
return spaceId;
}
public void setComponentId(String componentId) {
this.componentId = componentId;
}
public String getComponentId() {
return componentId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public String getAuthorId() {
return authorId;
}
public String getAfterDate() {
return afterDate;
}
public void setAfterDate(String afterDate) {
this.afterDate = afterDate;
}
public String getBeforeDate() {
return beforeDate;
}
public void setBeforeDate(String beforeDate) {
this.beforeDate = beforeDate;
}
public SearchContext getPdcContext() {
return pdcContext;
}
public void setPdcContext(SearchContext pdcContext) {
this.pdcContext = pdcContext;
}
public void setScope(String scope) {
this.scope = scope;
}
public int doStartTag() throws JspTagException {
String userId = AuthenticationManager.getUserId((HttpServletRequest) pageContext.getRequest());
SearchEngineTagUtil stu = new SearchEngineTagUtil(getQuery(), getSpaceId(),
getComponentId(), getAuthorId(), getAfterDate(), getBeforeDate(),
getPublicationEnabled(), getForumEnabled());
stu.setUserId(userId);
stu.setPdcContext(getPdcContext());
stu.setXmlQuery(getXmlQuery());
stu.setXmlTemplate(getXmlTemplate());
stu.setXmlTitle(getXmlTitle());
pageContext.setAttribute(getName(), stu, translateScope(scope));
return EVAL_PAGE;
}
protected int translateScope(String scope) {
if (scope.equalsIgnoreCase(PAGE_ID)) {
return PageContext.PAGE_SCOPE;
} else if (scope.equalsIgnoreCase(REQUEST_ID)) {
return PageContext.REQUEST_SCOPE;
} else if (scope.equalsIgnoreCase(SESSION_ID)) {
return PageContext.SESSION_SCOPE;
} else if (scope.equalsIgnoreCase(APPLICATION_ID)) {
return PageContext.APPLICATION_SCOPE;
} else
return PageContext.REQUEST_SCOPE;
}
public Hashtable getXmlQuery() {
return xmlQuery;
}
public void setXmlQuery(Hashtable xmlQuery) {
this.xmlQuery = xmlQuery;
}
public String getXmlTemplate() {
return xmlTemplate;
}
public void setXmlTemplate(String xmlTemplate) {
this.xmlTemplate = xmlTemplate;
}
public String getXmlTitle() {
return xmlTitle;
}
public void setXmlTitle(String xmlTitle) {
this.xmlTitle = xmlTitle;
}
public String getPublicationEnabled() {
return publicationEnabled;
}
public void setPublicationEnabled(String publicationEnabled) {
this.publicationEnabled = publicationEnabled;
}
public String getForumEnabled() {
return forumEnabled;
}
public void setForumEnabled(String forumEnabled) {
this.forumEnabled = forumEnabled;
}
}
|
[
"emmanuel.hugonnet@silverpeas.com"
] |
emmanuel.hugonnet@silverpeas.com
|
41e901c341dddec71b4e60f692dc07c67c235a6c
|
ec69fe7051d32d34705646ab4d3512c247027f20
|
/src/main/java/converters/TransactionToStringConverter.java
|
0264c2430eb506408e6ac6665ef70cb2a2fc965d
|
[] |
no_license
|
jesvazarg/Acme-CnG
|
fe777ad55a2299c46f630b748db1462b0c53da28
|
204af7f24f42c17756e13503e98d35dede58c41d
|
refs/heads/master
| 2020-05-21T21:47:21.802517
| 2017-04-12T02:44:33
| 2017-04-12T02:44:33
| 84,651,676
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 548
|
java
|
package converters;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import domain.Transaction;
@Component
@Transactional
public class TransactionToStringConverter implements Converter<Transaction, String> {
@Override
public String convert(Transaction transaction) {
String result;
if (transaction == null){
result = null;
}else{
result = String.valueOf(transaction.getId());
}
return result;
}
}
|
[
"marcaroli1@gmail.com"
] |
marcaroli1@gmail.com
|
cf6784f5696169294af38b0fe9763d6a985dd966
|
8b4f30926eef1d7832ab666e27b6fe615d8604fd
|
/src/main/java/org/librairy/service/nlp/service/ServiceManager.java
|
d8faa03e9addb5786ae017247842b9feb818ef35
|
[
"Apache-2.0"
] |
permissive
|
librairy/nlpES-service
|
3dfb0888e992eb4f60971d56a3ce7b1080cec85d
|
5f07f08ee1059595ce9d4e817372e689d903f679
|
refs/heads/master
| 2021-05-12T14:05:37.348728
| 2019-03-12T23:55:37
| 2019-03-12T23:55:37
| 116,943,132
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,372
|
java
|
package org.librairy.service.nlp.service;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.librairy.service.nlp.annotators.StanfordAnnotatorWrapperES;
import org.librairy.service.nlp.annotators.StanfordPipeAnnotatorES;
import org.librairy.service.nlp.annotators.StanfordWordnetPipeAnnotatorES;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutionException;
/**
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*/
@Component
public class ServiceManager {
private static final Logger LOG = LoggerFactory.getLogger(ServiceManager.class);
@Value("#{environment['RESOURCE_FOLDER']?:'${resource.folder}'}")
String resourceFolder;
@Value("#{environment['SPOTLIGHT_ENDPOINT']?:'${spotlight.endpoint}'}")
String endpoint;
@Value("#{environment['SPOTLIGHT_THRESHOLD']?:${spotlight.threshold}}")
Double threshold;
LoadingCache<String, CoreNLPService> coreServices;
LoadingCache<String, IXAService> ixaModels;
LoadingCache<String, DBpediaService> dbpediaServices;
LoadingCache<String, CoreNLPService> wordnetServices;
@PostConstruct
public void setup(){
ixaModels = CacheBuilder.newBuilder()
.maximumSize(100)
.build(
new CacheLoader<String, IXAService>() {
public IXAService load(String key) throws ExecutionException {
try{
LOG.info("Initializing IXA service for thread: " + key);
IXAService ixaService = new IXAService(resourceFolder);
ixaService.setup();
return ixaService;
}catch(Exception e){
LOG.error("Unexpected error",e);
throw new ExecutionException(e);
}
}
});
coreServices = CacheBuilder.newBuilder()
.maximumSize(100)
.build(
new CacheLoader<String, CoreNLPService>() {
public CoreNLPService load(String key) throws ExecutionException {
LOG.info("Initializing CoreNLP service for thread: " + key);
try{
CoreNLPService coreService = new CoreNLPService();
coreService.setAnnotator(new StanfordPipeAnnotatorES());
coreService.setTokenizer(new StanfordAnnotatorWrapperES());
return coreService;
}catch(Exception e){
LOG.error("Unexpected error",e);
throw new ExecutionException(e);
}
}
});
wordnetServices = CacheBuilder.newBuilder()
.maximumSize(100)
.build(
new CacheLoader<String, CoreNLPService>() {
public CoreNLPService load(String key) throws ExecutionException {
try{
LOG.info("Initializing CoreNLP with Wordnet service for thread: " + key);
CoreNLPService coreService = new CoreNLPService();
coreService.setAnnotator(new StanfordWordnetPipeAnnotatorES(resourceFolder));
coreService.setTokenizer(new StanfordAnnotatorWrapperES());
return coreService;
}catch(Exception e){
LOG.error("Unexpected error",e);
throw new ExecutionException(e);
}
}
});
dbpediaServices = CacheBuilder.newBuilder()
.maximumSize(100)
.build(
new CacheLoader<String, DBpediaService>() {
public DBpediaService load(String key) throws ExecutionException {
try{
LOG.info("Initializing DBpedia service for thread: " + key);
return new DBpediaService(endpoint, threshold);
}catch(Exception e){
LOG.error("Unexpected error",e);
throw new ExecutionException(e);
}
}
});
}
public IXAService getIXAService(Thread thread) {
try {
return ixaModels.get("thread"+thread.getId());
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
public CoreNLPService getCoreService(Thread thread) {
try {
return coreServices.get("thread"+thread.getId());
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
public CoreNLPService getWordnetService(Thread thread) {
try {
return wordnetServices.get("thread"+thread.getId());
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
public DBpediaService getDBpediaService(Thread thread) {
try {
return dbpediaServices.get("thread"+thread.getId());
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
public void setResourceFolder(String resourceFolder) {
this.resourceFolder = resourceFolder;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public void setThreshold(Double threshold) {
this.threshold = threshold;
}
}
|
[
"cbadenes@gmail.com"
] |
cbadenes@gmail.com
|
88ee9699619ce92088e0427267961418b5d195ae
|
a862ef91b7d30f03744e2917a63bf63dd4a1b73e
|
/src/main/java/ir/sk/atm/controller/ATMController.java
|
297cc8632ab128b690b2a1bf4676620898c7f49a
|
[] |
no_license
|
skayvanfar/atm-console-simulator
|
f15c4620f79a4b321ea1846ff89ccb19e8144443
|
a31e5eb966af188a8b75b8cafa6ad97a4b1fe12e
|
refs/heads/master
| 2023-08-25T22:01:49.955486
| 2021-10-24T12:14:00
| 2021-10-24T12:14:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 656
|
java
|
package ir.sk.atm.controller;
import ir.sk.atm.others.MenuOption;
import ir.sk.atm.transiction.Deposit;
import ir.sk.atm.transiction.Transaction;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "v1/atm")
public class ATMController {
Deposit deposit;
@PostMapping(value = "/deposit")
public void deposit(@RequestParam("amount") int amount) {
Transaction.newInstance(MenuOption.DEPOSIT, 10).execute();
}
@PostMapping(value = "/withdraw")
public int withdraw() {
return 0;
}
@GetMapping("/checkBalance")
public int checkBalance() {
return 0;
}
}
|
[
"skayvanfar.sj@gmail.com"
] |
skayvanfar.sj@gmail.com
|
eec34d37aa0eb258e2e8463870baadfc0de93fa2
|
4cc7c4e40b121c233b24178055b4e66c2d36910f
|
/src/main/java/com/smartitcording/controller/SampleController.java
|
274a8b22dc9193f761f19a4680452d5b7d17cb1d
|
[] |
no_license
|
kofelo123/smartitcording
|
11c0beb1b1538cad2a32de5329ec0602931b89bd
|
4b608bcd6fb86075b49c1d42dc4b820d277dc23e
|
refs/heads/master
| 2021-01-10T22:20:36.022053
| 2018-12-23T13:38:22
| 2018-12-23T13:38:22
| 69,138,471
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,933
|
java
|
package com.smartitcording.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.smartitcording.domain.SampleVO;
@RestController
@RequestMapping("/sample")
public class SampleController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello World ";
}
@RequestMapping("/sendVO")
public SampleVO sendVO() {
SampleVO vo = new SampleVO();
vo.setFirstName("길동");
vo.setLastName("홍");
vo.setMno(123);
return vo;
}
@RequestMapping("/sendList")
public List<SampleVO> sendList() {
List<SampleVO> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
SampleVO vo = new SampleVO();
vo.setFirstName("길동");
vo.setLastName("홍");
vo.setMno(i);
list.add(vo);
}
return list;
}
@RequestMapping("/sendMap")
public Map<Integer, SampleVO> sendMap() {
Map<Integer, SampleVO> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
SampleVO vo = new SampleVO();
vo.setFirstName("길동");
vo.setLastName("홍");
vo.setMno(i);
map.put(i, vo);
}
return map;
}
@RequestMapping("/sendErrorAuth")
public ResponseEntity<Void> sendListAuth() {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
@RequestMapping("/sendErrorNot")
public ResponseEntity<List<SampleVO>> sendListNot() {
List<SampleVO> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
SampleVO vo = new SampleVO();
vo.setFirstName("길동");
vo.setLastName("홍");
vo.setMno(i);
list.add(vo);
}
return new ResponseEntity<>(list, HttpStatus.NOT_FOUND);
}
}
|
[
"hlw123@naver.com"
] |
hlw123@naver.com
|
3819fa556cd3ff8ef629ea42d548e8194e5a19b7
|
1698eaa2d9ffaac28ced3b4239a8de9f2621b032
|
/org/omg/CosNaming/NamingContextPackage/AlreadyBoundHelper.java
|
d8f9f943e9b3fda4a4c64f38264d2ce2023dae0c
|
[] |
no_license
|
k42jc/java8-src
|
ff264ce6669dc46b4362a190e3060628b87d0503
|
0ff109df18e441f698a5b3f8cd3cb76cc796f9b8
|
refs/heads/master
| 2020-03-21T08:09:28.750430
| 2018-07-09T14:58:34
| 2018-07-09T14:58:34
| 138,324,536
| 1
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,360
|
java
|
package org.omg.CosNaming.NamingContextPackage;
/**
* org/omg/CosNaming/NamingContextPackage/AlreadyBoundHelper.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/workspace/8-2-build-windows-i586-cygwin/jdk8u144/9417/corba/src/share/classes/org/omg/CosNaming/nameservice.idl
* Friday, July 21, 2017 9:58:50 PM PDT
*/
abstract public class AlreadyBoundHelper
{
private static String _id = "IDL:omg.org/CosNaming/NamingContext/AlreadyBound:1.0";
public static void insert (org.omg.CORBA.Any a, org.omg.CosNaming.NamingContextPackage.AlreadyBound that)
{
org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
a.type (type ());
write (out, that);
a.read_value (out.create_input_stream (), type ());
}
public static org.omg.CosNaming.NamingContextPackage.AlreadyBound extract (org.omg.CORBA.Any a)
{
return read (a.create_input_stream ());
}
private static org.omg.CORBA.TypeCode __typeCode = null;
private static boolean __active = false;
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
synchronized (org.omg.CORBA.TypeCode.class)
{
if (__typeCode == null)
{
if (__active)
{
return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
}
__active = true;
org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0];
org.omg.CORBA.TypeCode _tcOf_members0 = null;
__typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper.id (), "AlreadyBound", _members0);
__active = false;
}
}
}
return __typeCode;
}
public static String id ()
{
return _id;
}
public static org.omg.CosNaming.NamingContextPackage.AlreadyBound read (org.omg.CORBA.portable.InputStream istream)
{
org.omg.CosNaming.NamingContextPackage.AlreadyBound value = new org.omg.CosNaming.NamingContextPackage.AlreadyBound ();
// read and discard the repository ID
istream.read_string ();
return value;
}
public static void write (org.omg.CORBA.portable.OutputStream ostream, org.omg.CosNaming.NamingContextPackage.AlreadyBound value)
{
// write the repository ID
ostream.write_string (id ());
}
}
|
[
"liao"
] |
liao
|
cf5b8d0a7151d43f41b50a46de6516e8959642a5
|
0364bc5eaecda1ca3d1f4218ba414bc85bba24e6
|
/src/abstractClass/Employee.java
|
959a9432de648a96f553c7707a2263e2c9182beb
|
[] |
no_license
|
promethuesYuan/JavaSELearning
|
45d008b4d66c55fd05ab80f1fe9ca082d7bd4df2
|
c297eeec2b5b44ace12becae89c6974b4beaa4cc
|
refs/heads/master
| 2021-04-08T10:05:10.919990
| 2020-04-04T08:18:44
| 2020-04-04T08:18:44
| 248,765,369
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 827
|
java
|
package abstractClass;
import java.time.LocalDate;
/**
* @author Yuan Zhibo
* @ClassName Employee.java
* @Description TODO
* @createTime 2020年03月19日 20:15:00
*/
public class Employee extends Person{
private String name;
private double salary;
private LocalDate hireDay;
public Employee(String name, double salary, int year, int month, int day){
super(name);
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public double getSalary() {
return salary;
}
public LocalDate getHireDay(){
return hireDay;
}
public String getDescription(){
return String.format("an employee with a salary of %.2f", salary);
}
public void raiseSalary(double percent){
salary = salary * (1 + percent/100);
}
}
|
[
"769847637@qq.com"
] |
769847637@qq.com
|
b9d21ddec8e35ba9c5bb4b52c5d3d915a4f51f38
|
089358c5129a614dfcfd54937ed6c5cfc27e0505
|
/workspace/be/demo/src/main/java/com/example/demo/uss/repository/UserRepository.java
|
c8cfbce4bd78d4a8ef777995e9594cdd1277b12b
|
[] |
no_license
|
wlsdnr4675/WebDevStudies
|
3b05a499f1e5f9fd5ca3b210a4d5415baa469451
|
7a42707e0c4483040ee3d6074de9356fc32de362
|
refs/heads/main
| 2023-06-18T06:13:26.559142
| 2021-07-18T09:58:24
| 2021-07-18T09:58:24
| 346,032,772
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 327
|
java
|
package com.example.demo.uss.repository;
import com.example.demo.uss.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
interface UserCustomRepository {
}
public interface UserRepository extends JpaRepository<User, Long>, UserCustomRepository {
}
|
[
"wlsdnr4675@gmail.com"
] |
wlsdnr4675@gmail.com
|
ee1bb7d4e19cb99acec9199df537c0e268535506
|
aefc5520e395f4756ffae24cbfb2c7178ca723ab
|
/day 1/2D Array.java
|
e4eea7423a5a56ee5edb75324ade959b058c9185
|
[] |
no_license
|
Noahs-Snail/DS-Handson
|
9822538386ea5e7df3019503beefd35ff53b6908
|
bc0043f7ff73b684eb1e5c81feb5107f4763369d
|
refs/heads/main
| 2023-04-20T21:16:27.425285
| 2021-05-12T13:18:18
| 2021-05-12T13:18:18
| 359,396,117
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,566
|
java
|
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the hourglassSum function below.
static int hourglassSum(int[][] arr) {
int max=-9999;
int sum=0;
int a,b;
a=arr.length;
b=arr[0].length;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
sum=arr[i][j]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i][j+1]+arr[i][j+2]+arr[i+2][j+2];
//System.out.println(sum);
if(sum>max)
max=sum;
}
}
return max;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int[][] arr = new int[6][6];
for (int i = 0; i < 6; i++) {
String[] arrRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 6; j++) {
int arrItem = Integer.parseInt(arrRowItems[j]);
arr[i][j] = arrItem;
}
}
int result = hourglassSum(arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
cadf8b3f58ec42a5acecf4009179f0669ebc4fd3
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/12/12_e0b5343d3ea032f6db4c1085d53fd44dbaade8c5/WeatherSupport/12_e0b5343d3ea032f6db4c1085d53fd44dbaade8c5_WeatherSupport_t.java
|
1bbec2249bb3380284cf5ff6b94c03af623dfc63
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692
| 2023-06-22T07:55:56
| 2023-06-22T07:55:56
| 259,613,157
| 6
| 2
| null | 2023-06-22T07:55:57
| 2020-04-28T11:07:49
| null |
UTF-8
|
Java
| false
| false
| 13,165
|
java
|
/**
*
*/
package org.weather.weatherman.content;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONValue;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.util.Log;
import com.baidu.mobstat.StatService;
/**
* 天气信息服务类
*
* @author gengmaozhang01
* @since 2014-1-3 下午7:05:57
*/
public class WeatherSupport {
private static final String tag = WeatherSupport.class.getSimpleName();
private static final String api = "http://42.96.143.229:8387/openapi/api/weather";
private int connectTimeout = 30000;
private int readTimeout = 30000;
private int retry = 3;
private DatabaseSupport databaseSupport;
public WeatherSupport(DatabaseSupport databaseSupport) {
super();
this.databaseSupport = databaseSupport;
}
/**
* 获取天气实况信息
*
* @author gengmaozhang01
* @since 2014-1-3 下午7:28:04
*/
private Weather.RealtimeWeather getRealtimeWeather(String citycode) throws Exception {
if (citycode == null || citycode.length() == 0) {
throw new IllegalArgumentException("citycode is required");
}
String url = api + "/realtime/" + citycode;
for (int i = 0; i < retry; i++) {
try {
String json = this.request(url);
@SuppressWarnings("unchecked")
Map<String, Object> value = (Map<String, Object>) JSONValue.parse(json);
Object code = value.get("code");
if (code == null || !Number.class.isInstance(code) || ((Number) code).intValue() != 0) {
Object msg = value.get("message");
throw new Exception(msg != null ? msg.toString() : "get realtime weather failed");
}
StatService.onEvent(databaseSupport.getContext(), "api", "realtime-success", 1);
return new Weather.RealtimeWeather(value);
} catch (Exception ex) {
Log.e(tag, "get realtime weather failed", ex);
StatService.onEvent(databaseSupport.getContext(), "api", "realtime-failure", 1);
}
}
return null;
}
/**
* 获取天气预报信息
*
* @author gengmaozhang01
* @since 2014-1-3 下午7:28:04
*/
private Weather.ForecastWeather getForecastWeather(String citycode) throws Exception {
if (citycode == null || citycode.length() == 0) {
throw new IllegalArgumentException("citycode is required");
}
String url = api + "/forecast/" + citycode;
for (int i = 0; i < retry; i++) {
try {
String json = this.request(url);
@SuppressWarnings("unchecked")
Map<String, Object> value = (Map<String, Object>) JSONValue.parse(json);
Object code = value.get("code");
if (code == null || !Number.class.isInstance(code) || ((Number) code).intValue() != 0) {
Object msg = value.get("message");
throw new Exception(msg != null ? msg.toString() : "get forecast weather failed");
}
StatService.onEvent(databaseSupport.getContext(), "api", "forecast-success", 1);
return new Weather.ForecastWeather(value);
} catch (Exception ex) {
Log.e(tag, "get forecast weather failed", ex);
StatService.onEvent(databaseSupport.getContext(), "api", "forecast-failure", 1);
}
}
return null;
}
private String request(String url) throws Exception {
String json = null;
HttpURLConnection conn = null;
InputStream ins = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", "WeatherMan/1.7 Android");
conn.setRequestProperty("Content-Type", "text/html; charset=utf-8");
if (connectTimeout > 0) {
conn.setConnectTimeout(connectTimeout);
}
if (readTimeout > 0) {
conn.setReadTimeout(readTimeout);
}
// read
conn.connect();
ins = conn.getInputStream();
ByteArrayOutputStream ous = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = ins.read(b)) > -1) {
ous.write(b, 0, len);
}
json = ous.toString();
ous.close();
} finally {
if (ins != null) {
ins.close();
}
if (conn != null) {
conn.disconnect();
}
}
return json;
}
/**
* 获取天气实况信息
*
* @author gengmaozhang01
* @since 2014-1-3 下午7:53:19
*/
public Cursor findRealtimeWeather(String citycode) {
Log.i(tag, "city is " + citycode);
MatrixCursor result = new MatrixCursor(new String[] { Weather.RealtimeWeather.ID, Weather.RealtimeWeather.NAME,
Weather.RealtimeWeather.TIME, Weather.RealtimeWeather.TEMPERATURE, Weather.RealtimeWeather.HUMIDITY,
Weather.RealtimeWeather.WINDDIRECTION, Weather.RealtimeWeather.WINDFORCE });
// database
String value = null;
Cursor cursor = databaseSupport.find(DatabaseSupport.COL_TYPE + "=? and " + DatabaseSupport.COL_CODE + "=?",
new Object[] { Weather.RealtimeWeather.TYPE, citycode });
if (cursor.moveToFirst()) {
value = cursor.getString(cursor.getColumnIndex(DatabaseSupport.COL_VALUE));
String uptime = cursor.getString(cursor.getColumnIndex(DatabaseSupport.COL_UPDATETIME));
if (this.isNotOvertime(uptime)) {
try {
result.addRow(value.split(";"));
Log.i(tag, "get realtime weather from database");
return result;
} catch (Exception ex) {
Log.e(tag, "parse realtime weather failed", ex);
} finally {
cursor.close();
}
}
}
cursor.close();
// web
Weather.RealtimeWeather realtime = null;
try {
realtime = this.getRealtimeWeather(citycode);
} catch (Exception e) {
Log.e(tag, "get realtime weather failed", e);
}
if (realtime != null) {
result.addRow(new Object[] { realtime.getCityId(), realtime.getCityName(), realtime.getTime(),
realtime.getTemperature(), realtime.getHumidity(), realtime.getWindDirection(),
realtime.getWindForce() });
databaseSupport.saveRealtimeWeather(realtime);
Log.i(tag, "refresh realtime weather by api");
} else if (value != null) { // 网络异常使用旧的实况信息
try {
result.addRow(value.split(";"));
Log.i(tag, "using old realtime weather");
} catch (Exception ex) {
Log.e(tag, "parse realtime weather failed", ex);
}
}
return result;
}
/**
* 获取天气预报信息
*
* @author gengmaozhang01
* @since 2014-1-3 下午7:53:35
*/
public Cursor findForecastWeather(String citycode) {
Log.i(tag, "city is " + citycode);
MatrixCursor result = new MatrixCursor(new String[] { Weather.ForecastWeather.ID, Weather.ForecastWeather.NAME,
Weather.ForecastWeather.TIME, Weather.ForecastWeather.WEATHER, Weather.ForecastWeather.TEMPERATURE,
Weather.ForecastWeather.IMAGE, Weather.ForecastWeather.WIND, Weather.ForecastWeather.WINDFORCE });
// query database
String value = null;
Cursor cursor = databaseSupport.find(DatabaseSupport.COL_TYPE + "=? and " + DatabaseSupport.COL_CODE + "=?",
new Object[] { Weather.ForecastWeather.TYPE, citycode });
if (cursor.moveToFirst()) {
value = cursor.getString(cursor.getColumnIndex(DatabaseSupport.COL_VALUE));
String uptime = cursor.getString(cursor.getColumnIndex(DatabaseSupport.COL_UPDATETIME));
if (this.isNotOvertime(uptime)) {
try {
String[] rows = value.split("#");
for (String row : rows) {
result.addRow(row.split(";"));
}
Log.i(tag, "get forecast weather from database");
return result;
} catch (Exception ex) {
result.close();
result = new MatrixCursor(new String[] { Weather.ForecastWeather.ID, Weather.ForecastWeather.NAME,
Weather.ForecastWeather.TIME, Weather.ForecastWeather.WEATHER,
Weather.ForecastWeather.TEMPERATURE, Weather.ForecastWeather.IMAGE,
Weather.ForecastWeather.WIND, Weather.ForecastWeather.WINDFORCE });
Log.e(tag, "parse forcast weather failed", ex);
} finally {
cursor.close();
}
}
}
cursor.close();
// query web server
Weather.ForecastWeather forecast = null;
try {
forecast = this.getForecastWeather(citycode);
} catch (Exception e) {
Log.e(tag, "get forecast weather failed", e);
}
if (forecast != null) {
List<String> wl = forecast.getWeather(), tl = forecast.getTemperature(), il = forecast.getImage(), wdl = forecast
.getWind(), wfl = forecast.getWindForce();
int length = Math
.min(wl.size(), Math.min(tl.size(), Math.min(il.size(), Math.min(wdl.size(), wfl.size()))));
for (int i = 0; i < length; i++) {
result.addRow(new Object[] { forecast.getCityId(), forecast.getCityName(), forecast.getTime(),
wl.size() > i ? wl.get(i) : null, tl.size() > i ? tl.get(i) : null,
il.size() > i ? il.get(i) : null, wdl.size() > i ? wdl.get(i) : null,
wfl.size() > i ? wfl.get(i) : null });
}
databaseSupport.saveForecastAndIndexWeather(forecast);
Log.i(tag, "refresh forecast weather by api");
} else if (value != null && value.length() > 0) { // 网络异常使用旧的预报信息
try {
String[] rows = value.split("#");
for (String row : rows) {
result.addRow(row.split(";"));
}
Log.i(tag, "using old forecast weather");
} catch (Exception ex) {
Log.e(tag, "parse forcast weather failed", ex);
result.close();
result = new MatrixCursor(new String[] { Weather.ForecastWeather.ID, Weather.ForecastWeather.NAME,
Weather.ForecastWeather.TIME, Weather.ForecastWeather.WEATHER,
Weather.ForecastWeather.TEMPERATURE, Weather.ForecastWeather.IMAGE,
Weather.ForecastWeather.WIND, Weather.ForecastWeather.WINDFORCE });
}
}
return result;
}
/**
* 获取天气指数信息
*
* @author gengmaozhang01
* @since 2014-1-3 下午7:57:48
*/
public Cursor findIndexWeather(String citycode) {
Log.i(tag, "city is " + citycode);
MatrixCursor result = new MatrixCursor(new String[] { Weather.LivingIndex.ID, Weather.LivingIndex.NAME,
Weather.LivingIndex.TIME, Weather.LivingIndex.DRESS, Weather.LivingIndex.ULTRAVIOLET,
Weather.LivingIndex.CLEANCAR, Weather.LivingIndex.TRAVEL, Weather.LivingIndex.COMFORT,
Weather.LivingIndex.MORNINGEXERCISE, Weather.LivingIndex.SUNDRY, Weather.LivingIndex.IRRITABILITY });
// database
String value = null;
Cursor cursor = databaseSupport.find(DatabaseSupport.COL_TYPE + "=? and " + DatabaseSupport.COL_CODE + "=?",
new Object[] { Weather.LivingIndex.TYPE, citycode });
if (cursor.moveToFirst()) {
value = cursor.getString(cursor.getColumnIndex(DatabaseSupport.COL_VALUE));
String uptime = cursor.getString(cursor.getColumnIndex(DatabaseSupport.COL_UPDATETIME));
if (this.isNotOvertime(uptime)) {
try {
result.addRow(value.split(";"));
Log.i(tag, "get living index from database");
return result;
} catch (Exception ex) {
Log.e(tag, "parse living index failed", ex);
} finally {
cursor.close();
}
}
}
cursor.close();
// web
Weather.ForecastWeather forecast = null;
try {
forecast = this.getForecastWeather(citycode);
} catch (Exception e) {
Log.e(tag, "get living index failed", e);
}
if (forecast != null) {
List<Object> row = new ArrayList<Object>();
Collections.addAll(row, forecast.getCityId(), forecast.getCityName(), forecast.getTime());
Weather.LivingIndex li = forecast.getDressIndex();
row.add(li != null ? li.getIndex() : null);
li = forecast.getUltravioletIndex();
row.add(li != null ? li.getIndex() : null);
li = forecast.getCleanCarIndex();
row.add(li != null ? li.getIndex() : null);
li = forecast.getTravelIndex();
row.add(li != null ? li.getIndex() : null);
li = forecast.getComfortIndex();
row.add(li != null ? li.getIndex() : null);
li = forecast.getMorningExerciseIndex();
row.add(li != null ? li.getIndex() : null);
li = forecast.getSunDryIndex();
row.add(li != null ? li.getIndex() : null);
li = forecast.getIrritabilityIndex();
row.add(li != null ? li.getIndex() : null);
result.addRow(row);
databaseSupport.saveForecastAndIndexWeather(forecast);
Log.i(tag, "refresh living index by api");
} else if (value != null && value.length() > 0) { // 网络异常使用旧的指数信息
try {
result.addRow(value.split(";"));
Log.i(tag, "using old living index");
} catch (Exception ex) {
Log.e(tag, "using old living index failed", ex);
}
}
return result;
}
private boolean isNotOvertime(String uptime) {
if (System.currentTimeMillis() - Long.parseLong(uptime) > 10 * 60 * 1000) {
return false;
}
return true;
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
8cc831da9f8d2a13a7fa82d8f0e29dfcc4f4d35d
|
d5e3f47fff3ee1954bcb7573217c66fb41fb434e
|
/src/main/java/com/ss/template/service/BaseService.java
|
7f1ce01cbe44c889589266911974e260899e7a59
|
[] |
no_license
|
shisongWjj/java18
|
76ca436456733a7422be4bb86c0f57e1ef387638
|
55ebe2dd4d1fbd9957aec4a88873983279289949
|
refs/heads/master
| 2022-07-02T09:50:13.087141
| 2021-11-09T07:27:34
| 2021-11-09T07:27:34
| 131,385,925
| 0
| 0
| null | 2022-07-01T21:25:13
| 2018-04-28T07:39:15
|
Java
|
UTF-8
|
Java
| false
| false
| 1,018
|
java
|
package com.ss.template.service;
import java.util.Date;
/**
* BaseService
*
* @author shisong
* @date 2020/5/19
*/
public interface BaseService<Entity,ID> {
/**
* 根据主键删除数据
* @param id 主键
* @param operatorName 操作人
* @param updateTime 修改时间
*/
void deleteOneById(ID id, String operatorName, Date updateTime);
/**
* 根据主键查询数据
* @param id 主键
* @return 查询到的数据
*/
Entity queryOneById(ID id);
/**
* 保存单个数据
* @param entity 保存的实体
* @param createTime 创建时间
* @param operatorName 操作人
*/
void saveOne(Entity entity, Date createTime, String operatorName);
/**
* 根据主键进行修改
* @param entity 修改的实体
* @param id 主键
* @param updateTime 修改时间
* @param operatorName 操作人
*/
void updateOneById(Entity entity, ID id, Date updateTime, String operatorName);
}
|
[
"song.shi@atzuche.com"
] |
song.shi@atzuche.com
|
8d4e0d0a37cdff1f7cd33c3d4f237a2870ce6746
|
af99ef87742b6010787d793d3c6b2ed3fb5ee14c
|
/src/main/java/com/fms/freight/importratequote/config/SwaggerConfig.java
|
9cf40cb7b7609ae7ce9dfdcdab4c85d9359f9312
|
[] |
no_license
|
mssaairaam/import-rate-quote
|
04f2c1cb9691022926bf14b79e6f0c6daca95784
|
449aeae760d0d9011feafe9ebd0a6bc757d717f0
|
refs/heads/master
| 2020-08-02T17:16:22.286421
| 2020-01-09T05:34:33
| 2020-01-09T05:34:33
| 211,442,423
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,280
|
java
|
package com.fms.freight.importratequote.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.fms.freight.importratequote.quotecalc"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfoMetaData());
}
private ApiInfo apiInfoMetaData() {
return new ApiInfo(
"Import Quote Calculator API",
"Calculates Total Cost of the Quote with the given weight(kg) and volume(m3).",
"0.0.1",
"",
null,
"",
"",
null);
}
}
|
[
"mssaairaamz@gmail.com"
] |
mssaairaamz@gmail.com
|
7a295ada98d5f521392a817c59e9203ab604d743
|
ca9de4854beddfbbbffb4692cff3e1a14e47b3fd
|
/src/main/java/br/com/milebrito/controller/dto/EmailResponseDTO.java
|
43e2eec6c4f8af4613e5f46624207b30f4890b72
|
[] |
no_license
|
FelipeBritoFerreira/milebrito
|
3cff143da49cba6ff9a94274d6acbb1c80bd84ca
|
ef908765ea495e674118c20645878dc6e1ef0dbb
|
refs/heads/master
| 2021-01-18T18:09:59.481915
| 2017-03-31T18:07:56
| 2017-03-31T18:07:56
| 86,847,220
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 365
|
java
|
package br.com.milebrito.controller.dto;
public class EmailResponseDTO {
private boolean erro;
private String resposta;
public boolean isErro() {
return erro;
}
public void setErro(boolean erro) {
this.erro = erro;
}
public String getResposta() {
return resposta;
}
public void setResposta(String resposta) {
this.resposta = resposta;
}
}
|
[
"Sulamer09!"
] |
Sulamer09!
|
fbd228b72bb734b527fc9aa466bb6cd8833cef21
|
b8e65c579a780478c489ca4561b3ea58d0132699
|
/FlooringMastery/src/main/java/com/sg/flooringmastery/dao/NoSuchDateException.java
|
b91363e2a375d61caf08e5e6ba0aea5f7f7164d6
|
[] |
no_license
|
kellermartin13/FlooringMastery
|
bf0d2f3db200bbd34337e8b025ea4cfd85b405ac
|
674508321bed8843ec311a5ac13c35b7b2bb0558
|
refs/heads/master
| 2020-03-22T20:10:57.228586
| 2018-07-11T13:30:11
| 2018-07-11T13:30:11
| 140,579,043
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 505
|
java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sg.flooringmastery.dao;
/**
*
* @author Keller Martin
*/
public class NoSuchDateException extends Exception {
public NoSuchDateException(String message) {
super(message);
}
public NoSuchDateException(String message, Throwable cause) {
super(message, cause);
}
}
|
[
"kellermartin13@gmail.com"
] |
kellermartin13@gmail.com
|
be62f73bc747c80f732db9ed69df3e4dc17675f2
|
075b5a0b7ca631494201ac554aaf051c14cd45d9
|
/src/me/itsatacoshop247/TreeAssist/core/TreeBlock.java
|
6c5bfdd2e090dde228accaf662585a2dca9e8685
|
[] |
no_license
|
SidShakal/TreeAssist
|
629dbfc1fa5dac8403f4b2dff908b8adb351bd35
|
a9acc51b8363c161ca02243ce7c10952b30a4af5
|
refs/heads/master
| 2020-12-27T15:04:59.160402
| 2016-08-16T18:22:31
| 2016-08-16T18:22:31
| 54,504,810
| 0
| 0
| null | 2016-03-22T19:57:50
| 2016-03-22T19:57:50
| null |
UTF-8
|
Java
| false
| false
| 2,165
|
java
|
package me.itsatacoshop247.TreeAssist.core;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import java.util.HashMap;
import java.util.Map;
public class TreeBlock implements ConfigurationSerializable {
private final int x, y, z;
public final String world;
public final long time;
public TreeBlock(final Block b, final long timestamp) {
x = b.getX();
y = b.getY();
z = b.getZ();
world = b.getWorld().getName();
time = timestamp;
}
public TreeBlock(final Map<String, Object> map) {
x = (Integer) map.get("x");
y = (Integer) map.get("y");
z = (Integer) map.get("z");
world = map.get("w").toString();
time = (Long) map.get("t");
}
public Block getBukkitBlock() {
return Bukkit.getWorld(world).getBlockAt(x, y, z);
}
@Override
public Map<String, Object> serialize() {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("w", world);
map.put("x", x);
map.put("y", y);
map.put("z", z);
map.put("t", time);
return map;
}
@Override
public boolean equals(final Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (getClass() != other.getClass()) {
return false;
}
final TreeBlock theOther = (TreeBlock) other;
if (this.x != theOther.x) {
return false;
}
if (this.y != theOther.y) {
return false;
}
if (this.z != theOther.z) {
return false;
}
return this.world.equals(theOther.world);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (world == null ? 0 : world.hashCode());
result = prime * result + (x ^ x >>> 32);
result = prime * result + (y ^ y >>> 32);
result = prime * result + (z ^ z >>> 32);
return result;
}
}
|
[
"chris@slipcor.de"
] |
chris@slipcor.de
|
580d3732a4e193c83f2bf277b55d79a5101318a4
|
d8e695d863aea3293e04efd91f01f4298adbc3a0
|
/apache-ode-1.3.5/ode-bpel-dao/src/main/java/org/apache/ode/bpel/dao/CorrelatorDAO.java
|
162c0f806a7654dc22a066b34f848a6a8b1eaa6c
|
[] |
no_license
|
polyu-lsgi-xiaofei/bpelcube
|
685469261d5ca9b7ee4c7288cf47a950d116b21f
|
45b371a9353209bcc7c4b868cbae2ce500f54e01
|
refs/heads/master
| 2021-01-13T02:31:47.445295
| 2012-11-01T16:20:11
| 2012-11-01T16:20:11
| 35,921,433
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,480
|
java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.bpel.dao;
import java.util.List;
import org.apache.ode.bpel.common.CorrelationKey;
import org.apache.ode.bpel.common.CorrelationKeySet;
import java.util.Collection;
/**
* <p>
* Data access object representing a <em>correlator</em>. A correlator
* does not have a simple explanation: it acts as match-maker connecting
* messages with <em>message consumers</em> (i.e. BPEL pick and receive
* operations) across time. For each partnerLink "myRole" and operation
* there is one correlator.
* </p>
* <p>
* The correlator functions as a two-sided queue: when a message is
* received the correlator is used to dequeue a consumer based on the
* keys from the message. If no consumer matches the keys in the message,
* the message itself is enqueued along with its keys. Conversely, when
* a BPEL pick/receive operation is performed, the correlator is used
* to dequeue a message matching a given correlation key. If no message is
* found, the consumer (i.e. the pick/receive operation) is enqueued
* along with the target key.
* </p>
* <p>
* The end result is matching of messages to pick/receive operations,
* irrespective of whether the operation or the message arrives first.
* Make sense?
* </p>
*/
public interface CorrelatorDAO {
/**
* Get the correlator identifier.
* @return correlator identifier
*/
String getCorrelatorId();
void setCorrelatorId(String newId);
/**
* Enqueue a message exchange to the queue with a set of correlation keys.
*
* @param mex message exchange
* @param correlationKeys pre-computed set of correlation keys for this message
*/
void enqueueMessage(MessageExchangeDAO mex, CorrelationKeySet correlationKeySet);
/**
* Dequeue a message exchange matching a correlationKey constraint.
*
* @param correlationKey correlation correlationKey constraint
* @return opaque message-related data previously enqueued with the
* given correlation correlationKey
*/
MessageExchangeDAO dequeueMessage(CorrelationKeySet correlationKeySet);
/**
* @return all messages waiting on this correlator, use with care as it can potentially return a lot of values
*/
Collection<CorrelatorMessageDAO> getAllMessages();
/**
* Find a route matching the given correlation key.
* @param correlationKey correlation key
* @return route matching the given correlation key
*/
List<MessageRouteDAO> findRoute(CorrelationKeySet correlationKeySet);
/**
* Check if corresponding key set is free to register (see ODE-804)
* @param correlationKeySet
* @return true - available, false - not available
*/
boolean checkRoute(CorrelationKeySet correlationKeySet);
/**
* Add a route from the given correlation key to the given process instance.
* @param routeGroupId identifier of the group of routes to which this route belongs
* @param target target process instance
* @param index relative order in which the route should be considered
* @param correlationKey correlation key to match
*/
void addRoute(String routeGroupId, ProcessInstanceDAO target, int index, CorrelationKeySet correlationKeySet, String routePolicy);
/**
* Remove all routes with the given route-group identifier.
* @param routeGroupId
*/
void removeRoutes(String routeGroupId, ProcessInstanceDAO target);
/**
* @return all routes registered on this correlator, use with care as it can potentially return a lot of values
*/
Collection<MessageRouteDAO> getAllRoutes();
}
|
[
"michael.pantazoglou@gmail.com@f004a122-f478-6e0f-c15d-9ccb889b5864"
] |
michael.pantazoglou@gmail.com@f004a122-f478-6e0f-c15d-9ccb889b5864
|
9a121584f645c207e26b6b7d90297c897a4577df
|
0ece901d73df6f7ed7f36200690e583d1df70d89
|
/src/main/java/net/glowstone/net/codec/EntityTeleportCodec.java
|
569fe0c319e35cbd1232cd76177265136419cd1c
|
[
"MIT"
] |
permissive
|
apiocera/GlowstoneAC
|
49943096a8bf9e8b6904db1be37c85c180d23376
|
a51491c8b7cdd01c66b3f3dc514847b24d5ad01b
|
refs/heads/master
| 2020-03-28T19:22:49.674709
| 2011-11-27T04:12:25
| 2011-11-27T04:12:25
| 2,850,385
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,119
|
java
|
package net.glowstone.net.codec;
import net.glowstone.msg.EntityTeleportMessage;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.IOException;
public final class EntityTeleportCodec extends MessageCodec<EntityTeleportMessage> {
public EntityTeleportCodec() {
super(EntityTeleportMessage.class, 0x22);
}
@Override
public EntityTeleportMessage decode(ChannelBuffer buffer) throws IOException {
int id = buffer.readInt();
int x = buffer.readInt();
int y = buffer.readInt();
int z = buffer.readInt();
int rotation = buffer.readUnsignedByte();
int pitch = buffer.readUnsignedByte();
return new EntityTeleportMessage(id, x, y, z, rotation, pitch);
}
@Override
public ChannelBuffer encode(EntityTeleportMessage message) throws IOException {
ChannelBuffer buffer = ChannelBuffers.buffer(18);
buffer.writeInt(message.getId());
buffer.writeInt(message.getX());
buffer.writeInt(message.getY());
buffer.writeInt(message.getZ());
buffer.writeByte(message.getRotation());
buffer.writeByte(message.getPitch());
return buffer;
}
}
|
[
"apiocera@gmail.com"
] |
apiocera@gmail.com
|
4b0b67951facfd267a6d7325ef01ce3d36d4815b
|
a8b0cce63db49e8f3bcf9275bb96e057d6c2797a
|
/src/nmu/sagrada/messages/client/PlaceDie.java
|
dcda111e18166a332d32acf01f1bad4933161bff
|
[] |
no_license
|
Onke/sagrada-server
|
404025ff5b68bb2035fbe153e21d9950d6adabe4
|
061337c676cc46113e9ecfa94fab1fcb67ae5ec4
|
refs/heads/main
| 2023-04-04T07:03:41.126945
| 2021-04-23T11:01:37
| 2021-04-23T11:01:37
| 356,244,086
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 616
|
java
|
package nmu.sagrada.messages.client;
import nmu.sagrada.ClientHandler;
import nmu.sagrada.Game;
import nmu.sagrada.messages.Message;
public class PlaceDie extends Message<ClientHandler> {
private static final long serialVersionUID = 102L;
private int draftPoolSelection, windowSelection;
public PlaceDie(int draftPoolSelection, int windowSelection) {
this.draftPoolSelection = draftPoolSelection;
this.windowSelection = windowSelection;
}
@Override
public void apply(ClientHandler client) {
Game.playerMove(client, draftPoolSelection, windowSelection);
}
}
|
[
"s217182941@Mandela.ac.za"
] |
s217182941@Mandela.ac.za
|
800d4b62502b0cb508114a5300defdd9e845583f
|
ba15925bedd986dbcc3ca615ea990606e51793d3
|
/app/src/main/java/com/sunfusheng/scrollable/adapter/FragmentPagerItemAdapter.java
|
60930f4fdd4c759f7438e0f88d94a68b9d520156
|
[] |
no_license
|
sunfusheng/NestedScrollableDemo
|
07b58da395f69e26a5cc16ba99ff98e8f4ccd3cd
|
face6b206d9475ba70e53443ed7bbd940bef1520
|
refs/heads/master
| 2021-09-19T08:10:49.079311
| 2018-07-25T11:57:13
| 2018-07-25T11:57:13
| 98,730,452
| 3
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,650
|
java
|
package com.sunfusheng.scrollable.adapter;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sunfusheng on 2017/7/20.
*/
public class FragmentPagerItemAdapter extends FragmentPagerAdapter {
private Context context;
private List<FragmentPagerItem> items;
private SparseArray<Fragment> fragments = new SparseArray<>();
private OnInstantiateFragmentListener listener;
private FragmentPagerItemAdapter(Context context, FragmentManager fragmentManager, List<FragmentPagerItem> items) {
super(fragmentManager);
this.context = context;
this.items = items;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
fragments.put(position, fragment);
if (listener != null) {
listener.onInstantiate(position, fragment, items.get(position).getArgs());
}
return fragment;
}
@Override
public Fragment getItem(int position) {
return items.get(position).newInstance(context);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
fragments.remove(position);
}
@Override
public int getCount() {
return items.size();
}
public Fragment getFragment(int position) {
return fragments.get(position);
}
@Override
public String getPageTitle(int position) {
return items.get(position).getPageTitle();
}
public void setOnInstantiateFragmentListener(OnInstantiateFragmentListener listener) {
this.listener = listener;
}
public interface OnInstantiateFragmentListener {
void onInstantiate(int position, Fragment fragment, Bundle args);
}
public static class Builder {
private Context context;
private FragmentManager fragmentManager;
private List<FragmentPagerItem> items = new ArrayList<>();
public Builder(Context context, FragmentManager fragmentManager) {
this.context = context;
this.fragmentManager = fragmentManager;
}
public Builder add(FragmentPagerItem item) {
items.add(item);
return this;
}
public Builder add(int resId, Fragment fragment) {
return add(context.getString(resId), fragment);
}
public Builder add(int resId, Class<? extends Fragment> clazz) {
return add(context.getString(resId), clazz);
}
public Builder add(int resId, Class<? extends Fragment> clazz, Bundle args) {
return add(context.getString(resId), clazz, args);
}
public Builder add(String title, Fragment fragment) {
return add(FragmentPagerItem.create(title, fragment));
}
public Builder add(String title, Class<? extends Fragment> clazz) {
return add(FragmentPagerItem.create(title, clazz));
}
public Builder add(String title, Class<? extends Fragment> clazz, Bundle args) {
return add(FragmentPagerItem.create(title, clazz, args));
}
public FragmentPagerItemAdapter build() {
return new FragmentPagerItemAdapter(context, fragmentManager, items);
}
}
}
|
[
"sfsheng0322@gmail.com"
] |
sfsheng0322@gmail.com
|
24f89ab645ed2414cb8ae74f768dc4ce5c1b6a6f
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/2/2_d1114666defb0564b5e3248061bc6684373cfa16/DecayingBloomFilter/2_d1114666defb0564b5e3248061bc6684373cfa16_DecayingBloomFilter_t.java
|
32d232f0fa1e1f75c0e7853bf1c2edfed4a9b736
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692
| 2023-06-22T07:55:56
| 2023-06-22T07:55:56
| 259,613,157
| 6
| 2
| null | 2023-06-22T07:55:57
| 2020-04-28T11:07:49
| null |
UTF-8
|
Java
| false
| false
| 11,044
|
java
|
package net.i2p.util;
import java.util.Random;
import net.i2p.I2PAppContext;
import net.i2p.data.DataHelper;
import org.xlattice.crypto.filters.BloomSHA1;
/**
* Series of bloom filters which decay over time, allowing their continual use
* for time sensitive data. This has a fixed size (currently 1MB per decay
* period, using two periods overall), allowing this to pump through hundreds of
* entries per second with virtually no false positive rate. Down the line,
* this may be refactored to allow tighter control of the size necessary for the
* contained bloom filters, but a fixed 2MB overhead isn't that bad.
*/
public class DecayingBloomFilter {
private I2PAppContext _context;
private Log _log;
private BloomSHA1 _current;
private BloomSHA1 _previous;
private int _durationMs;
private int _entryBytes;
private byte _extenders[][];
private byte _extended[];
private byte _longToEntry[];
private long _longToEntryMask;
private long _currentDuplicates;
private boolean _keepDecaying;
private DecayEvent _decayEvent;
private static final int DEFAULT_M = 23;
private static final boolean ALWAYS_MISS = false;
/**
* Create a bloom filter that will decay its entries over time.
*
* @param durationMs entries last for at least this long, but no more than twice this long
* @param entryBytes how large are the entries to be added? if this is less than 32 bytes,
* the entries added will be expanded by concatenating their XORing
* against with sufficient random values.
*/
public DecayingBloomFilter(I2PAppContext context, int durationMs, int entryBytes) {
_context = context;
_log = context.logManager().getLog(DecayingBloomFilter.class);
_entryBytes = entryBytes;
// this is instantiated in four different places, they may have different
// requirements, but for now use this as a gross method of memory reduction.
// m == 23 => 1MB each BloomSHA1 (4 pairs = 8MB total)
int m = context.getProperty("router.decayingBloomFilterM", DEFAULT_M);
_current = new BloomSHA1(m, 11); //new BloomSHA1(23, 11);
_previous = new BloomSHA1(m, 11); //new BloomSHA1(23, 11);
_durationMs = durationMs;
int numExtenders = (32+ (entryBytes-1))/entryBytes - 1;
if (numExtenders < 0)
numExtenders = 0;
_extenders = new byte[numExtenders][entryBytes];
for (int i = 0; i < numExtenders; i++)
_context.random().nextBytes(_extenders[i]);
if (numExtenders > 0) {
_extended = new byte[32];
_longToEntry = new byte[_entryBytes];
_longToEntryMask = (1l << (_entryBytes * 8l)) -1;
}
_currentDuplicates = 0;
_decayEvent = new DecayEvent();
_keepDecaying = true;
SimpleTimer.getInstance().addEvent(_decayEvent, _durationMs);
}
public long getCurrentDuplicateCount() { return _currentDuplicates; }
public int getInsertedCount() {
synchronized (this) {
return _current.size() + _previous.size();
}
}
public double getFalsePositiveRate() {
synchronized (this) {
return _current.falsePositives();
}
}
/**
* return true if the entry added is a duplicate
*
*/
public boolean add(byte entry[]) {
return add(entry, 0, entry.length);
}
public boolean add(byte entry[], int off, int len) {
if (ALWAYS_MISS) return false;
if (entry == null)
throw new IllegalArgumentException("Null entry");
if (len != _entryBytes)
throw new IllegalArgumentException("Bad entry [" + len + ", expected "
+ _entryBytes + "]");
synchronized (this) {
return locked_add(entry, off, len);
}
}
/**
* return true if the entry added is a duplicate. the number of low order
* bits used is determined by the entryBytes parameter used on creation of the
* filter.
*
*/
public boolean add(long entry) {
if (ALWAYS_MISS) return false;
synchronized (this) {
if (_entryBytes <= 7)
entry = ((entry ^ _longToEntryMask) & ((1 << 31)-1)) | (entry ^ _longToEntryMask);
//entry &= _longToEntryMask;
if (entry < 0) {
DataHelper.toLong(_longToEntry, 0, _entryBytes, 0-entry);
_longToEntry[0] |= (1 << 7);
} else {
DataHelper.toLong(_longToEntry, 0, _entryBytes, entry);
}
return locked_add(_longToEntry, 0, _longToEntry.length);
}
}
/**
* return true if the entry is already known. this does NOT add the
* entry however.
*
*/
public boolean isKnown(long entry) {
if (ALWAYS_MISS) return false;
synchronized (this) {
if (_entryBytes <= 7)
entry = ((entry ^ _longToEntryMask) & ((1 << 31)-1)) | (entry ^ _longToEntryMask);
if (entry < 0) {
DataHelper.toLong(_longToEntry, 0, _entryBytes, 0-entry);
_longToEntry[0] |= (1 << 7);
} else {
DataHelper.toLong(_longToEntry, 0, _entryBytes, entry);
}
return locked_add(_longToEntry, 0, _longToEntry.length, false);
}
}
private boolean locked_add(byte entry[], int offset, int len) {
return locked_add(entry, offset, len, true);
}
private boolean locked_add(byte entry[], int offset, int len, boolean addIfNew) {
if (_extended != null) {
// extend the entry to 32 bytes
System.arraycopy(entry, offset, _extended, 0, len);
for (int i = 0; i < _extenders.length; i++)
DataHelper.xor(entry, offset, _extenders[i], 0, _extended, _entryBytes * (i+1), _entryBytes);
boolean seen = _current.locked_member(_extended);
seen = seen || _previous.locked_member(_extended);
if (seen) {
_currentDuplicates++;
return true;
} else {
if (addIfNew) {
_current.locked_insert(_extended);
_previous.locked_insert(_extended);
}
return false;
}
} else {
boolean seen = _current.locked_member(entry, offset, len);
seen = seen || _previous.locked_member(entry, offset, len);
if (seen) {
_currentDuplicates++;
return true;
} else {
if (addIfNew) {
_current.locked_insert(entry, offset, len);
_previous.locked_insert(entry, offset, len);
}
return false;
}
}
}
public void clear() {
synchronized (this) {
_current.clear();
_previous.clear();
_currentDuplicates = 0;
}
}
public void stopDecaying() {
_keepDecaying = false;
SimpleTimer.getInstance().removeEvent(_decayEvent);
}
private void decay() {
int currentCount = 0;
long dups = 0;
synchronized (this) {
BloomSHA1 tmp = _previous;
currentCount = _current.size();
_previous = _current;
_current = tmp;
_current.clear();
dups = _currentDuplicates;
_currentDuplicates = 0;
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Decaying the filter after inserting " + currentCount
+ " elements and " + dups + " false positives");
}
private class DecayEvent implements SimpleTimer.TimedEvent {
public void timeReached() {
if (_keepDecaying) {
decay();
SimpleTimer.getInstance().addEvent(DecayEvent.this, _durationMs);
}
}
}
public static void main(String args[]) {
int kbps = 256;
int iterations = 100;
testByLong(kbps, iterations);
testByBytes(kbps, iterations);
}
public static void testByLong(int kbps, int numRuns) {
int messages = 60 * 10 * kbps;
Random r = new Random();
DecayingBloomFilter filter = new DecayingBloomFilter(I2PAppContext.getGlobalContext(), 600*1000, 8);
int falsePositives = 0;
long totalTime = 0;
for (int j = 0; j < numRuns; j++) {
long start = System.currentTimeMillis();
for (int i = 0; i < messages; i++) {
if (filter.add(r.nextLong())) {
falsePositives++;
System.out.println("False positive " + falsePositives + " (testByLong j=" + j + " i=" + i + ")");
}
}
totalTime += System.currentTimeMillis() - start;
filter.clear();
}
filter.stopDecaying();
System.out.println("After " + numRuns + " runs pushing " + messages + " entries in "
+ DataHelper.formatDuration(totalTime/numRuns) + " per run, there were "
+ falsePositives + " false positives");
}
public static void testByBytes(int kbps, int numRuns) {
byte iv[][] = new byte[60*10*kbps][16];
Random r = new Random();
for (int i = 0; i < iv.length; i++)
r.nextBytes(iv[i]);
DecayingBloomFilter filter = new DecayingBloomFilter(I2PAppContext.getGlobalContext(), 600*1000, 16);
int falsePositives = 0;
long totalTime = 0;
for (int j = 0; j < numRuns; j++) {
long start = System.currentTimeMillis();
for (int i = 0; i < iv.length; i++) {
if (filter.add(iv[i])) {
falsePositives++;
System.out.println("False positive " + falsePositives + " (testByLong j=" + j + " i=" + i + ")");
}
}
totalTime += System.currentTimeMillis() - start;
filter.clear();
}
filter.stopDecaying();
System.out.println("After " + numRuns + " runs pushing " + iv.length + " entries in "
+ DataHelper.formatDuration(totalTime/numRuns) + " per run, there were "
+ falsePositives + " false positives");
//System.out.println("inserted: " + bloom.size() + " with " + bloom.capacity()
// + " (" + bloom.falsePositives()*100.0d + "% false positive)");
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
a67c335322ae4a3ee34bf211a81872fd00e52b56
|
a1e0706bf1bc83919654b4517730c9aed6499355
|
/drools/gen/com/intellij/plugins/drools/lang/psi/impl/DroolsVariableInitializerImpl.java
|
955c08b23e2b19074846a0b3cd73052b55ae52d7
|
[
"Apache-2.0"
] |
permissive
|
JetBrains/intellij-plugins
|
af734c74c10e124011679e3c7307b63d794da76d
|
f6723228208bfbdd49df463046055ea20659b519
|
refs/heads/master
| 2023-08-23T02:59:46.681310
| 2023-08-22T13:35:06
| 2023-08-22T15:23:46
| 5,453,324
| 2,018
| 1,202
| null | 2023-09-13T10:51:36
| 2012-08-17T14:31:20
|
Java
|
UTF-8
|
Java
| false
| false
| 1,336
|
java
|
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// This is a generated file. Not intended for manual editing.
package com.intellij.plugins.drools.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.plugins.drools.lang.lexer.DroolsTokenTypes.*;
import com.intellij.plugins.drools.lang.psi.*;
public class DroolsVariableInitializerImpl extends DroolsPsiCompositeElementImpl implements DroolsVariableInitializer {
public DroolsVariableInitializerImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull DroolsVisitor visitor) {
visitor.visitVariableInitializer(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof DroolsVisitor) accept((DroolsVisitor)visitor);
else super.accept(visitor);
}
@Override
@Nullable
public DroolsArrayInitializer getArrayInitializer() {
return findChildByClass(DroolsArrayInitializer.class);
}
@Override
@Nullable
public DroolsExpression getExpression() {
return findChildByClass(DroolsExpression.class);
}
}
|
[
"intellij-monorepo-bot-no-reply@jetbrains.com"
] |
intellij-monorepo-bot-no-reply@jetbrains.com
|
b1a0e233024292e775a3dfd5415fed8b044ba7b0
|
3cd9e48a30dee122038f69f5fc279a2a2851a865
|
/src/main/java/com/common/pattern/visitor/StaffA.java
|
e0ddad2f8dbfefb04a17b05ce4629745185236ae
|
[] |
no_license
|
SuperProjectGit/super-repository
|
fafa5f085664df5f668442b9073709263bb3f83c
|
34b0749bc432be3cf90f3d28c581df280ddbd18a
|
refs/heads/master
| 2022-12-26T00:22:32.687028
| 2019-11-19T13:38:07
| 2019-11-19T13:38:07
| 55,777,332
| 0
| 0
| null | 2022-12-16T08:42:28
| 2016-04-08T12:28:01
|
Java
|
UTF-8
|
Java
| false
| false
| 291
|
java
|
package com.common.pattern.visitor;
/**
* @author subo
* @create 2019-10-28 17:07
**/
public class StaffA extends Staff {
public StaffA(String name, Integer age, String kpi) {
super(name, age, kpi);
}
@Override
void accept(Visitor visitor) {
visitor.visit(this);
}
}
|
[
"subo@ucredit.com"
] |
subo@ucredit.com
|
d9207611bfd2d47ef0b72d289bc3a0b93e1f8dff
|
3e84a4ddeffe9ea2fb20c4f0c40446a238860b71
|
/src/main/java/com/example/demo/ExternalApiStatus.java
|
e967513faca2e3e638720221f6b304d644325709
|
[] |
no_license
|
tanay2000/MessageService
|
c0e4722b36fa8a4d54ee43f29300b4c7874434bc
|
8e68fd7228e881af44d8ab7b51955fdcd4d53a82
|
refs/heads/master
| 2023-06-24T16:56:15.504210
| 2021-02-19T13:11:39
| 2021-02-19T13:11:39
| 333,728,678
| 0
| 0
| null | 2021-07-22T19:58:20
| 2021-01-28T10:49:39
|
Java
|
UTF-8
|
Java
| false
| false
| 218
|
java
|
package com.example.demo;
public enum ExternalApiStatus {
SUCCESS("1001"),
FAILURE("7004");
public final String label;
private ExternalApiStatus(String label) {
this.label = label;
}
}
|
[
"tanaygupta2000@gmail.com"
] |
tanaygupta2000@gmail.com
|
dd3b62b9c622d8e883d47dc465514e448cb2d30b
|
5ec9ad33ba409ddb2f7e93c8ace9a024618e5e9b
|
/DannyGit/src/util/Attachments.java
|
5c7bd14c6a7ea9e01a02e1c05528392bc01a5b94
|
[] |
no_license
|
majordillow1/plugintest
|
55493b2f55a8809925c5619ffa555d97aaab03fb
|
0a7d01a84ec59a0a151eea9eb52dd3a41435a330
|
refs/heads/master
| 2021-01-25T09:01:15.932788
| 2017-06-27T21:22:23
| 2017-06-27T21:22:23
| 93,774,289
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,105
|
java
|
/*
* 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 util;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
/**
*
* @author knightmare
*/
public class Attachments {
public static Boolean canAttachThorsHammer(ItemStack item){
if(item.getType() == Material.DIAMOND_AXE){
return true;
}
if(item.getType() == Material.STICK){
return true;
}
return false;
}
public static Boolean canAttachPoisionSword(ItemStack item){
if(item.getType() == Material.WOOD_SWORD || item.getType() == Material.IRON_SWORD || item.getType()==Material.STONE_SWORD||item.getType()==Material.GOLD_SWORD||item.getType()==Material.DIAMOND_SWORD){
return true;
}
return false;
}
public static Boolean canAttachAchoo(ItemStack item){
if(item.getType() == Material.SLIME_BALL){
return true;
}
return false;
}
}
|
[
"unconfigured@null.spigotmc.org"
] |
unconfigured@null.spigotmc.org
|
58015a8ef54960c348fc9113d65f8f9da4daf197
|
ceb7796663ab7feab44ceb0c1755b0a89b92691d
|
/src/main/java/vn/xteam/savemoneyapi/service/IUserService.java
|
c7b45aeb4b4165705c1f115ef1f589c8277b00f4
|
[] |
no_license
|
tuancamtbtx/save-money-api
|
b3f63a2cb2d66b9f49794998cbecdd1fcc0d44a2
|
5720edb88688c24905bca3bdb7f27a80d2e3f493
|
refs/heads/master
| 2023-06-10T19:47:16.840673
| 2021-07-04T03:36:46
| 2021-07-04T03:36:46
| 365,549,008
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 384
|
java
|
package vn.xteam.savemoneyapi.service;
import vn.xteam.savemoneyapi.entities.v1.UserEntity;
import java.sql.SQLException;
import java.util.List;
public interface IUserService {
List<UserEntity> findAll();
UserEntity findById(String id);
boolean save(UserEntity product);
boolean remove(String id) throws SQLException;
boolean update(UserEntity product);
}
|
[
"nguyenvantuan140397@gmail.com"
] |
nguyenvantuan140397@gmail.com
|
85f1e3c8ec2995145f783e7dad8cfad90553dc13
|
e0df39af41e1b914577ffff6c1eb195c10c2751c
|
/src/main/java/com/id/sigada/entities/RmJbt.java
|
a2162c4fbb9f8eec85fade75980789402762ebf9
|
[
"Apache-2.0"
] |
permissive
|
AfesOkta/sigada
|
b09a918ac1a084b29ea891784cf04413641616d1
|
995aafc0b66a34c2c5862bb3e0d26ff4f7d043fd
|
refs/heads/master
| 2020-04-18T18:48:00.491130
| 2019-02-17T13:07:02
| 2019-02-17T13:07:02
| 167,695,303
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,596
|
java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.id.sigada.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
/**
*
* @author Afes
*/
@Entity
@Table(name = "rmjbt")
@Data
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "RmJbt.findAll", query = "SELECT r FROM RmJbt r")
, @NamedQuery(name = "RmJbt.findByJbkod", query = "SELECT r FROM RmJbt r WHERE r.jbkod = :jbkod")
, @NamedQuery(name = "RmJbt.findByJbnam", query = "SELECT r FROM RmJbt r WHERE r.jbnam = :jbnam")})
public class RmJbt implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "uuid" )
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "jbkod")
private String jbkod;
@Size(max = 25)
@Column(name = "jbnam")
private String jbnam;
}
|
[
"afes,.okta@gmail.com"
] |
afes,.okta@gmail.com
|
5f40fcbb577102b13b05c2915d87f22ecbdbee15
|
4f4c3d72c06c9c33bae6cd3385784b7f4f2b1b5f
|
/src/test/Test_MPHS.java
|
7a09b3b002392038ef625fde1a3b5efa4b0e6130
|
[] |
no_license
|
tode91/BloomFilters
|
7ee6b56527c5ecaa7f0e63bd5afdd78d31ed2dd9
|
eb8d06010f8e9fc225abe8812236429e6686b0ac
|
refs/heads/master
| 2021-05-08T11:07:10.889451
| 2018-02-01T19:16:52
| 2018-02-01T19:16:52
| 119,881,137
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 616
|
java
|
package test;
import java.util.List;
import bloomfilter.MPHS;
import data.Data;
import net.sourceforge.sizeof.SizeOf;
public class Test_MPHS {
public static void main(String[] args){
int size=10000;
List<String> lst=Data.getArrayRandomString(10, 10000);
MPHS mp=new MPHS(lst,0.0001);
List<String> lst2=Data.getArrayRandomString(10, 10000);
lst2.addAll(lst);
int nfound=0;
for(String s: lst2) if(mp.lookup(s)==false){System.out.println(s+"\t"+lst.indexOf(s)+"\t"+lst2.indexOf(s));nfound++;}
System.out.println(nfound);
System.out.println(SizeOf.humanReadable(SizeOf.deepSizeOf(mp)));
}
}
|
[
"tode91@gmail.com"
] |
tode91@gmail.com
|
4e017fd1f83fbcbe95088378829f8abdff3a3731
|
597ecb3f9917da2b4c6db23f119e7adbe93faeeb
|
/utils/src/main/java/fi/kapsi/kosmik/devmail/Utils.java
|
543196a492662671bf96cbb6448e86c1be3be740
|
[
"Apache-2.0"
] |
permissive
|
suniala/devmail
|
bbf5a16d3fc9901cdcaf396524bfb0bae970510d
|
12024d42a0736d8dff93f32cae5241310e530e9b
|
refs/heads/master
| 2021-01-25T05:35:10.321363
| 2015-05-02T15:46:06
| 2015-05-02T15:46:06
| 34,906,706
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 170
|
java
|
package fi.kapsi.kosmik.devmail;
import org.joda.time.LocalDateTime;
public class Utils {
public String getTestString() {
return new LocalDateTime().toString();
}
}
|
[
"kosmik@hub.mail.kapsi.fi"
] |
kosmik@hub.mail.kapsi.fi
|
2ba5406a6905f218de6dc17e74d248c825fb9e1d
|
70af297144558943cd1d160922a50a3a10c63ab6
|
/src/com/mateusborja/java1/aula11/VariaveisFlutuante.java
|
6daf8796bd2e25fb709a598f4a3c774e944f42ea
|
[] |
no_license
|
mateusborja/loianetraining-java1
|
deeb0976bb4c08d0c90444d3ba3a1b987ae7d0d4
|
526d15123dbc06a0b6e510278f6fbf31df8d3efb
|
refs/heads/main
| 2023-01-27T19:47:14.226479
| 2020-12-01T21:43:03
| 2020-12-01T21:43:03
| 304,153,267
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 686
|
java
|
//java 1 loiane aula 11
package com.mateusborja.java1.aula11;
import java.text.DecimalFormat;
public class VariaveisFlutuante {
public static void main(String[] args) {
DecimalFormat dc = new DecimalFormat();
double valorPassagem = 2.90;
float valorTomate = 3.95f;
//utilizando o metodo format
System.out.println("Valor da passagem = " + dc.format(valorPassagem));
System.out.println("Valor do Tomate= " + dc.format(valorTomate));
//utilizando o metodo de impressao printf com duas casas decimais
System.out.println();
System.out.printf("Valor da Passagem = %.2f%n", valorPassagem);
System.out.printf("Valor do Tomate = %.2f%n", valorTomate);
}
}
|
[
"mateus.borja@gmail.com"
] |
mateus.borja@gmail.com
|
84508cc12a3f8699eaa3ea92690a4a3a845b993f
|
171b6556e1e6f2f7f2ba3a6a116d1560e5a2e9b3
|
/ejercitoUnlam/src/ejercitoTest/EjercitoTest.java
|
f659087c091fdfa22b0c140648e2129db6692548
|
[] |
no_license
|
micaderito/ProgramacionAvanzada
|
b8e4c1987074fd81859cbf72c50d6d00fd8ad494
|
44844e7190cc5cf1dc6f7d11e9ed584b9557edc8
|
refs/heads/master
| 2021-08-07T16:59:27.411802
| 2017-11-08T15:07:18
| 2017-11-08T15:07:18
| 100,806,316
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 629
|
java
|
package ejercitoTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import ejercitoUnlam.Arma;
import ejercitoUnlam.Nene;
public class EjercitoTest {
private Nene nenito;
private Arma armita;
@Before
public void antesDeCadaPrueba() {
nenito = new Nene();
}
@Test
public void queNOCargueArmaNene() {
armita = new Arma(130,0.5);
Assert.assertEquals(false, nenito.equipar(armita));
}
@Test
public void queCargueArmaNene() {
armita = new Arma(10,0.5);
Arma armita2 = new Arma(40,0.1);
Assert.assertEquals(true,( nenito.equipar(armita) && nenito.equipar(armita2)));
}
}
|
[
"micaeladerito@gmail.com"
] |
micaeladerito@gmail.com
|
11d1cc5f29c0c549e531621823ab8353f75c7e5e
|
543b2f4db4f0429b1dc4be98fe765a783cff190b
|
/javacourse-study-homework/src/main/java/com/study/week7/mapper/SpringUserMapper.java
|
d87b58ac43f2f55869a5c577ba2dcc7e1351123c
|
[] |
no_license
|
Alan-H1927/Java-Advanced-Boot-Camp
|
e2af7dbb01e2d6ea05c68a656e4e17ea0b3e3e88
|
20c4233412e32fe11a0bc3c5fe195e2ec9ce31c2
|
refs/heads/master
| 2023-06-17T23:20:21.715570
| 2021-07-18T14:50:49
| 2021-07-18T14:50:49
| 365,697,868
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 288
|
java
|
package com.study.week7.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.study.week7.entity.SpringUser;
/**
* //TODO 添加类/接口功能描述
*
* @author me-ht
* @date 2021-06-20
*/
public interface SpringUserMapper extends BaseMapper<SpringUser> {
}
|
[
"qwer1927@126.com"
] |
qwer1927@126.com
|
31addf2587f9aa37303eaa3311cda5ba13fea5cb
|
7e74f8e6cf410c476b822b4ca362587fbaa341a1
|
/app/src/main/java/com/app/discovergolf/Model/ModMissionModel.java
|
109c022054f05f00c565c0000284b446a045244d
|
[] |
no_license
|
nisargtrivedi/GolfApp
|
ecd6d8b3b72297021c92c282c6428019755de933
|
ba6e13fcca904f2e9d629d708537ed0d90104f5b
|
refs/heads/main
| 2023-01-08T16:13:09.345463
| 2020-11-10T06:49:16
| 2020-11-10T06:49:16
| 311,570,857
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,748
|
java
|
package com.app.discovergolf.Model;
import java.io.Serializable;
import java.util.ArrayList;
public class ModMissionModel implements Serializable {
public int id;
public String academy_id;
public String ageRange;
public String cat_id;
public String class_id;
public String course_id;
public String created_at;
public int create_team;
public String description;
public String gameFrame;
public String metrics;
public String missionDuration;
public int my_team_id;
public String scheduled_date;
public String status;
public String teamSize;
public int team_admin;
public String timeDuration;
public String title;
public String updated_at;
public String upload_video;
public String mission_type;
public String is_Class;
public String TeamID;
public MissionTeam missionTeam;
public MissionTeam getMissionTeam() {
return missionTeam;
}
public void setMissionTeam(MissionTeam missionTeam) {
this.missionTeam = missionTeam;
}
public class MissionTeam implements Serializable {
public int id;
public int TeamID;
public String team;
public String score;
public ArrayList<PlayerModel> playerModels=new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
}
|
[
"nisarg.trivedi@vovance.com"
] |
nisarg.trivedi@vovance.com
|
3350e69ebe93b98c49ed50639ff19ed796ef2ab6
|
6e256043a49ecf35801c657ef41dee29bc064452
|
/src/java/com/epic/cms/camm/applicationconfirmation/servlet/LoadBinProfilesServlet.java
|
b92ca7b0ba2d5c0d067442ec7065281c8678714d
|
[] |
no_license
|
chinthakasajith/epic
|
19ac105981176edf7f8a585b60bd4144c10be605
|
a6bf9555663d85bb3b1fdc3fedb71443c38b3491
|
refs/heads/master
| 2021-01-01T02:49:52.954515
| 2020-02-08T14:24:32
| 2020-02-08T14:24:32
| 239,144,084
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,001
|
java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.epic.cms.camm.applicationconfirmation.servlet;
import com.epic.cms.admin.controlpanel.systemconfigmgt.bean.CardBinBean;
import com.epic.cms.admin.controlpanel.systemconfigmgt.bean.ProductionModeBean;
import com.epic.cms.camm.applicationconfirmation.businesslogic.ApplicationConfirmationManager;
import com.epic.cms.system.util.json.JSONException;
import com.epic.cms.system.util.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author mahesh_m
*/
public class LoadBinProfilesServlet extends HttpServlet {
private ApplicationConfirmationManager confirmationManager;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, JSONException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// String productionModeCode = request.getParameter("promode");
String cardProductVal = request.getParameter("cardProductVal");
//String cardType = request.getParameter("cardType");
List<CardBinBean> cardBinList = new ArrayList<CardBinBean>();
try {
confirmationManager = new ApplicationConfirmationManager();
JSONObject jCombo = new JSONObject();// if there are several combo box to load
//load combo box data
JSONObject jObject = new JSONObject();
cardBinList = confirmationManager.getBinList(cardProductVal);
//jObject.put("", "-------------SELECT-------------");
for (int i = 0; i < cardBinList.size(); i++) {
jObject.put(cardBinList.get(i).getBinNumber(), cardBinList.get(i).getDescription());
}
jCombo.put("combo1", jObject);
out.print(jCombo);
} catch (Exception e) {
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (JSONException ex) {
Logger.getLogger(LoadBinProfilesServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (JSONException ex) {
Logger.getLogger(LoadBinProfilesServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
[
"sajithdoo@gmail.com"
] |
sajithdoo@gmail.com
|
7b436fe7004cca565941ccc2a8e9a781f04bf832
|
f7b427368d86dbbd7b5544d5e01423a958e0415b
|
/src/main/java/org/sonar/plugins/clojure/sensors/cloverage/FileAnalysis.java
|
72187c85fb058ad79f9672f0566087adf92124c0
|
[
"MIT"
] |
permissive
|
hjhamala/sonar-clojure
|
5f84fc22ad3459b62e4d7388ec0450d7e52b4192
|
ce2519c6594013d8a33d193754274891dad523fc
|
refs/heads/master
| 2020-04-15T16:15:04.873563
| 2019-01-15T06:50:01
| 2019-01-15T06:50:01
| 164,826,972
| 1
| 0
| null | 2019-01-09T09:01:53
| 2019-01-09T09:01:52
| null |
UTF-8
|
Java
| false
| false
| 757
|
java
|
package org.sonar.plugins.clojure.sensors.cloverage;
import java.util.ArrayList;
import java.util.List;
public class FileAnalysis {
private String path = null;
private List<LineAnalysis> entries = new ArrayList<>();
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public void addLine(int number, int hits){
entries.add(new LineAnalysis().setLineNumber(number).setHits(hits));
}
public List<LineAnalysis> getEntries(){
return this.entries;
}
@Override
public String toString() {
return "FileAnalysis{" +
"path='" + path + '\'' +
", entries=" + entries +
'}';
}
}
|
[
"heikki.hamalainen@solita.fi"
] |
heikki.hamalainen@solita.fi
|
d2e5f74ddb81344310ab846feea7912b37cfed8b
|
b0fb31a57febee9841df0ad791b22f99399e379b
|
/node4-tomcat&servlet/src/com/yong/web/Demo05HttpServlet.java
|
e133b24b64534ebbe7621e807cbcff508197e879
|
[] |
no_license
|
yongorg/java-web
|
45862240b894963eb3d0fcf10b3ddcc7baa789e8
|
02d583a05ce1a2b4b67443f762462d261b630782
|
refs/heads/master
| 2022-12-21T11:21:56.605387
| 2019-07-12T01:06:22
| 2019-07-12T01:06:22
| 190,356,889
| 1
| 0
| null | 2022-12-16T04:24:22
| 2019-06-05T08:32:01
|
Java
|
UTF-8
|
Java
| false
| false
| 755
|
java
|
package com.yong.web;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/demo5")
public class Demo05HttpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("doget");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
System.out.println("dopost");
}
}
|
[
"1435024583@qq.com"
] |
1435024583@qq.com
|
67a24676c4162d74711c169ffe12ced011ec607d
|
03ebfe94e62d84153406848268753ff7754818ad
|
/HCF/src/com/fishy/HCF/listener/fixes/BlockJumpGlitchFixListener.java
|
1c3a0a3977fb0df6ec479c538d0ab29062f9d16d
|
[
"Apache-2.0"
] |
permissive
|
Taxcut/Fishy
|
9d7900321e40da321ee172fe9ccb746a809661d1
|
d01f3a10a6309d310832ba35b244e9e18b1709bd
|
refs/heads/master
| 2023-02-17T22:11:14.899612
| 2021-01-04T10:28:55
| 2021-01-04T10:28:55
| 264,900,953
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,454
|
java
|
package com.fishy.hcf.listener.fixes;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.util.Vector;
public class BlockJumpGlitchFixListener implements Listener {
@EventHandler(ignoreCancelled = false, priority = EventPriority.MONITOR)
public void onBlockBreak(BlockPlaceEvent event) {
if (event.isCancelled()) {
Player player = event.getPlayer();
if ((player.getGameMode() == GameMode.CREATIVE) || (player.getAllowFlight())) {
return;
}
Location location = player.getLocation();
Block blockAgainst = event.getBlockAgainst();
Block blockPlaced = event.getBlockPlaced();
if(location.getBlockX() == blockAgainst.getX() && location.getBlockZ() == blockAgainst.getZ() && blockAgainst.getY() < location.getBlockY() - 1 && blockPlaced.getY() < location.getBlockY()){
if (blockPlaced.getType().isSolid() && !(blockPlaced.getState() instanceof Sign)) {
Vector vector = player.getVelocity();
player.setVelocity(vector.setY(vector.getY() - 0.41999998688697815D));
}
}
}
}
}
|
[
"noreply@github.com"
] |
noreply@github.com
|
f8917e8444232d52cfeb5b0a0a3bb84b060fbd5c
|
fd6ea3c5ec215f35a67f23aec1544f2d9df18aec
|
/recommendation-system-work/src/main/java/br/com/ufu/lsi/recommendation/statistics/StatisticalSignificanceCalculator.java
|
2af2c7692d1f74e359460ed729e380e49053c442
|
[] |
no_license
|
fabsfernandes/movie-recommendation-work
|
418c529f63ffbfdaa08bf121dc0e2b649a65399d
|
c31d6451e566e5333f0a7ead36a56ea1a9de23d4
|
refs/heads/master
| 2020-12-25T19:14:28.496373
| 2014-07-25T12:14:07
| 2014-07-25T12:14:07
| 33,134,942
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,179
|
java
|
package br.com.ufu.lsi.recommendation.statistics;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StatisticalSignificanceCalculator {
//private static final String PATH_RESULTS = "/home/fabiola/Desktop/Doutorado/DataMining/Trabalho-Recomendacao/notas_results.csv";
private static final String PATH_RESULTS = "/home/fabiola/Desktop/Doutorado/DataMining/Trabalho-Recomendacao/bool_results.csv";
private int significancePresence = 0;
private int significanceAbsent = 0;
private Map< String, Item > items = new HashMap< String, Item >();
private List<Item> itemsInOrder = new ArrayList<Item>();
public static void main( String... args ) {
StatisticalSignificanceCalculator calculator = new StatisticalSignificanceCalculator();
calculator.readFile();
calculator.calculateSignificance();
for ( Map.Entry< String, Item > itemMap : calculator.items.entrySet() ) {
Item i = itemMap.getValue();
if ( i.getFloorLimit() <= 0.0 && i.getCeilingLimit() >= 0 ){
calculator.significanceAbsent++;
i.setSignificance( false );
}
else{
calculator.significancePresence++;
i.setSignificance( true );
}
}
System.out.println( "#significancePresence = " + calculator.significancePresence );
System.out.println( "#significanceAbsent = " + calculator.significanceAbsent );
System.out.println("#itens = " + calculator.itemsInOrder.size() );
for( Item i : calculator.itemsInOrder ){
//System.out.println( i.getFloorLimit() + "," + i.getCeilingLimit() + "," + i.isSignificance() );
//System.out.println( i.getFloorLimit() );
//System.out.println( i.getCeilingLimit() );
System.out.println( i.isSignificance() );
}
}
public void calculateSignificance() {
for ( Map.Entry< String, Item > itemMap : items.entrySet() ) {
List< Accuracy > accuracies = itemMap.getValue().getAccuracies();
double ac11 = accuracies.get( 0 ).getModel1();
double ac21 = accuracies.get( 0 ).getModel2();
double ac12 = accuracies.get( 1 ).getModel1();
double ac22 = accuracies.get( 1 ).getModel2();
double ac13 = accuracies.get( 2 ).getModel1();
double ac23 = accuracies.get( 2 ).getModel2();
double ac14 = accuracies.get( 3 ).getModel1();
double ac24 = accuracies.get( 3 ).getModel2();
double ac15 = accuracies.get( 4 ).getModel1();
double ac25 = accuracies.get( 4 ).getModel2();
double d1 = ( 1 - ac11 ) - ( 1 - ac21 );
double d2 = ( 1 - ac12 ) - ( 1 - ac22 );
double d3 = ( 1 - ac13 ) - ( 1 - ac23 );
double d4 = ( 1 - ac14 ) - ( 1 - ac24 );
double d5 = ( 1 - ac15 ) - ( 1 - ac25 );
double dbar = ( d1 + d2 + d3 + d4 + d5 ) / 5;
double variance = ( Math.pow( d1 - dbar, 2.0 ) + Math.pow( d2 - dbar, 2.0 ) + Math.pow( d3 - dbar, 2.0 )
+ Math.pow( d4 - dbar, 2.0 ) + Math.pow( d5 - dbar, 2.0 ) ) / 20.0;
double deviation = Math.sqrt( variance );
double floorLimit = dbar - ( 2.77 * deviation );
double ceilingLimit = dbar + ( 2.77 * deviation );
if ( floorLimit < ceilingLimit ) {
itemMap.getValue().setFloorLimit( floorLimit );
itemMap.getValue().setCeilingLimit( ceilingLimit );
}
else {
itemMap.getValue().setFloorLimit( ceilingLimit );
itemMap.getValue().setCeilingLimit( floorLimit );
}
}
}
public void handleLine( String currentLine ) {
String[] tokens = currentLine.split( "," );
String itemName = tokens[ 0 ];
Item item = items.get( itemName );
if ( item == null ) {
Item it = new Item( itemName );
items.put( itemName, it );
item = it;
itemsInOrder.add( item );
}
Accuracy acc = new Accuracy();
acc.setModel1( Double.parseDouble( tokens[ 2 ] ) );
acc.setModel2( Double.parseDouble( tokens[ 3 ] ) );
item.getAccuracies().add( acc );
}
public void readFile() {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader( new FileReader( PATH_RESULTS ) );
while ( ( sCurrentLine = br.readLine() ) != null ) {
handleLine( sCurrentLine );
}
}
catch ( IOException e ) {
e.printStackTrace();
}
finally {
try {
if ( br != null )
br.close();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
}
|
[
"fabsfernandes@gmail.com@5a95a59a-becb-8371-d290-99d7c0dbf8b3"
] |
fabsfernandes@gmail.com@5a95a59a-becb-8371-d290-99d7c0dbf8b3
|
073869ccd04ac0ee5c4de9a354b111f44221f35d
|
c2f20761d08989a412b1b17b9b747240bec1537e
|
/src/main/java/dziennik/DataGenerator.java
|
5252152d1851954bed6112d6112ade6c72e00baf
|
[] |
no_license
|
modernsege/GroupsAndStudentManagmentAPP
|
10e04c9d6e2ab9744112bffc37811a682aec2782
|
fc09429ae7b51b1b91c7853856a075ef7539aecd
|
refs/heads/master
| 2023-09-05T21:25:09.299287
| 2021-11-19T19:27:36
| 2021-11-19T19:27:36
| 429,905,630
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,827
|
java
|
package dziennik;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class DataGenerator {
private static DataGenerator instance; //Singleton
private DataGenerator (){
}
public ClassContainer generate(){
ClassContainer generatedContainer = new ClassContainer();
String Names[] = {"Laura", "Marcin", "Mariola", "Martyna", "Natalia", "Piotr", "Rafal", "Szymon", "Sebastian", "Tobiasz", "Urszula", "Vladimir", "Wojciech", "Zbigniew", "Agnieszka", "Adrian", "Agata", "Bonifacy", "Barbara", "Bartek", "Cecylia", "Dorota", "Dorian", "Eugeniusz", "Elzbieta", "Faustyna", "Faust", "Franek", "Fryderyk", "Grazyna", "Gawel", "Halina", "Herbert", "Iga", "Igor", "Jacek", "Janina", "Kamil", "Katarzyna"};
String Surnames[] = {"Kalinowski", "Masa", "Nara", "Oslo", "Pomidor", "Rakieta", "Sosna", "Trakor", "Usas", "Was", "Zaza", "Agni", "Azai", "Awi", "Bezimienny", "Battlerage", "Bofur", "Cari", "Carrion", "Calvary", "Cyjanek", "Crow", "Dori", "DeZakreble", "Drow", "Dissous", "Eryn", "Ericsson", "Ester", "Egilow", "Gryc", "Garada", "Glab", "Hrow", "Ileou", "Kagur", "Krayn", "Kowi"};
int maxNumberOfStudents = 100;
int minNumberOfStudents = 10;
int maxNumberOfGroups = 8;
int minNumberOfGroups = 4;
Random random = new Random();
int randomNumberOfGroups = random.nextInt(maxNumberOfGroups - minNumberOfGroups+1) + minNumberOfGroups;
for (int i = 0; i<randomNumberOfGroups; i++){
List<Student> studentList = new ArrayList<Student>();
int randomNumberOfStudents = random.nextInt(maxNumberOfStudents - minNumberOfStudents+1) + minNumberOfStudents;
int randomYear = random.nextInt(4) + 1998;
for(int j = 0; j<randomNumberOfStudents; j++){
int randomIndexOfNames = random.nextInt(Names.length);
int randomIndexOfSurnames = random.nextInt(Surnames.length);
int randomIndexOfStudentCondition = random.nextInt(4);
int randomPoints = random.nextInt(101);
Student st = new Student(Names[randomIndexOfNames], Surnames[randomIndexOfSurnames], StudentCondition.values()[randomIndexOfStudentCondition] , randomYear, randomPoints);
studentList.add(st);
}
Integer classNum = i+1;
Class cl = new Class("Class "+classNum.toString(), studentList, maxNumberOfStudents);
generatedContainer.addClass(cl);
}
generatedContainer.addClass("Klasa z1", maxNumberOfStudents);
return generatedContainer;
}
public static DataGenerator getInstance() { //Singleton
if(instance == null){
instance = new DataGenerator();
}
return instance;
}
}
|
[
"simonconbrio@gmail.com"
] |
simonconbrio@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.