hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9236656eff351e112158afd59ec7a089145613e5 | 12,126 | java | Java | src/main/java/com/chinaBank/service/ExcelFileModel/impl/ExcelFileModelServiceImpl.java | whl0919/renhang | 1cc64d337a9b36393c0834e1ee12885577439e61 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/chinaBank/service/ExcelFileModel/impl/ExcelFileModelServiceImpl.java | whl0919/renhang | 1cc64d337a9b36393c0834e1ee12885577439e61 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/chinaBank/service/ExcelFileModel/impl/ExcelFileModelServiceImpl.java | whl0919/renhang | 1cc64d337a9b36393c0834e1ee12885577439e61 | [
"Apache-2.0"
] | null | null | null | 32.861789 | 129 | 0.813953 | 997,656 | package com.chinaBank.service.ExcelFileModel.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chinaBank.bean.ExcelFileModel.ExcelBaseColData;
import com.chinaBank.bean.ExcelFileModel.ExcelBaseTabData;
import com.chinaBank.bean.ExcelFileModel.ExcelCheckRuleData;
import com.chinaBank.bean.ExcelFileModel.ExcelModelData;
import com.chinaBank.bean.ExcelFileModel.ExcelScriptInfoData;
import com.chinaBank.mapper.ExcelFileModelMapper;
import com.chinaBank.service.ExcelFileModel.ExcelFileModelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Service(value = "excelService")
public class ExcelFileModelServiceImpl implements ExcelFileModelService {
@Autowired
private ExcelFileModelMapper excelFileModelMapper;
@Override
public String addExcelModel(String excel_model_name, String model_status, String create_user) {
excelFileModelMapper.addExcelModel(excel_model_name, model_status, create_user);
return "success";
}
@Override
public String updateExcelModel(String excel_model_name, String model_status, String id, String update_user) {
excelFileModelMapper.updateExcelModel(excel_model_name, model_status, id, update_user);
return "success";
}
@Override
public String deleteExcelModel(String id) {
excelFileModelMapper.deleteExcelModel(id);
return "success";
}
@Override
public ExcelModelData selectExcelModelById(String id) {
ExcelModelData excelModelDatas = excelFileModelMapper.selectExcelModelById(id);
return excelModelDatas;
}
@Override
public List<ExcelModelData> selectExcelModelByName(String excel_model_name) {
List<ExcelModelData> excelModelDatas = excelFileModelMapper.selectExcelModelByName(excel_model_name);
return excelModelDatas;
}
@Override
public PageInfo<ExcelModelData> findAllExcelModel(int pageNum, int pageSize, String excel_model_name) {
PageHelper.startPage(pageNum, pageSize);
List<ExcelModelData> excelModelDatas = excelFileModelMapper.selectExcelModelByName(excel_model_name);
PageInfo result = new PageInfo(excelModelDatas);
return result;
}
@Override
public String addBaseTabInfo(ExcelBaseTabData excelBaseTabData) {
excelFileModelMapper.addBaseTabInfo(excelBaseTabData);
return "success";
}
@Override
public String updateBaseTabInfo(ExcelBaseTabData excelBaseTabData) {
excelFileModelMapper.updateBaseTabInfo(excelBaseTabData);
return "success";
}
@Override
public String deleteBaseTabInfo(String id) {
excelFileModelMapper.deleteBaseTabInfo(id);
return "success";
}
@Override
public ExcelBaseTabData selecBaseTabInfoById(String id) {
ExcelBaseTabData excelBaseTabDatas = excelFileModelMapper.selectBaseTabInfoById(id);
return excelBaseTabDatas;
}
@Override
public ExcelBaseTabData selectBaseTabInfoByTableName(String table_name) {
ExcelBaseTabData excelBaseTabDatas = excelFileModelMapper.selectBaseTabInfoByTableName(table_name);
return excelBaseTabDatas;
}
@Override
public PageInfo<ExcelBaseTabData> findAllBaseTabInfo(int pageNum, int pageSize, ExcelBaseTabData excelBaseTabData) {
PageHelper.startPage(pageNum, pageSize);
List<ExcelBaseTabData> excelBaseTabDatas = excelFileModelMapper.selectBaseTabInfo(excelBaseTabData);
PageInfo result = new PageInfo(excelBaseTabDatas);
return result;
}
@Override
public String addBasecolumnInfo(ExcelBaseColData excelBaseColData) {
excelFileModelMapper.addBasecolumnInfo(excelBaseColData);
return "success";
}
@Override
public String updateBasecolumnInfo(ExcelBaseColData excelBaseColData) {
excelFileModelMapper.updateBasecolumnInfo(excelBaseColData);
return "success";
}
@Override
public String deleteBasecolumnInfo(String id) {
excelFileModelMapper.deleteBasecolumnInfo(id);
return "success";
}
@Override
public ExcelBaseColData selectBasecolumnInfoById(String id) {
ExcelBaseColData excelBaseColDatas = excelFileModelMapper.selectBasecolumnInfoById(id);
return excelBaseColDatas;
}
@Override
public PageInfo<ExcelBaseColData> findAllBasecolumnInfo(int pageNum, int pageSize,
String table_id) {
PageHelper.startPage(pageNum, pageSize);
List<ExcelBaseColData> excelBaseColDatas = excelFileModelMapper.findAllBasecolumnInfo(table_id);
PageInfo result = new PageInfo(excelBaseColDatas);
return result;
}
@Override
public List<ExcelBaseColData> selectcolumnsInfoByTabId(String table_id) {
List<ExcelBaseColData> excelBaseColDatas = excelFileModelMapper.selectcolumnsInfoByTabId(table_id);
return excelBaseColDatas;
}
@Override
public String addScriptInfo(ExcelScriptInfoData excelScriptInfoData) {
excelFileModelMapper.addScriptInfo(excelScriptInfoData);
return "success";
}
@Override
public String addCheckRulesInfo(ExcelCheckRuleData excelCheckRuleData) {
excelFileModelMapper.addCheckRulesInfo(excelCheckRuleData);
return "success";
}
@Override
public String updateCheckRulesInfo(ExcelCheckRuleData excelCheckRuleData) {
excelFileModelMapper.updateCheckRulesInfo(excelCheckRuleData);
return "success";
}
@Override
public String deleteCheckRulesInfo(String id) {
excelFileModelMapper.deleteCheckRulesInfo(id);
return "success";
}
@Override
public ExcelCheckRuleData selectCheckRulesInfoById(String id) {
ExcelCheckRuleData excelCheckRuleDatas = excelFileModelMapper.selectCheckRulesInfoById(id);
return excelCheckRuleDatas;
}
@Override
public List<ExcelCheckRuleData> findAllCheckRulesInfo(ExcelCheckRuleData excelCheckRuleData) {
return excelFileModelMapper.selectCheckRulesInfo(excelCheckRuleData);
}
// @Override
// public String addConfigFileInfo(ExcelConfigFileData excelConfigFileData) {
// excelFileModelMapper.addConfigFileInfo(excelConfigFileData);
// return "success";
// }
//
// @Override
// public ExcelConfigFileData selectConfigFileInfoByFileName(String FileName) {
// return excelFileModelMapper.selectConfigFileInfoByFileName(FileName);
// }
//
// @Override
// public String updateConfigFileInfo(ExcelConfigFileData excelConfigFileData) {
// excelFileModelMapper.updateConfigFileInfo(excelConfigFileData);
// return "success";
// }
//
// @Override
// public String deleteConfigFileInfo(String id) {
// excelFileModelMapper.deleteConfigFileInfo(id);
// return "success";
// }
//
// @Override
// public List<ExcelConfigFileData> selectConfigFileInfoById(String id) {
// return excelFileModelMapper.selectConfigFileInfoById(id);
// }
//
// @Override
// public PageInfo<ExcelConfigFileData> findAllConfigFileInfo(int pageNum, int pageSize,
// ExcelConfigFileData excelConfigFileData) {
// PageHelper.startPage(pageNum, pageSize);
// List<ExcelConfigFileData> excelConfigFileDatas = excelFileModelMapper.selectConfigFileInfo(excelConfigFileData);
// PageInfo result = new PageInfo(excelConfigFileDatas);
// return result;
// }
// @Override
// public String addModelFileRelationship(String file_id, String status, String model_id, String model_name,String create_user) {
// excelFileModelMapper.addModelFileRelationship(file_id, status, model_id, model_name,create_user);
// return "success";
// }
//
// @Override
// public String deleteModelFileRelationship(String file_id, String model_id) {
// excelFileModelMapper.deleteModelFileRelationship(file_id, model_id);
// return "success";
// }
//
// @Override
// public PageInfo<ExcelModelData> findModelFileRelationship(int pageNum, int pageSize, String file_id) {
// PageHelper.startPage(pageNum, pageSize);
// List<ExcelModelData> excelModelDatas = excelFileModelMapper.findModelFileRelationship(file_id, "");
// PageInfo result = new PageInfo(excelModelDatas);
// return result;
// }
//
// @Override
// public List<ExcelModelData> findModelFileByFileId(String file_id) {
// List<ExcelModelData> excelModelDatas = excelFileModelMapper.findModelFileRelationship(file_id, "");
// return excelModelDatas;
// }
@Override
public List<ExcelBaseTabData> selectBaseTabInfoByName(ExcelBaseTabData excelBaseTabData) {
List<ExcelBaseTabData> excelBaseTabDatas = excelFileModelMapper.selectBaseTabInfo(excelBaseTabData);
return excelBaseTabDatas;
}
@Override
public List<ExcelCheckRuleData> findCheckRulesInfoByTabId(String model_id) {
ExcelCheckRuleData excelCheckRuleData = new ExcelCheckRuleData();
excelCheckRuleData.setModel_id(model_id);
List<ExcelCheckRuleData> excelCheckRuleDatas = excelFileModelMapper.selectCheckRulesInfo(excelCheckRuleData);
return excelCheckRuleDatas;
}
@Override
public ExcelScriptInfoData selectScriptInfoByTableName(String table_name,String script_type) {
ExcelScriptInfoData excelScriptInfoData = excelFileModelMapper.selectScriptInfoByTableName(table_name,script_type);
return excelScriptInfoData;
}
@Override
public String runSqlScript(String sql) {
excelFileModelMapper.runSqlScript(sql);
return "success";
}
@Override
public String updateScriptInfo(ExcelScriptInfoData excelScriptInfoData) {
excelFileModelMapper.updateScriptInfo(excelScriptInfoData);
return "success";
}
@Override
public List<ExcelBaseColData> selectBasecolumnInfoByTableId(String tableId) {
List<ExcelBaseColData> excelBaseColDatas = excelFileModelMapper.selectBasecolumnInfoByName(tableId,"");
return excelBaseColDatas;
}
@Override
public int selectCount(String sql) {
int count = excelFileModelMapper.selectCount(sql);
return count;
}
// @Override
// public ExcelSheetData selectSheetInfoBySheetName(String sheet_name) {
// return excelFileModelMapper.selectSheetInfoBySheetName(sheet_name);
// }
@Override
public ExcelModelData selectExcelModelByModelName(String excel_model_name) {
return excelFileModelMapper.selectExcelModelByModelName(excel_model_name);
}
@Override
public ExcelBaseColData selectBasecolumnInfoByColumnName(String tableId, String colUmnName) {
return excelFileModelMapper.selectBasecolumnInfoByColumnName(tableId, colUmnName);
}
@Override
public String deleteScript(String table_name) {
excelFileModelMapper.deleteScript(table_name);
return "success";
}
@Override
public List<ExcelModelData> selectExcelModelAll() {
return excelFileModelMapper.selectExcelModelAll();
}
@Override
public ExcelModelData findModelFileById(String file_id, String model_id) {
return excelFileModelMapper.findModelFileById(file_id, model_id);
}
@Override
public String addCheckRulesPublic(ExcelCheckRuleData excelCheckRuleData) {
excelFileModelMapper.addCheckRulesPublic(excelCheckRuleData);
return "success";
}
@Override
public String updateCheckRulesPublic(ExcelCheckRuleData excelCheckRuleData) {
excelFileModelMapper.updateCheckRulesPublic(excelCheckRuleData);
return "success";
}
@Override
public String deleteCheckRulesPublic(String id) {
excelFileModelMapper.deleteCheckRulesPublic(id);
return "success";
}
@Override
public ExcelCheckRuleData selectCheckRulesPublicById(String id) {
return excelFileModelMapper.selectCheckRulesPublicById(id);
}
@Override
public List<ExcelCheckRuleData> findAllCheckRulesPublic(String check_desc,String check_class,String check_type) {
return excelFileModelMapper.findAllCheckRulesPublic(check_desc,check_class,check_type);
}
@Override
public String createTable(String sql) {
excelFileModelMapper.createTable(sql);
return "success";
}
@Override
public String addCheckRulesPublicShip(String table_id, String public_id, String model_id,String create_user,String col) {
excelFileModelMapper.addCheckRulesPublicShip(table_id, public_id, model_id,create_user,col);
return "success";
}
@Override
public List<String> selectCheckRulesPubShipForId(String model_id, String table_id,String col) {
return excelFileModelMapper.selectCheckRulesPubShipForId(model_id, table_id,col);
}
@Override
public String deleteCheckRulesPublicByTab(String model_id, String table_id,String col) {
excelFileModelMapper.deleteCheckRulesPublicByTab(model_id, table_id,col);
return "success";
}
@Override
public String deleteCheckRulesPubShip(String id) {
excelFileModelMapper.deleteCheckRulesPubShip(id);
return "success";
}
}
|
92366580a91ef73dbc4c75e7ec1080136b41f14f | 1,919 | java | Java | test/hotspot/jtreg/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/MethodUniverse.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | test/hotspot/jtreg/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/MethodUniverse.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | test/hotspot/jtreg/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/MethodUniverse.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | 36.903846 | 95 | 0.699844 | 997,657 | /*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.vm.ci.runtime.test;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* Context for method related tests.
*/
public class MethodUniverse extends TypeUniverse {
public static final Map<Method, ResolvedJavaMethod> methods = new HashMap<>();
public static final Map<Constructor<?>, ResolvedJavaMethod> constructors = new HashMap<>();
{
for (Class<?> c : classes) {
for (Method m : c.getDeclaredMethods()) {
ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m);
methods.put(m, method);
}
for (Constructor<?> m : c.getDeclaredConstructors()) {
constructors.put(m, metaAccess.lookupJavaMethod(m));
}
}
}
}
|
92366705f7273b6e1b0e8d1e4a0841b4953f1f6a | 529 | java | Java | jpa-mapper-core/src/main/java/cn/pomit/jpamapper/core/entity/MethodParameters.java | ffch/jpa-mapper | 0ac6eccd0295017767f9edbe3d3a1b045aa67c3d | [
"Apache-2.0"
] | 6 | 2019-07-12T10:52:52.000Z | 2020-12-27T09:42:53.000Z | jpa-mapper-core/src/main/java/cn/pomit/jpamapper/core/entity/MethodParameters.java | feiyangtianyao/jpa-mapper | 0ac6eccd0295017767f9edbe3d3a1b045aa67c3d | [
"Apache-2.0"
] | 2 | 2019-07-24T06:41:13.000Z | 2020-03-26T08:36:57.000Z | jpa-mapper-core/src/main/java/cn/pomit/jpamapper/core/entity/MethodParameters.java | ffch/jpa-mapper | 0ac6eccd0295017767f9edbe3d3a1b045aa67c3d | [
"Apache-2.0"
] | 4 | 2019-03-02T16:08:01.000Z | 2021-02-05T07:36:29.000Z | 19.592593 | 44 | 0.669187 | 997,658 | package cn.pomit.jpamapper.core.entity;
public class MethodParameters {
private String column;
private String property;
private Class<?> type;
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
}
|
92366790cccdbcfad98df36580e96202a479a412 | 786 | java | Java | src/main/java/se/itello/junitparallel/StreamGobbler.java | Itello/junitparallel2 | 9359ec68d69cde66b57c43d844de1d0ce6969c4c | [
"Apache-2.0"
] | null | null | null | src/main/java/se/itello/junitparallel/StreamGobbler.java | Itello/junitparallel2 | 9359ec68d69cde66b57c43d844de1d0ce6969c4c | [
"Apache-2.0"
] | null | null | null | src/main/java/se/itello/junitparallel/StreamGobbler.java | Itello/junitparallel2 | 9359ec68d69cde66b57c43d844de1d0ce6969c4c | [
"Apache-2.0"
] | null | null | null | 24.5625 | 67 | 0.575064 | 997,659 | package se.itello.junitparallel;
import java.io.*;
class StreamGobbler extends Thread {
private final InputStream is;
private final PrintStream output;
private volatile boolean shouldStop = false;
StreamGobbler(InputStream is, PrintStream output) {
this.is = is;
this.output = output;
}
void pleaseStop() {
shouldStop = true;
}
@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while (!shouldStop && (line = br.readLine()) != null) {
output.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} |
9236688c679981b0c2a20de0cf3b8784a45c48e6 | 1,658 | java | Java | mybatis/mybatis-standalone/src/test/java/com/ithawk/demo/spring/v1/JdbcC3p0Test.java | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | mybatis/mybatis-standalone/src/test/java/com/ithawk/demo/spring/v1/JdbcC3p0Test.java | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | mybatis/mybatis-standalone/src/test/java/com/ithawk/demo/spring/v1/JdbcC3p0Test.java | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | 34.541667 | 87 | 0.603739 | 997,660 | package com.ithawk.demo.spring.v1;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcC3p0Test {
@Test
public void testC3p0() throws IOException,PropertyVetoException {
// 硬编码,没有使用到配置文件
ComboPooledDataSource dataSource1=new ComboPooledDataSource();
dataSource1.setDriverClass("com.mysql.jdbc.Driver");
dataSource1.setJdbcUrl("jdbc:mysql://localhost:23306/mybatis?useUnicode=true");
dataSource1.setUser("root");
dataSource1.setPassword("123456");
//使用自定义配置
// ComboPooledDataSource dataSource2 = new ComboPooledDataSource();
//建立连接
try{
Connection conn = dataSource1.getConnection();
String sql = "SELECT bid, name, author_id FROM blog";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while(rs.next()){
Integer bid = rs.getInt("bid");
String name = rs.getString("name");
Integer authorId = rs.getInt("author_id");
System.out.print("bid: " + bid);
System.out.print(", 标题: " + name);
System.out.print(", 作者编号: " + authorId);
System.out.print("\n");
}
rs.close();
pst.close();
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
|
923668c58af43a1236e5eaa2776eb72f090603eb | 2,754 | java | Java | src/main/java/kr/gooroom/gpms/site/service/SiteMngVO.java | gooroom/gooroom-admin | d7d165b4849769dd7aed22e27656da60238aba7c | [
"Apache-2.0"
] | null | null | null | src/main/java/kr/gooroom/gpms/site/service/SiteMngVO.java | gooroom/gooroom-admin | d7d165b4849769dd7aed22e27656da60238aba7c | [
"Apache-2.0"
] | 8 | 2020-01-17T02:43:58.000Z | 2021-12-14T20:51:15.000Z | src/main/java/kr/gooroom/gpms/site/service/SiteMngVO.java | gooroom/gooroom-admin | d7d165b4849769dd7aed22e27656da60238aba7c | [
"Apache-2.0"
] | 1 | 2022-02-25T01:57:02.000Z | 2022-02-25T01:57:02.000Z | 18.993103 | 75 | 0.729484 | 997,661 | /*
* Copyright 2015-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 kr.gooroom.gpms.site.service;
import java.io.Serializable;
import java.util.Date;
/**
* administrator user data bean
*
* @author HNC
*/
@SuppressWarnings("serial")
public class SiteMngVO implements Serializable {
private String siteId;
private String siteNm;
private String comment;
private String status;
private String pollingCycle;
private String serverVersion;
private String rootDeptCd;
private String rootGrpId;
private Date modDate;
private String modUserId;
private Date regDate;
private String regUserId;
public String getSiteId() {
return siteId;
}
public void setSiteId(String siteId) {
this.siteId = siteId;
}
public String getSiteNm() {
return siteNm;
}
public void setSiteNm(String siteNm) {
this.siteNm = siteNm;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPollingCycle() {
return pollingCycle;
}
public void setPollingCycle(String pollingCycle) {
this.pollingCycle = pollingCycle;
}
public String getServerVersion() {
return serverVersion;
}
public void setServerVersion(String serverVersion) {
this.serverVersion = serverVersion;
}
public String getRootDeptCd() {
return rootDeptCd;
}
public void setRootDeptCd(String rootDeptCd) {
this.rootDeptCd = rootDeptCd;
}
public String getRootGrpId() {
return rootGrpId;
}
public void setRootGrpId(String rootGrpId) {
this.rootGrpId = rootGrpId;
}
public Date getModDate() {
return modDate;
}
public void setModDate(Date modDate) {
this.modDate = modDate;
}
public String getModUserId() {
return modUserId;
}
public void setModUserId(String modUserId) {
this.modUserId = modUserId;
}
public Date getRegDate() {
return regDate;
}
public void setRegDate(Date regDate) {
this.regDate = regDate;
}
public String getRegUserId() {
return regUserId;
}
public void setRegUserId(String regUserId) {
this.regUserId = regUserId;
}
}
|
923668e274997174ed9f7989a8fd78268a51fc4e | 1,201 | java | Java | java/desktop/src/com/upseil/maze/desktop/definition/EnumPropertyView.java | Upseil/maze-generator | 554f9a432a44b546f1d215a98a408fa7e8f185cd | [
"MIT"
] | null | null | null | java/desktop/src/com/upseil/maze/desktop/definition/EnumPropertyView.java | Upseil/maze-generator | 554f9a432a44b546f1d215a98a408fa7e8f185cd | [
"MIT"
] | null | null | null | java/desktop/src/com/upseil/maze/desktop/definition/EnumPropertyView.java | Upseil/maze-generator | 554f9a432a44b546f1d215a98a408fa7e8f185cd | [
"MIT"
] | null | null | null | 27.930233 | 96 | 0.68776 | 997,662 | package com.upseil.maze.desktop.definition;
import java.beans.PropertyDescriptor;
import java.util.ResourceBundle;
import com.upseil.maze.desktop.Launcher;
import com.upseil.maze.desktop.util.GenericStringFormatter;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
public class EnumPropertyView extends AbstractPropertyView {
private final ResourceBundle resources;
private final ComboBox<Enum<?>> comboBox;
public EnumPropertyView(PropertyDescriptor property) {
super(property);
resources = Launcher.getResourceLoader().getResourceBundle();
comboBox = new ComboBox<>();
comboBox.setConverter(new GenericStringFormatter<>(t -> resources.getString(t.name())));
for (Object value : property.getPropertyType().getEnumConstants()) {
comboBox.getItems().add((Enum<?>) value);
}
comboBox.setValue(comboBox.getItems().get(0));
}
@Override
public Node getView() {
return comboBox;
}
@Override
public Object getValue() {
return comboBox.getValue();
}
@Override
public void setValue(Object value) {
comboBox.setValue((Enum<?>) value);
}
} |
92366a01324d2166f94214a9f2a325a2adf505f7 | 3,151 | java | Java | src/test/java/ch/rhj/embedded/plexus/PlexiTests.java | rhjoerg/rhj-embedded | 66461f38eb3e449688072b6f637ceb010d9a7f07 | [
"MIT"
] | null | null | null | src/test/java/ch/rhj/embedded/plexus/PlexiTests.java | rhjoerg/rhj-embedded | 66461f38eb3e449688072b6f637ceb010d9a7f07 | [
"MIT"
] | 6 | 2020-06-04T11:53:24.000Z | 2020-06-07T14:55:45.000Z | src/test/java/ch/rhj/embedded/plexus/PlexiTests.java | rhjoerg/rhj-embedded | 66461f38eb3e449688072b6f637ceb010d9a7f07 | [
"MIT"
] | null | null | null | 30.009524 | 86 | 0.76928 | 997,663 | package ch.rhj.embedded.plexus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import javax.inject.Inject;
import org.codehaus.plexus.DefaultContainerConfiguration;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.junit.jupiter.api.Test;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import ch.rhj.embedded.test.Foo;
public class PlexiTests
{
@Inject
private static Foo staticFoo;
@Inject
private Foo instanceFoo;
@Test
public void testNewClassWorld() throws Exception
{
ClassWorld classWorld = Plexi.newClassWorld();
ClassRealm classRealm = classWorld.getClassRealm(Plexi.DEFAULT_REALM_NAME);
Class<?> expected = PlexiTests.class;
Class<?> actual = classRealm.loadClass(PlexiTests.class.getName());
assertEquals(expected, actual);
}
@Test
public void testConfigurationBuilder() throws Exception
{
DefaultContainerConfiguration configuration = Plexi.configurationBuilder().build();
assertTrue(configuration.getAutoWiring());
assertEquals(PlexusConstants.SCANNING_OFF, configuration.getClassPathScanning());
}
@Test
public void testNewConfiguration() throws Exception
{
DefaultContainerConfiguration configuration = Plexi.newConfiguration();
assertTrue(configuration.getAutoWiring());
assertEquals(PlexusConstants.SCANNING_OFF, configuration.getClassPathScanning());
}
@Test
public void testNewContainer() throws Exception
{
DefaultPlexusContainer container = Plexi.newContainer(Plexi.newConfiguration());
Injector injector;
Binding<Foo> binding;
injector = container.addPlexusInjector(List.of());
binding = injector.getExistingBinding(Key.get(Foo.class));
assertNull(binding);
assertThrows(ComponentLookupException.class, () -> container.lookup(Foo.class));
injector = Plexi.index(container, List.of());
binding = injector.getExistingBinding(Key.get(Foo.class));
assertNotNull(binding);
assertNotNull(container.lookup(Foo.class));
}
@Test
public void testRequestStaticInjection() throws Exception
{
DefaultPlexusContainer container = Plexi.newContainer(Plexi.newConfiguration());
assertTrue(staticFoo == null);
Plexi.requestStaticInjection(container, PlexiTests.class);
assertTrue(staticFoo != null);
}
@Test
public void testRequestInjection() throws Exception
{
DefaultPlexusContainer container = Plexi.newContainer(Plexi.newConfiguration());
assertTrue(instanceFoo == null);
Plexi.requestInjection(container, this);
assertTrue(instanceFoo != null);
}
}
|
92366a1f73040140793e8c1a60e9d03aa0542679 | 407 | java | Java | business-center/maps-center/src/main/java/com/open/capacity/entity/GisConfig.java | jecinfo2016/open-capacity-platform-backend | bfcb2cee2e8b47a40555a7ec7749b8e23a66a2ad | [
"Apache-2.0"
] | 1 | 2021-01-30T06:06:43.000Z | 2021-01-30T06:06:43.000Z | business-center/maps-center/src/main/java/com/open/capacity/entity/GisConfig.java | jecinfo2016/open-capacity-platform-backend | bfcb2cee2e8b47a40555a7ec7749b8e23a66a2ad | [
"Apache-2.0"
] | null | null | null | business-center/maps-center/src/main/java/com/open/capacity/entity/GisConfig.java | jecinfo2016/open-capacity-platform-backend | bfcb2cee2e8b47a40555a7ec7749b8e23a66a2ad | [
"Apache-2.0"
] | 1 | 2021-03-13T21:19:24.000Z | 2021-03-13T21:19:24.000Z | 18.5 | 47 | 0.761671 | 997,664 | package com.open.capacity.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Data
@ApiModel("gis_config")
public class GisConfig {
private Integer id;
@ApiModelProperty("appID")
private Integer appId;
@ApiModelProperty("高德地图key")
private Integer AmapKey;
}
|
92366a60f8d1d0e4e307cc231a44d6642664ddfc | 3,327 | java | Java | src/library/management/system/PrintBookInfo.java | DLogarta/library-management-system | 837d466dafc696c5aa25a226acde04f27bd97a17 | [
"MIT"
] | null | null | null | src/library/management/system/PrintBookInfo.java | DLogarta/library-management-system | 837d466dafc696c5aa25a226acde04f27bd97a17 | [
"MIT"
] | null | null | null | src/library/management/system/PrintBookInfo.java | DLogarta/library-management-system | 837d466dafc696c5aa25a226acde04f27bd97a17 | [
"MIT"
] | null | null | null | 32.617647 | 179 | 0.606853 | 997,665 | package library.management.system;
import java.io.*;
import java.sql.*;
import javax.swing.JOptionPane;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class PrintBookInfo {
public void export(){
try {
conn con = new conn();
String sql = "SELECT * FROM book";
PreparedStatement st = con.c.prepareStatement(sql);
ResultSet rs = st.executeQuery();
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Book Information");
writeHeaderLine(sheet);
writeDataLines(rs, wb, sheet);
String outputPath = System.getProperty("user.home")+"\\Documents";
FileOutputStream output = new FileOutputStream(outputPath+"\\BookInformation.xlsx");
wb.write(output);
output.close();
JOptionPane.showMessageDialog(null,"Book Information has been exported to "+outputPath+"\nFilename: BookInformation.xlsx", "Export Success",JOptionPane.PLAIN_MESSAGE);
con.closeConnection();
} catch (Exception e){
System.out.println("Error: ");
e.printStackTrace();
}
}
private void writeHeaderLine(XSSFSheet sheet){
Row headerRow = sheet.createRow(0);
Cell headerCell = headerRow.createCell(0);
headerCell.setCellValue("Book ID");
headerCell = headerRow.createCell(1);
headerCell.setCellValue("Book Name");
headerCell = headerRow.createCell(2);
headerCell.setCellValue("ISBN");
headerCell = headerRow.createCell(3);
headerCell.setCellValue("Publisher");
headerCell = headerRow.createCell(4);
headerCell.setCellValue("Edition");
headerCell = headerRow.createCell(5);
headerCell.setCellValue("Price");
headerCell = headerRow.createCell(6);
headerCell.setCellValue("Pages");
}
private void writeDataLines(ResultSet result, XSSFWorkbook workbook, XSSFSheet sheet) throws SQLException{
int rowCount = 1;
while(result.next()){
int bookID = result.getInt("book_id");
String bookName = result.getString("name");
String bookISBN = result.getString("isbn");
String bookPublisher = result.getString("publisher");
String bookEdition = result.getString("edition");
String bookPrice = result.getString("price");
String bookPages = result.getString("pages");
Row row = sheet.createRow(rowCount++);
int columnCount = 0;
Cell cell = row.createCell(columnCount++);
cell.setCellValue(bookID);
cell = row.createCell(columnCount++);
cell.setCellValue(bookName);
cell = row.createCell(columnCount++);
cell.setCellValue(bookISBN);
cell = row.createCell(columnCount++);
cell.setCellValue(bookPublisher);
cell = row.createCell(columnCount++);
cell.setCellValue(bookEdition);
cell = row.createCell(columnCount++);
cell.setCellValue(bookPrice);
cell = row.createCell(columnCount++);
cell.setCellValue(bookPages);
}
}
}
|
92366ae1a8c597590110a9849fe967e33fd3a67f | 1,456 | java | Java | compiler/src/main/java/procedures/FactorAProcedure.java | emanoel-bruno/Compiler-CP | 20e42fdb586dcd31c3c00db0c05f5e5af2d6cf5c | [
"Apache-2.0"
] | null | null | null | compiler/src/main/java/procedures/FactorAProcedure.java | emanoel-bruno/Compiler-CP | 20e42fdb586dcd31c3c00db0c05f5e5af2d6cf5c | [
"Apache-2.0"
] | null | null | null | compiler/src/main/java/procedures/FactorAProcedure.java | emanoel-bruno/Compiler-CP | 20e42fdb586dcd31c3c00db0c05f5e5af2d6cf5c | [
"Apache-2.0"
] | null | null | null | 31.652174 | 110 | 0.655907 | 997,666 | package procedures;
import java.io.IOException;
import compiler.Token;
import compiler.PanicMode;
import compiler.Tag;
import exceptions.LexicalException;
import exceptions.SyntaxException;
import exceptions.UnexpectedTokenException;
import compiler.Procedure;
import compiler.SyntaxAnalyser;
public class FactorAProcedure extends Procedure {
public FactorAProcedure() {
this.tag = Procedure.FACTORA_PROCEDURE;
}
@Override
public void rule() throws IOException, LexicalException, SyntaxException {
Token t = SyntaxAnalyser.currentToken();
int line = SyntaxAnalyser.currentLine();
switch (t.getTag()) {
case Tag.IDENTIFIER:
case Tag.INTEGER_CONSTANT:
case Tag.FLOAT_CONSTANT:
case Tag.LITERAL:
case Tag.OPEN_PARENTHESIS:
this.invoke(Procedure.FACTOR_PROCEDURE);
break;
case Tag.MINUS:
this.consume(Tag.MINUS);
this.invoke(Procedure.FACTOR_PROCEDURE);
break;
case Tag.NOT:
this.consume(Tag.NOT);
this.invoke(Procedure.FACTOR_PROCEDURE);
break;
default:
PanicMode.nextToken(this, t, new int[] { Tag.IDENTIFIER, Tag.INTEGER_CONSTANT, Tag.FLOAT_CONSTANT,
Tag.LITERAL, Tag.OPEN_PARENTHESIS, Tag.MINUS, Tag.NOT });
SyntaxAnalyser.printError("\n Unexpected Token: " + t.toString(), line);
}
}
} |
92366b20f6bf9bc3523731f0228c029632fde67d | 3,386 | java | Java | rsocket/src/main/java/org/springframework/security/rsocket/core/PayloadSocketAcceptor.java | lenxin/spring-security | 9cc4bd14b66afcb0142c9a0df35738342a5eeaa4 | [
"Apache-2.0"
] | null | null | null | rsocket/src/main/java/org/springframework/security/rsocket/core/PayloadSocketAcceptor.java | lenxin/spring-security | 9cc4bd14b66afcb0142c9a0df35738342a5eeaa4 | [
"Apache-2.0"
] | null | null | null | rsocket/src/main/java/org/springframework/security/rsocket/core/PayloadSocketAcceptor.java | lenxin/spring-security | 9cc4bd14b66afcb0142c9a0df35738342a5eeaa4 | [
"Apache-2.0"
] | null | null | null | 38.477273 | 107 | 0.798287 | 997,667 | package org.springframework.security.rsocket.core;
import java.util.List;
import io.rsocket.ConnectionSetupPayload;
import io.rsocket.Payload;
import io.rsocket.RSocket;
import io.rsocket.SocketAcceptor;
import io.rsocket.metadata.WellKnownMimeType;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.lang.Nullable;
import org.springframework.security.rsocket.api.PayloadExchangeType;
import org.springframework.security.rsocket.api.PayloadInterceptor;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
/**
* @author Rob Winch
* @since 5.2
*/
class PayloadSocketAcceptor implements SocketAcceptor {
private final SocketAcceptor delegate;
private final List<PayloadInterceptor> interceptors;
@Nullable
private MimeType defaultDataMimeType;
private MimeType defaultMetadataMimeType = MimeTypeUtils
.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
PayloadSocketAcceptor(SocketAcceptor delegate, List<PayloadInterceptor> interceptors) {
Assert.notNull(delegate, "delegate cannot be null");
if (interceptors == null) {
throw new IllegalArgumentException("interceptors cannot be null");
}
if (interceptors.isEmpty()) {
throw new IllegalArgumentException("interceptors cannot be empty");
}
this.delegate = delegate;
this.interceptors = interceptors;
}
@Override
public Mono<RSocket> accept(ConnectionSetupPayload setup, RSocket sendingSocket) {
MimeType dataMimeType = parseMimeType(setup.dataMimeType(), this.defaultDataMimeType);
Assert.notNull(dataMimeType, "No `dataMimeType` in ConnectionSetupPayload and no default value");
MimeType metadataMimeType = parseMimeType(setup.metadataMimeType(), this.defaultMetadataMimeType);
Assert.notNull(metadataMimeType, "No `metadataMimeType` in ConnectionSetupPayload and no default value");
// FIXME do we want to make the sendingSocket available in the PayloadExchange
return intercept(setup, dataMimeType, metadataMimeType)
.flatMap(
(ctx) -> this.delegate.accept(setup, sendingSocket)
.map((acceptingSocket) -> new PayloadInterceptorRSocket(acceptingSocket,
this.interceptors, metadataMimeType, dataMimeType, ctx))
.subscriberContext(ctx));
}
private Mono<Context> intercept(Payload payload, MimeType dataMimeType, MimeType metadataMimeType) {
return Mono.defer(() -> {
ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors);
DefaultPayloadExchange exchange = new DefaultPayloadExchange(PayloadExchangeType.SETUP, payload,
metadataMimeType, dataMimeType);
return chain.next(exchange).then(Mono.fromCallable(() -> chain.getContext()))
.defaultIfEmpty(Context.empty());
});
}
private MimeType parseMimeType(String str, MimeType defaultMimeType) {
return StringUtils.hasText(str) ? MimeTypeUtils.parseMimeType(str) : defaultMimeType;
}
void setDefaultDataMimeType(@Nullable MimeType defaultDataMimeType) {
this.defaultDataMimeType = defaultDataMimeType;
}
void setDefaultMetadataMimeType(MimeType defaultMetadataMimeType) {
Assert.notNull(defaultMetadataMimeType, "defaultMetadataMimeType cannot be null");
this.defaultMetadataMimeType = defaultMetadataMimeType;
}
}
|
92366b56e200268bbddcad3c7325934cd35634af | 92 | java | Java | project-structures/clean/entity/src/main/java/lin/louis/clean/entity/OrderStatus.java | l-lin/architecture-cheat-sheet | ab93da38cb83675c1c7fd9d9bedd5e959aaf45c9 | [
"MIT"
] | 12 | 2018-02-28T05:42:34.000Z | 2021-03-08T11:30:15.000Z | project-structures/clean/entity/src/main/java/lin/louis/clean/entity/OrderStatus.java | l-lin/architecture-cheat-sheet | ab93da38cb83675c1c7fd9d9bedd5e959aaf45c9 | [
"MIT"
] | null | null | null | project-structures/clean/entity/src/main/java/lin/louis/clean/entity/OrderStatus.java | l-lin/architecture-cheat-sheet | ab93da38cb83675c1c7fd9d9bedd5e959aaf45c9 | [
"MIT"
] | 2 | 2020-05-11T15:43:41.000Z | 2022-03-01T13:46:32.000Z | 11.5 | 31 | 0.76087 | 997,668 | package lin.louis.clean.entity;
public enum OrderStatus {
PLACED,
APPROVED,
DELIVERED
}
|
92366bd7e19c5f9654f72ebd443c828e3f4def8c | 149 | java | Java | app/src/main/java/com/xiaogang/com/wanandroid_xg/ui/knowledge/KnowledgeArticlePresenter.java | fangxiaogang/WanAndroidxg | 28493604081d07512eca0a4ebee3f226bfb98164 | [
"Apache-2.0"
] | 108 | 2018-10-11T16:04:57.000Z | 2021-03-08T08:19:24.000Z | app/src/main/java/com/xiaogang/com/wanandroid_xg/ui/knowledge/KnowledgeArticlePresenter.java | fangxiaogang/WanAndroidxg | 28493604081d07512eca0a4ebee3f226bfb98164 | [
"Apache-2.0"
] | 7 | 2018-10-17T02:14:58.000Z | 2019-03-23T02:45:34.000Z | app/src/main/java/com/xiaogang/com/wanandroid_xg/ui/knowledge/KnowledgeArticlePresenter.java | fangxiaogang/WanAndroidxg | 28493604081d07512eca0a4ebee3f226bfb98164 | [
"Apache-2.0"
] | 14 | 2018-10-16T17:52:15.000Z | 2020-01-07T07:44:00.000Z | 14.9 | 52 | 0.738255 | 997,669 | package com.xiaogang.com.wanandroid_xg.ui.knowledge;
/**
* author: fangxiaogang
* date: 2018/9/29
*/
public class KnowledgeArticlePresenter {
}
|
92366d011dc423db624c84f93eacf52e292adf01 | 3,958 | java | Java | tests/src/test/java/net/devh/boot/grpc/test/config/OrderedServerInterceptorConfiguration.java | totorean/grpc-spring-boot-starter | b4b7947071b43808cf883050c39552ca30ba8825 | [
"MIT"
] | 2,460 | 2016-12-30T09:21:09.000Z | 2022-03-31T03:20:33.000Z | tests/src/test/java/net/devh/boot/grpc/test/config/OrderedServerInterceptorConfiguration.java | tentativafc/grpc-spring-boot-starter | b101f467f2ed5ecb4a30cb62613568472cc44bce | [
"MIT"
] | 471 | 2017-02-24T15:51:27.000Z | 2022-03-31T18:00:35.000Z | tests/src/test/java/net/devh/boot/grpc/test/config/OrderedServerInterceptorConfiguration.java | tentativafc/grpc-spring-boot-starter | b101f467f2ed5ecb4a30cb62613568472cc44bce | [
"MIT"
] | 705 | 2017-02-02T20:10:17.000Z | 2022-03-24T16:33:58.000Z | 41.25 | 120 | 0.722222 | 997,670 | /*
* Copyright (c) 2016-2021 Michael Zhang <envkt@example.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.devh.boot.grpc.test.config;
import javax.annotation.Priority;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;
@Configuration
public class OrderedServerInterceptorConfiguration {
@GrpcGlobalServerInterceptor
@Priority(30)
public class SecondPriorityAnnotatedInterceptor implements ServerInterceptor {
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
return next.startCall(call, headers);
}
}
@GrpcGlobalServerInterceptor
@Order(20)
public class SecondOrderAnnotatedInterceptor implements ServerInterceptor {
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
return next.startCall(call, headers);
}
}
@GrpcGlobalServerInterceptor
public class FirstOrderedInterfaceInterceptor implements ServerInterceptor, Ordered {
public int getOrder() {
return 40;
}
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
return next.startCall(call, headers);
}
}
@GrpcGlobalServerInterceptor
@Order(10)
public class FirstOrderAnnotatedInterceptor implements ServerInterceptor {
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
return next.startCall(call, headers);
}
}
@GrpcGlobalServerInterceptor
public class SecondOrderedInterfaceInterceptor implements ServerInterceptor, Ordered {
public int getOrder() {
return 50;
}
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
return next.startCall(call, headers);
}
}
@GrpcGlobalServerInterceptor
@Priority(5)
public class FirstPriorityAnnotatedInterceptor implements ServerInterceptor {
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
return next.startCall(call, headers);
}
}
}
|
92366d1653a8b3cf6a1be3df042088bd813fcb87 | 327 | java | Java | src/main/java/com/company/project/core/properties/AddListTest.java | justtankme/springbootapiseed | bfb78d2d4ba61da75f854034209d13d75bed4cdd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/company/project/core/properties/AddListTest.java | justtankme/springbootapiseed | bfb78d2d4ba61da75f854034209d13d75bed4cdd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/company/project/core/properties/AddListTest.java | justtankme/springbootapiseed | bfb78d2d4ba61da75f854034209d13d75bed4cdd | [
"Apache-2.0"
] | null | null | null | 19.235294 | 60 | 0.733945 | 997,671 | package com.company.project.core.properties;
import java.util.List;
import java.util.Map;
public class AddListTest {
private List<Map<String, String>> testmap;
public List<Map<String, String>> getTestmap() {
return testmap;
}
public void setTestmap(List<Map<String, String>> testmap) {
this.testmap = testmap;
}
}
|
92366d57e4efb4cbbcda8322ec52ff46a33c8fdc | 1,159 | java | Java | extensions/services/src/main/java/ca/bc/gov/educ/keycloak/soam/properties/ApplicationProperties.java | bcgov/EDUC-OIDC-SOAM | dc22935c2d4c4f638edd0049117907e0b6e1ae08 | [
"Apache-2.0"
] | 3 | 2019-12-14T06:01:44.000Z | 2020-02-19T18:40:11.000Z | extensions/services/src/main/java/ca/bc/gov/educ/keycloak/soam/properties/ApplicationProperties.java | bcgov/EDUC-OIDC-SOAM | dc22935c2d4c4f638edd0049117907e0b6e1ae08 | [
"Apache-2.0"
] | 3 | 2020-04-17T19:15:54.000Z | 2021-01-04T18:57:34.000Z | extensions/services/src/main/java/ca/bc/gov/educ/keycloak/soam/properties/ApplicationProperties.java | bcgov/EDUC-OIDC-SOAM | dc22935c2d4c4f638edd0049117907e0b6e1ae08 | [
"Apache-2.0"
] | null | null | null | 25.195652 | 89 | 0.761001 | 997,672 | package ca.bc.gov.educ.keycloak.soam.properties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.logging.Logger;
/**
* Class holds all application properties
*
* @author Marco Villeneuve
*
*/
public class ApplicationProperties {
public static final ObjectMapper mapper = new ObjectMapper();
private static Logger logger = Logger.getLogger(ApplicationProperties.class);
private String soamApiURL;
private String tokenURL;
private String clientID;
private String clientSecret;
public ApplicationProperties() {
logger.info("SOAM: Building application properties");
soamApiURL = System.getenv().getOrDefault("SOAMAPIURL", "MissingSoamURL");
tokenURL = System.getenv().getOrDefault("TOKENURL", "MissingSoamTokenURL");
clientID = System.getenv().getOrDefault("CLIENTID", "MissingSoamClientID");
clientSecret = System.getenv().getOrDefault("CLIENTSECRET", "MissingSoamClientSecret");
}
public String getSoamApiURL() {
return soamApiURL;
}
public String getTokenURL() {
return tokenURL;
}
public String getClientID() {
return clientID;
}
public String getClientSecret() {
return clientSecret;
}
}
|
92366ed2e4aa5de4c2fb2299c0115e801988145c | 782 | java | Java | app/src/main/java/com/example/android_architecture/core/CustomMessageQueue.java | yangkun19921001/Customhandler | ad262f3b39f66748fa46054ff6fa1b9595674b27 | [
"Apache-2.0"
] | 2 | 2020-03-13T00:48:37.000Z | 2020-06-28T08:32:27.000Z | app/src/main/java/com/example/android_architecture/core/CustomMessageQueue.java | yangkun19921001/Customhandler | ad262f3b39f66748fa46054ff6fa1b9595674b27 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android_architecture/core/CustomMessageQueue.java | yangkun19921001/Customhandler | ad262f3b39f66748fa46054ff6fa1b9595674b27 | [
"Apache-2.0"
] | 2 | 2020-03-13T00:48:40.000Z | 2020-08-06T02:34:41.000Z | 25.225806 | 79 | 0.627877 | 997,673 | package com.example.android_architecture.core;
import com.example.android_architecture.core.CustomMessage;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class CustomMessageQueue {
//阻塞队列
BlockingQueue<CustomMessage> blockingQueue = new ArrayBlockingQueue<>(50);
public void enqueueMessage(CustomMessage message) {
try {
blockingQueue.put(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//从消息队列中取出消息
public CustomMessage next() {
try {
return blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
|
92366f1fcc995a397db5d8994d97977c7e03284c | 66 | java | Java | src/main/java/com/volmit/fulcrum/custom/ICustom.java | Draww/FulcrumResourceAPI | ef1f6ca14351a6de2a8ac71455829c90b0a9899a | [
"WTFPL"
] | 1 | 2018-04-13T11:16:19.000Z | 2018-04-13T11:16:19.000Z | src/main/java/com/volmit/fulcrum/custom/ICustom.java | Draww/FulcrumResourceAPI | ef1f6ca14351a6de2a8ac71455829c90b0a9899a | [
"WTFPL"
] | 3 | 2018-03-03T16:40:05.000Z | 2018-03-25T09:19:58.000Z | src/main/java/com/volmit/fulcrum/custom/ICustom.java | Draww/FulcrumResourceAPI | ef1f6ca14351a6de2a8ac71455829c90b0a9899a | [
"WTFPL"
] | 2 | 2018-03-25T06:35:57.000Z | 2018-10-17T04:38:46.000Z | 9.428571 | 34 | 0.772727 | 997,674 | package com.volmit.fulcrum.custom;
public interface ICustom
{
}
|
92366f24253fe981155577081402dfb883c13b45 | 2,264 | java | Java | 04.Encapsulation - Exercise/05.FootballTeamGenerator/Player.java | denkaty/Java-OOP | a85db8e49cb62b2a5b8de0c38468d3c8ddab2787 | [
"MIT"
] | null | null | null | 04.Encapsulation - Exercise/05.FootballTeamGenerator/Player.java | denkaty/Java-OOP | a85db8e49cb62b2a5b8de0c38468d3c8ddab2787 | [
"MIT"
] | null | null | null | 04.Encapsulation - Exercise/05.FootballTeamGenerator/Player.java | denkaty/Java-OOP | a85db8e49cb62b2a5b8de0c38468d3c8ddab2787 | [
"MIT"
] | null | null | null | 29.025641 | 99 | 0.603799 | 997,675 | package FootballTeamGenerator_05;
public class Player {
private String name;
private int endurance;
private int sprint;
private int dribble;
private int passing;
private int shooting;
public Player(String name, int endurance, int sprint, int dribble, int passing, int shooting) {
this.setName(name);
this.setEndurance(endurance);
this.setSprint(sprint);
this.setDribble(dribble);
this.setPassing(passing);
this.setShooting(shooting);
}
private void setName(String name) {
if (name.trim().isEmpty()) {
throw new IllegalArgumentException("A name should not be empty.");
}
this.name = name;
}
public String getName() {
return name;
}
private void setEndurance(int endurance) {
if (!checkStatRange(endurance)) {
throw new IllegalArgumentException("Endurance" + " should be between 0 and 100.");
}
this.endurance = endurance;
}
private void setSprint(int sprint) {
if (!checkStatRange(sprint)) {
throw new IllegalArgumentException("Sprint" + " should be between 0 and 100.");
}
this.sprint = sprint;
}
private void setDribble(int dribble) {
if (!checkStatRange(dribble)) {
throw new IllegalArgumentException("Dribble" + " should be between 0 and 100.");
}
this.dribble = dribble;
}
private void setPassing(int passing) {
if (!checkStatRange(passing)) {
throw new IllegalArgumentException("Passing" + " should be between 0 and 100.");
}
this.passing = passing;
}
private void setShooting(int shooting) {
if (!checkStatRange(shooting)) {
throw new IllegalArgumentException("Shooting" + " should be between 0 and 100.");
}
this.shooting = shooting;
}
public double overallSkillLevel() {
return (this.endurance + this.sprint + this.dribble + this.passing + this.shooting) / 5.0;
}
private boolean checkStatRange(int statRange) {
boolean inRange = false;
if (statRange >= 0 && statRange <= 100) {
inRange = true;
}
return inRange;
}
}
|
92366f8365d6cd5c037ddeed07b975c01ca32f74 | 697 | java | Java | src/main/java/com/github/dkellenb/formulaevaluator/term/Term.java | dkellenb/formula-evaluator | 6b5290da07c10227c328367db43d237727a4e188 | [
"Apache-2.0"
] | 11 | 2016-09-07T12:37:27.000Z | 2020-12-02T16:25:44.000Z | src/main/java/com/github/dkellenb/formulaevaluator/term/Term.java | dkellenb/formula-evaluator | 6b5290da07c10227c328367db43d237727a4e188 | [
"Apache-2.0"
] | 7 | 2016-09-16T06:47:26.000Z | 2016-10-25T18:23:30.000Z | src/main/java/com/github/dkellenb/formulaevaluator/term/Term.java | dkellenb/formula-evaluator | 6b5290da07c10227c328367db43d237727a4e188 | [
"Apache-2.0"
] | 1 | 2020-04-04T07:10:23.000Z | 2020-04-04T07:10:23.000Z | 22.483871 | 90 | 0.728838 | 997,676 | package com.github.dkellenb.formulaevaluator.term;
import com.github.dkellenb.formulaevaluator.FormulaEvaluatorConfiguration;
import com.github.dkellenb.formulaevaluator.VariableValueProvider;
/**
* Calculator Term.
*
* @param <T> the result object after the evaluation
*/
public interface Term<T> {
/**
* Evaluates input I and returns output T.
*
* @param input the input
* @param configuration the formula evaluator configuration
*
* @return the evaluated output
*/
T evaluate(VariableValueProvider<T> input, FormulaEvaluatorConfiguration configuration);
/**
* Prints the calculation formula.
*
* @return the formula
*/
String printFormula();
}
|
92366f8e37c2641f0a8061795ace8c26caf01e6c | 6,652 | java | Java | flow-client/src/test-gwt/java/com/vaadin/client/flow/GwtStateTreeTest.java | rudiejd/flow | e54cd09e97552e3ba098eb5dfb7825cf3fec0108 | [
"Apache-2.0"
] | 402 | 2017-10-02T09:00:34.000Z | 2022-03-30T06:09:40.000Z | flow-client/src/test-gwt/java/com/vaadin/client/flow/GwtStateTreeTest.java | rudiejd/flow | e54cd09e97552e3ba098eb5dfb7825cf3fec0108 | [
"Apache-2.0"
] | 9,144 | 2017-10-02T07:12:23.000Z | 2022-03-31T19:16:56.000Z | flow-client/src/test-gwt/java/com/vaadin/client/flow/GwtStateTreeTest.java | flyzoner/flow | 3f00a72127a2191eb9b9d884370ca6c1cb2f80bf | [
"Apache-2.0"
] | 167 | 2017-10-11T13:07:29.000Z | 2022-03-22T09:02:42.000Z | 33.094527 | 86 | 0.653337 | 997,677 | /*
* Copyright 2000-2021 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.flow;
import com.google.gwt.core.client.JavaScriptObject;
import com.vaadin.client.ClientEngineTestBase;
import com.vaadin.client.InitialPropertiesHandler;
import com.vaadin.client.Registry;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.communication.ServerConnector;
import com.vaadin.client.flow.binding.ServerEventObject;
import com.vaadin.client.flow.collection.JsArray;
import com.vaadin.client.flow.reactive.Reactive;
import com.vaadin.flow.internal.nodefeature.NodeFeatures;
import elemental.client.Browser;
import elemental.dom.Element;
import elemental.html.DivElement;
import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
/**
* @author Vaadin Ltd
* @since 1.0
*
*/
public class GwtStateTreeTest extends ClientEngineTestBase {
private StateTree tree;
private Registry registry;
private static class TestServerConnector extends ServerConnector {
private StateNode node;
private String methodName;
private JsonArray args;
private TestServerConnector(Registry registry) {
super(registry);
}
@Override
public void sendTemplateEventMessage(StateNode node, String methodName,
JsonArray array, int promiseId) {
this.node = node;
this.methodName = methodName;
args = array;
}
}
@Override
protected void gwtSetUp() throws Exception {
super.gwtSetUp();
registry = new Registry() {
{
set(ServerConnector.class, new TestServerConnector(this));
set(InitialPropertiesHandler.class,
new InitialPropertiesHandler(this));
}
};
tree = new StateTree(registry);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testSendTemplateEventToServer_delegateToServerConnector() {
StateNode node = new StateNode(0, tree);
tree.registerNode(node);
JsArray array = getArgArray();
tree.sendTemplateEventToServer(node, "foo", array, -1);
JsonObject object = Json.createObject();
object.put("key", "value");
array.set(array.length(), WidgetUtil.crazyJsCast(object));
array.set(array.length(), getNativeArray());
TestServerConnector serverConnector = (TestServerConnector) registry
.getServerConnector();
assertEquals(node, serverConnector.node);
assertEquals("foo", serverConnector.methodName);
JsonArray args = serverConnector.args;
assertEquals(true, args.getBoolean(0));
assertEquals("bar", args.getString(1));
assertEquals(46.2, args.getNumber(2));
assertEquals(object, args.getObject(3));
assertEquals("item", ((JsonArray) args.getObject(4)).getString(0));
}
public void testDeferredTemplateMessage_isIgnored() {
StateNode node = new StateNode(0, tree);
tree.registerNode(node);
Reactive.addPostFlushListener(() -> {
tree.sendTemplateEventToServer(node, "click", null, -1);
TestServerConnector serverConnector = (TestServerConnector) registry
.getServerConnector();
assertNull(
"Found node even though message should not have been sent.",
serverConnector.node);
assertNull(
"Found methodName even though message should not have been sent.",
serverConnector.methodName);
assertNull(
"Found arguments even though message should not have been sent.",
serverConnector.args);
});
tree.unregisterNode(node);
Reactive.flush();
}
public void testPrepareForResync_unregistersDescendantsAndClearsRootChildren() {
// given
StateNode root = tree.getRootNode();
StateNode child = new StateNode(2, tree);
child.setParent(root);
tree.registerNode(child);
root.getList(NodeFeatures.VIRTUAL_CHILDREN).add(0,child);
StateNode grandChild = new StateNode(3, tree);
grandChild.setParent(child);
tree.registerNode(grandChild);
child.getList(NodeFeatures.ELEMENT_CHILDREN).add(0, grandChild);
// when
tree.prepareForResync();
// then
assertTrue(!root.isUnregistered());
assertEquals(0, root.getList(NodeFeatures.VIRTUAL_CHILDREN).length());
assertTrue(child.isUnregistered());
assertEquals(0, child.getList(NodeFeatures.ELEMENT_CHILDREN).length());
assertTrue(grandChild.isUnregistered());
}
public void testPrepareForResync_rejectsPendingPromise() {
// given
StateNode root = tree.getRootNode();
StateNode child = new StateNode(2, tree);
child.setParent(root);
tree.registerNode(child);
root.getList(NodeFeatures.VIRTUAL_CHILDREN).add(0,child);
final DivElement element = Browser.getDocument().createDivElement();
child.setDomNode(element);
ServerEventObject.get(element);
createMockPromise(element);
// when
tree.prepareForResync();
// then
assertFalse(getMockPromiseResult(element));
}
private native JsArray<JavaScriptObject> getArgArray()
/*-{
return [ true, "bar", 46.2];
}-*/;
private native JsArray<JavaScriptObject> getNativeArray()
/*-{
return [ "item" ];
}-*/;
private static native boolean createMockPromise(Element element)
/*-{
var eventObject = element.$server["}p"];
eventObject.promiseResult = null;
eventObject.promises[0] = [function() {
eventObject.promiseResult = true;
},function() {
eventObject.promiseResult = false;
}];
}-*/;
private static native boolean getMockPromiseResult(Element element)
/*-{
return element.$server["}p"].promiseResult;
}-*/;
}
|
9236700355ce11e32620e1d7d5d0a8e4a2abe69c | 1,900 | java | Java | android-31/src/android/annotation/RequiresFeature.java | Pixelated-Project/aosp-android-jar | 72ae25d4fc6414e071fc1f52dd78080b84d524f8 | [
"MIT"
] | 93 | 2020-10-11T04:37:16.000Z | 2022-03-24T13:18:49.000Z | android-31/src/android/annotation/RequiresFeature.java | huangjxdev/aosp-android-jar | e22b61576b05ff7483180cb4d245921d66c26ee4 | [
"MIT"
] | 3 | 2020-10-11T04:27:44.000Z | 2022-01-19T01:31:52.000Z | android-31/src/android/annotation/RequiresFeature.java | huangjxdev/aosp-android-jar | e22b61576b05ff7483180cb4d245921d66c26ee4 | [
"MIT"
] | 10 | 2020-11-23T02:41:58.000Z | 2022-03-06T00:56:52.000Z | 36.538462 | 98 | 0.743684 | 997,678 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.annotation;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Denotes that the annotated element requires one or more device features. This
* is used to auto-generate documentation.
*
* @hide
*/
@Retention(SOURCE)
@Target({TYPE,FIELD,METHOD,CONSTRUCTOR})
public @interface RequiresFeature {
/**
* The name of the device feature that is required.
*/
String value();
/**
* Defines the name of the method that should be called to check whether the feature is
* available, using the same signature format as javadoc. The feature checking method can have
* multiple parameters, but the feature name parameter must be of type String and must also be
* the first String-type parameter.
* <p>
* By default, the enforcement is
* {@link android.content.pm.PackageManager#hasSystemFeature(String)}.
*/
String enforcement() default("android.content.pm.PackageManager#hasSystemFeature");
}
|
9236716bc41840bc73089932fd8541f2cdf90e0a | 880 | java | Java | python/experiments/projects/seedstack-seed/real_error_dataset/1/276/SecurityScope.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | python/experiments/projects/seedstack-seed/real_error_dataset/1/276/SecurityScope.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | python/experiments/projects/seedstack-seed/real_error_dataset/1/276/SecurityScope.java | andre15silva/styler | f3d752d2785c2ab76bacbe5793bd8306ac7961a1 | [
"MIT"
] | null | null | null | 30.344828 | 110 | 0.732955 | 997,679 | /*
* Copyright © 2013-2020, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.security.spi;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation that gives an explicit name to a Scope class. If a scope class doesn't have this annotation, its
* simple name will be used instead.
*/
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface SecurityScope {
/**
* @return the name of the scope.
*/
String value();
}
|
923671c21123a41cd491e618687b61800e8457af | 5,220 | java | Java | src/younger/vrp/topological/Graph.java | younger-1/topological-value-in-graph | ec541a4634db5eebca962d046c227c5354a34c67 | [
"MIT"
] | null | null | null | src/younger/vrp/topological/Graph.java | younger-1/topological-value-in-graph | ec541a4634db5eebca962d046c227c5354a34c67 | [
"MIT"
] | null | null | null | src/younger/vrp/topological/Graph.java | younger-1/topological-value-in-graph | ec541a4634db5eebca962d046c227c5354a34c67 | [
"MIT"
] | null | null | null | 31.071429 | 118 | 0.586973 | 997,680 | package younger.vrp.topological;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Graph {
private List<Route> routes;
/**
* @implNote
* this.removeNodes is treated as a Stack
*/
private Deque<Node> removeNodes;
private Deque<Route> removeRoutes;
private double topoX;
private double topoY;
private Graph() {
this.routes = new ArrayList<>();
this.removeNodes = new LinkedList<>();
this.removeRoutes = new LinkedList<>();
}
public static Graph ofRandom(int route_num, int node_num) {
Random r = new Random(-1);
Graph g = new Graph();
for (int i = 0; i < route_num; i++) {
g.addRoute(Route.of());
}
for (int i = 0; i < node_num; i++) {
g.getRouteWithIndex(r.nextInt(g.getSize())).addNode(Node.of(r.nextInt(node_num), r.nextInt(node_num)));
}
return g;
}
/**
*
* @return
* The number of routes in this graph
*/
public int getSize() {
return this.routes.size();
}
public List<Route> getAllRoutes() {
return this.routes;
}
public Route getRouteWithIndex(int index) {
return this.routes.get(index);
}
public Route getRoute(int id) {
return this.routes.get(IntStream.range(0, this.getSize()).filter(i -> this.routes.get(i).getId() == id)
.findFirst().getAsInt());
}
public void removeRoute(int id) {
this.removeRoutes.add(this.routes.remove(IntStream.range(0, this.getSize())
.filter(i -> this.routes.get(i).getId() == id).findFirst().getAsInt()));
}
public void addRoute(Route r) {
this.routes.add(r);
}
@Override
public String toString() {
String result = "Graph: {";
for (Route r : this.routes) {
result += "\n\t" + r;
}
return result + "\n}";
}
public Node getNode(int id) {
return this.routes.stream().map(r -> r.getNodeWithId(id)).filter(Optional::isPresent).findFirst().get().get();
}
/**
* Remove nodes with node_ids from route and push them to <code>this.removeNodes</code>
* @apiNote
* usually be used before <code>joinAfter(int... node_ids)</code> and <code>joinBefore(int... node_ids)</code>
* @implNote
* Push nodes to <code>this.removeNodes</code> with opposite order of node_ids
*/
public Graph pickNode(int... node_ids) {
// for (int _k = node_ids.length - 1; _k >= 0; _k--) {
// int k = _k;
// Node rm = this.routes.stream().map(r -> r.removeNodeWithId(node_ids[k]))
// .reduce((a, b) -> a.isPresent() ? a : b).get().get();
// this.removeNodes.push(rm);
// }
Stream.iterate(node_ids.length - 1, i -> i >= 0, i -> i - 1).map(i -> this.routes.stream()
.map(r -> r.removeNodeWithId(node_ids[i])).filter(Optional::isPresent).findFirst().get())
.forEach(option_node -> this.removeNodes.push(option_node.get()));
return this;
}
/**
* @deprecated
*/
public Graph addBefore(int route_id, int node_id, Node node) {
this.routes.stream().filter(r -> r.getId() == route_id).forEach(r -> r.addBefore(node_id, node));
return this;
}
public Graph addNodeBefore(int node_id, Node node) {
this.routes.stream().forEach(r -> r.addBefore(node_id, node));
return this;
}
/**
* Pop nodes from <code>this.removeNodes</code> and add them before node_ids
* @implNote
* usually be used after <code>pickNode(int... node_ids)</code>
*/
public Graph joinBefore(int... node_ids) {
Arrays.stream(node_ids).forEach(id -> this.addNodeBefore(id, this.removeNodes.pop()));
return this;
}
/**
* @deprecated
*/
public Graph addAfter(int route_id, int node_id, Node node) {
this.routes.stream().filter(r -> r.getId() == route_id).forEach(r -> r.addAfter(node_id, node));
return this;
}
public Graph addNodeAfter(int node_id, Node node) {
this.routes.stream().forEach(r -> r.addAfter(node_id, node));
return this;
}
/**
* Pop nodes from <code>this.removeNodes</code> and add them after node_ids
* @implNote
* usually be used after <code>pickNode(int... node_ids)</code>
*/
public Graph joinAfter(int... node_ids) {
Arrays.stream(node_ids).forEach(id -> this.addNodeAfter(id, this.removeNodes.pop()));
return this;
}
public Graph moveBefore(int rm_node_id, int node_id) {
return this.pickNode(rm_node_id).addNodeBefore(node_id, this.removeNodes.pop());
}
public Graph moveAfter(int rm_node_id, int node_id) {
return this.pickNode(rm_node_id).addNodeAfter(node_id, this.removeNodes.pop());
}
public double topoX() {
topoX = this.routes.stream().mapToDouble(r -> r.getLenX() * r.getTopoX()).sum();
return topoX;
}
public double topoY() {
topoY = this.routes.stream().mapToDouble(r -> r.getLenY() * r.getTopoY()).sum();
return topoY;
}
}
|
92367213192b28418996ab8c88702f3aa93826d8 | 656 | java | Java | src/Main.java | jgbackes/ballz | 243d692f6012e09586fc194601ca3aaff29ff476 | [
"BSD-2-Clause"
] | null | null | null | src/Main.java | jgbackes/ballz | 243d692f6012e09586fc194601ca3aaff29ff476 | [
"BSD-2-Clause"
] | null | null | null | src/Main.java | jgbackes/ballz | 243d692f6012e09586fc194601ca3aaff29ff476 | [
"BSD-2-Clause"
] | null | null | null | 36.444444 | 85 | 0.594512 | 997,681 | import javax.swing.JFrame;
public class Main {
// Entry main program
public static void main(String[] args) {
// Run UI in the Event Dispatcher Thread (EDT), instead of Main thread
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("A World of Balls");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new BallWorld(1024, 768)); // BallWorld is a JPanel
frame.pack(); // Preferred size of BallWorld
frame.setVisible(true); // Show it
}
});
}
}
|
923672a721d4fac8429d4d69a3ba14ffe03ae47c | 294 | java | Java | JSqlServerBulkInsert/src/main/java/de/bytefish/jsqlserverbulkinsert/functional/Action2.java | vslee/JSqlServerBulkInsert | 1d1a7f15535d2369c152d5ef03d5971aab21ac61 | [
"MIT"
] | 1 | 2019-06-27T20:24:14.000Z | 2019-06-27T20:24:14.000Z | JSqlServerBulkInsert/src/main/java/de/bytefish/jsqlserverbulkinsert/functional/Action2.java | vslee/JSqlServerBulkInsert | 1d1a7f15535d2369c152d5ef03d5971aab21ac61 | [
"MIT"
] | null | null | null | JSqlServerBulkInsert/src/main/java/de/bytefish/jsqlserverbulkinsert/functional/Action2.java | vslee/JSqlServerBulkInsert | 1d1a7f15535d2369c152d5ef03d5971aab21ac61 | [
"MIT"
] | null | null | null | 29.4 | 101 | 0.765306 | 997,682 | // Copyright (c) Philipp Wagner. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package de.bytefish.jsqlserverbulkinsert.functional;
@FunctionalInterface
public interface Action2<S, T> {
void invoke(S s, T t);
}
|
923672b3a806a153fb0ce3eb478918be9425b7ff | 178 | java | Java | server/src/test/java/org/schoellerfamily/pathfinderhelper/controller/test/package-info.java | vitamort/Pathfinder-Helper | 99875535ac1eb5b13529703c828469050fc28ad2 | [
"Apache-2.0"
] | null | null | null | server/src/test/java/org/schoellerfamily/pathfinderhelper/controller/test/package-info.java | vitamort/Pathfinder-Helper | 99875535ac1eb5b13529703c828469050fc28ad2 | [
"Apache-2.0"
] | 36 | 2017-11-28T03:14:41.000Z | 2018-01-13T19:00:12.000Z | server/src/test/java/org/schoellerfamily/pathfinderhelper/controller/test/package-info.java | vitamort/Pathfinder-Helper | 99875535ac1eb5b13529703c828469050fc28ad2 | [
"Apache-2.0"
] | null | null | null | 25.428571 | 67 | 0.786517 | 997,683 | /**
* Copyright 2017 Jonathan Schoeller
*
* This package contains tests for Pathfinder Helper's controllers.
*/
package org.schoellerfamily.pathfinderhelper.controller.test;
|
923673643d4ab9b4d6cda4b015ea2ed2805eade1 | 1,645 | java | Java | permazen-kv-simple/src/main/java/io/permazen/kv/simple/Put.java | permazen/jsimpledb | 9ee1500b87ee9cab450434888f73a78b67244f35 | [
"Apache-2.0"
] | 202 | 2017-09-05T04:58:39.000Z | 2022-03-31T06:16:23.000Z | permazen-kv-simple/src/main/java/io/permazen/kv/simple/Put.java | permazen/jsimpledb | 9ee1500b87ee9cab450434888f73a78b67244f35 | [
"Apache-2.0"
] | 18 | 2017-09-26T20:15:29.000Z | 2022-01-21T23:55:22.000Z | permazen-kv-simple/src/main/java/io/permazen/kv/simple/Put.java | Joong/permazen | ad404a211c2887c6785992da296dee4271d9ae5b | [
"Apache-2.0"
] | 21 | 2017-09-26T20:12:20.000Z | 2022-02-16T11:55:17.000Z | 23.169014 | 113 | 0.627964 | 997,684 |
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package io.permazen.kv.simple;
import com.google.common.base.Preconditions;
import io.permazen.kv.KVStore;
import io.permazen.kv.util.KeyWatchTracker;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Map;
/**
* Represents the addition or changing of a key/value pair in a {@link SimpleKVTransaction}.
*
* <p>
* Note the definition of {@linkplain #equals equality} does <b>not</b> include the {@linkplain #getValue value}.
*/
class Put extends Mutation {
private final byte[] value;
Put(byte[] key, byte[] value) {
super(key);
Preconditions.checkArgument(value != null, "null value");
this.value = value.clone();
}
public byte[] getKey() {
return this.getMin();
}
public byte[] getValue() {
return this.value.clone();
}
public Map.Entry<byte[], byte[]> toMapEntry() {
return new AbstractMap.SimpleEntry<>(this.getKey(), this.getValue());
}
@Override
public void apply(KVStore kv) {
kv.put(this.getKey(), this.getValue());
}
@Override
public boolean trigger(KeyWatchTracker keyWatchTracker) {
return keyWatchTracker.trigger(this.getKey());
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!super.equals(obj))
return false;
final Put that = (Put)obj;
return Arrays.equals(this.value, that.value);
}
@Override
public int hashCode() {
return super.hashCode() ^ Arrays.hashCode(this.value);
}
}
|
923674d865acd7c361170ceaef29d55d677e85b3 | 7,289 | java | Java | recipesAPI/src/main/java/com/shiksha/recipesAPI/model/Recipe.java | PrashanthKR7/RecipeWorld | d1e05da0d747175551c22fd736ae95d6ff41e1e6 | [
"MIT"
] | null | null | null | recipesAPI/src/main/java/com/shiksha/recipesAPI/model/Recipe.java | PrashanthKR7/RecipeWorld | d1e05da0d747175551c22fd736ae95d6ff41e1e6 | [
"MIT"
] | null | null | null | recipesAPI/src/main/java/com/shiksha/recipesAPI/model/Recipe.java | PrashanthKR7/RecipeWorld | d1e05da0d747175551c22fd736ae95d6ff41e1e6 | [
"MIT"
] | null | null | null | 29.039841 | 117 | 0.717382 | 997,685 | package com.shiksha.recipesAPI.model;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Type;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.shiksha.recipesAPI.model.dto.Ingredient;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@NoArgsConstructor @ToString
@Entity
@Table(name = "recipe")
@EntityListeners(AuditingEntityListener.class)
@NamedStoredProcedureQueries({ @NamedStoredProcedureQuery(name = "getRecipeMeta", procedureName = "recipe_meta") })
public class Recipe extends BaseModel implements Serializable {
private static final long serialVersionUID = -1661496498457237508L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", unique = true, nullable = false)
private Long recipeId;
@Column(name = "title", length = 100, nullable = false)
private String title;
@Column(name = "thumbnail", nullable = false)
private String thumbnail;
@Column(name = "author", nullable = false)
private String author;
@Column(name = "description", length = 500, nullable = false)
@Size(max = 500)
private String description;
@Column(name = "created_on", nullable = false, updatable = false)
@CreatedDate
private Date createdOn;
@Column(name = "updated_on", nullable = false)
@LastModifiedDate
private Date lastUpdatedOn;
@Column(name = "prep_Time")
private int preparingTime;
@ManyToOne(optional = false)
@JoinColumn(name = "difficulty", referencedColumnName = "id", nullable = false)
private Difficulty difficulty;
@ManyToOne(optional = false)
@JoinColumn(name = "cuisine", referencedColumnName = "id", nullable = false)
private Cuisine cuisine;
@ManyToOne(optional = false)
@JoinColumn(name = "mealtype", referencedColumnName = "id", nullable = false)
private MealType mealtype;
@ManyToOne(optional = false)
@JoinColumn(name = "diettype", referencedColumnName = "id", nullable = false)
private DietType diettype;
@ManyToOne(optional = false)
@JoinColumn(name = "cookingstyle", referencedColumnName = "id", nullable = false)
private CookingStyle cookingstyle;
@Column(name = "link")
private String link;
@Type(type = "json")
@Column(columnDefinition = "json", name = "tags")
private String[] tags;
@Column(name = "veg", nullable = false)
private Boolean isVeg;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, mappedBy = "recipe")
private Set<Instruction> instructions = new HashSet<>();
@Column(name = "cooking_time", nullable = false)
private int cookingTime;
@Type(type = "json")
@Column(columnDefinition = "json", name = "ingredients", nullable = false)
private List<Ingredient> ingredients;
public Recipe(String title, String thumbnail, String author, @Size(max = 500) String description, int preparingTime,
Difficulty difficulty, Cuisine cuisine, MealType mealtype, DietType diettype, CookingStyle cookingstyle,
String link, String[] tags, Boolean isVeg, Set<Instruction> instructions, int cookingTime,
List<Ingredient> ingredients) {
this.title = title;
this.thumbnail = thumbnail;
this.author = author;
this.description = description;
this.preparingTime = preparingTime;
this.difficulty = difficulty;
this.cuisine = cuisine;
this.mealtype = mealtype;
this.diettype = diettype;
this.cookingstyle = cookingstyle;
this.link = link;
this.tags = tags;
this.isVeg = isVeg;
this.instructions = instructions;
this.cookingTime = cookingTime;
this.ingredients = ingredients;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Recipe other = (Recipe) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (cookingTime != other.cookingTime)
return false;
if (cookingstyle == null) {
if (other.cookingstyle != null)
return false;
} else if (!cookingstyle.equals(other.cookingstyle))
return false;
if (createdOn == null) {
if (other.createdOn != null)
return false;
} else if (!createdOn.equals(other.createdOn))
return false;
if (cuisine == null) {
if (other.cuisine != null)
return false;
} else if (!cuisine.equals(other.cuisine))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (diettype == null) {
if (other.diettype != null)
return false;
} else if (!diettype.equals(other.diettype))
return false;
if (difficulty == null) {
if (other.difficulty != null)
return false;
} else if (!difficulty.equals(other.difficulty))
return false;
if (ingredients == null) {
if (other.ingredients != null)
return false;
} else if (!ingredients.equals(other.ingredients))
return false;
if (instructions == null) {
if (other.instructions != null)
return false;
} else if (!instructions.equals(other.instructions))
return false;
if (isVeg == null) {
if (other.isVeg != null)
return false;
} else if (!isVeg.equals(other.isVeg))
return false;
if (lastUpdatedOn == null) {
if (other.lastUpdatedOn != null)
return false;
} else if (!lastUpdatedOn.equals(other.lastUpdatedOn))
return false;
if (link == null) {
if (other.link != null)
return false;
} else if (!link.equals(other.link))
return false;
if (mealtype == null) {
if (other.mealtype != null)
return false;
} else if (!mealtype.equals(other.mealtype))
return false;
if (preparingTime != other.preparingTime)
return false;
if (recipeId == null) {
if (other.recipeId != null)
return false;
} else if (!recipeId.equals(other.recipeId))
return false;
if (tags == null) {
if (other.tags != null)
return false;
} else if (!tags.equals(other.tags))
return false;
if (thumbnail == null) {
if (other.thumbnail != null)
return false;
} else if (!thumbnail.equals(other.thumbnail))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((recipeId == null) ? 0 : recipeId.hashCode());
return result;
}
}
|
923675243548d61f5fc07eccc55ec6dd9163c7d1 | 1,556 | java | Java | src/org/actorsguildframework/annotations/Message.java | timjansen/actorsguild | 8e0e15d40ff2961bfe28da6afc08d612885d0b11 | [
"Apache-2.0"
] | 1 | 2015-08-18T08:44:27.000Z | 2015-08-18T08:44:27.000Z | src/org/actorsguildframework/annotations/Message.java | timjansen/actorsguild | 8e0e15d40ff2961bfe28da6afc08d612885d0b11 | [
"Apache-2.0"
] | null | null | null | src/org/actorsguildframework/annotations/Message.java | timjansen/actorsguild | 8e0e15d40ff2961bfe28da6afc08d612885d0b11 | [
"Apache-2.0"
] | null | null | null | 37.047619 | 97 | 0.719794 | 997,686 | /*
* Copyright 2008 Tim Jansen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.actorsguildframework.annotations;
import java.lang.annotation.*;
/**
* Message marks a method of an Actor as message receiver.
* <p>
* There are several prerequisites for such a method, beside the annotation:
* <ol>
* <li>All arguments must be immutable (Java primitives, String, Enum or classes with
* implementing Immutable) or Serializable (much slower, will be serialized and
* deserialized)</li>
* <li>The method must return the type AsyncResult<T> (with T being immutable as well)</li>
* <li>The method must not be abstract, static or final</li>
* <li>The method must be public</li>
* </ol>
*
* A Message implementation can throw any exception. Please note that non-RuntimeExceptions will
* be wrapped and transported to the caller as WrappedException.
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Message {
}
|
9236769da593608e228fb75f00212610b06fc339 | 3,797 | java | Java | jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtilsTest.java | aHenryJard/jetty.project | 5bd4cee7c8070895908699393a7f9dc48457d5fb | [
"Apache-2.0"
] | null | null | null | jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtilsTest.java | aHenryJard/jetty.project | 5bd4cee7c8070895908699393a7f9dc48457d5fb | [
"Apache-2.0"
] | null | null | null | jetty-websocket/websocket-javax-common/src/test/java/org/eclipse/jetty/websocket/javax/common/util/ReflectUtilsTest.java | aHenryJard/jetty.project | 5bd4cee7c8070895908699393a7f9dc48457d5fb | [
"Apache-2.0"
] | null | null | null | 27.316547 | 135 | 0.662628 | 997,687 | //
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.websocket.javax.common.util;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ReflectUtilsTest
{
public interface Fruit<T>
{
}
public interface Color<T>
{
}
public interface Food<T> extends Fruit<T>
{
}
public abstract static class Apple<T extends Object> implements Fruit<T>, Color<String>
{
}
public abstract static class Cherry<A extends Object, B extends Number> implements Fruit<A>, Color<B>
{
}
public abstract static class Banana implements Fruit<String>, Color<String>
{
}
public static class Washington<Z extends Number, X extends Object> extends Cherry<X, Z>
{
}
public static class Rainier extends Washington<Float, Short>
{
}
public static class Pizza implements Food<Integer>
{
}
public static class Cavendish extends Banana
{
}
public static class GrannySmith extends Apple<Long>
{
}
public static class Pear implements Fruit<String>, Color<Double>
{
}
public static class Kiwi implements Fruit<Character>
{
}
@Test
public void testFindGeneric_PearFruit()
{
assertFindGenericClass(Pear.class, Fruit.class, String.class);
}
@Test
public void testFindGeneric_PizzaFruit()
{
assertFindGenericClass(Pizza.class, Fruit.class, Integer.class);
}
@Test
public void testFindGeneric_KiwiFruit()
{
assertFindGenericClass(Kiwi.class, Fruit.class, Character.class);
}
@Test
public void testFindGeneric_PearColor()
{
assertFindGenericClass(Pear.class, Color.class, Double.class);
}
@Test
public void testFindGeneric_GrannySmithFruit()
{
assertFindGenericClass(GrannySmith.class, Fruit.class, Long.class);
}
@Test
public void testFindGeneric_CavendishFruit()
{
assertFindGenericClass(Cavendish.class, Fruit.class, String.class);
}
@Test
public void testFindGeneric_RainierFruit()
{
assertFindGenericClass(Rainier.class, Fruit.class, Short.class);
}
@Test
public void testFindGeneric_WashingtonFruit()
{
// Washington does not have a concrete implementation
// of the Fruit interface, this should return null
Class<?> impl = ReflectUtils.findGenericClassFor(Washington.class, Fruit.class);
assertThat("Washington -> Fruit implementation", impl, nullValue());
}
private void assertFindGenericClass(Class<?> baseClass, Class<?> ifaceClass, Class<?> expectedClass)
{
Class<?> foundClass = ReflectUtils.findGenericClassFor(baseClass, ifaceClass);
String msg = String.format("Expecting %s<%s> found on %s", ifaceClass.getName(), expectedClass.getName(), baseClass.getName());
assertEquals(expectedClass, foundClass, msg);
}
}
|
923678c5bb49a02ae20c7ad81cd53bc947381fd6 | 514 | java | Java | customer-microservice/src/main/java/com/oi/hermes/customer/dao/CustomerRepository.java | open-insights/micro-service-sample-implementation | 760f1c34ca6ed98e150838cbb0ee1417235d9a47 | [
"MIT"
] | null | null | null | customer-microservice/src/main/java/com/oi/hermes/customer/dao/CustomerRepository.java | open-insights/micro-service-sample-implementation | 760f1c34ca6ed98e150838cbb0ee1417235d9a47 | [
"MIT"
] | null | null | null | customer-microservice/src/main/java/com/oi/hermes/customer/dao/CustomerRepository.java | open-insights/micro-service-sample-implementation | 760f1c34ca6ed98e150838cbb0ee1417235d9a47 | [
"MIT"
] | null | null | null | 28.555556 | 76 | 0.826848 | 997,688 | package com.oi.hermes.customer.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.oi.hermes.customer.entity.Customer;
@RepositoryRestResource
public interface CustomerRepository extends
JpaRepository<Customer, Long> {
List<Customer> findByName(@Param("name") String name);
Customer findAllByCustomerId(Long customerId);
} |
9236795a04851feb880a49fcc92442c99321d2cb | 8,111 | java | Java | AndroidARSample/app/src/main/java/com/example/bhaskar/android_ar_sample/AR/ARActivity.java | bhaskar-majumder/Android-AR-Sample | b7fcc77977f8a8d998912db470f7400cf0141719 | [
"Apache-2.0"
] | null | null | null | AndroidARSample/app/src/main/java/com/example/bhaskar/android_ar_sample/AR/ARActivity.java | bhaskar-majumder/Android-AR-Sample | b7fcc77977f8a8d998912db470f7400cf0141719 | [
"Apache-2.0"
] | null | null | null | AndroidARSample/app/src/main/java/com/example/bhaskar/android_ar_sample/AR/ARActivity.java | bhaskar-majumder/Android-AR-Sample | b7fcc77977f8a8d998912db470f7400cf0141719 | [
"Apache-2.0"
] | null | null | null | 41.594872 | 147 | 0.630132 | 997,689 | package com.example.bhaskar.android_ar_sample.AR;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.bhaskar.android_ar_sample.Logger;
import com.example.bhaskar.android_ar_sample.R;
import com.example.bhaskar.android_ar_sample.preview_model.view.ModelActivity;
import com.google.ar.core.Anchor;
import com.google.ar.core.HitResult;
import com.google.ar.core.Plane;
import com.google.ar.sceneform.AnchorNode;
import com.google.ar.sceneform.HitTestResult;
import com.google.ar.sceneform.Node;
import com.google.ar.sceneform.math.Quaternion;
import com.google.ar.sceneform.math.Vector3;
import com.google.ar.sceneform.rendering.ModelRenderable;
import com.google.ar.sceneform.ux.ArFragment;
import com.google.ar.sceneform.ux.RotationController;
import com.google.ar.sceneform.ux.TransformableNode;
import org.andresoviedo.util.android.ContentUtils;
import static java.lang.Thread.sleep;
public class ARActivity extends AppCompatActivity {
private static final String TAG = ARActivity.class.getSimpleName();
private static final double MIN_OPENGL_VERSION = 3.0;
private static final float ROTATION_ANGLE = 5;
private ArFragment arFragment;
private ModelRenderable renderable;
private TransformableNodeEx transformableNode;
private float angle = 0;
private Node.OnTouchListener onTransformableNodeTouchListener = new Node.OnTouchListener() {
@Override
public boolean onTouch(HitTestResult hitTestResult, MotionEvent motionEvent) {
String pressureValue = " - Pressure = " + String.valueOf(motionEvent.getPressure());
Logger.getInstance().log(motionEvent.toString() + pressureValue);
TransformableNodeEx node = (TransformableNodeEx)hitTestResult.getNode();
if(node != null) {
transformableNode = node;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (!checkIsSupportedDeviceOrFinish(this)) {
return;
}
setContentView(R.layout.ar_activity_ux);
arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);
Intent intent = getIntent();
int resourceId = intent.getExtras().getInt("RESOURCE_ID");
ModelRenderable.builder()
.setSource(this, resourceId)
.build()
.thenAccept(renderable -> this.renderable = renderable)
.exceptionally(
throwable -> {
Toast toast =
Toast.makeText(this, "Unable to load renderable", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return null;
});
arFragment.setOnTapArPlaneListener(
(HitResult hitResult, Plane plane, MotionEvent motionEvent) -> {
if (renderable == null) {
return;
}
Anchor anchor = hitResult.createAnchor();
AnchorNode anchorNode = new AnchorNode(anchor);
anchorNode.setParent(arFragment.getArSceneView().getScene());
TransformableNodeEx node = new TransformableNodeEx(arFragment.getTransformationSystem());
//node.setLocalRotation(Quaternion.axisAngle(new Vector3(0, 0, 1f), 180));
node.setParent(anchorNode);
node.setRenderable(renderable);
node.select();
node.setOnTouchListener(onTransformableNodeTouchListener);
transformableNode = node;
configureLeftRightDeleteImageButtons();
});
}
private void configureLeftRightDeleteImageButtons(){
ImageButton leftButton = findViewById(R.id.button_moveLeft);
leftButton.setVisibility(View.VISIBLE);
leftButton.setImageResource(R.drawable.left_arrow);
leftButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(transformableNode != null) {
transformableNode.rotateHorizontally(ROTATION_ANGLE * -1);
Logger.getInstance().log("Left rotation - Current angle = " + Float.toString(transformableNode.getHorizontalRotationAngle()));
}
}
});
ImageButton rightButton = findViewById(R.id.button_moveRight);
rightButton.setVisibility(View.VISIBLE);
rightButton.setImageResource(R.drawable.right_arrow);
rightButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(transformableNode != null) {
transformableNode.rotateHorizontally(ROTATION_ANGLE);
Logger.getInstance().log("Right rotation - Current angle = " + Float.toString(transformableNode.getHorizontalRotationAngle()));
}
}
});
ImageButton deleteButton = findViewById(R.id.button_delete);
deleteButton.setVisibility(View.VISIBLE);
deleteButton.setImageResource(R.drawable.delete_node);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(transformableNode != null) {
transformableNode.getParent().removeChild(transformableNode);
transformableNode = null;
}
}
});
// ImageButton infoButton = findViewById(R.id.button_info);
// infoButton.setVisibility(View.VISIBLE);
// infoButton.setImageResource(R.drawable.info);
// infoButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// if(transformableNode != null) {
// Uri uri;
// ContentUtils.provideAssets(ARActivity.this);
// uri = Uri.parse("assets://" + getPackageName() + transformableNode.getObjectFilePath());
// launchModelRendererActivity(uri);
// }
// }
// });
}
private void launchModelRendererActivity(Uri uri) {
Intent intent = new Intent(getApplicationContext(), ModelActivity.class);
intent.putExtra("uri", uri.toString());
intent.putExtra("immersiveMode", "true");
startActivity(intent);
}
private static boolean checkIsSupportedDeviceOrFinish(final Activity activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Log.e(TAG, "App requires Android N or later");
Toast.makeText(activity, "App requires Android N or later", Toast.LENGTH_LONG).show();
activity.finish();
return false;
}
String openGlVersionString =
((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE))
.getDeviceConfigurationInfo()
.getGlEsVersion();
if (Double.parseDouble(openGlVersionString) < MIN_OPENGL_VERSION) {
Log.e(TAG, "App requires OpenGL ES 3.0 later");
Toast.makeText(activity, "App requires OpenGL ES 3.0 or later", Toast.LENGTH_LONG)
.show();
activity.finish();
return false;
}
return true;
}
}
|
92367962011ffcbb98270f0d24e83f8f1ed14bbd | 5,729 | java | Java | adminfly/commons/src/main/java/org/papaja/adminfly/commons/dao/repository/AbstractRepository.java | papajaOrg/adminflyModular | 8634e3ec159493fc7bec0bac475c03bf68ea518b | [
"Apache-2.0"
] | null | null | null | adminfly/commons/src/main/java/org/papaja/adminfly/commons/dao/repository/AbstractRepository.java | papajaOrg/adminflyModular | 8634e3ec159493fc7bec0bac475c03bf68ea518b | [
"Apache-2.0"
] | 3 | 2021-01-21T00:28:51.000Z | 2021-12-09T21:38:28.000Z | adminfly/commons/src/main/java/org/papaja/adminfly/commons/dao/repository/AbstractRepository.java | org-papaja/papaja-adminfly | 8634e3ec159493fc7bec0bac475c03bf68ea518b | [
"Apache-2.0"
] | 1 | 2022-03-06T08:42:20.000Z | 2022-03-06T08:42:20.000Z | 28.934343 | 110 | 0.654914 | 997,690 | package org.papaja.adminfly.commons.dao.repository;
import org.hibernate.MultiIdentifierLoadAccess;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.papaja.adminfly.commons.dao.entity.api.Entity;
import org.papaja.function.TriConsumer;
import org.papaja.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static java.lang.String.format;
import static java.util.Arrays.asList;
@SuppressWarnings({"all"})
abstract public class AbstractRepository<E extends Entity> {
@Autowired
protected SessionFactory factory;
public void persist(E entity) {
session().persist(entity);
}
protected Session session() {
return factory.getCurrentSession();
}
public void save(E entity) {
session().save(entity);
}
public void merge(E entity) {
session().merge(entity);
}
public void saveOrUpdate(E entity) {
session().saveOrUpdate(entity);
}
public void flush() {
session().flush();
}
public void remove(E entity) {
session().delete(entity);
}
public void remove(Integer id) {
remove(get(id));
}
public <T extends Serializable> E get(T id) {
return session().get(getReflection(), id);
}
public void refresh(E entity) {
session().refresh(entity);
}
public CriteriaBuilder criteriaBuilder() {
return session().getCriteriaBuilder();
}
public List<E> getList(CriteriaQuery<E> criteria) {
return createQuery(criteria).getResultList();
}
public List<E> getList(String column, Object value) {
return getList(criteriaQuery(column, value));
}
public List<E> getList() {
return createQuery().getResultList();
}
public E uniqueResult(CriteriaQuery<E> criteria) {
return createQuery(criteria).uniqueResult();
}
public E uniqueResult() {
return createQuery().uniqueResult();
}
public <T extends Serializable> List<E> getList(T... ids) {
return getList(asList(ids));
}
public <T extends Serializable> List<E> getList(List<T> ids) {
return getMultiAccessor(getReflection()).multiLoad(cleanIds(ids));
}
public MultiIdentifierLoadAccess getMultiAccessor(Class<E> reflection) {
return session().byMultipleIds(reflection);
}
public Query<E> createQuery() {
return session().createQuery(format("from %s", getReflection().getSimpleName()));
}
public Query<E> createQuery(CriteriaQuery<E> criteria) {
return session().createQuery(criteria);
}
public Query<E> createQuery(TriConsumer<CriteriaBuilder, CriteriaQuery<E>, Root<E>> consumer) {
return createQuery(criteriaQuery(consumer));
}
public CriteriaQuery<E> criteriaQuery(String column, Object value) {
return criteriaQuery((builder, query, root) -> {
query.where(builder.equal(root.get(column), value));
});
}
public CriteriaQuery<E> criteriaQuery(TriConsumer<CriteriaBuilder, CriteriaQuery<E>, Root<E>> consumer) {
CriteriaBuilder builder = criteriaBuilder();
CriteriaQuery<E> query = builder.createQuery(getReflection());
Root<E> root = query.from(getReflection());
query.select(root);
consumer.accept(builder, query, root);
return query;
}
public E getOne(String column, String value) {
return uniqueResult(criteriaQuery(column, value));
}
public List<E> getList(String column, String value) {
return getList(criteriaQuery(column, value));
}
public E getOne(TriConsumer<CriteriaBuilder, CriteriaQuery<E>, Root<E>> consumer) {
return uniqueResult(criteriaQuery(consumer));
}
public List<E> getList(TriConsumer<CriteriaBuilder, CriteriaQuery<E>, Root<E>> consumer) {
return getList(criteriaQuery(consumer));
}
public QueryConsumer<E> getConsumer(List<Pair<String, ?>> pairs) {
return (builder, query, root) -> {
List<Predicate> predicates = new ArrayList<>();
for (Pair<String, ?> pair : pairs) {
predicates.add(builder.equal(root.get(pair.getA()), pair.getB()));
}
query.where(builder.and(predicates.toArray(new Predicate[] {})));
};
}
public CriteriaQuery<E> getQuery(List<Pair<String, ?>> pairs) {
return criteriaQuery(getConsumer(pairs));
}
public CriteriaQuery<E> getQuery(Pair<String, ?>... pairs) {
return getQuery(asList(pairs));
}
public <T extends Serializable> List<T> cleanIds(List<T> ids) {
return cleanIds(ids, Objects::isNull);
}
public <T extends Serializable> List<T> cleanIds(List<T> ids, java.util.function.Predicate<T> predicate) {
ids.removeIf(predicate);
return ids;
}
abstract public Class<E> getReflection();
@FunctionalInterface
public interface QueryConsumer<E> extends TriConsumer<CriteriaBuilder, CriteriaQuery<E>, Root<E>> {
default QueryConsumer<E> before(QueryConsumer<E> consumer) {
return (a, b, c) -> { consumer.accept(a, b, c); accept(a, b, c); };
}
default QueryConsumer<E> after(QueryConsumer<E> consumer) {
return (a, b, c) -> { accept(a, b, c); consumer.accept(a, b, c); };
}
}
}
|
923679713bfb63d2620dc13fd18c5bca4af412d9 | 2,371 | java | Java | appengine-java8/tasks/snippets/src/main/java/com/example/task/CreateQueue.java | sirinartk/java-docs-samples | c9aab34adf449040fc0968251caff81bd55c0702 | [
"Apache-2.0"
] | 1 | 2019-11-14T17:35:49.000Z | 2019-11-14T17:35:49.000Z | appengine-java8/tasks/snippets/src/main/java/com/example/task/CreateQueue.java | sirinartk/java-docs-samples | c9aab34adf449040fc0968251caff81bd55c0702 | [
"Apache-2.0"
] | 2 | 2021-03-10T23:29:41.000Z | 2021-06-23T20:57:37.000Z | appengine-java8/tasks/snippets/src/main/java/com/example/task/CreateQueue.java | sirinartk/java-docs-samples | c9aab34adf449040fc0968251caff81bd55c0702 | [
"Apache-2.0"
] | 1 | 2020-06-12T09:27:40.000Z | 2020-06-12T09:27:40.000Z | 37.634921 | 91 | 0.691691 | 997,691 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.task;
// [START taskqueues_using_yaml]
import com.google.cloud.tasks.v2.AppEngineRouting;
import com.google.cloud.tasks.v2.CloudTasksClient;
import com.google.cloud.tasks.v2.LocationName;
import com.google.cloud.tasks.v2.Queue;
import com.google.cloud.tasks.v2.QueueName;
import com.google.cloud.tasks.v2.RateLimits;
public class CreateQueue {
public static void createQueue(
String projectId, String locationId, String queueBlueName, String queueRedName)
throws Exception {
try (CloudTasksClient client = CloudTasksClient.create()) {
// TODO(developer): Uncomment these lines and replace with your values.
// String projectId = "your-project-id";
// String locationId = "us-central1";
// String queueBlueName = "queue-blue";
// String queueRedName = "queue-red";
LocationName parent = LocationName.of(projectId, locationId);
Queue queueBlue =
Queue.newBuilder()
.setName(QueueName.of(projectId, locationId, queueBlueName).toString())
.setRateLimits(RateLimits.newBuilder().setMaxDispatchesPerSecond(5.0))
.setAppEngineRoutingOverride(
AppEngineRouting.newBuilder().setVersion("v2").setService("task-module"))
.build();
Queue queueRed =
Queue.newBuilder()
.setName(QueueName.of(projectId, locationId, queueRedName).toString())
.setRateLimits(RateLimits.newBuilder().setMaxDispatchesPerSecond(1.0))
.build();
Queue[] queues = new Queue[] {queueBlue, queueRed};
for (Queue queue : queues) {
Queue response = client.createQueue(parent, queue);
System.out.println(response);
}
}
}
}
// [END taskqueues_using_yaml]
|
923679a14bc79d58184157e59c17c69eb644afe5 | 5,068 | java | Java | runtime/src/main/java/org/capnproto/BuilderArena.java | paxel/capnproto-java | fe453a59c40700799d97aa3257428a4ac532ae30 | [
"MIT"
] | null | null | null | runtime/src/main/java/org/capnproto/BuilderArena.java | paxel/capnproto-java | fe453a59c40700799d97aa3257428a4ac532ae30 | [
"MIT"
] | null | null | null | runtime/src/main/java/org/capnproto/BuilderArena.java | paxel/capnproto-java | fe453a59c40700799d97aa3257428a4ac532ae30 | [
"MIT"
] | null | null | null | 36.460432 | 128 | 0.687253 | 997,692 | // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package org.capnproto;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
public final class BuilderArena implements AllocatingArena {
public enum AllocationStrategy {
FIXED_SIZE,
GROW_HEURISTICALLY
}
public static final int SUGGESTED_FIRST_SEGMENT_WORDS = 1_024;
public static final AllocationStrategy SUGGESTED_ALLOCATION_STRATEGY
= AllocationStrategy.GROW_HEURISTICALLY;
public final ArrayList<GenericSegmentBuilder> segments;
private final Allocator allocator;
/**
* Constructs a BuilderArena with a default Allocator, that acts according
* to the {@link AllocationStrategy}.
*
* @param firstSegmentSizeWords The size of the first segment. (allocated on
* demand)
* @param allocationStrategy The allocation strategy.
*/
public BuilderArena(int firstSegmentSizeWords, AllocationStrategy allocationStrategy) {
this.segments = new ArrayList<>();
allocator = new DefaultAllocator(allocationStrategy);
((DefaultAllocator) allocator).setNextAllocationSizeBytes(firstSegmentSizeWords * Constants.BYTES_PER_WORD);
}
/**
* Constructs a BuilderArena with an Allocator.
*
* @param allocator is used to allocate memory for each segment.
*/
public BuilderArena(Allocator allocator) {
this.segments = new ArrayList<>();
this.allocator = allocator;
}
/**
* Constructs a BuilderArena with an immediately allocated first segment of
* given size. The Allocator is not used for the first segment.
*
* @param allocator The allocator for other segments.
* @param firstSegment The first segment.
*/
public BuilderArena(Allocator allocator, DataView firstSegment) {
this.segments = new ArrayList<>();
SegmentBuilder newSegment = new SegmentBuilder(firstSegment, this);
newSegment.buffer.order(ByteOrder.LITTLE_ENDIAN);
newSegment.id = 0;
this.segments.add(newSegment);
this.allocator = allocator;
}
@Override
public List<GenericSegmentBuilder> getSegments() {
return segments;
}
@Override
public final GenericSegmentBuilder tryGetSegment(int id) {
return this.segments.get(id);
}
@Override
public final void checkReadLimit(int numBytes) {
}
public static class AllocateResult {
public final GenericSegmentBuilder segment;
// offset to the beginning the of allocated memory
public final int offset;
public AllocateResult(GenericSegmentBuilder segment, int offset) {
this.segment = segment;
this.offset = offset;
}
}
@Override
public AllocateResult allocate(int amount) {
int len = this.segments.size();
// we allocate the first segment in the constructor.
if (len > 0) {
int result = this.segments.get(len - 1).allocate(amount);
if (result != SegmentBuilder.FAILED_ALLOCATION) {
return new AllocateResult(this.segments.get(len - 1), result);
}
}
SegmentBuilder newSegment = new SegmentBuilder(this.allocator.allocateSegment(amount * Constants.BYTES_PER_WORD), this);
newSegment.getBuffer().order(ByteOrder.LITTLE_ENDIAN);
newSegment.setId(len);
this.segments.add(newSegment);
return new AllocateResult(newSegment, newSegment.allocate(amount));
}
@Override
public final DataView[] getSegmentsForOutput() {
DataView[] result = new DataView[this.segments.size()];
for (int ii = 0; ii < this.segments.size(); ++ii) {
GenericSegmentBuilder segment = segments.get(ii);
result[ii] = segment.getSegmentForOutput();
}
return result;
}
}
|
923679b663252d965cd91742ce21b1585fec2471 | 1,712 | java | Java | src/main/java/dev/jacomet/gradle/plugins/logging/LoggingModuleIdentifiers.java | jlstrater/logging-capabilities | 3ad233b1579417dbc3676de80423493bfa7d2d70 | [
"Apache-2.0"
] | 27 | 2019-12-17T20:26:24.000Z | 2022-03-23T00:11:28.000Z | src/main/java/dev/jacomet/gradle/plugins/logging/LoggingModuleIdentifiers.java | jlstrater/logging-capabilities | 3ad233b1579417dbc3676de80423493bfa7d2d70 | [
"Apache-2.0"
] | 16 | 2020-01-10T08:33:05.000Z | 2022-03-09T20:04:37.000Z | src/main/java/dev/jacomet/gradle/plugins/logging/LoggingModuleIdentifiers.java | jlstrater/logging-capabilities | 3ad233b1579417dbc3676de80423493bfa7d2d70 | [
"Apache-2.0"
] | 4 | 2019-12-17T16:32:05.000Z | 2021-11-27T18:15:16.000Z | 37.217391 | 88 | 0.64778 | 997,693 | package dev.jacomet.gradle.plugins.logging;
import org.gradle.api.artifacts.Dependency;
public enum LoggingModuleIdentifiers {
LOG4J_SLF4J_IMPL("org.apache.logging.log4j", "log4j-slf4j-impl", "2.0"),
LOG4J_TO_SLF4J("org.apache.logging.log4j", "log4j-to-slf4j", "2.0"),
SLF4J_SIMPLE("org.slf4j", "slf4j-simple", "1.0"),
LOGBACK_CLASSIC("ch.qos.logback", "logback-classic", "1.0.0"),
SLF4J_LOG4J12("org.slf4j", "slf4j-log4j12", "1.0"),
SLF4J_JCL("org.slf4j", "slf4j-jcl", "1.0"),
SLF4J_JDK14("org.slf4j", "slf4j-jdk14", "1.0"),
LOG4J_OVER_SLF4J("org.slf4j", "log4j-over-slf4j", "1.4.2"),
LOG4J12API("org.apache.logging.log4j", "log4j-1.2-api", "2.0"),
LOG4J("log4j", "log4j", "1.1.3"),
JUL_TO_SLF4J("org.slf4j", "jul-to-slf4j", "1.5.10"),
LOG4J_JUL("org.apache.logging.log4j", "log4j-jul", "2.1"),
COMMONS_LOGGING("commons-logging", "commons-logging", "1.0"),
JCL_OVER_SLF4J("org.slf4j", "jcl-over-slf4j", "1.5.10"),
LOG4J_JCL("org.apache.logging.log4j", "log4j-jcl", "2.0");
public final String moduleId;
public final String group;
public final String name;
private final String firstVersion;
LoggingModuleIdentifiers(String group, String name, String firstVersion) {
this.group = group;
this.name = name;
this.firstVersion = firstVersion;
this.moduleId = group + ":" + name;
}
public boolean matches(Dependency dependency) {
return dependency.getGroup().equals(group) && dependency.getName().equals(name);
}
public String asFirstVersion() {
return moduleId + ":" + firstVersion;
}
public String asVersionZero() {
return moduleId + ":0";
}
}
|
923679dfcc4ba747b2318ae22b94f2c322782594 | 1,096 | java | Java | framework/frontend/src/main/java/org/koenighotze/jee7hotel/framework/frontend/CorsFilter.java | koenighotze/Hotel-Reservation-Tool | 7d217d738bdca0d8ace45149190e8c9ff73b6d9c | [
"Apache-2.0"
] | 6 | 2017-04-11T08:49:30.000Z | 2020-06-10T08:59:39.000Z | framework/frontend/src/main/java/org/koenighotze/jee7hotel/framework/frontend/CorsFilter.java | koenighotze/Hotel-Reservation-Tool | 7d217d738bdca0d8ace45149190e8c9ff73b6d9c | [
"Apache-2.0"
] | 29 | 2015-08-28T20:51:06.000Z | 2016-02-07T10:13:23.000Z | framework/frontend/src/main/java/org/koenighotze/jee7hotel/framework/frontend/CorsFilter.java | koenighotze/Hotel-Reservation-Tool | 7d217d738bdca0d8ace45149190e8c9ff73b6d9c | [
"Apache-2.0"
] | 2 | 2017-05-07T19:13:58.000Z | 2020-05-19T18:42:20.000Z | 34.25 | 127 | 0.713504 | 997,694 | package org.koenighotze.jee7hotel.framework.frontend;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author dschmitz
*/
@WebFilter(filterName = "CorsFilter",
urlPatterns = {"/*"})
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*"); // obviously not a good idea
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(request, res);
}
@Override
public void destroy() {
}
}
|
923679f05bc8bdfbacba4749cd856af13f768c77 | 4,292 | java | Java | giraph-block-app/src/main/java/org/apache/giraph/block_app/migration/MigrationFullBlockFactory.java | shantanusharma/giraph | 8ba2fea912ead1b8e3a81629250bdd684d36d23c | [
"ECL-2.0",
"Apache-2.0"
] | 411 | 2015-01-07T02:56:29.000Z | 2022-02-19T13:49:58.000Z | giraph-block-app/src/main/java/org/apache/giraph/block_app/migration/MigrationFullBlockFactory.java | shantanusharma/giraph | 8ba2fea912ead1b8e3a81629250bdd684d36d23c | [
"ECL-2.0",
"Apache-2.0"
] | 42 | 2016-11-28T22:27:01.000Z | 2021-05-14T15:42:21.000Z | giraph-block-app/src/main/java/org/apache/giraph/block_app/migration/MigrationFullBlockFactory.java | shantanusharma/giraph | 8ba2fea912ead1b8e3a81629250bdd684d36d23c | [
"ECL-2.0",
"Apache-2.0"
] | 234 | 2015-01-04T08:22:07.000Z | 2022-03-07T07:16:03.000Z | 37.649123 | 107 | 0.7048 | 997,695 | /*
* 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.giraph.block_app.migration;
import java.util.Iterator;
import org.apache.giraph.block_app.framework.AbstractBlockFactory;
import org.apache.giraph.block_app.framework.block.Block;
import org.apache.giraph.block_app.framework.block.PieceCount;
import org.apache.giraph.block_app.framework.block.SequenceBlock;
import org.apache.giraph.block_app.framework.piece.AbstractPiece;
import org.apache.giraph.block_app.framework.piece.Piece;
import org.apache.giraph.block_app.migration.MigrationAbstractComputation.MigrationFullAbstractComputation;
import org.apache.giraph.block_app.migration.MigrationMasterCompute.MigrationFullMasterCompute;
import org.apache.giraph.combiner.MessageCombiner;
import org.apache.giraph.conf.GiraphConfiguration;
import org.apache.giraph.function.Consumer;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterators;
/**
* BlockFactory to extend when using drop-in migration
*/
public abstract class MigrationFullBlockFactory
extends AbstractBlockFactory<MigrationSuperstepStage> {
@Override
public MigrationSuperstepStage createExecutionStage(
GiraphConfiguration conf) {
return new MigrationSuperstepStageImpl();
}
@Override
protected Class<? extends MigrationWorkerContext> getWorkerContextValueClass(
GiraphConfiguration conf) {
return MigrationWorkerContext.class;
}
@SuppressWarnings("rawtypes")
public <I extends WritableComparable, V extends Writable, E extends Writable,
MR extends Writable, MS extends Writable>
Block createMigrationAppBlock(
Class<? extends MigrationFullAbstractComputation<I, V, E, MR, MS>>
computationClass,
MigrationFullMasterCompute masterCompute,
Class<MS> messageClass,
Class<? extends MessageCombiner<? super I, MS>> messageCombinerClass,
GiraphConfiguration conf) {
final MigrationPiece<I, V, E, MR, MS> piece =
MigrationPiece.createFirstFullMigrationPiece(
computationClass, masterCompute, messageClass,
messageCombinerClass);
piece.sanityTypeChecks(conf, null);
return new SequenceBlock(
new Piece<WritableComparable, Writable, Writable,
Writable, MigrationSuperstepStage>() {
@Override
public MigrationSuperstepStage nextExecutionStage(
MigrationSuperstepStage executionStage) {
return executionStage.changedMigrationSuperstep(0);
}
},
new Block() {
private MigrationPiece curPiece = piece;
@Override
public Iterator<AbstractPiece> iterator() {
return Iterators.concat(
Iterators.singletonIterator(curPiece),
new AbstractIterator<AbstractPiece>() {
@Override
protected AbstractPiece computeNext() {
curPiece = curPiece.getNextPiece();
if (curPiece == null) {
endOfData();
}
return curPiece;
}
});
}
@Override
public void forAllPossiblePieces(Consumer<AbstractPiece> consumer) {
consumer.apply(curPiece);
}
@Override
public PieceCount getPieceCount() {
return curPiece.getPieceCount();
}
}
);
}
}
|
923679f4eea831d1dbc0f2f5b954cd2bf741b3ca | 1,447 | java | Java | projects/auth-system/src/main/java/me/abdera7mane/authsystem/control/ExceptionDialog.java | shellc0d3/H4ckT0b3rF3st-2k20 | cb5db6b5b22d28aeff441d4cf2cbb881fd6ed274 | [
"MIT"
] | 27 | 2020-10-04T14:11:54.000Z | 2021-05-14T03:51:43.000Z | projects/auth-system/src/main/java/me/abdera7mane/authsystem/control/ExceptionDialog.java | shellc0d3/H4ckT0b3rF3st-2k20 | cb5db6b5b22d28aeff441d4cf2cbb881fd6ed274 | [
"MIT"
] | 56 | 2020-10-06T06:38:54.000Z | 2020-11-25T10:22:40.000Z | projects/auth-system/src/main/java/me/abdera7mane/authsystem/control/ExceptionDialog.java | shellc0d3/H4ckT0b3rF3st-2k20 | cb5db6b5b22d28aeff441d4cf2cbb881fd6ed274 | [
"MIT"
] | 63 | 2020-10-04T12:46:09.000Z | 2021-01-10T16:35:53.000Z | 32.155556 | 76 | 0.712509 | 997,696 | package me.abdera7mane.authsystem.control;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionDialog extends Alert {
public ExceptionDialog(String contentText, Throwable throwable) {
super(AlertType.ERROR);
this.setTitle("Exception");
this.setHeaderText("An exception occured when running the program");
this.setContentText(contentText);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
throwable.printStackTrace(printWriter);
String exceptionText = stringWriter.toString();
Label label = new Label("Stacktrace:");
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
this.getDialogPane().setExpandableContent(expContent);
}
}
|
92367a173ccc998dd98dd36ff8ccec9070afccd0 | 16,403 | java | Java | vscrawler-core/src/main/java/com/virjar/vscrawler/core/selector/string/function/awk/util/AwkSettings.java | virjar/vscrawler | 58fbf61375c90650af6e677190a2dfbd2639295b | [
"Apache-2.0"
] | 44 | 2017-06-12T09:00:26.000Z | 2022-02-17T08:48:52.000Z | vscrawler-core/src/main/java/com/virjar/vscrawler/core/selector/string/function/awk/util/AwkSettings.java | virjar/vscrawler | 58fbf61375c90650af6e677190a2dfbd2639295b | [
"Apache-2.0"
] | 1 | 2018-11-28T08:56:48.000Z | 2018-11-30T08:13:41.000Z | vscrawler-core/src/main/java/com/virjar/vscrawler/core/selector/string/function/awk/util/AwkSettings.java | virjar/vscrawler | 58fbf61375c90650af6e677190a2dfbd2639295b | [
"Apache-2.0"
] | 11 | 2017-06-16T12:42:07.000Z | 2020-01-09T06:34:22.000Z | 27.661046 | 117 | 0.710297 | 997,697 | package com.virjar.vscrawler.core.selector.string.function.awk.util;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple container for the parameters of a single AWK invocation.
* These values have defaults.
* These defaults may be changed through command line arguments,
* or when invoking Jawk programmatically, from within Java code.
*/
public class AwkSettings {
/**
* Where input is read from.
* By default, this is {@link System#in}.
*/
private InputStream input = System.in;
/**
* Contains variable assignments which are applied prior to
* executing the script (-v assignments).
* The values may be of type <code>Integer</code>,
* <code>Double</code> or <code>String</code>.
*/
private Map<String, Object> variables = new HashMap<String, Object>();
/**
* Contains name=value or filename entries.
* Order is important, which is why name=value and filenames
* are listed in the same List container.
*/
private List<String> nameValueOrFileNames = new ArrayList<String>();
/**
* Script sources meta info.
* This will usually be either one String container,
* made up of the script given on the command line directly,
* with the first non-"-" parameter,
* or one or multiple script file names (if provided with -f switches).
*/
private List<ScriptSource> scriptSources = new ArrayList<ScriptSource>();
/**
* Whether to interpret or compile the script.
* Initial value is set to <code>false</code> (interpret).
*/
private boolean compile = false;
/**
* Whether to compile and execute the script.
* Initial value is set to <code>false</code> (interpret).
*/
private boolean compileRun = false;
/**
* Initial Field Separator (FS) value.
* <code>null</code> means the default FS value.
*/
private String fieldSeparator = null;
/**
* Whether to dump the syntax tree;
* <code>false</code> by default.
*/
private boolean dumpSyntaxTree = false;
/**
* Whether to dump the intermediate code;
* <code>false</code> by default.
*/
private boolean dumpIntermediateCode = false;
/**
* Whether to enable additional functions (_sleep/_dump);
* <code>false</code> by default.
*/
private boolean additionalFunctions = false;
/**
* Whether to enable additional type functions (_INTEGER/_DOUBLE/_STRING);
* <code>false</code> by default.
*/
private boolean additionalTypeFunctions = false;
/**
* Whether to maintain array keys in sorted order;
* <code>false</code> by default.
*/
private boolean useSortedArrayKeys = false;
/**
* Whether to trap <code>IllegalFormatExceptions</code>
* for <code>[s]printf</code>;
* <code>true</code> by default.
*/
private boolean catchIllegalFormatExceptions = true;
/**
* Whether user extensions are enabled;
* <code>false</code> by default.
*/
private boolean userExtensions = false;
/**
* Whether Jawk consumes stdin or ARGV file input;
* <code>true</code> by default.
*/
private boolean useStdIn = false;
/**
* Write to intermediate file;
* <code>false</code> by default.
*/
private boolean writeIntermediateFile = false;
/**
* Output filename;
* <code>null</code> by default,
* which means the appropriate default file-name will get used.
*/
private String outputFilename = null;
/**
* Compiled destination directory (if provided);
* <code>"."</code> by default.
*/
private String destinationDirectory = ".";
/**
* Provide a human readable representation of the parameters values.
*/
public String toDescriptionString() {
StringBuilder desc = new StringBuilder();
final char newLine = '\n';
desc.append("variables = ")
.append(getVariables()).append(newLine);
desc.append("nameValueOrFileNames = ")
.append(getNameValueOrFileNames()).append(newLine);
desc.append("scriptSources = ")
.append(scriptSources).append(newLine);
desc.append("(should) compile = ")
.append(isCompile()).append(newLine);
desc.append("(should) compile & run = ")
.append(isCompileRun()).append(newLine);
desc.append("fieldSeparator = ")
.append(getFieldSeparator()).append(newLine);
desc.append("dumpSyntaxTree = ")
.append(isDumpSyntaxTree()).append(newLine);
desc.append("dumpIntermediateCode = ")
.append(isDumpIntermediateCode()).append(newLine);
desc.append("additionalFunctions = ")
.append(isAdditionalFunctions()).append(newLine);
desc.append("additionalTypeFunctions = ")
.append(isAdditionalTypeFunctions()).append(newLine);
desc.append("useSortedArrayKeys = ")
.append(isUseSortedArrayKeys()).append(newLine);
desc.append("catchIllegalFormatExceptions = ")
.append(isCatchIllegalFormatExceptions()).append(newLine);
desc.append("writeIntermediateFile = ")
.append(isWriteIntermediateFile()).append(newLine);
desc.append("outputFilename = ")
.append(getOutputFilename()).append(newLine);
desc.append("destinationDirectory = ")
.append(getDestinationDirectory()).append(newLine);
return desc.toString();
}
/**
* Provides a description of extensions that are enabled/disabled.
* The default compiler implementation uses this method
* to describe extensions which are compiled into the script.
* The description is then provided to the user within the usage.
*
* @return A description of the extensions which are enabled/disabled.
*/
public String toExtensionDescription() {
StringBuilder extensions = new StringBuilder();
if (isAdditionalFunctions()) {
extensions.append(", _sleep & _dump enabled");
}
if (isAdditionalTypeFunctions()) {
extensions.append(", _INTEGER, _DOUBLE, _STRING enabled");
}
if (isUseSortedArrayKeys()) {
extensions.append(", associative array keys are sorted");
}
if (isCatchIllegalFormatExceptions()) {
extensions.append(", IllegalFormatExceptions NOT trapped");
}
if (extensions.length() > 0) {
return "{extensions: " + extensions.substring(2) + "}";
} else {
return "{no compiled extensions utilized}";
}
}
private void addInitialVariable(String keyValue) {
int equalsIdx = keyValue.indexOf('=');
assert equalsIdx >= 0;
String name = keyValue.substring(0, equalsIdx);
String valueString = keyValue.substring(equalsIdx + 1);
Object value;
// deduce type
try {
value = Integer.parseInt(valueString);
} catch (NumberFormatException nfe) {
try {
value = Double.parseDouble(valueString);
} catch (NumberFormatException nfe2) {
value = valueString;
}
}
// note: can overwrite previously defined variables
getVariables().put(name, value);
}
/**
* @param defaultFileName The filename to return if -o argument
* is not used.
*
* @return the optarg for the -o parameter, or the defaultFileName
* parameter if -o is not utilized.
*/
public String getOutputFilename(String defaultFileName) {
if (getOutputFilename() == null) {
return defaultFileName;
} else {
return getOutputFilename();
}
}
/**
* Returns the script sources meta info.
* This will usually be either one String container,
* made up of the script given on the command line directly,
* with the first non-"-" parameter,
* or one or multiple script file names (if provided with -f switches).
*/
public List<ScriptSource> getScriptSources() {
return scriptSources;
}
public void addScriptSource(ScriptSource scriptSource) {
scriptSources.add(scriptSource);
}
/**
* Where input is read from.
* By default, this is {@link System#in}.
* @return the input
*/
public InputStream getInput() {
return input;
}
/**
* Where input is read from.
* By default, this is {@link System#in}.
* @param input the input to set
*/
public void setInput(InputStream input) {
this.input = input;
}
/**
* Contains variable assignments which are applied prior to
* executing the script (-v assignments).
* The values may be of type <code>Integer</code>,
* <code>Double</code> or <code>String</code>.
* @return the variables
*/
public Map<String, Object> getVariables() {
return variables;
}
/**
* Contains variable assignments which are applied prior to
* executing the script (-v assignments).
* The values may be of type <code>Integer</code>,
* <code>Double</code> or <code>String</code>.
* @param variables the variables to set
*/
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
/**
* Contains name=value or filename entries.
* Order is important, which is why name=value and filenames
* are listed in the same List container.
* @return the nameValueOrFileNames
*/
public List<String> getNameValueOrFileNames() {
return nameValueOrFileNames;
}
/**
* Contains name=value or filename entries.
* Order is important, which is why name=value and filenames
* are listed in the same List container.
* @param nameValueOrFileNames the nameValueOrFileNames to set
*/
public void setNameValueOrFileNames(List<String> nameValueOrFileNames) {
this.nameValueOrFileNames = nameValueOrFileNames;
}
/**
* Script sources meta info.
* This will usually be either one String container,
* made up of the script given on the command line directly,
* with the first non-"-" parameter,
* or one or multiple script file names (if provided with -f switches).
* @param scriptSources the scriptSources to set
*/
public void setScriptSources(List<ScriptSource> scriptSources) {
this.scriptSources = scriptSources;
}
/**
* Whether to interpret or compile the script.
* Initial value is set to <code>false</code> (interpret).
* @return the compile
*/
public boolean isCompile() {
return compile;
}
/**
* Whether to interpret or compile the script.
* Initial value is set to <code>false</code> (interpret).
* @param compile the compile to set
*/
public void setCompile(boolean compile) {
this.compile = compile;
}
/**
* Whether to compile and execute the script.
* Initial value is set to <code>false</code> (interpret).
* @return the compileRun
*/
public boolean isCompileRun() {
return compileRun;
}
/**
* Whether to compile and execute the script.
* Initial value is set to <code>false</code> (interpret).
* @param compileRun the compileRun to set
*/
public void setCompileRun(boolean compileRun) {
this.compileRun = compileRun;
}
/**
* Initial Field Separator (FS) value.
* <code>null</code> means the default FS value.
* @return the fieldSeparator
*/
public String getFieldSeparator() {
return fieldSeparator;
}
/**
* Initial Field Separator (FS) value.
* <code>null</code> means the default FS value.
* @param fieldSeparator the fieldSeparator to set
*/
public void setFieldSeparator(String fieldSeparator) {
this.fieldSeparator = fieldSeparator;
}
/**
* Whether to dump the syntax tree;
* <code>false</code> by default.
* @return the dumpSyntaxTree
*/
public boolean isDumpSyntaxTree() {
return dumpSyntaxTree;
}
/**
* Whether to dump the syntax tree;
* <code>false</code> by default.
* @param dumpSyntaxTree the dumpSyntaxTree to set
*/
public void setDumpSyntaxTree(boolean dumpSyntaxTree) {
this.dumpSyntaxTree = dumpSyntaxTree;
}
/**
* Whether to dump the intermediate code;
* <code>false</code> by default.
* @return the dumpIntermediateCode
*/
public boolean isDumpIntermediateCode() {
return dumpIntermediateCode;
}
/**
* Whether to dump the intermediate code;
* <code>false</code> by default.
* @param dumpIntermediateCode the dumpIntermediateCode to set
*/
public void setDumpIntermediateCode(boolean dumpIntermediateCode) {
this.dumpIntermediateCode = dumpIntermediateCode;
}
/**
* Whether to enable additional functions (_sleep/_dump);
* <code>false</code> by default.
* @return the additionalFunctions
*/
public boolean isAdditionalFunctions() {
return additionalFunctions;
}
/**
* Whether to enable additional functions (_sleep/_dump);
* <code>false</code> by default.
* @param additionalFunctions the additionalFunctions to set
*/
public void setAdditionalFunctions(boolean additionalFunctions) {
this.additionalFunctions = additionalFunctions;
}
/**
* Whether to enable additional type functions (_INTEGER/_DOUBLE/_STRING);
* <code>false</code> by default.
* @return the additionalTypeFunctions
*/
public boolean isAdditionalTypeFunctions() {
return additionalTypeFunctions;
}
/**
* Whether to enable additional type functions (_INTEGER/_DOUBLE/_STRING);
* <code>false</code> by default.
* @param additionalTypeFunctions the additionalTypeFunctions to set
*/
public void setAdditionalTypeFunctions(boolean additionalTypeFunctions) {
this.additionalTypeFunctions = additionalTypeFunctions;
}
/**
* Whether to maintain array keys in sorted order;
* <code>false</code> by default.
* @return the useSortedArrayKeys
*/
public boolean isUseSortedArrayKeys() {
return useSortedArrayKeys;
}
/**
* Whether to maintain array keys in sorted order;
* <code>false</code> by default.
* @param useSortedArrayKeys the useSortedArrayKeys to set
*/
public void setUseSortedArrayKeys(boolean useSortedArrayKeys) {
this.useSortedArrayKeys = useSortedArrayKeys;
}
/**
* Whether user extensions are enabled;
* <code>false</code> by default.
* @return the userExtensions
*/
public boolean isUserExtensions() {
return userExtensions;
}
/**
* Whether user extensions are enabled;
* <code>false</code> by default.
* @param userExtensions the userExtensions to set
*/
public void setUserExtensions(boolean userExtensions) {
this.userExtensions = userExtensions;
}
/**
* Write to intermediate file;
* <code>false</code> by default.
* @return the writeIntermediateFile
*/
public boolean isWriteIntermediateFile() {
return writeIntermediateFile;
}
/**
* Write to intermediate file;
* <code>false</code> by default.
* @param writeIntermediateFile the writeIntermediateFile to set
*/
public void setWriteIntermediateFile(boolean writeIntermediateFile) {
this.writeIntermediateFile = writeIntermediateFile;
}
/**
* Output filename;
* <code>null</code> by default,
* which means the appropriate default file-name will get used.
* @return the outputFilename
*/
public String getOutputFilename() {
return outputFilename;
}
/**
* Output filename;
* <code>null</code> by default,
* which means the appropriate default file-name will get used.
* @param outputFilename the outputFilename to set
*/
public void setOutputFilename(String outputFilename) {
this.outputFilename = outputFilename;
}
/**
* Compiled destination directory (if provided);
* <code>"."</code> by default.
* @return the destinationDirectory
*/
public String getDestinationDirectory() {
return destinationDirectory;
}
/**
* Compiled destination directory (if provided).
* @param destinationDirectory the destinationDirectory to set,
* <code>"."</code> by default.
*/
public void setDestinationDirectory(String destinationDirectory) {
if (destinationDirectory == null) {
throw new IllegalArgumentException("The destination directory might never be null (you might want to use \".\")");
}
this.destinationDirectory = destinationDirectory;
}
/**
* Whether to trap <code>IllegalFormatExceptions</code>
* for <code>[s]printf</code>;
* <code>true</code> by default.
* @return the catchIllegalFormatExceptions
*/
public boolean isCatchIllegalFormatExceptions() {
return catchIllegalFormatExceptions;
}
/**
* Whether to trap <code>IllegalFormatExceptions</code>
* for <code>[s]printf</code>;
* <code>true</code> by default.
* @param catchIllegalFormatExceptions the catchIllegalFormatExceptions to set
*/
public void setCatchIllegalFormatExceptions(boolean catchIllegalFormatExceptions) {
this.catchIllegalFormatExceptions = catchIllegalFormatExceptions;
}
/**
* Whether Jawk consumes stdin or ARGV file input;
* <code>true</code> by default.
* @return the useStdIn
*/
public boolean isUseStdIn() {
return useStdIn;
}
/**
* Whether Jawk consumes stdin or ARGV file input;
* <code>true</code> by default.
* @param useStdIn the useStdIn to set
*/
public void setUseStdIn(boolean useStdIn) {
this.useStdIn = useStdIn;
}
}
|
92367a292c8738c52d818f5a1b7b30960351c9d3 | 922 | java | Java | guava-testlib/src/com/google/common/collect/testing/TestCollectionGenerator.java | TeamNyx/external_guava | adee4a2c97a40a92d5b65962d73321e3da4e2679 | [
"Apache-2.0"
] | 3 | 2015-06-21T12:37:25.000Z | 2021-05-11T08:08:07.000Z | guava-testlib/src/com/google/common/collect/testing/TestCollectionGenerator.java | TeamNyx/external_guava | adee4a2c97a40a92d5b65962d73321e3da4e2679 | [
"Apache-2.0"
] | null | null | null | guava-testlib/src/com/google/common/collect/testing/TestCollectionGenerator.java | TeamNyx/external_guava | adee4a2c97a40a92d5b65962d73321e3da4e2679 | [
"Apache-2.0"
] | 15 | 2015-11-19T15:16:30.000Z | 2019-07-05T22:39:02.000Z | 29.741935 | 75 | 0.741866 | 997,698 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import java.util.Collection;
/**
* Creates collections, containing sample elements, to be tested.
*
* <p>This class is GWT compatible.
*
* @author Kevin Bourrillion
*/
public interface TestCollectionGenerator<E>
extends TestContainerGenerator<Collection<E>, E> {
}
|
92367b437362497924229dbc7d0f429a46c1f7e5 | 472 | java | Java | _src/Chapter04/P92_VarAndMethodReturnAndArgumentsTypes/src/modern/challenge/Main.java | paullewallencom/java-978-1-7898-0141-5 | f5c900281b0263faaecf6e4c5b3e8562d7a437d0 | [
"Apache-2.0"
] | 427 | 2019-10-08T11:17:47.000Z | 2022-03-30T10:26:57.000Z | Chapter04/P92_VarAndMethodReturnAndArgumentsTypes/src/modern/challenge/Main.java | Danrusu1/Java-Coding-Problems | 21a1169cd2742559b586a972fa0d31e6f106cae2 | [
"MIT"
] | 7 | 2019-12-07T22:32:09.000Z | 2021-06-04T22:03:30.000Z | Chapter04/P92_VarAndMethodReturnAndArgumentsTypes/src/modern/challenge/Main.java | Danrusu1/Java-Coding-Problems | 21a1169cd2742559b586a972fa0d31e6f106cae2 | [
"MIT"
] | 284 | 2019-09-27T13:31:55.000Z | 2022-03-31T14:18:51.000Z | 18.88 | 69 | 0.622881 | 997,699 | package modern.challenge;
import java.util.Date;
public class Main {
public static void main(String[] args) {
System.out.println(checkPlayer());
}
public static Report checkPlayer() {
var player = new Player();
var timestamp = new Date();
var report = fetchReport(player, timestamp);
return report;
}
public static Report fetchReport(Player player, Date timestamp) {
return new Report();
}
}
|
92367ba69f6298d1461bb2c270efd3e491c9427e | 120 | java | Java | orienteer-standalone/src/main/java/org/orienteer/standalone/package-info.java | xiayingfeng/Orienteer | 23112f0c1f130522d07d49d9ee8e201a3f757ac2 | [
"Apache-2.0"
] | 143 | 2016-06-21T08:15:37.000Z | 2022-03-26T17:17:29.000Z | orienteer-standalone/src/main/java/org/orienteer/standalone/package-info.java | xiayingfeng/Orienteer | 23112f0c1f130522d07d49d9ee8e201a3f757ac2 | [
"Apache-2.0"
] | 277 | 2016-06-07T06:10:20.000Z | 2022-03-08T21:12:50.000Z | orienteer-standalone/src/main/java/org/orienteer/standalone/package-info.java | xiayingfeng/Orienteer | 23112f0c1f130522d07d49d9ee8e201a3f757ac2 | [
"Apache-2.0"
] | 61 | 2016-06-14T02:36:59.000Z | 2022-03-06T19:09:45.000Z | 30 | 78 | 0.791667 | 997,700 | /**
* Package contains classes required for starting Orienteer in standalone mode
*/
package org.orienteer.standalone; |
92367c424f4ff2205bf7a2ad3b0f9591165996b9 | 4,470 | java | Java | bundles/org.tmdmaker.ui/src/org/tmdmaker/ui/editor/gef3/editparts/node/AbstractSubsetTypeEditPart.java | tmdmaker/tmdmaker | 1491f15e8f3cb8db61bb63dd75c3692e7edf3608 | [
"Apache-2.0"
] | 7 | 2017-12-14T02:52:52.000Z | 2022-01-23T05:50:17.000Z | bundles/org.tmdmaker.ui/src/org/tmdmaker/ui/editor/gef3/editparts/node/AbstractSubsetTypeEditPart.java | tmdmaker/tmdmaker | 1491f15e8f3cb8db61bb63dd75c3692e7edf3608 | [
"Apache-2.0"
] | 7 | 2020-07-04T00:39:53.000Z | 2021-01-10T07:19:13.000Z | bundles/org.tmdmaker.ui/src/org/tmdmaker/ui/editor/gef3/editparts/node/AbstractSubsetTypeEditPart.java | tmdmaker/tmdmaker | 1491f15e8f3cb8db61bb63dd75c3692e7edf3608 | [
"Apache-2.0"
] | null | null | null | 25.397727 | 135 | 0.744966 | 997,701 | /*
* Copyright 2009-2019 TMD-Maker Project <https://www.tmdmaker.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tmdmaker.ui.editor.gef3.editparts.node;
import java.beans.PropertyChangeEvent;
import java.util.Collections;
import java.util.List;
import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.ConnectionEditPart;
import org.eclipse.gef.Request;
import org.tmdmaker.core.model.AbstractSubsetType;
import org.tmdmaker.core.model.ConnectableElement;
import org.tmdmaker.ui.editor.draw2d.anchors.CenterAnchor;
import org.tmdmaker.ui.editor.draw2d.figure.node.SubsetTypeFigure;
/**
* スーパーセットとサブセットとの接点のEditPartの基底クラス.
*
* @author nakag
*
*/
public abstract class AbstractSubsetTypeEditPart<T extends ConnectableElement>
extends AbstractModelEditPart<T> {
/**
* コンストラクタ.
*/
public AbstractSubsetTypeEditPart() {
super();
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#createFigure()
*/
@Override
protected IFigure createFigure() {
Figure figure = new SubsetTypeFigure();
updateFigure(figure);
return figure;
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#getConnectionAnchor()
*/
@Override
protected ConnectionAnchor getConnectionAnchor() {
return new CenterAnchor(getFigure());
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#propertyChange(java.beans.PropertyChangeEvent)
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(AbstractSubsetType.PROPERTY_DIRECTION)) {
refreshVisuals();
} else {
super.propertyChange(evt);
}
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#getSourceConnectionAnchor(org.eclipse.gef.ConnectionEditPart)
*/
@Override
public ConnectionAnchor getSourceConnectionAnchor(ConnectionEditPart connection) {
return new CenterAnchor(getFigure());
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#getSourceConnectionAnchor(org.eclipse.gef.Request)
*/
@Override
public ConnectionAnchor getSourceConnectionAnchor(Request request) {
return new CenterAnchor(getFigure());
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#getTargetConnectionAnchor(org.eclipse.gef.ConnectionEditPart)
*/
@Override
public ConnectionAnchor getTargetConnectionAnchor(ConnectionEditPart connection) {
return new CenterAnchor(getFigure());
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#getTargetConnectionAnchor(org.eclipse.gef.Request)
*/
@Override
public ConnectionAnchor getTargetConnectionAnchor(Request request) {
return new CenterAnchor(getFigure());
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#getModelChildren()
*/
@SuppressWarnings("rawtypes")
@Override
protected List getModelChildren() {
return Collections.emptyList();
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#getContentPane()
*/
@Override
public IFigure getContentPane() {
return getFigure();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.gef.editparts.AbstractEditPart#createEditPolicies()
*/
@Override
protected void createEditPolicies() {
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#canAutoSize()
*/
@Override
public boolean canAutoSize() {
return ((SubsetTypeFigure) getFigure()).canAutoSize();
}
@Override
protected void updateFigure(IFigure figure) {
// do nothing
}
@Override
public boolean canCallSelectionAction() {
return false;
}
}
|
92367c5533d06be456eff3ea70b3bfe57ce97c45 | 1,210 | java | Java | src/main/java/recursion_and_dynamic_programminng/TripleStep.java | mohnoor94/ProblemsSolving | fc861a5804c448d76c4785f3c98943a1e9accfd2 | [
"Apache-2.0"
] | 8 | 2018-10-13T05:46:06.000Z | 2021-10-13T10:13:05.000Z | src/main/java/recursion_and_dynamic_programminng/TripleStep.java | mohnoor94/ProblemsSolving | fc861a5804c448d76c4785f3c98943a1e9accfd2 | [
"Apache-2.0"
] | null | null | null | src/main/java/recursion_and_dynamic_programminng/TripleStep.java | mohnoor94/ProblemsSolving | fc861a5804c448d76c4785f3c98943a1e9accfd2 | [
"Apache-2.0"
] | 1 | 2020-03-31T16:25:55.000Z | 2020-03-31T16:25:55.000Z | 30.25 | 117 | 0.609917 | 997,702 | package recursion_and_dynamic_programminng;
import java.util.Arrays;
/**
* A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement
* a method to count how many possible ways the child can run up the stairs.
* ***
* - Cracking the coding interview, a book by Gayle Mcdowell (6th ed., q 8.1)
*/
public class TripleStep {
public static void main(String[] args) {
System.out.println(countWays(0));
System.out.println(countWays(1));
System.out.println(countWays(2));
System.out.println(countWays(3));
System.out.println(countWays(4));
System.out.println(countWays(5));
System.out.println(countWays(10));
System.out.println(countWays(15));
}
private static int countWays(int n) {
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return countWays(n, memo);
}
private static int countWays(int n, int[] memo) {
if (n < 0) return 0;
if (n == 0) return 1;
if (memo[n] != -1) return memo[n];
memo[n] = countWays(n - 1, memo) + countWays(n - 2, memo) + countWays(n - 3, memo);
return memo[n];
}
}
|
92367d5b80d12b81d2228247c3c83cb7ed89dfed | 976 | java | Java | src/main/java/com/example/demo/BasicConfiguration.java | ferrelm/spring-boot-rest-api | 2699d47f2db28e40705202c31f95b292ce258af3 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/BasicConfiguration.java | ferrelm/spring-boot-rest-api | 2699d47f2db28e40705202c31f95b292ce258af3 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/BasicConfiguration.java | ferrelm/spring-boot-rest-api | 2699d47f2db28e40705202c31f95b292ce258af3 | [
"MIT"
] | null | null | null | 19.52 | 75 | 0.641393 | 997,703 | package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("basic")
public class BasicConfiguration {
private int number;
private boolean value;
private String message;
public int getNumber() {
return number;
}
public boolean isValue() {
return value;
}
public String getMessage() {
return message;
}
public void setNumber(int number) {
this.number = number;
}
public void setValue(boolean value) {
this.value = value;
}
public void setMessage(String message) {
this.message = message;
}
public List<Object> getAll() {
List<Object> list = new ArrayList<>();
list.add(number);
list.add(value);
list.add(message);
return list;
}
}
|
92367dd06fa2f986faf46e6cd45900c2716e7cc6 | 3,276 | java | Java | src/main/java/com/github/jonathanxd/wcommands/ext/reflect/visitors/containers/TreeNamedContainer.java | JonathanxD/WCommands | 754502500510753e44d97a884456cb76ab87e7c2 | [
"MIT"
] | null | null | null | src/main/java/com/github/jonathanxd/wcommands/ext/reflect/visitors/containers/TreeNamedContainer.java | JonathanxD/WCommands | 754502500510753e44d97a884456cb76ab87e7c2 | [
"MIT"
] | null | null | null | src/main/java/com/github/jonathanxd/wcommands/ext/reflect/visitors/containers/TreeNamedContainer.java | JonathanxD/WCommands | 754502500510753e44d97a884456cb76ab87e7c2 | [
"MIT"
] | null | null | null | 38.267442 | 153 | 0.714676 | 997,704 | /*
* WCommands - Yet Another Command API! <https://github.com/JonathanxD/WCommands>
*
* The MIT License (MIT)
*
* Copyright (c) 2016 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/ & https://github.com/TheRealBuggy/) <anpch@example.com>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.wcommands.ext.reflect.visitors.containers;
import com.github.jonathanxd.wcommands.util.reflection.ElementBridge;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jonathan on 27/02/16.
*/
public class TreeNamedContainer extends NamedContainer {
private final List<TreeNamedContainer> child = new ArrayList<>();
private final List<SingleNamedContainer> argumentContainers = new ArrayList<>();
public TreeNamedContainer(String name, Annotation value, ElementBridge bridge) {
super(name, value, bridge);
}
public boolean isMethod() {
return getBridge().getMember() instanceof Method;
}
public boolean isField() {
return getBridge().getMember() instanceof Field;
}
public List<TreeNamedContainer> getChild() {
return child;
}
public List<SingleNamedContainer> getArgumentContainers() {
return argumentContainers;
}
public TreeNamedContainer recreate(String name) {
return recreate(name, this.get(), this.getBridge());
}
public TreeNamedContainer recreate(Annotation value) {
return recreate(this.getName(), value, this.getBridge());
}
public TreeNamedContainer recreate(String name, Annotation value) {
return recreate(name, value, this.getBridge());
}
public TreeNamedContainer recreate(String name, Annotation value, ElementBridge bridge) {
TreeNamedContainer treeNamedContainer = new TreeNamedContainer(name, value, bridge);
treeNamedContainer.child.addAll(this.child);
treeNamedContainer.argumentContainers.addAll(this.argumentContainers);
return treeNamedContainer;
}
}
|
92367ebd58ea817cfd758cf51c2c49a2e8a369aa | 710 | java | Java | concurrentCode/src/main/java/com/wkc/java/threadbasic/Priority_11.java | weikaichen20/notes | 1b59ce0b0786345880081ce0b1f871248efa0b31 | [
"Apache-2.0"
] | null | null | null | concurrentCode/src/main/java/com/wkc/java/threadbasic/Priority_11.java | weikaichen20/notes | 1b59ce0b0786345880081ce0b1f871248efa0b31 | [
"Apache-2.0"
] | null | null | null | concurrentCode/src/main/java/com/wkc/java/threadbasic/Priority_11.java | weikaichen20/notes | 1b59ce0b0786345880081ce0b1f871248efa0b31 | [
"Apache-2.0"
] | null | null | null | 22.903226 | 65 | 0.447887 | 997,705 | package com.wkc.java.threadbasic;
/**
* Created on 2022/3/9.
*
* @author Weikaichen
*/
public class Priority_11 {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
int count = 0;
while (true) {
System.out.println("t1===>" + count++);
}
}, "t1");
Thread t2 = new Thread(() -> {
int count = 0;
while (true) {
// Thread.yield();
System.out.println("t2=============>" + count++);
}
}, "t2");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
|
923680048ceae5550d818a0d67606fff8c22d0bc | 5,227 | java | Java | metrics/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/metrics/score/FuzzyScore.java | AlexRogalskiy/Comparalyzer | 42a03c14d639663387e7b796dca41cb1300ad36b | [
"MIT"
] | 1 | 2019-02-27T00:28:14.000Z | 2019-02-27T00:28:14.000Z | metrics/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/metrics/score/FuzzyScore.java | AlexRogalskiy/Comparalyzer | 42a03c14d639663387e7b796dca41cb1300ad36b | [
"MIT"
] | 8 | 2019-11-13T09:02:17.000Z | 2021-12-09T20:49:03.000Z | metrics/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/metrics/score/FuzzyScore.java | AlexRogalskiy/Diffy | 42a03c14d639663387e7b796dca41cb1300ad36b | [
"MIT"
] | 1 | 2019-02-01T08:48:24.000Z | 2019-02-01T08:48:24.000Z | 42.844262 | 103 | 0.63612 | 997,706 | /*
* The MIT License
*
* Copyright 2019 WildBees Labs, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software andAll associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, andAll/or sell
* copies of the Software, andAll to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice andAll this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.wildbeeslabs.sensiblemetrics.diffy.metrics.score;
import com.wildbeeslabs.sensiblemetrics.diffy.common.utils.ValidationUtils;
import com.wildbeeslabs.sensiblemetrics.diffy.metrics.interfaces.SimilarityScore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.Locale;
/**
* Fuzzy {@link SimilarityScore} implementation
*/
@Data
@EqualsAndHashCode
@ToString
public class FuzzyScore implements SimilarityScore<CharSequence, Integer> {
/**
* Locale used to change the case of text.
*/
private final Locale locale;
/**
* <p>This returns a {@link Locale}-specific {@link FuzzyScore}.</p>
*
* @param locale The string matching logic is case insensitive.
* A {@link Locale} is necessary to normalize both Strings to lower case.
* @throws IllegalArgumentException This is thrown if the {@link Locale} parameter is {@code null}.
*/
public FuzzyScore(final Locale locale) {
ValidationUtils.notNull(locale, "Locale should not be null");
this.locale = locale;
}
/**
* <p>
* Find the Fuzzy Score which indicates the similarity score between two
* Strings.
* </p>
*
* <pre>
* score.fuzzyScore(null, null, null) = IllegalArgumentException
* score.fuzzyScore("", "", Locale.ENGLISH) = 0
* score.fuzzyScore("Workshop", "b", Locale.ENGLISH) = 0
* score.fuzzyScore("Room", "o", Locale.ENGLISH) = 1
* score.fuzzyScore("Workshop", "w", Locale.ENGLISH) = 1
* score.fuzzyScore("Workshop", "ws", Locale.ENGLISH) = 2
* score.fuzzyScore("Workshop", "wo", Locale.ENGLISH) = 4
* score.fuzzyScore("Apache Software Foundation", "asf", Locale.ENGLISH) = 3
* </pre>
*
* @param first a full term that should be matched against, must not be null
* @param last the query that will be matched against a term, must not be
* null
* @return result score
* @throws IllegalArgumentException if either CharSequence input is {@code null}
*/
@Override
public Integer apply(final CharSequence first, final CharSequence last) {
ValidationUtils.notNull(first, "First sequence should not be null");
ValidationUtils.notNull(last, "Last sequence should not be null");
final String termLowerCase = first.toString().toLowerCase(locale);
final String queryLowerCase = last.toString().toLowerCase(locale);
// the resulting score
int score = 0;
// the position in the term which will be scanned next for potential
// query character matches
int termIndex = 0;
// index of the previously matched character in the term
int previousMatchingCharacterIndex = Integer.MIN_VALUE;
for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) {
final char queryChar = queryLowerCase.charAt(queryIndex);
boolean termCharacterMatchFound = false;
for (; termIndex < termLowerCase.length()
&& !termCharacterMatchFound; termIndex++) {
final char termChar = termLowerCase.charAt(termIndex);
if (queryChar == termChar) {
// simple character matches result in one point
score++;
// subsequent character matches further improve
// the score.
if (previousMatchingCharacterIndex + 1 == termIndex) {
score += 2;
}
previousMatchingCharacterIndex = termIndex;
// we can leave the nested loop. Every character in the
// query can match at most one character in the term.
termCharacterMatchFound = true;
}
}
}
return score;
}
}
|
9236810412cd055f6a5cc73e9ea776468c622eac | 1,184 | java | Java | src/main/java/br/com/bovbi/embed/rest/response/UserLoggedResponse.java | fernandommota/embed-pentaho-server | b37d4fd50f44f61c8dbc4b37951f8d4fa49588bd | [
"CC0-1.0"
] | 1 | 2021-02-10T01:48:14.000Z | 2021-02-10T01:48:14.000Z | src/main/java/br/com/bovbi/embed/rest/response/UserLoggedResponse.java | fernandommota/embed-pentaho-server | b37d4fd50f44f61c8dbc4b37951f8d4fa49588bd | [
"CC0-1.0"
] | null | null | null | src/main/java/br/com/bovbi/embed/rest/response/UserLoggedResponse.java | fernandommota/embed-pentaho-server | b37d4fd50f44f61c8dbc4b37951f8d4fa49588bd | [
"CC0-1.0"
] | 1 | 2021-02-04T00:09:17.000Z | 2021-02-04T00:09:17.000Z | 21.527273 | 56 | 0.554899 | 997,707 | package br.com.bovbi.embed.rest.response;
import java.util.ArrayList;
import java.util.Date;
public class UserLoggedResponse {
private String token;
private String username;
private ArrayList<String> roles;
private Boolean active;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Boolean isActive() {
return this.active;
}
public void setActive(Boolean active) {
this.active = active;
}
public ArrayList<String> getRoles() {
return this.roles;
}
public void setLogin(ArrayList<String> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "UserLoggedResponse{" +
"username=\'" + this.username + "\'" +
", token=\'" + this.token + "\'" +
", active=\'" + this.active + "\'" +
", roles=\'" + roles.toString() + "\'" +
'}';
}
}
|
92368219a035e9e02d8a6c0a9b7691ff232df1c5 | 634 | java | Java | app/src/main/java/com/itzxx/mvphabit/utils/SingletonRxRetrofit.java | zhanghacker/MvpHabit | de2bfa6fc26ec2ed2670de6ade40e3ea70522930 | [
"Apache-2.0"
] | 39 | 2018-09-18T09:12:43.000Z | 2022-03-25T08:36:10.000Z | app/src/main/java/com/itzxx/mvphabit/utils/SingletonRxRetrofit.java | zhanghacker/HelperHabit | de2bfa6fc26ec2ed2670de6ade40e3ea70522930 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/itzxx/mvphabit/utils/SingletonRxRetrofit.java | zhanghacker/HelperHabit | de2bfa6fc26ec2ed2670de6ade40e3ea70522930 | [
"Apache-2.0"
] | 3 | 2018-12-31T03:42:07.000Z | 2022-03-25T08:36:10.000Z | 23.481481 | 94 | 0.684543 | 997,708 | package com.itzxx.mvphabit.utils;
import com.itzxx.helperlibrary.network.RetrofitUtil;
import com.itzxx.mvphabit.UserApi;
public class SingletonRxRetrofit {
private static SingletonRxRetrofit okHttpClient;
private UserApi mUserApi;
public static SingletonRxRetrofit getInstance() {
if (okHttpClient == null) {
okHttpClient = new SingletonRxRetrofit();
}
return okHttpClient;
}
public SingletonRxRetrofit(){
mUserApi = RetrofitUtil.Builder.create("http://47.106.132.104/").build(UserApi.class);
}
public UserApi getApi() {
return mUserApi;
}
}
|
92368429be16487945b7ef484dc9e2219b466b86 | 4,093 | java | Java | core/cli/src/test/java/org/locationtech/geowave/core/cli/prefix/PrefixedJCommanderTest.java | e2000y/geowave | 6cc4d39c7bd4cbfe57095559ee2fb1e1cfa89890 | [
"Apache-2.0"
] | 280 | 2017-06-14T01:26:19.000Z | 2022-03-28T15:45:23.000Z | core/cli/src/test/java/org/locationtech/geowave/core/cli/prefix/PrefixedJCommanderTest.java | e2000y/geowave | 6cc4d39c7bd4cbfe57095559ee2fb1e1cfa89890 | [
"Apache-2.0"
] | 458 | 2017-06-12T20:00:59.000Z | 2022-03-31T04:41:59.000Z | core/cli/src/test/java/org/locationtech/geowave/core/cli/prefix/PrefixedJCommanderTest.java | e2000y/geowave | 6cc4d39c7bd4cbfe57095559ee2fb1e1cfa89890 | [
"Apache-2.0"
] | 135 | 2017-06-12T20:39:34.000Z | 2022-03-15T13:42:30.000Z | 32.484127 | 100 | 0.724408 | 997,709 | /**
* Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.core.cli.prefix;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.locationtech.geowave.core.cli.annotations.PrefixParameter;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParametersDelegate;
public class PrefixedJCommanderTest {
@Test
public void testAddCommand() {
final PrefixedJCommander prefixedJCommander = new PrefixedJCommander();
prefixedJCommander.addCommand("abc", (Object) "hello, world", "a");
prefixedJCommander.addCommand("def", (Object) "goodbye, world", "b");
prefixedJCommander.parse("abc");
Assert.assertEquals(prefixedJCommander.getParsedCommand(), "abc");
}
@Test
public void testNullDelegate() {
final PrefixedJCommander commander = new PrefixedJCommander();
final NullDelegate nullDelegate = new NullDelegate();
commander.addPrefixedObject(nullDelegate);
commander.parse();
}
@Test
public void testMapDelegatesPrefix() {
final Arguments args = new Arguments();
args.argChildren.put("abc", new ArgumentChildren());
args.argChildren.put("def", new ArgumentChildren());
final PrefixedJCommander commander = new PrefixedJCommander();
commander.addPrefixedObject(args);
commander.parse("--abc.arg", "5", "--def.arg", "blah");
Assert.assertEquals("5", args.argChildren.get("abc").arg);
Assert.assertEquals("blah", args.argChildren.get("def").arg);
}
@Test
public void testCollectionDelegatesPrefix() {
final ArgumentsCollection args = new ArgumentsCollection();
args.argChildren.add(new ArgumentChildren());
args.argChildren.add(new ArgumentChildrenOther());
final PrefixedJCommander commander = new PrefixedJCommander();
commander.addPrefixedObject(args);
commander.parse("--arg", "5", "--arg2", "blah");
Assert.assertEquals("5", ((ArgumentChildren) args.argChildren.get(0)).arg);
Assert.assertEquals("blah", ((ArgumentChildrenOther) args.argChildren.get(1)).arg2);
}
@Test
public void testPrefixParameter() {
final PrefixedArguments args = new PrefixedArguments();
final PrefixedJCommander commander = new PrefixedJCommander();
commander.addPrefixedObject(args);
commander.parse("--abc.arg", "5", "--arg", "blah");
Assert.assertEquals("5", args.child.arg);
Assert.assertEquals("blah", args.blah);
}
@Test
public void testAddGetPrefixedObjects() {
final PrefixedArguments args = new PrefixedArguments();
final PrefixedJCommander commander = new PrefixedJCommander();
commander.addPrefixedObject(args);
Assert.assertTrue(
commander.getPrefixedObjects().contains(args)
&& (commander.getPrefixedObjects().size() == 1));
}
private static class PrefixedArguments {
@ParametersDelegate
@PrefixParameter(prefix = "abc")
private final ArgumentChildren child = new ArgumentChildren();
@Parameter(names = "--arg")
private String blah;
}
private static class NullDelegate {
@ParametersDelegate
private final ArgumentChildren value = null;
}
private static class ArgumentsCollection {
@ParametersDelegate
private final List<Object> argChildren = new ArrayList<>();
}
private static class Arguments {
@ParametersDelegate
private final Map<String, ArgumentChildren> argChildren = new HashMap<>();
}
private static class ArgumentChildren {
@Parameter(names = "--arg")
private String arg;
}
private static class ArgumentChildrenOther {
@Parameter(names = "--arg2")
private String arg2;
}
}
|
9236843362b19f8ab8ef0abc0bbcd2b7bf270961 | 1,613 | java | Java | 03_Assignment/dream_park/src/park/Game.java | CSEMN/FEE_SWE | 4607a42674883927427b85f393a027ac82a82186 | [
"MIT"
] | null | null | null | 03_Assignment/dream_park/src/park/Game.java | CSEMN/FEE_SWE | 4607a42674883927427b85f393a027ac82a82186 | [
"MIT"
] | null | null | null | 03_Assignment/dream_park/src/park/Game.java | CSEMN/FEE_SWE | 4607a42674883927427b85f393a027ac82a82186 | [
"MIT"
] | null | null | null | 22.09589 | 70 | 0.637322 | 997,710 | package park;
import utilities.Generate;
import people.GameManager;
public class Game {
private String g_id;
private String gName;
private double price;
private int ageRestriction;
private String description;
private GameManager gameManager;
public Game(String gName, GameManager gameManager) {
this.g_id=Generate.id("G");
this.gName = gName;
this.price = Generate.money(5.0, 50.0);
this.ageRestriction= Generate.integer(7, 18);
this.gameManager = gameManager;
}
public Game(String gName, double price, GameManager gameManager) {
this.gName = gName;
this.price = price;
this.gameManager = gameManager;
}
public String getG_id() {
return this.g_id;
}
public String getGName() {
return this.gName;
}
public void setGName(String gName) {
this.gName = gName;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public int getAgeRestriction() {
return this.ageRestriction;
}
public void setAgeRestriction(int ageRestriction) {
this.ageRestriction = ageRestriction;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public GameManager getGameManager() {
return this.gameManager;
}
public void setGameManager(GameManager gameManager) {
this.gameManager = gameManager;
}
}
|
923684ac0320a5f09eca78f755e899d4fe1da82b | 1,513 | java | Java | drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/FileUtil.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 3,631 | 2017-03-14T08:54:05.000Z | 2022-03-31T19:59:10.000Z | drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/FileUtil.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 2,274 | 2017-03-13T14:02:17.000Z | 2022-03-28T17:23:17.000Z | drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/FileUtil.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 1,490 | 2017-03-14T11:37:37.000Z | 2022-03-31T08:50:22.000Z | 32.891304 | 141 | 0.673496 | 997,711 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.testcoverage.common.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import org.kie.api.builder.ReleaseId;
public final class FileUtil {
public static File bytesToTempKJARFile(ReleaseId releaseId, byte[] bytes, String extension ) {
File file = new File( System.getProperty( "java.io.tmpdir" ), releaseId.getArtifactId() + "-" + releaseId.getVersion() + extension );
try {
new PrintWriter(file).close();
FileOutputStream fos = new FileOutputStream(file, false );
fos.write( bytes );
fos.flush();
fos.close();
} catch ( IOException e ) {
throw new RuntimeException( e );
}
return file;
}
private FileUtil() {
// Creating instances of this class is not allowed.
}
}
|
923684b25792f16b79f13605dacd88617831e208 | 7,559 | java | Java | src/org/hy/common/ldap/annotation/LdapAnnotation.java | HY-ZhengWei/hy.common.ldap | 2114acf3c6091fd8cc17d6284517bca44ff0c4a1 | [
"Apache-2.0"
] | 5 | 2017-02-17T06:50:12.000Z | 2017-03-13T02:33:28.000Z | src/org/hy/common/ldap/annotation/LdapAnnotation.java | HY-ZhengWei/hy.common.ldap | 2114acf3c6091fd8cc17d6284517bca44ff0c4a1 | [
"Apache-2.0"
] | null | null | null | src/org/hy/common/ldap/annotation/LdapAnnotation.java | HY-ZhengWei/hy.common.ldap | 2114acf3c6091fd8cc17d6284517bca44ff0c4a1 | [
"Apache-2.0"
] | 2 | 2017-03-09T09:40:59.000Z | 2017-06-30T06:30:21.000Z | 40.207447 | 155 | 0.486308 | 997,712 | package org.hy.common.ldap.annotation;
import java.lang.annotation.ElementType;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.hy.common.ClassInfo;
import org.hy.common.ClassReflect;
import org.hy.common.Help;
import org.hy.common.MethodReflect;
import org.hy.common.PartitionMap;
import org.hy.common.TablePartitionRID;
import org.hy.common.xml.XJava;
/**
* Ladp注解解释类
*
* @author ZhengWei(HY)
* @createDate 2017-02-14
* @version v1.0
*/
public class LdapAnnotation
{
public static final String $LdapEntryClasses = "LdapEntryClasses";
public static final String $LdapEntryClassIDs = "LdapEntryClassIDs";
public static void parser()
{
parser("org.hy.common.ldap.objectclasses");
}
/**
* 追加方式的解释@Ladp。
*
* @author ZhengWei(HY)
* @createDate 2018-12-13
* @version v1.0
*
* @param i_PackageName 包路径
*/
@SuppressWarnings("unchecked")
public synchronized static void parser(String i_PackageName)
{
Map<Class<?> ,LdapEntry> v_LdapEntryClasses = (Map<Class<?> ,LdapEntry>)XJava.getObject($LdapEntryClasses);
Map<String ,LdapEntry> v_LdapEntryClassIDs = (Map<String ,LdapEntry>)XJava.getObject($LdapEntryClassIDs);
if ( XJava.getObject($LdapEntryClasses) == null )
{
v_LdapEntryClasses = new Hashtable<Class<?> ,LdapEntry>();
v_LdapEntryClassIDs = new Hashtable<String ,LdapEntry>();
XJava.putObject($LdapEntryClasses ,v_LdapEntryClasses);
XJava.putObject($LdapEntryClassIDs ,v_LdapEntryClassIDs);
}
parser(Help.getClasses(i_PackageName) ,v_LdapEntryClasses ,v_LdapEntryClassIDs);
}
private static void parser(List<Class<?>> i_Classes ,Map<Class<?> ,LdapEntry> io_LdapEntryClasses ,Map<String ,LdapEntry> io_LdapEntryClassIDs)
{
PartitionMap<ElementType ,ClassInfo> v_Annotations = ClassReflect.getAnnotations(i_Classes ,Ldap.class);
List<ClassInfo> v_ClassInfos = null;
ClassInfo v_ClassInfo = null;
TablePartitionRID<String ,Method> v_GetSetMethods = null;
Ldap v_AnnoObjectClass = null;
LdapEntry v_LdapEntry = null;
if ( Help.isNull(v_Annotations) )
{
return;
}
// Ldap.objectClass 注解功能的实现
v_ClassInfos = v_Annotations.get(ElementType.TYPE);
if ( !Help.isNull(v_ClassInfos) )
{
for (int i=0; i<v_ClassInfos.size(); i++)
{
v_ClassInfo = v_ClassInfos.get(i);
v_GetSetMethods = MethodReflect.getGetSetMethods(v_ClassInfo.getClassObj());
v_AnnoObjectClass = v_ClassInfo.getClassObj().getAnnotation(Ldap.class);
v_LdapEntry = new LdapEntry(v_ClassInfo.getClassObj() ,Help.NVL(v_AnnoObjectClass.objectClass() ,v_AnnoObjectClass.value()));
if ( !Help.isNull(v_ClassInfo.getFields()) )
{
// Java对象属性:Ldap.name 注解功能的实现
for (int x=0; x<v_ClassInfo.getFields().size(); x++)
{
Field v_Field = v_ClassInfo.getFields().get(x);
String v_FieldName = v_Field.getName().substring(0 ,1).toUpperCase() + v_Field.getName().substring(1);
Method v_GetMethod = v_GetSetMethods.getRow(MethodReflect.$Partition_GET ,v_FieldName);
Method v_SetMethod = v_GetSetMethods.getRow(MethodReflect.$Partition_SET ,v_FieldName);
Ldap v_AnnoAttr = v_Field.getAnnotation(Ldap.class);
if ( v_AnnoAttr.type() == LdapType.DN )
{
v_LdapEntry.setDnGetMethod(v_GetMethod);
v_LdapEntry.setDnSetMethod(v_SetMethod);
String v_Name = Help.NVL(v_AnnoAttr.name() ,v_AnnoAttr.value());
if ( !Help.isNull(v_Name) )
{
v_LdapEntry.setRdn(v_Name);
}
}
else
{
v_LdapEntry.putElement(Help.NVL(v_AnnoAttr.name() ,Help.NVL(v_AnnoAttr.value() ,v_Field.getName())) ,v_GetMethod ,v_SetMethod);
}
}
}
if ( !Help.isNull(v_ClassInfo.getMethods()) )
{
// Java对象方法:Ldap.name 注解功能的实现
for (int x=0; x<v_ClassInfo.getMethods().size(); x++)
{
Method v_Method = v_ClassInfo.getMethods().get(x);
Ldap v_AnnoAttr = v_Method.getAnnotation(Ldap.class);
String v_Name = Help.NVL(v_AnnoAttr.name() ,v_AnnoAttr.value());
if ( Help.isNull(v_Name) )
{
v_Name = v_Method.getName();
if ( v_Name.startsWith("get") )
{
v_Name = v_Name.substring(3);
}
else if ( v_Name.startsWith("is") )
{
v_Name = v_Name.substring(2);
}
}
else
{
v_Name = v_Name.substring(0 ,1).toUpperCase() + v_Name.substring(1);
}
Method v_GetMethod = v_GetSetMethods.getRow(MethodReflect.$Partition_GET ,v_Name);
Method v_SetMethod = v_GetSetMethods.getRow(MethodReflect.$Partition_SET ,v_Name);
if ( v_AnnoAttr.type() == LdapType.DN )
{
v_LdapEntry.setDnGetMethod(v_GetMethod);
v_LdapEntry.setDnSetMethod(v_SetMethod);
if ( !Help.isNull(v_Name) )
{
v_LdapEntry.setRdn(v_AnnoAttr.value());
}
}
else
{
v_LdapEntry.putElement(v_Name ,v_GetMethod ,v_SetMethod);
}
}
}
// 只保存有对象类和属性的LDAP条目信息
if ( !Help.isNull(v_LdapEntry.getObjectClasses())
&& (!Help.isNull(v_LdapEntry.getElementsToLDAP())
|| !Help.isNull(v_LdapEntry.getElementsToObject())) )
{
io_LdapEntryClasses .put(v_LdapEntry.getMetaClass() ,v_LdapEntry);
io_LdapEntryClassIDs.put(v_LdapEntry.getObjectClassesID() ,v_LdapEntry);
}
}
}
}
}
|
9236851657a3ce73ff782dff4c30f41e70921180 | 457 | java | Java | core/src/test/java/net/onedaybeard/constexpr/model/PlainPrimitive.java | junkdog/constexpr-java | 1e89cabb019392c21e1b0a2cabddd891632203aa | [
"Apache-2.0"
] | 57 | 2016-10-31T00:45:47.000Z | 2022-01-14T11:05:54.000Z | core/src/test/java/net/onedaybeard/constexpr/model/PlainPrimitive.java | junkdog/constexpr-java | 1e89cabb019392c21e1b0a2cabddd891632203aa | [
"Apache-2.0"
] | 3 | 2016-10-31T13:27:27.000Z | 2020-06-22T11:23:34.000Z | core/src/test/java/net/onedaybeard/constexpr/model/PlainPrimitive.java | junkdog/constexpr-java | 1e89cabb019392c21e1b0a2cabddd891632203aa | [
"Apache-2.0"
] | 4 | 2016-10-31T11:46:59.000Z | 2021-06-07T12:42:43.000Z | 22.85 | 76 | 0.730853 | 997,713 | package net.onedaybeard.constexpr.model;
import net.onedaybeard.constexpr.ConstExpr;
import java.util.Random;
public class PlainPrimitive {
@ConstExpr public static final long timestamp = System.currentTimeMillis();
@ConstExpr public static final int seed = generateSeed();
@ConstExpr
private static int generateSeed() {
String s = "hellooooo";
int sum = 0;
for (char c : s.toCharArray())
sum += c;
return new Random(sum).nextInt();
}
}
|
923685be6fd96305a6d7b2df386192c1f3f3e41f | 96 | java | Java | src/main/java/com/lofi/springbean/dynamic/Customer.java | dataronio/springbean-dynamic | ad59dd65cad2f0e28c2b8872030f9b24dd3f44a6 | [
"Apache-2.0"
] | 9 | 2019-01-07T11:46:10.000Z | 2021-11-21T16:24:10.000Z | src/main/java/com/lofi/springbean/dynamic/Customer.java | dataronio/springbean-dynamic | ad59dd65cad2f0e28c2b8872030f9b24dd3f44a6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/lofi/springbean/dynamic/Customer.java | dataronio/springbean-dynamic | ad59dd65cad2f0e28c2b8872030f9b24dd3f44a6 | [
"Apache-2.0"
] | 6 | 2019-03-07T13:24:17.000Z | 2021-12-30T13:34:26.000Z | 12 | 36 | 0.760417 | 997,714 | package com.lofi.springbean.dynamic;
public interface Customer {
public String getName();
}
|
923686b7b57941ee86ceb90d06d047767ed11aaa | 688 | java | Java | jboss/jboss-netty/ff-netty-5.0/src/main/java/org/ko/netty/t2/handler/HwClientHandler.java | le3t/ko-repo | 50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5 | [
"Apache-2.0"
] | 4 | 2018-03-13T09:49:43.000Z | 2018-04-04T11:27:40.000Z | jboss/jboss-netty/ff-netty-5.0/src/main/java/org/ko/netty/t2/handler/HwClientHandler.java | le3t/ko-repo | 50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5 | [
"Apache-2.0"
] | 3 | 2019-08-26T13:41:57.000Z | 2019-08-26T13:44:21.000Z | jboss/jboss-netty/ff-netty-5.0/src/main/java/org/ko/netty/t2/handler/HwClientHandler.java | le3t/ko-repo | 50eb0b4cadb9db9bf608a9e5d36376f38ff5cce5 | [
"Apache-2.0"
] | 1 | 2018-12-07T10:06:42.000Z | 2018-12-07T10:06:42.000Z | 29.913043 | 85 | 0.732558 | 997,715 | package org.ko.netty.t2.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class HwClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("server say : "+msg.toString());
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Handler1");
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client is close");
}
} |
9236878c4547d40732f3bb65580a6e07c8d2f7c2 | 2,155 | java | Java | src/main/java/dansapps/interakt/actions/ReproduceAction.java | dmccoystephenson/Interakt | 42f744607c10017310cba5866a4de42b03a66f64 | [
"Apache-2.0"
] | null | null | null | src/main/java/dansapps/interakt/actions/ReproduceAction.java | dmccoystephenson/Interakt | 42f744607c10017310cba5866a4de42b03a66f64 | [
"Apache-2.0"
] | 10 | 2022-01-08T07:11:39.000Z | 2022-01-10T06:45:20.000Z | src/main/java/dansapps/interakt/actions/ReproduceAction.java | dmccoystephenson/Interakt | 42f744607c10017310cba5866a4de42b03a66f64 | [
"Apache-2.0"
] | null | null | null | 43.1 | 188 | 0.704408 | 997,716 | package dansapps.interakt.actions;
import dansapps.interakt.Interakt;
import dansapps.interakt.actions.abs.Action;
import dansapps.interakt.data.PersistentData;
import dansapps.interakt.factories.ActionRecordFactory;
import dansapps.interakt.factories.ActorFactory;
import dansapps.interakt.factories.EventFactory;
import dansapps.interakt.objects.Actor;
import dansapps.interakt.objects.Event;
import dansapps.interakt.objects.World;
import dansapps.interakt.utils.Logger;
public class ReproduceAction implements Action {
public static void execute(Actor actor, Actor other) {
if (!actor.isFriend(other)) {
return;
}
Actor offspring = ActorFactory.getInstance().createActorFromParents(actor, other);
World world = actor.getWorld();
boolean success = PersistentData.getInstance().placeIntoEnvironment(world, offspring); // TODO: place in same square as parents
if (!success) {
Logger.getInstance().logError("Something went wrong placing a new offspring into their environment.");
return;
}
Event event = EventFactory.getInstance().createEvent(actor.getName() + " reproduced with " + other.getName() + ", resulting in " + offspring.getName() + " coming into existence.");
Logger.getInstance().logEvent(event);
if (actor.getName().equalsIgnoreCase(Interakt.getInstance().getPlayerActorName())) {
Interakt.getInstance().getCommandSender().sendMessage("You reproduced with " + other.getName() + ", resulting in " + offspring.getName() + " coming into existence.");
}
if (other.getName().equalsIgnoreCase(Interakt.getInstance().getPlayerActorName())) {
Interakt.getInstance().getCommandSender().sendMessage(other.getName() + " reproduced with you, resulting in " + offspring.getName() + " coming into existence.");
}
ActionRecordFactory.getInstance().createActionRecord(actor, new ReproduceAction());
actor.increaseRelation(other, 100);
other.increaseRelation(actor, 100);
}
@Override
public String getName() {
return "reproduce";
}
} |
923688ac73b6266338c371d851e94e27483b1e89 | 43 | java | Java | testdata/BxExampleTest/Test.java | Billy-sm24/megamodelbuild | 023c0fe9a5409b8066e3b317921c2cf818b18c43 | [
"Apache-2.0"
] | null | null | null | testdata/BxExampleTest/Test.java | Billy-sm24/megamodelbuild | 023c0fe9a5409b8066e3b317921c2cf818b18c43 | [
"Apache-2.0"
] | null | null | null | testdata/BxExampleTest/Test.java | Billy-sm24/megamodelbuild | 023c0fe9a5409b8066e3b317921c2cf818b18c43 | [
"Apache-2.0"
] | 1 | 2020-12-03T18:58:25.000Z | 2020-12-03T18:58:25.000Z | 14.333333 | 20 | 0.627907 | 997,717 | public class Test {
// Some test code
} |
9236896dd40ae2a9369d738cb32e324d1b372a4a | 118 | java | Java | src/main/java/com/google/teampot/model/TaskActivityEventVerb.java | andryfailli/teampot | 18992bfc2aa264a9034143acf36e6374e2665012 | [
"Apache-2.0"
] | 4 | 2015-01-27T17:43:11.000Z | 2020-01-29T02:54:11.000Z | src/main/java/com/google/teampot/model/TaskActivityEventVerb.java | andryfailli/teampot | 18992bfc2aa264a9034143acf36e6374e2665012 | [
"Apache-2.0"
] | 1 | 2017-01-13T20:57:28.000Z | 2017-02-22T18:22:51.000Z | src/main/java/com/google/teampot/model/TaskActivityEventVerb.java | andryfailli/teampot | 18992bfc2aa264a9034143acf36e6374e2665012 | [
"Apache-2.0"
] | 1 | 2020-06-17T16:36:29.000Z | 2020-06-17T16:36:29.000Z | 19.666667 | 44 | 0.822034 | 997,718 | package com.google.teampot.model;
public enum TaskActivityEventVerb {
CREATE,EDIT,DELETE,ASSIGN,UNASSIGN,COMPLETE
}
|
923689a2142ae0bb75179643ed6cde365db03c16 | 3,271 | java | Java | helper/impls/helper-impl-110/src/main/java/com/linkedin/avroutil1/compatibility/avro110/FieldBuilder110.java | Lincong/avro-util | b7688c4dff8b6e62939e98b1b477cd88b28c0e38 | [
"BSD-2-Clause"
] | 60 | 2019-04-14T11:45:14.000Z | 2022-03-31T16:46:30.000Z | helper/impls/helper-impl-110/src/main/java/com/linkedin/avroutil1/compatibility/avro110/FieldBuilder110.java | Lincong/avro-util | b7688c4dff8b6e62939e98b1b477cd88b28c0e38 | [
"BSD-2-Clause"
] | 214 | 2019-04-01T04:45:45.000Z | 2022-03-30T17:35:57.000Z | helper/impls/helper-impl-110/src/main/java/com/linkedin/avroutil1/compatibility/avro110/FieldBuilder110.java | Lincong/avro-util | b7688c4dff8b6e62939e98b1b477cd88b28c0e38 | [
"BSD-2-Clause"
] | 59 | 2019-03-15T22:30:19.000Z | 2022-03-09T20:33:28.000Z | 29.736364 | 130 | 0.685112 | 997,719 | /*
* Copyright 2020 LinkedIn Corp.
* Licensed under the BSD 2-Clause License (the "License").
* See License in the project root for license information.
*/
package com.linkedin.avroutil1.compatibility.avro110;
import com.linkedin.avroutil1.compatibility.AvroSchemaUtil;
import com.linkedin.avroutil1.compatibility.FieldBuilder;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field.Order;
import java.util.Map;
public class FieldBuilder110 implements FieldBuilder {
private String _name;
private Schema _schema;
private String _doc;
private Object _defaultVal;
private Order _order;
private Map<String, Object> _props;
public FieldBuilder110(Schema.Field other) {
if (other != null) {
_name = other.name();
_schema = other.schema();
_doc = other.doc();
_defaultVal = other.defaultVal();
_order = other.order();
_props = other.getObjectProps();
}
}
@Override
public FieldBuilder setName(String name) {
_name = name;
return this;
}
@Override
public FieldBuilder setSchema(Schema schema) {
_schema = schema;
if (_defaultVal == Schema.Field.NULL_DEFAULT_VALUE) {
// Check if null is still a valid default for the schema.
setDefault(null);
}
return this;
}
@Override
public FieldBuilder setDoc(String doc) {
_doc = doc;
return this;
}
@Override
public FieldBuilder setDefault(Object defaultValue) {
// If defaultValue is null, it's ambiguous. It could mean either of these:
// (1) The default value was not specified, or
// (2) The default value was specified to be null.
//
// To disambiguate, we check to see if null is a valid value for the
// field's schema. If it is, we convert it into a special object (marker)
// that's known to Avro. If it's not, it's case (1); we leave it as is.
//
// This means there's no way (using the helper) to create a field whose
// schema allows null as a default, but you want to say "no default was
// specified". That's a small price to pay for not bloating the helper API.
//
// Note that we don't validate all possible default values against the
// schema. That's Avro's job. We only check for the ambiguous case here.
if (defaultValue == null && AvroSchemaUtil.isNullAValidDefaultForSchema(_schema)) {
defaultValue = Schema.Field.NULL_DEFAULT_VALUE;
}
_defaultVal = defaultValue;
return this;
}
@Override
public FieldBuilder setOrder(Order order) {
_order = order;
return this;
}
@Override
@Deprecated
public FieldBuilder copyFromField() {
return this;
}
@Override
public Schema.Field build() {
Object avroFriendlyDefault;
try {
avroFriendlyDefault = AvroSchemaUtil.avroFriendlyDefaultValue(_defaultVal);
} catch (Exception e) {
throw new IllegalArgumentException("unable to convert default value " + _defaultVal + " into something avro can handle", e);
}
Schema.Field result = new Schema.Field(_name, _schema, _doc, avroFriendlyDefault, _order);
if (_props != null) {
for (Map.Entry<String, Object> entry : _props.entrySet()) {
result.addProp(entry.getKey(), entry.getValue());
}
}
return result;
}
}
|
92368aa83e99b4be99fa40beeb9cc6a83d89dc4c | 638 | java | Java | enterprise/j2ee.ejbcore/test/unit/data/golden/ProductTblLocalHome.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | enterprise/j2ee.ejbcore/test/unit/data/golden/ProductTblLocalHome.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | enterprise/j2ee.ejbcore/test/unit/data/golden/ProductTblLocalHome.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 39.875 | 342 | 0.805643 | 997,720 |
package testPackage;
/**
* This is the local-home interface for ProductTbl enterprise bean.
*/
public interface ProductTblLocalHome extends javax.ejb.EJBLocalHome {
testPackage.ProductTblLocal findByPrimaryKey(java.lang.Integer key) throws javax.ejb.FinderException;
public testPackage.ProductTblLocal create(java.lang.Integer productNum, java.math.BigDecimal purchaseCost, java.lang.Integer qtyOnHand, java.math.BigDecimal markup, java.lang.Boolean avail, java.lang.String description, testPackage.ManufactureTblLocal mfrNum, testPackage.ProductCodeTblLocal productCode) throws javax.ejb.CreateException;
}
|
92368af60285aad769e8f3ee3d2f9fd2ff8b9d86 | 963 | java | Java | Plugins/Aspose_Cells_for_Apache_POI/Aspose-Cells-for-Apache-POI/src/featurescomparison/workingwithcellsrowscolumns/hideunhidecells/java/AsposeHideUnHideCells.java | Aspose/Aspose.Cells-for-Java | e2d4f31315723aa8ff305e5515016b700f1605b7 | [
"MIT"
] | 1 | 2021-03-15T03:38:02.000Z | 2021-03-15T03:38:02.000Z | Aspose.Cells vs ApachePOI SS/src/featurescomparison/workingwithcellsrowscolumns/hideunhidecells/java/AsposeHideUnHideCells.java | KadriyeAksakal/Aspose_for_Apache_POI | bac2bfe123d699f729a4415a80c9e8bbbb53a829 | [
"MIT"
] | null | null | null | Aspose.Cells vs ApachePOI SS/src/featurescomparison/workingwithcellsrowscolumns/hideunhidecells/java/AsposeHideUnHideCells.java | KadriyeAksakal/Aspose_for_Apache_POI | bac2bfe123d699f729a4415a80c9e8bbbb53a829 | [
"MIT"
] | 2 | 2017-01-16T10:04:13.000Z | 2021-04-26T15:30:26.000Z | 32.1 | 95 | 0.74974 | 997,721 | package featurescomparison.workingwithcellsrowscolumns.hideunhidecells.java;
import com.aspose.cells.Cells;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
public class AsposeHideUnHideCells
{
public static void main(String[] args) throws Exception
{
String dataPath = "src/featurescomparison/workingwithcellsrowscolumns/hideunhidecells/data/";
Workbook workbook = new Workbook(dataPath + "workbook.xls");
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.getWorksheets().get(0);
Cells cells = worksheet.getCells();
cells.hideRow(2); //Hiding the 3rd row of the worksheet
cells.hideColumn(1); //Hiding the 2nd column of the worksheet
//Saving the modified Excel file in default (that is Excel 2003) format
workbook.save(dataPath + "hideUnhideCells_Aspose_Out.xls");
//Print message
System.out.println("Rows and Columns hidden successfully.");
}
}
|
92368b8c09a1d59db4bcf1231d7be22e8fbde855 | 5,543 | java | Java | components/org.wso2.carbon.identity.application.authenticator.oidc/src/main/java/org/wso2/carbon/identity/application/authenticator/oidc/OIDCAuthenticatorConstants.java | IsankaSR/identity-outbound-auth-oidc | bfde44e4aefdd7fe2d24c8fb7543dc376c5b3e85 | [
"Apache-2.0"
] | 3 | 2016-09-07T06:12:17.000Z | 2020-10-27T14:14:08.000Z | components/org.wso2.carbon.identity.application.authenticator.oidc/src/main/java/org/wso2/carbon/identity/application/authenticator/oidc/OIDCAuthenticatorConstants.java | IsankaSR/identity-outbound-auth-oidc | bfde44e4aefdd7fe2d24c8fb7543dc376c5b3e85 | [
"Apache-2.0"
] | 35 | 2018-01-05T14:42:56.000Z | 2022-03-11T08:56:46.000Z | components/org.wso2.carbon.identity.application.authenticator.oidc/src/main/java/org/wso2/carbon/identity/application/authenticator/oidc/OIDCAuthenticatorConstants.java | IsankaSR/identity-outbound-auth-oidc | bfde44e4aefdd7fe2d24c8fb7543dc376c5b3e85 | [
"Apache-2.0"
] | 70 | 2016-03-02T07:02:15.000Z | 2022-03-15T04:25:52.000Z | 40.166667 | 120 | 0.709724 | 997,722 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.application.authenticator.oidc;
import java.util.regex.Pattern;
public class OIDCAuthenticatorConstants {
private OIDCAuthenticatorConstants() {
}
public static final String AUTHENTICATOR_NAME = "OpenIDConnectAuthenticator";
public static final String AUTHENTICATOR_FRIENDLY_NAME = "openidconnect";
public static final String LOGIN_TYPE = "OIDC";
public static final String OAUTH_OIDC_SCOPE = "openid";
public static final String OAUTH2_GRANT_TYPE_CODE = "code";
public static final String OAUTH2_PARAM_STATE = "state";
public static final String OAUTH2_ERROR = "error";
public static final String REDIRECT_URI = "redirect_uri";
public static final String ACCESS_TOKEN = "access_token";
public static final String ID_TOKEN = "id_token";
public static final String CLIENT_ID = "ClientId";
public static final String CLIENT_SECRET = "ClientSecret";
public static final String OAUTH2_AUTHZ_URL = "OAuth2AuthzEPUrl";
public static final String OAUTH2_TOKEN_URL = "OAuth2TokenEPUrl";
public static final String IS_BASIC_AUTH_ENABLED = "IsBasicAuthEnabled";
public static final String OIDC_QUERY_PARAM_MAP_PROPERTY_KEY = "oidc:param.map";
public static final String HTTP_ORIGIN_HEADER = "Origin";
public static final String POST_LOGOUT_REDIRECT_URI = "post_logout_redirect_uri";
public static final String ID_TOKEN_HINT = "id_token_hint";
public static final String AUTH_PARAM = "$authparam";
public static final String DYNAMIC_AUTH_PARAMS_LOOKUP_REGEX = "\\$authparam\\{(\\w+)\\}";
public static final String LOGOUT_TOKEN = "logout_token";
public static final Pattern OIDC_BACKCHANNEL_LOGOUT_ENDPOINT_URL_PATTERN = Pattern.compile("(.*)/identity/oidc" +
"/slo(.*)");
public class AuthenticatorConfParams {
private AuthenticatorConfParams() {
}
public static final String DEFAULT_IDP_CONFIG = "DefaultIdPConfig";
}
public class IdPConfParams {
private IdPConfParams() {
}
public static final String CLIENT_ID = "ClientId";
public static final String CLIENT_SECRET = "ClientSecret";
public static final String AUTHORIZATION_EP = "AuthorizationEndPoint";
public static final String TOKEN_EP = "TokenEndPoint";
public static final String OIDC_LOGOUT_URL = "OIDCLogoutEPUrl";
public static final String USER_INFO_EP = "UserInfoEndPoint";
}
public class Claim {
private Claim() {
}
public static final String SUB = "sub";
public static final String NAME = "name";
public static final String GIVEN_NAME = "given_name";
public static final String FAMILY_NAME = "family_name";
public static final String MIDDLE_NAME = "middle_name";
public static final String NICK_NAME = "nickname";
public static final String PREFERED_USERNAME = "preferred_username";
public static final String PROFILE = "profile";
public static final String PICTURE = "picture";
public static final String WEBSITE = "website";
public static final String EMAIL = "email";
public static final String EMAIL_VERIFIED = "email_verified";
public static final String GENDER = "gender";
public static final String BIRTH_DATE = "birthdate";
public static final String ZONE_INFO = "zoneinfo";
public static final String LOCALE = "locale";
public static final String PHONE_NUMBER = "phone_number";
public static final String PHONE_NUMBER_VERIFIED = "phone_number_verified";
public static final String ADDRESS = "address";
public static final String UPDATED_AT = "updated_at";
// Logout token claims.
public static final String SID = "sid";
public static final String NONCE = "nonce";
public static final String EVENTS = "events";
public static final String BACKCHANNEL_LOGOUT_EVENT = "http://schemas.openid.net/event/backchannel-logout";
public static final String BACKCHANNEL_LOGOUT_EVENT_CLAIM = "{}";
}
public class BackchannelLogout {
private BackchannelLogout() {
}
public static final String DEFAULT_IDP_NAME = "default";
public static final String OIDC_IDP_ENTITY_ID = "IdPEntityId";
public static final String ENABLE_IAT_VALIDATION = "enableIatValidation";
public static final String IAT_VALIDITY_PERIOD = "iatValidityPeriod";
public static final String LOGOUT_SUCCESS = "OIDC back-channel logout success.";
public static final String LOGOUT_FAILURE_SERVER_ERROR = "OIDC Back-channel logout failed due to an internal " +
"server error.";
public static final long DEFAULT_IAT_VALIDITY_PERIOD = 15000;
}
}
|
92368beb1cacc7f5791e2e1784d64f207c5cbaae | 2,523 | java | Java | android/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java | macintoshhelper/expo | 162a8054bae5dc45d36921e3a1505242278eed1a | [
"Apache-2.0",
"MIT"
] | 456 | 2020-09-07T05:26:22.000Z | 2022-03-29T06:43:13.000Z | android/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java | macintoshhelper/expo | 162a8054bae5dc45d36921e3a1505242278eed1a | [
"Apache-2.0",
"MIT"
] | 23 | 2021-01-03T07:48:10.000Z | 2022-03-29T11:42:12.000Z | android/ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevSupportManager.java | macintoshhelper/expo | 162a8054bae5dc45d36921e3a1505242278eed1a | [
"Apache-2.0",
"MIT"
] | 228 | 2020-10-07T17:15:26.000Z | 2022-03-25T18:09:28.000Z | 26.557895 | 97 | 0.80222 | 997,723 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.devsupport.interfaces;
import android.view.View;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.NativeModuleCallExceptionHandler;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.modules.debug.interfaces.DeveloperSettings;
import java.io.File;
/**
* Interface for accessing and interacting with development features. In dev mode, use the
* implementation {@link DevSupportManagerImpl}. In production mode, use the dummy implementation
* {@link DisabledDevSupportManager}.
*/
public interface DevSupportManager extends NativeModuleCallExceptionHandler {
void showNewJavaError(String message, Throwable e);
void addCustomDevOption(String optionName, DevOptionHandler optionHandler);
@Nullable
View createRootView(String appKey);
void destroyRootView(View rootView);
void showNewJSError(String message, ReadableArray details, int errorCookie);
void updateJSError(final String message, final ReadableArray details, final int errorCookie);
void hideRedboxDialog();
void showDevOptionsDialog();
void setDevSupportEnabled(boolean isDevSupportEnabled);
void startInspector();
void stopInspector();
boolean getDevSupportEnabled();
DeveloperSettings getDevSettings();
void onNewReactContextCreated(ReactContext reactContext);
void onReactInstanceDestroyed(ReactContext reactContext);
String getSourceMapUrl();
String getSourceUrl();
String getJSBundleURLForRemoteDebugging();
String getDownloadedJSBundleFile();
boolean hasUpToDateJSBundleInCache();
void reloadSettings();
void handleReloadJS();
void reloadExpoApp();
void reloadJSFromServer(final String bundleURL);
void isPackagerRunning(PackagerStatusCallback callback);
void setHotModuleReplacementEnabled(final boolean isHotModuleReplacementEnabled);
void setRemoteJSDebugEnabled(final boolean isRemoteJSDebugEnabled);
void setFpsDebugEnabled(final boolean isFpsDebugEnabled);
void toggleElementInspector();
@Nullable
File downloadBundleResourceFromUrlSync(final String resourceURL, final File outputFile);
@Nullable
String getLastErrorTitle();
@Nullable
StackFrame[] getLastErrorStack();
void registerErrorCustomizer(ErrorCustomizer errorCustomizer);
}
|
92368bede325ce9896e07d0058adfdf1ccc60b33 | 662 | java | Java | jaxrs-service/src/test/java/com/quorum/tessera/api/exception/DefaultExceptionMapperTest.java | vdamle/tessera | 64c40d1aeffe3a6d914e2fbe70ee744447007c55 | [
"Apache-2.0"
] | 2 | 2019-03-03T07:53:51.000Z | 2019-06-27T12:06:51.000Z | jaxrs-service/src/test/java/com/quorum/tessera/api/exception/DefaultExceptionMapperTest.java | vdamle/tessera | 64c40d1aeffe3a6d914e2fbe70ee744447007c55 | [
"Apache-2.0"
] | null | null | null | jaxrs-service/src/test/java/com/quorum/tessera/api/exception/DefaultExceptionMapperTest.java | vdamle/tessera | 64c40d1aeffe3a6d914e2fbe70ee744447007c55 | [
"Apache-2.0"
] | null | null | null | 22.827586 | 75 | 0.70997 | 997,724 |
package com.quorum.tessera.api.exception;
import org.junit.Test;
import javax.ws.rs.core.Response;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultExceptionMapperTest {
private DefaultExceptionMapper instance = new DefaultExceptionMapper();
@Test
public void toResponse() {
final String message = "OUCH That's gotta smart!!";
Exception exception = new Exception(message);
Response result = instance.toResponse(exception);
assertThat(result).isNotNull();
assertThat(result.getStatus()).isEqualTo(500);
assertThat(result.getEntity()).isEqualTo(message);
}
}
|
92368cda7c64b9039945f6c1d0512932e04dedfe | 1,962 | java | Java | src/authoring/factories/ElementFactory.java | cndracos/voogasalad_oneclassonemethod | a431184a7f094c6dc18a7ef8b5e3b0edd9c5de95 | [
"MIT"
] | null | null | null | src/authoring/factories/ElementFactory.java | cndracos/voogasalad_oneclassonemethod | a431184a7f094c6dc18a7ef8b5e3b0edd9c5de95 | [
"MIT"
] | null | null | null | src/authoring/factories/ElementFactory.java | cndracos/voogasalad_oneclassonemethod | a431184a7f094c6dc18a7ef8b5e3b0edd9c5de95 | [
"MIT"
] | null | null | null | 38.470588 | 117 | 0.758919 | 997,725 | package authoring.factories;
import java.util.function.Consumer;
/**
* Factory class that is used to build a frontend element that is defined in this package. Example
* elements include buttons and menuitems. A new frontend element can be added by adding a new field
* to either the Enum ElementType or the Enum ClickElementType.
* @author Hemanth Yakkali(hy115)
*/
public class ElementFactory {
private final static String PACKAGE_NAME = "authoring.factories.";
private final static String ELEMENT = "Element";
/**
* Empty constructor, makes it easier to be instantiated anywhere in the project
*/
public ElementFactory() {}
/**
* Builds a non-clickable element of a specified type and contains the specified text.
* @param elementName Type of Element to be created
* @param text {@code String} text to be placed in the new Element
* @return Desired element
* @throws Exception
*/
public Element buildElement(ElementType elementName, String text) throws Exception {
String builderName = PACKAGE_NAME+elementName+ELEMENT;
Class<?> elementClass = Class.forName(builderName);
return (Element) elementClass.getConstructor(text.getClass()).newInstance(text);
}
/**
* Builds a clickable element of a particular type containing a specific action and text.
* @param elementName Type of Element to be created
* @param text {@code String} text to be placed in the new Element
* @param event {@code Consumer} event that the element will perform on action
* @return Desired clickable element
* @throws Exception
*/
public Element buildClickElement(ClickElementType elementName, String text, Consumer<Void> event) throws Exception {
String builderName = PACKAGE_NAME+elementName+ELEMENT;
Class<?> elementClass = Class.forName(builderName);
ClickableElement element = (ClickableElement) elementClass.getConstructor(text.getClass()).newInstance(text);
element.handleConsumer(event);
return element;
}
}
|
92368d1b3cd6013ef11bd743938f70a34aa5071d | 1,954 | java | Java | javacord-core/src/main/java/org/javacord/core/event/server/ServerChangeDefaultMessageNotificationLevelEventImpl.java | dylhack/Javacord | f825905377ee30f8614190aef55da0e6b629da7f | [
"Apache-2.0"
] | 474 | 2018-07-05T13:13:14.000Z | 2022-03-30T01:14:31.000Z | javacord-core/src/main/java/org/javacord/core/event/server/ServerChangeDefaultMessageNotificationLevelEventImpl.java | MusaBrt/Javacord | f784bc71dcad1e4626817ea7e9f93652d196cb80 | [
"Apache-2.0"
] | 446 | 2018-07-08T15:32:08.000Z | 2022-03-30T10:13:41.000Z | javacord-core/src/main/java/org/javacord/core/event/server/ServerChangeDefaultMessageNotificationLevelEventImpl.java | MusaBrt/Javacord | f784bc71dcad1e4626817ea7e9f93652d196cb80 | [
"Apache-2.0"
] | 168 | 2018-07-08T14:52:49.000Z | 2022-03-31T08:06:04.000Z | 39.877551 | 106 | 0.787615 | 997,726 | package org.javacord.core.event.server;
import org.javacord.api.entity.server.DefaultMessageNotificationLevel;
import org.javacord.api.entity.server.Server;
import org.javacord.api.event.server.ServerChangeDefaultMessageNotificationLevelEvent;
/**
* The implementation of {@link ServerChangeDefaultMessageNotificationLevelEvent}.
*/
public class ServerChangeDefaultMessageNotificationLevelEventImpl extends ServerEventImpl
implements ServerChangeDefaultMessageNotificationLevelEvent {
/**
* The new default message notification level of the server.
*/
private final DefaultMessageNotificationLevel newDefaultMessageNotificationLevel;
/**
* The old default message notification level of the server.
*/
private final DefaultMessageNotificationLevel oldDefaultMessageNotificationLevel;
/**
* Creates a new server change default message notification level event.
*
* @param server The server of the event.
* @param newDefaultMessageNotificationLevel The new default message notification level of the server.
* @param oldDefaultMessageNotificationLevel The old default message notification level of the server.
*/
public ServerChangeDefaultMessageNotificationLevelEventImpl(
Server server, DefaultMessageNotificationLevel newDefaultMessageNotificationLevel,
DefaultMessageNotificationLevel oldDefaultMessageNotificationLevel) {
super(server);
this.newDefaultMessageNotificationLevel = newDefaultMessageNotificationLevel;
this.oldDefaultMessageNotificationLevel = oldDefaultMessageNotificationLevel;
}
@Override
public DefaultMessageNotificationLevel getOldDefaultMessageNotificationLevel() {
return oldDefaultMessageNotificationLevel;
}
@Override
public DefaultMessageNotificationLevel getNewDefaultMessageNotificationLevel() {
return newDefaultMessageNotificationLevel;
}
}
|
92368d408a6261ec8ea3b81bc77f3d68b4f90634 | 481 | java | Java | PeepholeBenchmarks/bench05/DungeonGenerator.java | GuillaumeLam/COMP520-Peephole-g4 | 339deb47d4f6cd66a418710f4ce2e058d6cf3ae5 | [
"BSD-3-Clause"
] | 1 | 2018-04-23T19:41:40.000Z | 2018-04-23T19:41:40.000Z | PeepholeBenchmarks/bench05/DungeonGenerator.java | GuillaumeLam/COMP520-Peephole-g4 | 339deb47d4f6cd66a418710f4ce2e058d6cf3ae5 | [
"BSD-3-Clause"
] | 9 | 2019-03-24T23:04:07.000Z | 2019-04-13T21:50:53.000Z | PeepholeBenchmarks/bench05/DungeonGenerator.java | GuillaumeLam/COMP520-Peephole-g4 | 339deb47d4f6cd66a418710f4ce2e058d6cf3ae5 | [
"BSD-3-Clause"
] | 1 | 2017-10-02T15:44:15.000Z | 2017-10-02T15:44:15.000Z | 15.516129 | 44 | 0.569647 | 997,727 | /*
A really simple dungeon generator
By Jodi & Kevin.
McGill 2011.
*/
import joos.lib.*;
public class DungeonGenerator {
public DungeonGenerator() {
super();
}
public static void main(String[] args) {
DungeonInfos infos;
Dungeon dungeon;
JoosIO io;
infos = new DungeonInfos();
infos.initializeFromStdIn();
dungeon = new Dungeon(infos);
io = new JoosIO();
dungeon.draw();
}
}
|
92368de3e0a8412062124bc6f43a99870e73751f | 83 | java | Java | src/main/java/io/tripled/cashlesspay/model/event/AccountToppedUpEvent.java | domenique/cashlesspay | e0f78a106013a85bb5cddf4f07f1e01acdb88414 | [
"MIT"
] | null | null | null | src/main/java/io/tripled/cashlesspay/model/event/AccountToppedUpEvent.java | domenique/cashlesspay | e0f78a106013a85bb5cddf4f07f1e01acdb88414 | [
"MIT"
] | null | null | null | src/main/java/io/tripled/cashlesspay/model/event/AccountToppedUpEvent.java | domenique/cashlesspay | e0f78a106013a85bb5cddf4f07f1e01acdb88414 | [
"MIT"
] | null | null | null | 16.6 | 43 | 0.819277 | 997,728 | package io.tripled.cashlesspay.model.event;
public class AccountToppedUpEvent {
}
|
92368e6a0b6dae01dee01228216c6d18341c55f3 | 3,590 | java | Java | ExtractedJars/iRobot_com.irobot.home/javafiles/com/irobot/home/MapCustomizationActivity$25.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 3 | 2019-05-01T09:22:08.000Z | 2019-07-06T22:21:59.000Z | ExtractedJars/iRobot_com.irobot.home/javafiles/com/irobot/home/MapCustomizationActivity$25.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | null | null | null | ExtractedJars/iRobot_com.irobot.home/javafiles/com/irobot/home/MapCustomizationActivity$25.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 1 | 2020-11-26T12:22:02.000Z | 2020-11-26T12:22:02.000Z | 42.738095 | 119 | 0.64039 | 997,729 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.irobot.home;
import android.content.DialogInterface;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.irobot.core.*;
// Referenced classes of package com.irobot.home:
// MapCustomizationActivity
class MapCustomizationActivity$25
implements android.content.ner
{
public void onClick(DialogInterface dialoginterface, int i)
{
dialoginterface = ((DialogInterface) (MapsUIServiceData.create()));
// 0 0:invokestatic #36 <Method MapsUIServiceData MapsUIServiceData.create()>
// 1 3:astore_1
((MapsUIServiceData) (dialoginterface)).setNewMapName(((Object) (a.getText())).toString());
// 2 4:aload_1
// 3 5:aload_0
// 4 6:getfield #23 <Field EditText a>
// 5 9:invokevirtual #42 <Method android.text.Editable EditText.getText()>
// 6 12:invokevirtual #46 <Method String Object.toString()>
// 7 15:invokevirtual #50 <Method void MapsUIServiceData.setNewMapName(String)>
MapCustomizationActivity.e(c).sendCommand(MapsUIServiceCommand.NewMapName, ((MapsUIServiceData) (dialoginterface)));
// 8 18:aload_0
// 9 19:getfield #21 <Field MapCustomizationActivity c>
// 10 22:invokestatic #54 <Method MapsUIService MapCustomizationActivity.e(MapCustomizationActivity)>
// 11 25:getstatic #60 <Field MapsUIServiceCommand MapsUIServiceCommand.NewMapName>
// 12 28:aload_1
// 13 29:invokevirtual #66 <Method void MapsUIService.sendCommand(MapsUIServiceCommand, MapsUIServiceData)>
dialoginterface = ((DialogInterface) ((InputMethodManager)c.getSystemService("input_method")));
// 14 32:aload_0
// 15 33:getfield #21 <Field MapCustomizationActivity c>
// 16 36:ldc1 #68 <String "input_method">
// 17 38:invokevirtual #72 <Method Object MapCustomizationActivity.getSystemService(String)>
// 18 41:checkcast #74 <Class InputMethodManager>
// 19 44:astore_1
if(dialoginterface != null)
//* 20 45:aload_1
//* 21 46:ifnull 62
((InputMethodManager) (dialoginterface)).hideSoftInputFromWindow(b.getWindowToken(), 2);
// 22 49:aload_1
// 23 50:aload_0
// 24 51:getfield #25 <Field View b>
// 25 54:invokevirtual #80 <Method android.os.IBinder View.getWindowToken()>
// 26 57:iconst_2
// 27 58:invokevirtual #84 <Method boolean InputMethodManager.hideSoftInputFromWindow(android.os.IBinder, int)>
// 28 61:pop
// 29 62:return
}
final EditText a;
final View b;
final MapCustomizationActivity c;
MapCustomizationActivity$25(MapCustomizationActivity mapcustomizationactivity, EditText edittext, View view)
{
c = mapcustomizationactivity;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #21 <Field MapCustomizationActivity c>
a = edittext;
// 3 5:aload_0
// 4 6:aload_2
// 5 7:putfield #23 <Field EditText a>
b = view;
// 6 10:aload_0
// 7 11:aload_3
// 8 12:putfield #25 <Field View b>
super();
// 9 15:aload_0
// 10 16:invokespecial #27 <Method void Object()>
// 11 19:return
}
}
|
92368e72bf2d61f7fcc4eba7a089e6efad5b3986 | 1,018 | java | Java | lengwj-myrpc/src/main/java/com/atlwj/framework/ProxyFactory.java | lengweijian/dubbo | d3d3c6f212698c2f168156e2d2c926574f6f816b | [
"Apache-2.0"
] | 3 | 2019-09-03T09:45:31.000Z | 2019-09-19T03:10:09.000Z | lengwj-myrpc/src/main/java/com/atlwj/framework/ProxyFactory.java | lengweijian/dubbo | d3d3c6f212698c2f168156e2d2c926574f6f816b | [
"Apache-2.0"
] | null | null | null | lengwj-myrpc/src/main/java/com/atlwj/framework/ProxyFactory.java | lengweijian/dubbo | d3d3c6f212698c2f168156e2d2c926574f6f816b | [
"Apache-2.0"
] | null | null | null | 37.703704 | 134 | 0.687623 | 997,730 | package com.atlwj.framework;
import com.atlwj.provider.api.HelloService;
import com.atlwj.provider.register.RemoteMapRegister;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
public class ProxyFactory {
public static <T> T getProxy(Class interfaceName){
return (T)Proxy.newProxyInstance(interfaceName.getClassLoader(), new Class[]{interfaceName}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Protocol protocol = ProtocolFactory.getProtocol();
Invocation invocation = new Invocation(HelloService.class.getName(),method.getName(),method.getParameterTypes(),args);
List<Url> urls = RemoteMapRegister.get(interfaceName.getName());
Url url = MyLoadbalance.random(urls);
return protocol.send(url, invocation);
}
});
}
}
|
92368f31e1de8a34e377eba54c3cdace88debcd8 | 20,803 | java | Java | wear/src/main/java/com/example/android/sunshine/MyWatchFace.java | fawazeez/Ubiquitous | 42a20608fd0ca1d3782a3a0175d2b49a91dd38a4 | [
"Apache-2.0"
] | null | null | null | wear/src/main/java/com/example/android/sunshine/MyWatchFace.java | fawazeez/Ubiquitous | 42a20608fd0ca1d3782a3a0175d2b49a91dd38a4 | [
"Apache-2.0"
] | null | null | null | wear/src/main/java/com/example/android/sunshine/MyWatchFace.java | fawazeez/Ubiquitous | 42a20608fd0ca1d3782a3a0175d2b49a91dd38a4 | [
"Apache-2.0"
] | null | null | null | 41.275794 | 206 | 0.601211 | 997,731 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.WindowInsets;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import java.lang.ref.WeakReference;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* Digital watch face with seconds. In ambient mode, the seconds aren't displayed. On devices with
* low-bit ambient mode, the text is drawn without anti-aliasing in ambient mode.
*/
public class MyWatchFace extends CanvasWatchFaceService {
private static final String TAG = "MyWatchFace";
private static final Typeface BOLD_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
private static final Typeface NORMAL_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
/**
* Update rate in milliseconds for interactive mode. We update once a second since seconds are
* displayed in interactive mode.
*/
private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);
/**
* Handler message id for updating the time periodically in interactive mode.
*/
private static final int MSG_UPDATE_TIME = 0;
public static int getIconResourceForWeatherCondition(int weatherId) {
// Based on weather code data found at:
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
if (weatherId >= 200 && weatherId <= 232) {
return R.drawable.ic_storm;
} else if (weatherId >= 300 && weatherId <= 321) {
return R.drawable.ic_light_rain;
} else if (weatherId >= 500 && weatherId <= 504) {
return R.drawable.ic_rain;
} else if (weatherId == 511) {
return R.drawable.ic_snow;
} else if (weatherId >= 520 && weatherId <= 531) {
return R.drawable.ic_rain;
} else if (weatherId >= 600 && weatherId <= 622) {
return R.drawable.ic_snow;
} else if (weatherId >= 701 && weatherId <= 761) {
return R.drawable.ic_fog;
} else if (weatherId == 761 || weatherId == 781) {
return R.drawable.ic_storm;
} else if (weatherId == 800) {
return R.drawable.ic_clear;
} else if (weatherId == 801) {
return R.drawable.ic_light_clouds;
} else if (weatherId >= 802 && weatherId <= 804) {
return R.drawable.ic_cloudy;
}
return -1;
}
@Override
public Engine onCreateEngine() {
return new Engine();
}
private static class EngineHandler extends Handler {
private final WeakReference<MyWatchFace.Engine> mWeakReference;
public EngineHandler(MyWatchFace.Engine reference) {
mWeakReference = new WeakReference<>(reference);
}
@Override
public void handleMessage(Message msg) {
MyWatchFace.Engine engine = mWeakReference.get();
if (engine != null) {
switch (msg.what) {
case MSG_UPDATE_TIME:
engine.handleUpdateTimeMessage();
break;
}
}
}
}
private class Engine extends CanvasWatchFaceService.Engine implements DataApi.DataListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String PATH_WEATHER = "/weather";
private static final String KEY_HIGH = "high_temp";
private static final String KEY_LOW = "low_temp";
private static final String KEY_ID = "weather_id";
private String mHighTemp;
private String mLowTemp;
private int mWeatherId;
private GoogleApiClient mGoogleApiClient;
final Handler mUpdateTimeHandler = new EngineHandler(this);
boolean mRegisteredTimeZoneReceiver = false;
Paint mBackgroundPaint;
Paint mTimeTextPaint;
Paint mTempLowTextPaint;
Paint mTempHighTextPaint;
Paint mDateTextPaint;
boolean mAmbient;
Calendar mCalendar;
final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mCalendar.setTimeZone(TimeZone.getDefault());
invalidate();
}
};
float mXOffset;
float mTimeXOffset;
float mTimeYOffset;
float mYOffset;
float mDateYOffset;
float mDateXOffset;
float mLineYOffset;
float mTempYOffset;
float mHighXOffset;
float mLowXOffset;
float mWeatherYOffset;
/**
* Whether the display supports fewer bits for each color in ambient mode. When true, we
* disable anti-aliasing in ambient mode.
*/
boolean mLowBitAmbient;
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFace.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.setAcceptsTapEvents(true)
.build());
mGoogleApiClient = new GoogleApiClient.Builder(MyWatchFace.this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wearable.API)
.build();
Resources resources = MyWatchFace.this.getResources();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
mLineYOffset = resources.getDimension(R.dimen.line_y_offset);
mWeatherYOffset = resources.getDimension(R.dimen.weather_y_offset);
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(ContextCompat.getColor(getApplicationContext(), R.color.primary));
mTimeTextPaint = new Paint();
mTimeTextPaint = createTimeTextPaint(ContextCompat.getColor(getApplicationContext(), R.color.digital_text));
mDateTextPaint = new Paint();
mDateTextPaint = createDateTextPaint();
mTempLowTextPaint = new Paint();
mTempLowTextPaint = createTempTextPaint(ContextCompat.getColor(getApplicationContext(),R.color.primary_light));
mTempLowTextPaint.setTypeface(NORMAL_TYPEFACE);
mTempHighTextPaint = new Paint();
mTempHighTextPaint = createTempTextPaint(ContextCompat.getColor(getApplicationContext(),R.color.digital_text));
mTempHighTextPaint.setTypeface(BOLD_TYPEFACE);
mCalendar = Calendar.getInstance();
}
@Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
super.onDestroy();
}
private Paint createTimeTextPaint(int textColor) {
Paint paint = new Paint();
paint.setColor(textColor);
paint.setTypeface(NORMAL_TYPEFACE);
paint.setAntiAlias(true);
return paint;
}
private Paint createDateTextPaint() {
Paint paint = new Paint();
paint.setTypeface(BOLD_TYPEFACE);
paint.setAntiAlias(true);
paint.setTextSize(getResources().getDimension(R.dimen.date_text_size));
return paint;
}
private Paint createTempTextPaint(int textColor) {
Paint paint = new Paint();
paint.setColor(textColor);
paint.setAntiAlias(true);
paint.setTextSize(getResources().getDimension(R.dimen.temp_text_size));
return paint;
}
@Override
public void onVisibilityChanged(boolean visible) {
// if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onVisibilityChanged: " + visible);
// }
super.onVisibilityChanged(visible);
if (visible) {
mGoogleApiClient.connect();
registerReceiver();
// Update time zone in case it changed while we weren't visible.
mCalendar.setTimeZone(TimeZone.getDefault());
invalidate();
} else {
unregisterReceiver();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Wearable.DataApi.removeListener(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
private void registerReceiver() {
if (mRegisteredTimeZoneReceiver) {
return;
}
mRegisteredTimeZoneReceiver = true;
IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
MyWatchFace.this.registerReceiver(mTimeZoneReceiver, filter);
}
private void unregisterReceiver() {
if (!mRegisteredTimeZoneReceiver) {
return;
}
mRegisteredTimeZoneReceiver = false;
MyWatchFace.this.unregisterReceiver(mTimeZoneReceiver);
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
// Load resources that have alternate values for round watches.
Resources resources = MyWatchFace.this.getResources();
boolean isRound = insets.isRound();
mXOffset = resources.getDimension(isRound
? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset);
float textSize = resources.getDimension(isRound
? R.dimen.digital_text_size_round : R.dimen.digital_text_size);
mTimeTextPaint.setTextSize(textSize);
}
@Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
}
@Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
@Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (mAmbient != inAmbientMode) {
mAmbient = inAmbientMode;
if (mLowBitAmbient) {
mTimeTextPaint.setAntiAlias(!inAmbientMode);
}
invalidate();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
/**
* Captures tap event (and tap type) and toggles the background color if the user finishes
* a tap.
*/
@Override
public void onTapCommand(int tapType, int x, int y, long eventTime) {
switch (tapType) {
case TAP_TYPE_TOUCH:
// The user has started touching the screen.
break;
case TAP_TYPE_TOUCH_CANCEL:
// The user has started a different gesture or otherwise cancelled the tap.
break;
case TAP_TYPE_TAP:
// The user has completed the tap gesture.
// TODO: Add code to handle the tap gesture.
Toast.makeText(getApplicationContext(), R.string.message, Toast.LENGTH_SHORT)
.show();
break;
}
invalidate();
}
@Override
public void onDraw(Canvas canvas, Rect bounds) {
// Draw the background.
if (isInAmbientMode()) {
canvas.drawColor(Color.BLACK);
} else {
canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint);
}
// Draw H:MM in ambient mode or H:MM:SS in interactive mode.
long now = System.currentTimeMillis();
mCalendar.setTimeInMillis(now);
String timeText = String.format("%d:%02d", mCalendar.get(Calendar.HOUR),
mCalendar.get(Calendar.MINUTE));
mTimeXOffset = mTimeTextPaint.measureText(timeText) / 2;
mTimeYOffset = mYOffset/2;
canvas.drawText(timeText, bounds.centerX() - mTimeXOffset , bounds.centerY() - mTimeYOffset, mTimeTextPaint);
String dayName = mCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());
String monthName = mCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());
int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);
int year = mCalendar.get(Calendar.YEAR);
String dateText = String.format("%s, %s %d, %d", dayName.toUpperCase(), monthName.toUpperCase(), dayOfMonth, year);
mDateXOffset = mDateTextPaint.measureText(dateText) / 2;
mDateYOffset = mTimeTextPaint.descent() - mTimeYOffset + mYOffset ;
if (isInAmbientMode()) {
mDateTextPaint.setColor(ContextCompat.getColor(getApplicationContext(), R.color.digital_text));
} else {
mDateTextPaint.setColor(ContextCompat.getColor(getApplicationContext(), R.color.primary_light));
}
canvas.drawText(dateText, bounds.centerX() - mDateXOffset, bounds.centerY() + mDateYOffset , mDateTextPaint);
if (mHighTemp != null && mLowTemp != null) {
mLineYOffset = mDateYOffset + mYOffset ;
mTempYOffset = mLineYOffset + (2 * mYOffset);
mHighXOffset = mTempHighTextPaint.measureText(mHighTemp);
mLowXOffset = mTempHighTextPaint.measureText(mLowTemp);
canvas.drawLine(bounds.centerX() - mXOffset - mHighXOffset , bounds.centerY() + mLineYOffset , bounds.centerX() + mXOffset + mLowXOffset , bounds.centerY() + mLineYOffset , mDateTextPaint);
if (isInAmbientMode()) {
mTempLowTextPaint.setColor(ContextCompat.getColor(getApplicationContext(),R.color.digital_text));
} else {
mTempLowTextPaint.setColor(ContextCompat.getColor(getApplicationContext(),R.color.primary_light));
Drawable b = getResources().getDrawable(getIconResourceForWeatherCondition(mWeatherId));
Bitmap icon = ((BitmapDrawable) b).getBitmap();
canvas.drawBitmap(icon, bounds.centerX() - mXOffset, mYOffset, null);
}
canvas.drawText(mHighTemp, bounds.centerX() - mXOffset - mHighXOffset, bounds.centerY() + mTempYOffset, mTempHighTextPaint);
canvas.drawText(mLowTemp, bounds.centerX() + mXOffset , bounds.centerY() + mTempYOffset, mTempLowTextPaint);
}
}
/**
* Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently
* or stops it if it shouldn't be running but currently is.
*/
private void updateTimer() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
if (shouldTimerBeRunning()) {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
/**
* Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should
* only run when we're visible and in interactive mode.
*/
private boolean shouldTimerBeRunning() {
return isVisible() && !isInAmbientMode();
}
/**
* Handle updating the time periodically in interactive mode.
*/
private void handleUpdateTimeMessage() {
invalidate();
if (shouldTimerBeRunning()) {
long timeMs = System.currentTimeMillis();
long delayMs = INTERACTIVE_UPDATE_RATE_MS
- (timeMs % INTERACTIVE_UPDATE_RATE_MS);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onConnected: " + bundle);
}
Wearable.DataApi.addListener(mGoogleApiClient, Engine.this);
}
@Override
public void onConnectionSuspended(int cause) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onConnectionFailed: " + connectionResult);
}
}
@Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
for (DataEvent dataEvent : dataEventBuffer) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataItem dataItem = dataEvent.getDataItem();
if (dataItem.getUri().getPath().compareTo(PATH_WEATHER) == 0) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItem);
DataMap config = dataMapItem.getDataMap();
mHighTemp = config.getString(KEY_HIGH);
mLowTemp = config.getString(KEY_LOW);
mWeatherId = config.getInt(KEY_ID);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Config DataItem updated:" + config);
}
invalidate();
}
}
}
}
}
}
|
923690f4d3dc9584f584d7c83b6221854264d7e4 | 688 | java | Java | src/main/java/com/murex/tbw/domain/book/Book.java | rmadisonhaynie/mikado-testbuilders-kata | 1c46bdee4537b25428d2a81739a9310f453a88ad | [
"MIT"
] | 1 | 2020-04-22T16:59:10.000Z | 2020-04-22T16:59:10.000Z | src/main/java/com/murex/tbw/domain/book/Book.java | emilybache/mikado-testbuilders-kata | 20a8a7201ea4b84b554ad92a92b7a55064f6a3b0 | [
"MIT"
] | null | null | null | src/main/java/com/murex/tbw/domain/book/Book.java | emilybache/mikado-testbuilders-kata | 20a8a7201ea4b84b554ad92a92b7a55064f6a3b0 | [
"MIT"
] | null | null | null | 27.52 | 81 | 0.552326 | 997,732 | /*******************************************************************************
*
* Copyright (c) {2003-2019} Murex S.A.S. and its affiliates.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package com.murex.tbw.domain.book;
import com.murex.tbw.domain.country.Language;
public interface Book {
String getName();
double getPrice();
Author getAuthor();
Language getLanguage();
}
|
923692361958a2386536e68a5cd00a43286a9a25 | 43,127 | java | Java | dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java | osake/AgileAlligators | 55eacb362dcad6dfc2c3d067c136b84b34026bae | [
"BSD-3-Clause"
] | 1 | 2015-12-13T13:19:20.000Z | 2015-12-13T13:19:20.000Z | dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java | osake/AgileAlligators | 55eacb362dcad6dfc2c3d067c136b84b34026bae | [
"BSD-3-Clause"
] | 1 | 2016-08-08T05:19:01.000Z | 2018-10-16T18:44:32.000Z | dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java | osake/AgileAlligators | 55eacb362dcad6dfc2c3d067c136b84b34026bae | [
"BSD-3-Clause"
] | 3 | 2016-03-08T18:23:01.000Z | 2021-06-02T13:00:34.000Z | 44.007143 | 194 | 0.609827 | 997,733 | package org.hisp.dhis.dxf2.datavalueset;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import static org.apache.commons.lang3.StringUtils.trimToNull;
import static org.hisp.dhis.common.IdentifiableProperty.UUID;
import static org.hisp.dhis.system.notification.NotificationLevel.ERROR;
import static org.hisp.dhis.system.notification.NotificationLevel.INFO;
import static org.hisp.dhis.system.util.DateUtils.getDefaultDate;
import static org.hisp.dhis.system.util.DateUtils.parseDate;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.amplecode.quick.BatchHandler;
import org.amplecode.quick.BatchHandlerFactory;
import org.amplecode.staxwax.factory.XMLFactory;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.IdentifiableProperty;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.commons.collection.CachingMap;
import org.hisp.dhis.commons.util.DebugUtils;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.dataset.CompleteDataSetRegistration;
import org.hisp.dhis.dataset.CompleteDataSetRegistrationService;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.datavalue.DataValue;
import org.hisp.dhis.dxf2.common.IdSchemes;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.common.JacksonUtils;
import org.hisp.dhis.dxf2.importsummary.ImportConflict;
import org.hisp.dhis.dxf2.importsummary.ImportCount;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.dxf2.pdfform.PdfDataEntryFormUtil;
import org.hisp.dhis.i18n.I18n;
import org.hisp.dhis.i18n.I18nManager;
import org.hisp.dhis.importexport.ImportStrategy;
import org.hisp.dhis.jdbc.batchhandler.DataValueBatchHandler;
import org.hisp.dhis.node.types.CollectionNode;
import org.hisp.dhis.node.types.ComplexNode;
import org.hisp.dhis.node.types.RootNode;
import org.hisp.dhis.node.types.SimpleNode;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.scheduling.TaskId;
import org.hisp.dhis.setting.Setting;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.system.callable.CategoryOptionComboAclCallable;
import org.hisp.dhis.system.callable.IdentifiableObjectCallable;
import org.hisp.dhis.system.callable.PeriodCallable;
import org.hisp.dhis.system.notification.Notifier;
import org.hisp.dhis.system.util.Clock;
import org.hisp.dhis.system.util.DateUtils;
import org.hisp.dhis.system.util.ValidationUtils;
import org.hisp.dhis.user.CurrentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.csvreader.CsvReader;
/**
* @author Lars Helge Overland
*/
public class DefaultDataValueSetService
implements DataValueSetService
{
private static final Log log = LogFactory.getLog( DefaultDataValueSetService.class );
private static final String ERROR_OBJECT_NEEDED_TO_COMPLETE = "Must be provided to complete data set";
@Autowired
private IdentifiableObjectManager identifiableObjectManager;
@Autowired
private DataElementService dataElementService;
@Autowired
private DataElementCategoryService categoryService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private PeriodService periodService;
@Autowired
private BatchHandlerFactory batchHandlerFactory;
@Autowired
private CompleteDataSetRegistrationService registrationService;
@Autowired
private CurrentUserService currentUserService;
@Autowired
private DataValueSetStore dataValueSetStore;
@Autowired
private SystemSettingManager systemSettingManager;
@Autowired
private I18nManager i18nManager;
@Autowired
private Notifier notifier;
// Set methods for test purposes
public void setBatchHandlerFactory( BatchHandlerFactory batchHandlerFactory )
{
this.batchHandlerFactory = batchHandlerFactory;
}
public void setCurrentUserService( CurrentUserService currentUserService )
{
this.currentUserService = currentUserService;
}
//--------------------------------------------------------------------------
// DataValueSet implementation
//--------------------------------------------------------------------------
@Override
public DataExportParams getFromUrl( Set<String> dataSets, Set<String> periods, Date startDate, Date endDate,
Set<String> organisationUnits, boolean includeChildren, Date lastUpdated, Integer limit, IdSchemes idSchemes )
{
DataExportParams params = new DataExportParams();
if ( dataSets != null )
{
params.getDataSets().addAll( identifiableObjectManager.getByUid( DataSet.class, dataSets ) );
}
if ( periods != null && !periods.isEmpty() )
{
params.getPeriods().addAll( periodService.reloadIsoPeriods( new ArrayList<>( periods ) ) );
}
else if ( startDate != null && endDate != null )
{
params.setStartDate( startDate );
params.setEndDate( endDate );
}
if ( organisationUnits != null )
{
params.getOrganisationUnits().addAll( identifiableObjectManager.getByUid( OrganisationUnit.class, organisationUnits ) );
}
params.setIncludeChildren( includeChildren );
params.setLastUpdated( lastUpdated );
params.setLimit( limit );
params.setIdSchemes( idSchemes );
return params;
}
@Override
public void validate( DataExportParams params )
{
String violation = null;
if ( params == null )
{
throw new IllegalArgumentException( "Params cannot be null" );
}
if ( params.getDataSets().isEmpty() )
{
violation = "At least one valid data set must be specified";
}
if ( params.getPeriods().isEmpty() && !params.hasStartEndDate() )
{
violation = "At least one valid period or start/end dates must be specified";
}
if ( params.hasStartEndDate() && params.getStartDate().after( params.getEndDate() ) )
{
violation = "Start date must be before end date";
}
if ( params.getOrganisationUnits().isEmpty() )
{
violation = "At least one valid organisation unit must be specified";
}
if ( params.hasLimit() && params.getLimit() < 0 )
{
violation = "Limit cannot be less than zero: " + params.getLimit();
}
if ( violation != null )
{
log.warn( "Validation failed: " + violation );
throw new IllegalArgumentException( violation );
}
}
@Override
public void decideAccess( DataExportParams params )
{
for ( OrganisationUnit unit : params.getOrganisationUnits() )
{
if ( !organisationUnitService.isInUserHierarchy( unit ) )
{
throw new IllegalQueryException( "User is not allowed to view org unit: " + unit.getUid() );
}
}
}
//--------------------------------------------------------------------------
// Write
//--------------------------------------------------------------------------
@Override
public void writeDataValueSetXml( DataExportParams params, OutputStream out )
{
decideAccess( params );
validate( params );
dataValueSetStore.writeDataValueSetXml( params, getCompleteDate( params ), out );
}
@Override
public void writeDataValueSetJson( DataExportParams params, OutputStream out )
{
decideAccess( params );
validate( params );
dataValueSetStore.writeDataValueSetJson( params, getCompleteDate( params ), out );
}
@Override
public void writeDataValueSetJson( Date lastUpdated, OutputStream outputStream, IdSchemes idSchemes )
{
dataValueSetStore.writeDataValueSetJson( lastUpdated, outputStream, idSchemes );
}
@Override
public void writeDataValueSetCsv( DataExportParams params, Writer writer )
{
decideAccess( params );
validate( params );
dataValueSetStore.writeDataValueSetCsv( params, getCompleteDate( params ), writer );
}
private Date getCompleteDate( DataExportParams params )
{
if ( params.isSingleDataValueSet() )
{
DataElementCategoryOptionCombo optionCombo = categoryService.getDefaultDataElementCategoryOptionCombo(); //TODO
CompleteDataSetRegistration registration = registrationService
.getCompleteDataSetRegistration( params.getFirstDataSet(), params.getFirstPeriod(), params.getFirstOrganisationUnit(), optionCombo );
return registration != null ? registration.getDate() : null;
}
return null;
}
//--------------------------------------------------------------------------
// Template
//--------------------------------------------------------------------------
@Override
public RootNode getDataValueSetTemplate( DataSet dataSet, Period period, List<String> orgUnits,
boolean writeComments, String ouScheme, String deScheme )
{
RootNode rootNode = new RootNode( "dataValueSet" );
rootNode.setNamespace( DxfNamespaces.DXF_2_0 );
rootNode.setComment( "Data set: " + dataSet.getDisplayName() + " (" + dataSet.getUid() + ")" );
CollectionNode collectionNode = rootNode.addChild( new CollectionNode( "dataValues" ) );
collectionNode.setWrapping( false );
if ( orgUnits.isEmpty() )
{
for ( DataElement dataElement : dataSet.getDataElements() )
{
CollectionNode collection = getDataValueTemplate( dataElement, deScheme, null, ouScheme, period,
writeComments );
collectionNode.addChildren( collection.getChildren() );
}
}
else
{
for ( String orgUnit : orgUnits )
{
OrganisationUnit organisationUnit = identifiableObjectManager.search( OrganisationUnit.class, orgUnit );
if ( organisationUnit == null )
{
continue;
}
for ( DataElement dataElement : dataSet.getDataElements() )
{
CollectionNode collection = getDataValueTemplate( dataElement, deScheme, organisationUnit, ouScheme,
period, writeComments );
collectionNode.addChildren( collection.getChildren() );
}
}
}
return rootNode;
}
private CollectionNode getDataValueTemplate( DataElement dataElement, String deScheme,
OrganisationUnit organisationUnit, String ouScheme, Period period, boolean comment )
{
CollectionNode collectionNode = new CollectionNode( "dataValues" );
collectionNode.setWrapping( false );
for ( DataElementCategoryOptionCombo categoryOptionCombo : dataElement.getCategoryCombo().getSortedOptionCombos() )
{
ComplexNode complexNode = collectionNode.addChild( new ComplexNode( "dataValue" ) );
String label = dataElement.getDisplayName();
if ( !categoryOptionCombo.isDefault() )
{
label += " " + categoryOptionCombo.getDisplayName();
}
if ( comment )
{
complexNode.setComment( "Data element: " + label );
}
if ( IdentifiableProperty.CODE.toString().toLowerCase()
.equals( deScheme.toLowerCase() ) )
{
SimpleNode simpleNode = complexNode.addChild( new SimpleNode( "dataElement", dataElement.getCode() ) );
simpleNode.setAttribute( true );
}
else
{
SimpleNode simpleNode = complexNode.addChild( new SimpleNode( "dataElement", dataElement.getUid() ) );
simpleNode.setAttribute( true );
}
SimpleNode simpleNode = complexNode.addChild( new SimpleNode( "categoryOptionCombo", categoryOptionCombo.getUid() ) );
simpleNode.setAttribute( true );
simpleNode = complexNode.addChild( new SimpleNode( "period", period != null ? period.getIsoDate() : "" ) );
simpleNode.setAttribute( true );
if ( organisationUnit != null )
{
if ( IdentifiableProperty.CODE.toString().toLowerCase().equals( ouScheme.toLowerCase() ) )
{
simpleNode = complexNode.addChild( new SimpleNode( "orgUnit", organisationUnit.getCode() == null ? "" : organisationUnit.getCode() ) );
simpleNode.setAttribute( true );
}
else
{
simpleNode = complexNode.addChild( new SimpleNode( "orgUnit", organisationUnit.getUid() == null ? "" : organisationUnit.getUid() ) );
simpleNode.setAttribute( true );
}
}
simpleNode = complexNode.addChild( new SimpleNode( "value", "" ) );
simpleNode.setAttribute( true );
}
return collectionNode;
}
//--------------------------------------------------------------------------
// Save
//--------------------------------------------------------------------------
@Override
public ImportSummary saveDataValueSet( InputStream in )
{
return saveDataValueSet( in, ImportOptions.getDefaultImportOptions(), null );
}
@Override
public ImportSummary saveDataValueSetJson( InputStream in )
{
return saveDataValueSetJson( in, ImportOptions.getDefaultImportOptions(), null );
}
@Override
public ImportSummary saveDataValueSet( InputStream in, ImportOptions importOptions )
{
return saveDataValueSet( in, importOptions, null );
}
@Override
public ImportSummary saveDataValueSetJson( InputStream in, ImportOptions importOptions )
{
return saveDataValueSetJson( in, importOptions, null );
}
@Override
public ImportSummary saveDataValueSetCsv( InputStream in, ImportOptions importOptions )
{
return saveDataValueSetCsv( in, importOptions, null );
}
@Override
public ImportSummary saveDataValueSet( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = new StreamingDataValueSet( XMLFactory.getXMLReader( in ) );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( RuntimeException ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
@Override
public ImportSummary saveDataValueSetJson( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = JacksonUtils.fromJson( in, DataValueSet.class );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( Exception ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
@Override
public ImportSummary saveDataValueSetCsv( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = new StreamingCsvDataValueSet( new CsvReader( in, Charset.forName( "UTF-8" ) ) );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( RuntimeException ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.clear( id ).notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
@Override
public ImportSummary saveDataValueSetPdf( InputStream in, ImportOptions importOptions, TaskId id )
{
try
{
DataValueSet dataValueSet = PdfDataEntryFormUtil.getDataValueSet( in );
return saveDataValueSet( importOptions, id, dataValueSet );
}
catch ( RuntimeException ex )
{
log.error( DebugUtils.getStackTrace( ex ) );
notifier.clear( id ).notify( id, ERROR, "Process failed: " + ex.getMessage(), true );
return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() );
}
}
/**
* There are specific id schemes for data elements and organisation units and
* a generic id scheme for all objects. The specific id schemes will take
* precedence over the generic id scheme. The generic id scheme also applies
* to data set and category option combo.
* <p/>
* The id schemes uses the following order of precedence:
* <p/>
* <ul>
* <li>Id scheme from the data value set</li>
* <li>Id scheme from the import options</li>
* <li>Default id scheme which is UID</li>
* <ul>
* <p/>
* If id scheme is specific in the data value set, any id schemes in the import
* options will be ignored.
*
* @param importOptions
* @param id
* @param dataValueSet
* @return
*/
private ImportSummary saveDataValueSet( ImportOptions importOptions, TaskId id, DataValueSet dataValueSet )
{
Clock clock = new Clock( log ).startClock().logTime( "Starting data value import, options: " + importOptions );
notifier.clear( id ).notify( id, "Process started" );
ImportSummary summary = new ImportSummary();
I18n i18n = i18nManager.getI18n();
//----------------------------------------------------------------------
// Get import options
//----------------------------------------------------------------------
importOptions = importOptions != null ? importOptions : ImportOptions.getDefaultImportOptions();
log.info( "Import options: " + importOptions );
IdentifiableProperty dvSetIdScheme = dataValueSet.getIdSchemeProperty();
IdentifiableProperty dvSetDataElementIdScheme = dataValueSet.getDataElementIdSchemeProperty();
IdentifiableProperty dvSetOrgUnitIdScheme = dataValueSet.getOrgUnitIdSchemeProperty();
log.info( "Data value set scheme: " + dvSetIdScheme + ", data element scheme: " + dvSetDataElementIdScheme + ", org unit scheme: " + dvSetOrgUnitIdScheme );
IdentifiableProperty idScheme = dvSetIdScheme != null ? dvSetIdScheme : importOptions.getIdScheme();
IdentifiableProperty dataElementIdScheme = dvSetDataElementIdScheme != null ? dvSetDataElementIdScheme : importOptions.getDataElementIdScheme();
IdentifiableProperty orgUnitIdScheme = dvSetOrgUnitIdScheme != null ? dvSetOrgUnitIdScheme : importOptions.getOrgUnitIdScheme();
log.info( "Scheme: " + idScheme + ", data element scheme: " + dataElementIdScheme + ", org unit scheme: " + orgUnitIdScheme );
ImportStrategy strategy = dataValueSet.getStrategy() != null ?
ImportStrategy.valueOf( dataValueSet.getStrategy() ) : importOptions.getImportStrategy();
boolean dryRun = dataValueSet.getDryRun() != null ? dataValueSet.getDryRun() : importOptions.isDryRun();
boolean skipExistingCheck = importOptions.isSkipExistingCheck();
boolean strictPeriods = importOptions.isStrictPeriods() || (Boolean) systemSettingManager.getSystemSetting( Setting.DATA_IMPORT_STRICT_PERIODS );
boolean strictCategoryOptionCombos = importOptions.isStrictCategoryOptionCombos() || (Boolean) systemSettingManager.getSystemSetting( Setting.DATA_IMPORT_STRICT_CATEGORY_OPTION_COMBOS );
boolean strictAttrOptionCombos = importOptions.isStrictAttributeOptionCombos() || (Boolean) systemSettingManager.getSystemSetting( Setting.DATA_IMPORT_STRICT_ATTRIBUTE_OPTION_COMBOS );
boolean strictOrgUnits = importOptions.isStrictOrganisationUnits() || (Boolean) systemSettingManager.getSystemSetting( Setting.DATA_IMPORT_STRICT_ORGANISATION_UNITS );
boolean requireCategoryOptionCombo = importOptions.isRequireCategoryOptionCombo() || (Boolean) systemSettingManager.getSystemSetting( Setting.DATA_IMPORT_REQUIRE_CATEGORY_OPTION_COMBO );
boolean requireAttrOptionCombo = importOptions.isRequireAttributeOptionCombo() || (Boolean) systemSettingManager.getSystemSetting( Setting.DATA_IMPORT_REQUIRE_ATTRIBUTE_OPTION_COMBO );
//----------------------------------------------------------------------
// Create meta-data maps
//----------------------------------------------------------------------
CachingMap<String, DataElement> dataElementMap = new CachingMap<>();
CachingMap<String, OrganisationUnit> orgUnitMap = new CachingMap<>();
CachingMap<String, DataElementCategoryOptionCombo> optionComboMap = new CachingMap<>();
CachingMap<String, Period> periodMap = new CachingMap<>();
CachingMap<String, Set<PeriodType>> dataElementPeriodTypesMap = new CachingMap<>();
CachingMap<String, Set<DataElementCategoryOptionCombo>> dataElementCategoryOptionComboMap = new CachingMap<>();
CachingMap<String, Set<DataElementCategoryOptionCombo>> dataElementAttrOptionComboMap = new CachingMap<>();
CachingMap<String, Boolean> dataElementOrgUnitMap = new CachingMap<>();
CachingMap<String, Boolean> dataElementOpenFuturePeriodsMap = new CachingMap<>();
CachingMap<String, Boolean> orgUnitInHierarchyMap = new CachingMap<>();
//----------------------------------------------------------------------
// Load meta-data maps
//----------------------------------------------------------------------
if ( importOptions.isPreheatCache() )
{
notifier.notify( id, "Loading data elements and organisation units" );
dataElementMap.putAll( identifiableObjectManager.getIdMap( DataElement.class, dataElementIdScheme ) );
orgUnitMap.putAll( getOrgUnitMap( orgUnitIdScheme ) );
clock.logTime( "Preheated data element and organisation unit caches" );
}
IdentifiableObjectCallable<DataElement> dataElementCallable = new IdentifiableObjectCallable<>(
identifiableObjectManager, DataElement.class, dataElementIdScheme, null );
IdentifiableObjectCallable<OrganisationUnit> orgUnitCallable = new IdentifiableObjectCallable<>(
identifiableObjectManager, OrganisationUnit.class, orgUnitIdScheme, trimToNull( dataValueSet.getOrgUnit() ) );
IdentifiableObjectCallable<DataElementCategoryOptionCombo> optionComboCallable = new CategoryOptionComboAclCallable(
categoryService, idScheme, null );
IdentifiableObjectCallable<Period> periodCallable = new PeriodCallable(
periodService, null, trimToNull( dataValueSet.getPeriod() ) );
//----------------------------------------------------------------------
// Get outer meta-data
//----------------------------------------------------------------------
DataSet dataSet = dataValueSet.getDataSet() != null ? identifiableObjectManager.getObject( DataSet.class, idScheme, dataValueSet.getDataSet() ) : null;
Date completeDate = getDefaultDate( dataValueSet.getCompleteDate() );
Period outerPeriod = periodMap.get( trimToNull( dataValueSet.getPeriod() ), periodCallable );
OrganisationUnit outerOrgUnit = orgUnitMap.get( trimToNull( dataValueSet.getOrgUnit() ), orgUnitCallable );
DataElementCategoryOptionCombo fallbackCategoryOptionCombo = categoryService.getDefaultDataElementCategoryOptionCombo();
DataElementCategoryOptionCombo outerAttrOptionCombo = dataValueSet.getAttributeOptionCombo() != null ?
optionComboMap.get( trimToNull( dataValueSet.getAttributeOptionCombo() ), optionComboCallable.setId( trimToNull( dataValueSet.getAttributeOptionCombo() ) ) ) : null;
// ---------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------
if ( dataSet == null && trimToNull( dataValueSet.getDataSet() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValueSet.getDataSet(), "Data set not found or not accessible" ) );
summary.setStatus( ImportStatus.ERROR );
}
if ( outerOrgUnit == null && trimToNull( dataValueSet.getOrgUnit() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValueSet.getDataSet(), "Org unit not found or not accessible" ) );
summary.setStatus( ImportStatus.ERROR );
}
if ( outerAttrOptionCombo == null && trimToNull( dataValueSet.getAttributeOptionCombo() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValueSet.getDataSet(), "Attribute option combo not found or not accessible" ) );
summary.setStatus( ImportStatus.ERROR );
}
if ( ImportStatus.ERROR.equals( summary.getStatus() ) )
{
summary.setDescription( "Import process was aborted" );
notifier.notify( id, INFO, "Import process aborted", true ).addTaskSummary( id, summary );
dataValueSet.close();
return summary;
}
if ( dataSet != null && completeDate != null )
{
notifier.notify( id, "Completing data set" );
handleComplete( dataSet, completeDate, outerPeriod, outerOrgUnit, fallbackCategoryOptionCombo, summary ); //TODO
}
else
{
summary.setDataSetComplete( Boolean.FALSE.toString() );
}
final String currentUser = currentUserService.getCurrentUsername();
final Set<OrganisationUnit> currentOrgUnits = currentUserService.getCurrentUserOrganisationUnits();
BatchHandler<DataValue> batchHandler = batchHandlerFactory.createBatchHandler( DataValueBatchHandler.class ).init();
int importCount = 0;
int updateCount = 0;
int totalCount = 0;
// ---------------------------------------------------------------------
// Data values
// ---------------------------------------------------------------------
Date now = new Date();
clock.logTime( "Validated outer meta-data" );
notifier.notify( id, "Importing data values" );
while ( dataValueSet.hasNextDataValue() )
{
org.hisp.dhis.dxf2.datavalue.DataValue dataValue = dataValueSet.getNextDataValue();
totalCount++;
final DataElement dataElement =
dataElementMap.get( trimToNull( dataValue.getDataElement() ), dataElementCallable.setId( trimToNull( dataValue.getDataElement() ) ) );
final Period period = outerPeriod != null ? outerPeriod :
periodMap.get( trimToNull( dataValue.getPeriod() ), periodCallable.setId( trimToNull( dataValue.getPeriod() ) ) );
final OrganisationUnit orgUnit = outerOrgUnit != null ? outerOrgUnit :
orgUnitMap.get( trimToNull( dataValue.getOrgUnit() ), orgUnitCallable.setId( trimToNull( dataValue.getOrgUnit() ) ) );
DataElementCategoryOptionCombo categoryOptionCombo = optionComboMap.get( trimToNull( dataValue.getCategoryOptionCombo() ),
optionComboCallable.setId( trimToNull( dataValue.getCategoryOptionCombo() ) ) );
DataElementCategoryOptionCombo attrOptionCombo = outerAttrOptionCombo != null ? outerAttrOptionCombo :
optionComboMap.get( trimToNull( dataValue.getAttributeOptionCombo() ), optionComboCallable.setId( trimToNull( dataValue.getAttributeOptionCombo() ) ) );
// -----------------------------------------------------------------
// Validation
// -----------------------------------------------------------------
if ( dataElement == null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getDataElement(), "Data element not found or not acccessible" ) );
continue;
}
if ( period == null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getPeriod(), "Period not valid" ) );
continue;
}
if ( orgUnit == null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getOrgUnit(), "Organisation unit not found or not acccessible" ) );
continue;
}
if ( categoryOptionCombo == null && trimToNull( dataValue.getCategoryOptionCombo() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getCategoryOptionCombo(), "Category option combo not found or not accessible" ) );
continue;
}
if ( attrOptionCombo == null && trimToNull( dataValue.getAttributeOptionCombo() ) != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getAttributeOptionCombo(), "Attribute option combo not found or not accessible" ) );
continue;
}
boolean inUserHierarchy = orgUnitInHierarchyMap.get( orgUnit.getUid(),
() -> organisationUnitService.isInUserHierarchy( orgUnit.getUid(), currentOrgUnits ) );
if ( !inUserHierarchy )
{
summary.getConflicts().add( new ImportConflict( orgUnit.getUid(), "Organisation unit not in hierarchy of current user: " + currentUser ) );
continue;
}
boolean invalidFuturePeriod = period.isFuture() && dataElementOpenFuturePeriodsMap.get( dataElement.getUid(),
() -> dataElementService.isOpenFuturePeriods( dataElement.getId() ) );
if ( invalidFuturePeriod )
{
summary.getConflicts().add( new ImportConflict( period.getIsoDate(), "Data element does not allow for future periods through data sets: " + dataElement.getUid() ) );
continue;
}
if ( dataValue.getValue() == null && dataValue.getComment() == null )
{
continue;
}
String valueValid = ValidationUtils.dataValueIsValid( dataValue.getValue(), dataElement );
if ( valueValid != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), i18n.getString( valueValid ) + ", must match data element type: " + dataElement.getUid() ) );
continue;
}
String commentValid = ValidationUtils.commentIsValid( dataValue.getComment() );
if ( commentValid != null )
{
summary.getConflicts().add( new ImportConflict( "Comment", i18n.getString( commentValid ) ) );
continue;
}
// -----------------------------------------------------------------
// Constraints
// -----------------------------------------------------------------
if ( categoryOptionCombo == null )
{
if ( requireCategoryOptionCombo )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), "Category option combo is required but is not specified" ) );
continue;
}
else
{
categoryOptionCombo = fallbackCategoryOptionCombo;
}
}
if ( attrOptionCombo == null )
{
if ( requireAttrOptionCombo )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), "Attribute option combo is required but is not specified" ) );
continue;
}
else
{
attrOptionCombo = fallbackCategoryOptionCombo;
}
}
if ( strictPeriods && !dataElementPeriodTypesMap.get( dataElement.getUid(),
() -> dataElement.getPeriodTypes() ).contains( period.getPeriodType() ) )
{
summary.getConflicts().add( new ImportConflict( dataValue.getPeriod(),
"Period type of period: " + period.getIsoDate() + " not valid for data element: " + dataElement.getUid() ) );
continue;
}
if ( strictCategoryOptionCombos && !dataElementCategoryOptionComboMap.get( dataElement.getUid(),
() -> dataElement.getCategoryCombo().getOptionCombos() ).contains( categoryOptionCombo ) )
{
summary.getConflicts().add( new ImportConflict( categoryOptionCombo.getUid(),
"Category option combo: " + categoryOptionCombo.getUid() + " must be part of category combo of data element: " + dataElement.getUid() ) );
continue;
}
if ( strictAttrOptionCombos && !dataElementAttrOptionComboMap.get( dataElement.getUid(),
() -> dataElement.getDataSetCategoryOptionCombos() ).contains( attrOptionCombo ) )
{
summary.getConflicts().add( new ImportConflict( attrOptionCombo.getUid(),
"Attribute option combo: " + attrOptionCombo.getUid() + " must be part of category combo of data sets of data element: " + dataElement.getUid() ) );
continue;
}
if ( strictOrgUnits && BooleanUtils.isFalse( dataElementOrgUnitMap.get( dataElement.getUid() + orgUnit.getUid(),
() -> dataElement.hasDataSetOrganisationUnit( orgUnit ) ) ) )
{
summary.getConflicts().add( new ImportConflict( orgUnit.getUid(),
"Data element: " + dataElement.getUid() + " must be assigned through data sets to organisation unit: " + orgUnit.getUid() ) );
continue;
}
boolean zeroInsignificant = ValidationUtils.dataValueIsZeroAndInsignificant( dataValue.getValue(), dataElement );
if ( zeroInsignificant )
{
summary.getConflicts().add( new ImportConflict( dataValue.getValue(), "Value is zero and not significant, must match data element: " + dataElement.getUid() ) );
continue;
}
String storedByValid = ValidationUtils.storedByIsValid( dataValue.getStoredBy() );
if ( storedByValid != null )
{
summary.getConflicts().add( new ImportConflict( dataValue.getStoredBy(), i18n.getString( storedByValid ) ) );
continue;
}
String storedBy = dataValue.getStoredBy() == null || dataValue.getStoredBy().trim().isEmpty() ? currentUser : dataValue.getStoredBy();
// -----------------------------------------------------------------
// Create data value
// -----------------------------------------------------------------
DataValue internalValue = new DataValue();
internalValue.setDataElement( dataElement );
internalValue.setPeriod( period );
internalValue.setSource( orgUnit );
internalValue.setCategoryOptionCombo( categoryOptionCombo );
internalValue.setAttributeOptionCombo( attrOptionCombo );
internalValue.setValue( trimToNull( dataValue.getValue() ) );
internalValue.setStoredBy( storedBy );
internalValue.setCreated( dataValue.hasCreated() ? parseDate( dataValue.getCreated() ) : now );
internalValue.setLastUpdated( dataValue.hasLastUpdated() ? parseDate( dataValue.getLastUpdated() ) : now );
internalValue.setComment( trimToNull( dataValue.getComment() ) );
internalValue.setFollowup( dataValue.getFollowup() );
// -----------------------------------------------------------------
// Save, update or delete data value
// -----------------------------------------------------------------
if ( !skipExistingCheck && batchHandler.objectExists( internalValue ) )
{
if ( strategy.isCreateAndUpdate() || strategy.isUpdate() )
{
if ( !dryRun )
{
if ( !internalValue.isNullValue() )
{
batchHandler.updateObject( internalValue );
}
else
{
batchHandler.deleteObject( internalValue );
}
}
updateCount++;
}
}
else
{
if ( strategy.isCreateAndUpdate() || strategy.isCreate() )
{
if ( !dryRun && !internalValue.isNullValue() )
{
if ( batchHandler.addObject( internalValue ) )
{
importCount++;
}
}
}
}
}
batchHandler.flush();
int ignores = totalCount - importCount - updateCount;
summary.setImportCount( new ImportCount( importCount, updateCount, ignores, 0 ) );
summary.setStatus( ImportStatus.SUCCESS );
summary.setDescription( "Import process completed successfully" );
notifier.notify( id, INFO, "Import done", true ).addTaskSummary( id, summary );
clock.logTime( "Data value import done, total: " + totalCount + ", import: " + importCount + ", update: " + updateCount );
dataValueSet.close();
return summary;
}
//--------------------------------------------------------------------------
// Supportive methods
//--------------------------------------------------------------------------
private void handleComplete( DataSet dataSet, Date completeDate, Period period, OrganisationUnit orgUnit,
DataElementCategoryOptionCombo attributeOptionCombo, ImportSummary summary )
{
if ( orgUnit == null )
{
summary.getConflicts().add( new ImportConflict( OrganisationUnit.class.getSimpleName(), ERROR_OBJECT_NEEDED_TO_COMPLETE ) );
return;
}
if ( period == null )
{
summary.getConflicts().add( new ImportConflict( Period.class.getSimpleName(), ERROR_OBJECT_NEEDED_TO_COMPLETE ) );
return;
}
period = periodService.reloadPeriod( period );
CompleteDataSetRegistration completeAlready = registrationService
.getCompleteDataSetRegistration( dataSet, period, orgUnit, attributeOptionCombo );
String username = currentUserService.getCurrentUsername();
if ( completeAlready != null )
{
completeAlready.setStoredBy( username );
completeAlready.setDate( completeDate );
registrationService.updateCompleteDataSetRegistration( completeAlready );
}
else
{
CompleteDataSetRegistration registration = new CompleteDataSetRegistration( dataSet, period, orgUnit,
attributeOptionCombo, completeDate, username );
registrationService.saveCompleteDataSetRegistration( registration );
}
summary.setDataSetComplete( DateUtils.getMediumDateString( completeDate ) );
}
private Map<String, OrganisationUnit> getOrgUnitMap( IdentifiableProperty orgUnitIdScheme )
{
return UUID.equals( orgUnitIdScheme ) ?
organisationUnitService.getUuidOrganisationUnitMap() :
identifiableObjectManager.getIdMap( OrganisationUnit.class, orgUnitIdScheme );
}
}
|
923692548ea5fdb2b5f75abf262b9f9866ca4cfa | 263 | java | Java | app/src/main/java/com/novyr/callfilter/db/entity/enums/LogAction.java | korakinos/android-call-filter | 896a63778e3a397f13333d406dbaeae6104da4e6 | [
"MIT"
] | 8 | 2019-08-28T12:09:46.000Z | 2022-02-17T10:03:17.000Z | app/src/main/java/com/novyr/callfilter/db/entity/enums/LogAction.java | korakinos/android-call-filter | 896a63778e3a397f13333d406dbaeae6104da4e6 | [
"MIT"
] | 2 | 2021-03-04T13:16:38.000Z | 2021-08-13T11:01:05.000Z | app/src/main/java/com/novyr/callfilter/db/entity/enums/LogAction.java | korakinos/android-call-filter | 896a63778e3a397f13333d406dbaeae6104da4e6 | [
"MIT"
] | 2 | 2021-01-08T06:16:43.000Z | 2021-03-04T13:19:11.000Z | 14.611111 | 45 | 0.581749 | 997,734 | package com.novyr.callfilter.db.entity.enums;
public enum LogAction {
BLOCKED(0),
ALLOWED(1),
FAILED(2);
private final int code;
LogAction(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
|
9236928cd59a1cf8b3f9585c9b62c1015d5d598e | 1,372 | java | Java | src/main/java/org/fluentjdbc/DatabaseColumnReference.java | AndreasSM/fluent-jdbc | 32029029e2f0b5d07ca6562bb64e4432680fc879 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/fluentjdbc/DatabaseColumnReference.java | AndreasSM/fluent-jdbc | 32029029e2f0b5d07ca6562bb64e4432680fc879 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/fluentjdbc/DatabaseColumnReference.java | AndreasSM/fluent-jdbc | 32029029e2f0b5d07ca6562bb64e4432680fc879 | [
"Apache-2.0"
] | null | null | null | 26.901961 | 115 | 0.645044 | 997,735 | package org.fluentjdbc;
import java.util.Objects;
public class DatabaseColumnReference {
private final String columnName;
private final String tableName;
private final DatabaseTableAlias alias;
DatabaseColumnReference(DatabaseTableAlias alias, String columnName) {
this.columnName = columnName;
this.tableName = alias.getTableName();
this.alias = alias;
}
public DatabaseTableAlias getTableAlias() {
return alias;
}
public String getTableName() {
return tableName;
}
public String getQualifiedColumnName() {
return alias.getAlias() + "." + columnName;
}
public String getTableNameAndAlias() {
return alias.getTableNameAndAlias();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DatabaseColumnReference that = (DatabaseColumnReference) o;
return Objects.equals(alias, that.alias) &&
columnName.equalsIgnoreCase(that.columnName);
}
@Override
public int hashCode() {
return Objects.hash(alias, columnName.toUpperCase());
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + getQualifiedColumnName() + " in " + getTableNameAndAlias() + "]";
}
}
|
923692c644fa58d8568ccc0bd57a22c4d942fbdc | 472 | java | Java | src/main/java/com/xlx/majiang/dao/QuestionExtraMapper.java | XielinX/majiang | d657e7dae68d5be568dbaec3bbd895037779eca1 | [
"Apache-2.0"
] | 2 | 2019-08-19T02:19:06.000Z | 2019-08-26T04:30:34.000Z | src/main/java/com/xlx/majiang/dao/QuestionExtraMapper.java | XielinX/majiang | d657e7dae68d5be568dbaec3bbd895037779eca1 | [
"Apache-2.0"
] | 2 | 2020-03-10T04:01:58.000Z | 2020-03-10T04:04:30.000Z | src/main/java/com/xlx/majiang/dao/QuestionExtraMapper.java | XielinX/majiang | d657e7dae68d5be568dbaec3bbd895037779eca1 | [
"Apache-2.0"
] | 1 | 2020-03-18T08:31:32.000Z | 2020-03-18T08:31:32.000Z | 13.485714 | 50 | 0.618644 | 997,736 | package com.xlx.majiang.dao;
import com.xlx.majiang.entity.Question;
import java.util.List;
/**
* 问题
* @author: xielx on 2019/6/23
*/
public interface QuestionExtraMapper {
/**
* 阅读量
* @param record
* @return
*/
int incView(Question record);
/**
* 评论量
* @param record
* @return
*/
int incCommentCount(Question record);
/**
* 查询相关问题
* @param question
* @return
*/
List<Question> selectRelated(Question question);
}
|
923692e433fe8c655b79e82baf1d9d37022258ad | 1,307 | java | Java | librairie-shared/src/main/java/com/hogwai/librairieshared/dto/LoanDto.java | Hogwai/oc-librairie | 77b24c76f7699956cc4cfb4d500dd871fa3d0119 | [
"MIT"
] | null | null | null | librairie-shared/src/main/java/com/hogwai/librairieshared/dto/LoanDto.java | Hogwai/oc-librairie | 77b24c76f7699956cc4cfb4d500dd871fa3d0119 | [
"MIT"
] | null | null | null | librairie-shared/src/main/java/com/hogwai/librairieshared/dto/LoanDto.java | Hogwai/oc-librairie | 77b24c76f7699956cc4cfb4d500dd871fa3d0119 | [
"MIT"
] | null | null | null | 22.152542 | 244 | 0.765111 | 997,737 | package com.hogwai.librairieshared.dto;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.Date;
@Getter
@Setter
public class LoanDto implements Serializable {
private static final long serialVersionUID = 1L;
private Integer loanId;
private Date endDate;
private Boolean extended;
private Boolean returned;
private Date startDate;
/* Book information */
private Integer bookId;
private String bookAuthor;
private String bookTitle;
/* Library information */
private Integer libraryId;
private String libraryName;
/* User information */
private Integer userId;
private String userName;
private String userSurname;
public LoanDto(Integer loanId, Date endDate, Boolean extended, Boolean returned, Date startDate, Integer bookId, String bookAuthor, String bookTitle, Integer libraryId, String libraryName, Integer userId, String userName, String userSurname) {
this.loanId = loanId;
this.endDate = endDate;
this.extended = extended;
this.returned = returned;
this.startDate = startDate;
this.bookId = bookId;
this.bookAuthor = bookAuthor;
this.bookTitle = bookTitle;
this.libraryId = libraryId;
this.libraryName = libraryName;
this.userId = userId;
this.userName = userName;
this.userSurname = userSurname;
}
} |
923693141d446e44e2f7d8a8594f934e15e8620f | 146 | java | Java | playground/src/main/java/dp/command/NoCommand.java | pkumartv/java-playground | bf1ff566f360d2e35fbe9ac221a19c55b04b6280 | [
"MIT"
] | null | null | null | playground/src/main/java/dp/command/NoCommand.java | pkumartv/java-playground | bf1ff566f360d2e35fbe9ac221a19c55b04b6280 | [
"MIT"
] | null | null | null | playground/src/main/java/dp/command/NoCommand.java | pkumartv/java-playground | bf1ff566f360d2e35fbe9ac221a19c55b04b6280 | [
"MIT"
] | null | null | null | 12.166667 | 43 | 0.719178 | 997,738 | package dp.command;
public class NoCommand implements Command {
@Override
public void execute() {
// TODO Auto-generated method stub
}
}
|
92369340212d802bf2e65ec66e27ae7dfc087829 | 2,918 | java | Java | coeey/com/facebook/react/views/art/ARTSurfaceViewShadowNode.java | ankurshukla1993/IOT-test | 174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6 | [
"Apache-2.0"
] | 1 | 2021-08-21T17:56:56.000Z | 2021-08-21T17:56:56.000Z | coeey/com/facebook/react/views/art/ARTSurfaceViewShadowNode.java | ankurshukla1993/IOT-test | 174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6 | [
"Apache-2.0"
] | null | null | null | coeey/com/facebook/react/views/art/ARTSurfaceViewShadowNode.java | ankurshukla1993/IOT-test | 174c2f0f1b5ff7ef0ffb5eb29b6d68048b0af2b6 | [
"Apache-2.0"
] | 1 | 2018-11-26T08:56:33.000Z | 2018-11-26T08:56:33.000Z | 33.930233 | 105 | 0.660727 | 997,739 | package com.facebook.react.views.art;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import android.view.TextureView.SurfaceTextureListener;
import com.facebook.common.logging.FLog;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.uimanager.LayoutShadowNode;
import com.facebook.react.uimanager.ReactShadowNode;
import com.facebook.react.uimanager.UIViewOperationQueue;
import javax.annotation.Nullable;
public class ARTSurfaceViewShadowNode extends LayoutShadowNode implements SurfaceTextureListener {
@Nullable
private Surface mSurface;
public boolean isVirtual() {
return false;
}
public boolean isVirtualAnchor() {
return true;
}
public void onCollectExtraUpdates(UIViewOperationQueue uiUpdater) {
super.onCollectExtraUpdates(uiUpdater);
drawOutput();
uiUpdater.enqueueUpdateExtraData(getReactTag(), this);
}
private void drawOutput() {
RuntimeException e;
if (this.mSurface == null || !this.mSurface.isValid()) {
markChildrenUpdatesSeen(this);
return;
}
try {
Canvas canvas = this.mSurface.lockCanvas(null);
canvas.drawColor(0, Mode.CLEAR);
Paint paint = new Paint();
for (int i = 0; i < getChildCount(); i++) {
ARTVirtualNode child = (ARTVirtualNode) getChildAt(i);
child.draw(canvas, paint, FlexItem.FLEX_SHRINK_DEFAULT);
child.markUpdateSeen();
}
if (this.mSurface != null) {
this.mSurface.unlockCanvasAndPost(canvas);
}
} catch (IllegalArgumentException e2) {
e = e2;
FLog.e(ReactConstants.TAG, e.getClass().getSimpleName() + " in Surface.unlockCanvasAndPost");
} catch (IllegalStateException e3) {
e = e3;
FLog.e(ReactConstants.TAG, e.getClass().getSimpleName() + " in Surface.unlockCanvasAndPost");
}
}
private void markChildrenUpdatesSeen(ReactShadowNode shadowNode) {
for (int i = 0; i < shadowNode.getChildCount(); i++) {
ReactShadowNode child = shadowNode.getChildAt(i);
child.markUpdateSeen();
markChildrenUpdatesSeen(child);
}
}
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
this.mSurface = new Surface(surface);
drawOutput();
}
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
surface.release();
this.mSurface = null;
return true;
}
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
|
9236937edb5dfb08af925145c85bab1a1793005b | 4,096 | java | Java | cat-home/src/main/java/com/dianping/cat/home/alert/summary/transform/DefaultSaxMaker.java | ljj18/cat | 7396910b1b3b37f027a1c5bd306b0d03e759cca6 | [
"Apache-2.0"
] | null | null | null | cat-home/src/main/java/com/dianping/cat/home/alert/summary/transform/DefaultSaxMaker.java | ljj18/cat | 7396910b1b3b37f027a1c5bd306b0d03e759cca6 | [
"Apache-2.0"
] | null | null | null | cat-home/src/main/java/com/dianping/cat/home/alert/summary/transform/DefaultSaxMaker.java | ljj18/cat | 7396910b1b3b37f027a1c5bd306b0d03e759cca6 | [
"Apache-2.0"
] | null | null | null | 33.85124 | 110 | 0.650635 | 997,740 | package com.dianping.cat.home.alert.summary.transform;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_ALERT_DATE;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_ALERTTIME;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_CONTEXT;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_COUNT;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_DOMAIN;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_METRIC;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_NAME;
import static com.dianping.cat.home.alert.summary.Constants.ATTR_TYPE;
import org.xml.sax.Attributes;
import com.dianping.cat.home.alert.summary.entity.Alert;
import com.dianping.cat.home.alert.summary.entity.AlertSummary;
import com.dianping.cat.home.alert.summary.entity.Category;
public class DefaultSaxMaker implements IMaker<Attributes> {
@Override
public Alert buildAlert(Attributes attributes) {
String alertTime = attributes.getValue(ATTR_ALERTTIME);
String type = attributes.getValue(ATTR_TYPE);
String metric = attributes.getValue(ATTR_METRIC);
String context = attributes.getValue(ATTR_CONTEXT);
String domain = attributes.getValue(ATTR_DOMAIN);
String count = attributes.getValue(ATTR_COUNT);
Alert alert = new Alert();
if (alertTime != null) {
alert.setAlertTime(toDate(alertTime, "yyyy-MM-dd HH:mm:ss", null));
}
if (type != null) {
alert.setType(type);
}
if (metric != null) {
alert.setMetric(metric);
}
if (context != null) {
alert.setContext(context);
}
if (domain != null) {
alert.setDomain(domain);
}
if (count != null) {
alert.setCount(convert(Integer.class, count, null));
}
return alert;
}
@Override
public AlertSummary buildAlertSummary(Attributes attributes) {
String alertDate = attributes.getValue(ATTR_ALERT_DATE);
String domain = attributes.getValue(ATTR_DOMAIN);
AlertSummary alertSummary = new AlertSummary();
if (alertDate != null) {
alertSummary.setAlertDate(toDate(alertDate, "yyyy-MM-dd HH:mm:ss", null));
}
if (domain != null) {
alertSummary.setDomain(domain);
}
return alertSummary;
}
@Override
public Category buildCategory(Attributes attributes) {
String name = attributes.getValue(ATTR_NAME);
Category category = new Category(name);
return category;
}
@SuppressWarnings("unchecked")
protected <T> T convert(Class<T> type, String value, T defaultValue) {
if (value == null || value.length() == 0) {
return defaultValue;
}
if (type == Boolean.class || type == Boolean.TYPE) {
return (T) Boolean.valueOf(value);
} else if (type == Integer.class || type == Integer.TYPE) {
return (T) Integer.valueOf(value);
} else if (type == Long.class || type == Long.TYPE) {
return (T) Long.valueOf(value);
} else if (type == Short.class || type == Short.TYPE) {
return (T) Short.valueOf(value);
} else if (type == Float.class || type == Float.TYPE) {
return (T) Float.valueOf(value);
} else if (type == Double.class || type == Double.TYPE) {
return (T) Double.valueOf(value);
} else if (type == Byte.class || type == Byte.TYPE) {
return (T) Byte.valueOf(value);
} else if (type == Character.class || type == Character.TYPE) {
return (T) (Character) value.charAt(0);
} else {
return (T) value;
}
}
protected java.util.Date toDate(String str, String format, java.util.Date defaultValue) {
if (str == null || str.length() == 0) {
return defaultValue;
}
try {
return new java.text.SimpleDateFormat(format).parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(String.format("Unable to parse date(%s) in format(%s)!", str, format), e);
}
}
}
|
923693ba22df71c81c858fe23ef102fbe42896a6 | 7,128 | java | Java | src/test/java/fuzzy/mf/TestTrapezoidalMembershipFunction.java | tupilabs/nebular | 05fcde0930a21efb3d3a17750fcca361cfa31cdc | [
"Apache-2.0"
] | 4 | 2016-02-16T05:11:34.000Z | 2017-09-09T17:08:46.000Z | src/test/java/fuzzy/mf/TestTrapezoidalMembershipFunction.java | tupilabs/nebular | 05fcde0930a21efb3d3a17750fcca361cfa31cdc | [
"Apache-2.0"
] | null | null | null | src/test/java/fuzzy/mf/TestTrapezoidalMembershipFunction.java | tupilabs/nebular | 05fcde0930a21efb3d3a17750fcca361cfa31cdc | [
"Apache-2.0"
] | null | null | null | 37.515789 | 115 | 0.630191 | 997,741 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package fuzzy.mf;
import static org.junit.Assert.assertEquals;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for Trapezoidal Membership Function.
*
* @since 0.1
* @see TrapezoidalMembershipFunction
*/
public class TestTrapezoidalMembershipFunction extends BaseMembershipFunctionTest<TrapezoidalMembershipFunction> {
protected TrapezoidalMembershipFunction mf;
private final double a = 1.0;
private final double b = 5.0;
private final double c = 7.0;
private final double d = 8.0;
private final double[][] expected = new double[101][2];
@Override
protected TrapezoidalMembershipFunction makeMembershipFunction() {
return new TrapezoidalMembershipFunction(a, b, c, d);
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
mf = makeMembershipFunction();
/*
* Results from Matlab trapmf.
*
* x=0:0.1:10;
* y=trapmf(x,[1 5 7 8]);
*/
expected[0] = new double[]{0.0000, 0.0000};
expected[1] = new double[]{0.1000, 0.0000};
expected[2] = new double[]{0.2000, 0.0000};
expected[3] = new double[]{0.3000, 0.0000};
expected[4] = new double[]{0.4000, 0.0000};
expected[5] = new double[]{0.5000, 0.0000};
expected[6] = new double[]{0.6000, 0.0000};
expected[7] = new double[]{0.7000, 0.0000};
expected[8] = new double[]{0.8000, 0.0000};
expected[9] = new double[]{0.9000, 0.0000};
expected[10] = new double[]{1.0000, 0.0000};
expected[11] = new double[]{1.1000, 0.0250};
expected[12] = new double[]{1.2000, 0.0500};
expected[13] = new double[]{1.3000, 0.0750};
expected[14] = new double[]{1.4000, 0.1000};
expected[15] = new double[]{1.5000, 0.1250};
expected[16] = new double[]{1.6000, 0.1500};
expected[17] = new double[]{1.7000, 0.1750};
expected[18] = new double[]{1.8000, 0.2000};
expected[19] = new double[]{1.9000, 0.2250};
expected[20] = new double[]{2.0000, 0.2500};
expected[21] = new double[]{2.1000, 0.2750};
expected[22] = new double[]{2.2000, 0.3000};
expected[23] = new double[]{2.3000, 0.3250};
expected[24] = new double[]{2.4000, 0.3500};
expected[25] = new double[]{2.5000, 0.3750};
expected[26] = new double[]{2.6000, 0.4000};
expected[27] = new double[]{2.7000, 0.4250};
expected[28] = new double[]{2.8000, 0.4500};
expected[29] = new double[]{2.9000, 0.4750};
expected[30] = new double[]{3.0000, 0.5000};
expected[31] = new double[]{3.1000, 0.5250};
expected[32] = new double[]{3.2000, 0.5500};
expected[33] = new double[]{3.3000, 0.5750};
expected[34] = new double[]{3.4000, 0.6000};
expected[35] = new double[]{3.5000, 0.6250};
expected[36] = new double[]{3.6000, 0.6500};
expected[37] = new double[]{3.7000, 0.6750};
expected[38] = new double[]{3.8000, 0.7000};
expected[39] = new double[]{3.9000, 0.7250};
expected[40] = new double[]{4.0000, 0.7500};
expected[41] = new double[]{4.1000, 0.7750};
expected[42] = new double[]{4.2000, 0.8000};
expected[43] = new double[]{4.3000, 0.8250};
expected[44] = new double[]{4.4000, 0.8500};
expected[45] = new double[]{4.5000, 0.8750};
expected[46] = new double[]{4.6000, 0.9000};
expected[47] = new double[]{4.7000, 0.9250};
expected[48] = new double[]{4.8000, 0.9500};
expected[49] = new double[]{4.9000, 0.9750};
expected[50] = new double[]{5.0000, 1.0000};
expected[51] = new double[]{5.1000, 1.0000};
expected[52] = new double[]{5.2000, 1.0000};
expected[53] = new double[]{5.3000, 1.0000};
expected[54] = new double[]{5.4000, 1.0000};
expected[55] = new double[]{5.5000, 1.0000};
expected[56] = new double[]{5.6000, 1.0000};
expected[57] = new double[]{5.7000, 1.0000};
expected[58] = new double[]{5.8000, 1.0000};
expected[59] = new double[]{5.9000, 1.0000};
expected[60] = new double[]{6.0000, 1.0000};
expected[61] = new double[]{6.1000, 1.0000};
expected[62] = new double[]{6.2000, 1.0000};
expected[63] = new double[]{6.3000, 1.0000};
expected[64] = new double[]{6.4000, 1.0000};
expected[65] = new double[]{6.5000, 1.0000};
expected[66] = new double[]{6.6000, 1.0000};
expected[67] = new double[]{6.7000, 1.0000};
expected[68] = new double[]{6.8000, 1.0000};
expected[69] = new double[]{6.9000, 1.0000};
expected[70] = new double[]{7.0000, 1.0000};
expected[71] = new double[]{7.1000, 0.9000};
expected[72] = new double[]{7.2000, 0.8000};
expected[73] = new double[]{7.3000, 0.7000};
expected[74] = new double[]{7.4000, 0.6000};
expected[75] = new double[]{7.5000, 0.5000};
expected[76] = new double[]{7.6000, 0.4000};
expected[77] = new double[]{7.7000, 0.3000};
expected[78] = new double[]{7.8000, 0.2000};
expected[79] = new double[]{7.9000, 0.1000};
expected[80] = new double[]{8.0000, 0.0000};
expected[81] = new double[]{8.1000, 0.0000};
expected[82] = new double[]{8.2000, 0.0000};
expected[83] = new double[]{8.3000, 0.0000};
expected[84] = new double[]{8.4000, 0.0000};
expected[85] = new double[]{8.5000, 0.0000};
expected[86] = new double[]{8.6000, 0.0000};
expected[87] = new double[]{8.7000, 0.0000};
expected[88] = new double[]{8.8000, 0.0000};
expected[89] = new double[]{8.9000, 0.0000};
expected[90] = new double[]{9.0000, 0.0000};
expected[91] = new double[]{9.1000, 0.0000};
expected[92] = new double[]{9.2000, 0.0000};
expected[93] = new double[]{9.3000, 0.0000};
expected[94] = new double[]{9.4000, 0.0000};
expected[95] = new double[]{9.5000, 0.0000};
expected[96] = new double[]{9.6000, 0.0000};
expected[97] = new double[]{9.7000, 0.0000};
expected[98] = new double[]{9.8000, 0.0000};
expected[99] = new double[]{9.9000, 0.0000};
expected[100] = new double[]{10.0000, 0.0000};
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
mf = null;
}
/**
* Test method for {@link fuzzy.mf.TrapezoidalMembershipFunction#evaluate(java.lang.Double)}.
*/
@Test
public void testEvaluate() {
final NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMaximumFractionDigits(4);
nf.setRoundingMode(RoundingMode.HALF_UP);
int i = 0;
for(double x = 0.0 ; x <= 10.0 ; x+=0.1) {
double y = Double.parseDouble(nf.format(mf.apply(x)));
assertEquals(Double.valueOf(expected[i][1]), Double.valueOf(y));
i++;
}
}
}
|
9236940616f5acce01f96ef5ea60185963985d4c | 1,021 | java | Java | OAuthManager/src/main/java/io/apimatic/oauthmanager/common/httpClient/headers/MediaTypeHeaderParser.java | IAmWaseem/oauth2-android | 87692822b35a5b51edbbde753f5f7b28926b69fc | [
"MIT"
] | null | null | null | OAuthManager/src/main/java/io/apimatic/oauthmanager/common/httpClient/headers/MediaTypeHeaderParser.java | IAmWaseem/oauth2-android | 87692822b35a5b51edbbde753f5f7b28926b69fc | [
"MIT"
] | null | null | null | OAuthManager/src/main/java/io/apimatic/oauthmanager/common/httpClient/headers/MediaTypeHeaderParser.java | IAmWaseem/oauth2-android | 87692822b35a5b51edbbde753f5f7b28926b69fc | [
"MIT"
] | null | null | null | 40.84 | 152 | 0.781587 | 997,742 | package io.apimatic.oauthmanager.common.httpClient.headers;
import io.apimatic.oauthmanager.common.Holder;
final class MediaTypeHeaderParser extends BaseHeaderParser
{
public static final MediaTypeHeaderParser SingleValueParser = new MediaTypeHeaderParser(false);
private MediaTypeHeaderParser(final boolean supportsMultipleValues)
{
super(supportsMultipleValues);
}
@Override
protected int getParsedValueLength(final String value, final int startIndex, final Object storeValue, final Holder<Object> parsedValue)
{
final Holder<Integer> index = new Holder<Integer>(startIndex);
final Holder<io.apimatic.oauthmanager.common.httpClient.headers.MediaTypeHeaderValue> mediaTypeHeaderValue = new Holder<MediaTypeHeaderValue>();
final int mediaTypeLength = MediaTypeHeaderValueBase.getMediaTypeLength(value, index, mediaTypeHeaderValue, MediaTypeHeaderValue.class);
parsedValue.value = mediaTypeHeaderValue.value;
return mediaTypeLength;
}
} |
9236947ca10a454b2713241b9a06e593d6a33b83 | 6,359 | java | Java | mathletfactory_lib/src/net/mumie/mathletfactory/display/LineDisplayProperties.java | TU-Berlin/Mumie | 322f6772f5bf1ce42fc00d0c6f8c3eba27ecc010 | [
"MIT"
] | null | null | null | mathletfactory_lib/src/net/mumie/mathletfactory/display/LineDisplayProperties.java | TU-Berlin/Mumie | 322f6772f5bf1ce42fc00d0c6f8c3eba27ecc010 | [
"MIT"
] | null | null | null | mathletfactory_lib/src/net/mumie/mathletfactory/display/LineDisplayProperties.java | TU-Berlin/Mumie | 322f6772f5bf1ce42fc00d0c6f8c3eba27ecc010 | [
"MIT"
] | null | null | null | 31.480198 | 88 | 0.726687 | 997,743 | /*
* The MIT License (MIT)
*
* Copyright (c) 2010 Technische Universitaet Berlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.mumie.mathletfactory.display;
import java.awt.geom.Arc2D;
import java.awt.geom.GeneralPath;
/**
* This class handles the specific display properties for all types of lines.
*
* @author Amsel
* @mm.docstatus finished
*/
public class LineDisplayProperties extends DisplayProperties {
public final static String DP_BASE_PATH = "display.line.";
/**
* Name of the <i>line width</i> property.
* @see #getLineWidth()
*/
public final static String LINE_WIDTH_PROPERTY = DP_BASE_PATH + "width";
public final static LineDisplayProperties DEFAULT = new LineDisplayProperties();
public final static LineDisplayProperties VECTOR_DEFAULT = new LineDisplayProperties();
/**
* Name of the <i>arrow at start</i> property.
* @see #getArrowAtStart()
*/
public final static String ARROW_AT_START_PROPERTY = DP_BASE_PATH + "arrowAtStart";
/**
* Name of the <i>arrow at end</i> property.
* @see #getArrowAtEnd()
*/
public final static String ARROW_AT_END_PROPERTY = DP_BASE_PATH + "arrowAtEnd";
// Standardmaessig ist eine Linie 3 Pixel dick (wenn TUBES_DRAW = false)
public final static double DEFAULT_LINE_WIDTH = 3;
/** Constant for a straight line ending. */
public final static GeneralPath LINE_END = new GeneralPath();
/** Constant for a curved line ending. */
public final static GeneralPath ARC_END = new GeneralPath();
/** Constant for a simple arrow line ending. */
public final static GeneralPath SIMPLE_ARROW_END = new GeneralPath();
/** Constant for a plain arrow line ending. */
public final static GeneralPath PLAIN_ARROW_END = new GeneralPath();
/** Constant for a complex arrow line ending. */
public final static GeneralPath COMPLEX_ARROW_END = new GeneralPath();
/** Constant for an arrow line ending. */
public final static GeneralPath ARROW_END = new GeneralPath();
//
// load default properties into static map
//
static {
LINE_END.moveTo( 0, 0 );
LINE_END.lineTo( 10, 0 );
ARC_END.append( new Arc2D.Double( 5, -5, 10, 10, 0, 180, Arc2D.OPEN ), false );
SIMPLE_ARROW_END.moveTo( 20, 25 );
SIMPLE_ARROW_END.lineTo( 20, 14 );
SIMPLE_ARROW_END.lineTo( 27, 25 );
SIMPLE_ARROW_END.lineTo( 30, 22 );
SIMPLE_ARROW_END.lineTo( 15, 0 );
SIMPLE_ARROW_END.lineTo( 0, 22 );
SIMPLE_ARROW_END.lineTo( 3, 25 );
SIMPLE_ARROW_END.lineTo( 10, 14 );
SIMPLE_ARROW_END.lineTo( 10, 25 );
PLAIN_ARROW_END.moveTo( 20, 25 );
PLAIN_ARROW_END.lineTo( 30, 25 );
PLAIN_ARROW_END.lineTo( 15, 0 );
PLAIN_ARROW_END.lineTo( 0, 25 );
PLAIN_ARROW_END.lineTo( 10, 25 );
COMPLEX_ARROW_END.moveTo( 20, 25 );
COMPLEX_ARROW_END.lineTo( 20, 20 );
COMPLEX_ARROW_END.lineTo( 30, 25 );
COMPLEX_ARROW_END.lineTo( 15, 0 );
COMPLEX_ARROW_END.lineTo( 0, 25 );
COMPLEX_ARROW_END.lineTo( 10, 20 );
COMPLEX_ARROW_END.lineTo( 10, 25 );
ARROW_END.moveTo( 30, 38 );
ARROW_END.lineTo( 45, 38 );
ARROW_END.lineTo( 22, 0 );
ARROW_END.lineTo( 0, 38 );
ARROW_END.lineTo( 15, 38 );
VECTOR_DEFAULT.setDefaultProperty(LINE_WIDTH_PROPERTY, DEFAULT_LINE_WIDTH);
VECTOR_DEFAULT.setArrowAtStart( ARC_END );
VECTOR_DEFAULT.setArrowAtEnd( COMPLEX_ARROW_END );
DEFAULT.setDefaultProperty(LINE_WIDTH_PROPERTY, DEFAULT_LINE_WIDTH);
DEFAULT.setDefaultProperty(ARROW_AT_START_PROPERTY, ARC_END);
DEFAULT.setDefaultProperty(ARROW_AT_END_PROPERTY, ARC_END);
}
public LineDisplayProperties() {
this(null);
}
// public LineDisplayProperties( String name ) {
// super( name );
// this.getShaderDisplayProperties().setVertexVisible( false );
// this.getShaderDisplayProperties().setFaceVisible( false );
// }
public LineDisplayProperties( DisplayProperties p ) {
super( p );
// if(p != null)
// copyPropertiesFrom(p);
// DP: moved to JR3DShaderDisplayProperties's copy constructor
// if ( !( p instanceof LineDisplayProperties ) ) {
// this.getShaderDisplayProperties().setEdgeVisible( true );
// this.getShaderDisplayProperties().setVertexVisible( false );
// this.getShaderDisplayProperties().setFaceVisible( false );
// }
}
public GeneralPath getArrowAtStart() {
Object value = this.getProperty( ARROW_AT_START_PROPERTY );
if ( value == null ) {
value = ARC_END;
}
return ( GeneralPath ) value;
}
public void setArrowAtStart( GeneralPath value ) {
this.setProperty( ARROW_AT_START_PROPERTY, value );
}
public GeneralPath getArrowAtEnd() {
Object value = this.getProperty( ARROW_AT_END_PROPERTY );
if ( value == null ) {
value = ARC_END;
}
return ( GeneralPath ) value;
}
public void setArrowAtEnd( GeneralPath value ) {
this.setProperty( ARROW_AT_END_PROPERTY, value );
}
public double getLineWidth() {
Object value = this.getProperty( LINE_WIDTH_PROPERTY );
if ( value == null ) {
value = new Double( DEFAULT_LINE_WIDTH );
}
return (( Double ) value).doubleValue();
}
public void setLineWidth( double width ) {
this.setProperty( LINE_WIDTH_PROPERTY, new Double( width ) );
}
protected DisplayProperties createInstance() {
return new LineDisplayProperties();
}
public Object clone() {
DisplayProperties props = (DisplayProperties) super.clone();
return new LineDisplayProperties( props );
}
}
|
923694edf2e891cab2b3295a91d544ae13c16047 | 4,601 | java | Java | google-tv-pairing-protocol/java/src/com/google/polo/wire/json/JsonWireAdapter.java | OpenSource-Infinix/android_external_crcalc | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | google-tv-pairing-protocol/java/src/com/google/polo/wire/json/JsonWireAdapter.java | OpenSource-Infinix/android_external_crcalc | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | google-tv-pairing-protocol/java/src/com/google/polo/wire/json/JsonWireAdapter.java | OpenSource-Infinix/android_external_crcalc | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | 32.174825 | 80 | 0.727451 | 997,744 | /*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.polo.wire.json;
import com.google.polo.exception.PoloException;
import com.google.polo.json.JSONException;
import com.google.polo.json.JSONObject;
import com.google.polo.pairing.PairingContext;
import com.google.polo.pairing.PoloUtil;
import com.google.polo.pairing.message.PoloMessage;
import com.google.polo.pairing.message.PoloMessage.PoloMessageType;
import com.google.polo.wire.PoloWireInterface;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A {@link PoloWireInterface} which uses JavaScript Object Notation (JSON) for
* the message representation.
* <p>
* Messages are streamed over the wire prepended with an integer which indicates
* the total length, in bytes, of the message which follows. The format of the
* message is JSON.
* <p>
* See {@link JsonMessageBuilder} for the underlying message translation
* implementation.
*/
public class JsonWireAdapter implements PoloWireInterface {
/**
* The output coming from the peer.
*/
private final DataInputStream mInputStream;
/**
* The input going to the peer.
*/
private final DataOutputStream mOutputStream;
/**
* Constructor.
*
* @param input the {@link InputStream} from the peer
* @param output the {@link OutputStream} to the peer
*/
public JsonWireAdapter(InputStream input, OutputStream output) {
mInputStream = new DataInputStream(input);
mOutputStream = new DataOutputStream(output);
}
/**
* Generates a new instance from a {@link PairingContext}.
*
* @param context the {@link PairingContext}
* @return the new instance
*/
public static JsonWireAdapter fromContext(PairingContext context) {
return new JsonWireAdapter(context.getPeerInputStream(), context
.getPeerOutputStream());
}
public PoloMessage getNextMessage() throws IOException, PoloException {
byte[] payloadLenBytes = new byte[4];
mInputStream.readFully(payloadLenBytes);
long payloadLen = PoloUtil.intBigEndianBytesToLong(payloadLenBytes);
byte[] outerJsonBytes = new byte[(int) payloadLen];
mInputStream.readFully(outerJsonBytes);
return parseOuterMessageString(new String(outerJsonBytes));
}
public PoloMessage parseOuterMessageString(String outerString)
throws PoloException {
JSONObject outerMessage;
try {
outerMessage = new JSONObject(outerString);
} catch (JSONException e) {
throw new PoloException("Error parsing incoming message", e);
}
return JsonMessageBuilder.outerJsonToPoloMessage(outerMessage);
}
public PoloMessage getNextMessage(PoloMessageType type) throws IOException,
PoloException {
PoloMessage message = getNextMessage();
if (message.getType() != type) {
throw new PoloException("Wrong message type (wanted " + type + ", got "
+ message.getType() + ")");
}
return message;
}
public void sendErrorMessage(Exception exception) throws IOException {
try {
writeJson(JsonMessageBuilder.getErrorJson(exception));
} catch (PoloException e) {
throw new IOException("Error sending error message");
}
}
public void sendMessage(PoloMessage message) throws IOException {
String outString;
JSONObject outerJson;
try {
outerJson = JsonMessageBuilder.getOuterJson(message);
} catch (PoloException e) {
throw new IOException("Error generating message");
}
writeJson(outerJson);
}
/**
* Writes a {@link JSONObject} to the output stream as a {@link String}.
*
* @param message the message to write
* @throws IOException on error generating the serialized message
*/
private void writeJson(JSONObject message) throws IOException {
byte[] outBytes = message.toString().getBytes();
mOutputStream.write(PoloUtil.intToBigEndianIntBytes(outBytes.length));
mOutputStream.write(outBytes);
}
}
|
9236950e5ad248bffb59842ed4d8bd06fc0d6481 | 17,467 | java | Java | src/org/apache/mahout/classifier/chi_rw/RuleBase.java | saradelrio/Chi-FRBCS-BigData-Ave | 750f07d059c785cee40ebf7f4e42d4a3385bbc9c | [
"Apache-2.0"
] | 3 | 2016-05-26T09:42:44.000Z | 2021-04-06T14:43:11.000Z | src/org/apache/mahout/classifier/chi_rw/RuleBase.java | saradelrio/Chi-FRBCS-BigData-Ave | 750f07d059c785cee40ebf7f4e42d4a3385bbc9c | [
"Apache-2.0"
] | 2 | 2017-06-11T04:56:09.000Z | 2019-04-05T13:12:19.000Z | src/org/apache/mahout/classifier/chi_rw/RuleBase.java | saradelrio/Chi-FRBCS-BigData-Ave | 750f07d059c785cee40ebf7f4e42d4a3385bbc9c | [
"Apache-2.0"
] | 2 | 2018-11-22T08:19:48.000Z | 2020-04-20T07:32:35.000Z | 32.832707 | 145 | 0.556249 | 997,745 | package org.apache.mahout.classifier.chi_rw;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Mapper.Context;
import org.apache.mahout.classifier.chi_rw.data.Data;
import org.apache.mahout.classifier.chi_rw.data.Dataset;
import org.apache.mahout.classifier.chi_rw.data.Instance;
import org.apache.mahout.classifier.chi_rw.mapreduce.*;
import com.google.common.io.Closeables;
public class RuleBase implements Writable {
ArrayList<Rule> ruleBase;
DataBase dataBase;
int n_variables, n_labels, ruleWeight, inferenceType, compatibilityType;
String[] names, classes;
int[] ruleBaseSizes;
public RuleBase(){
ruleBase = new ArrayList<Rule>();
}
/**
* Rule Base Constructor
* @param dataBase DataBase the Data Base containing the fuzzy partitions
* @param inferenceType int the inference type for the FRM
* @param compatibilityType int the compatibility type for the t-norm
* @param ruleWeight int the rule weight heuristic
* @param names String[] the names for the features of the problem
* @param classes String[] the labels for the class attributes
*/
public RuleBase(DataBase dataBase, int inferenceType, int compatibilityType, int ruleWeight, String[] names, String[] classes) {
ruleBase = new ArrayList<Rule>();
this.dataBase = dataBase;
n_variables = dataBase.numVariables();
n_labels = dataBase.numLabels();
this.inferenceType = inferenceType;
this.compatibilityType = compatibilityType;
this.ruleWeight = ruleWeight;
this.names = names.clone();
this.classes = classes.clone();
this.ruleBaseSizes = new int[1];
Arrays.fill(this.ruleBaseSizes, 0);
}
/**
* Rule Base Constructor
* @param dataBase DataBase the Data Base containing the fuzzy partitions
* @param inferenceType int the inference type for the FRM
* @param compatibilityType int the compatibility type for the t-norm
* @param ruleWeight int the rule weight heuristic
* @param names String[] the names for the features of the problem
* @param classes String[] the labels for the class attributes
*/
public RuleBase(DataBase dataBase, int inferenceType, int compatibilityType, int ruleWeight, String[] names, String[] classes, int mappers) {
ruleBase = new ArrayList<Rule>();
this.dataBase = dataBase;
n_variables = dataBase.numVariables();
n_labels = dataBase.numLabels();
this.inferenceType = inferenceType;
this.compatibilityType = compatibilityType;
this.ruleWeight = ruleWeight;
this.names = names.clone();
this.classes = classes.clone();
this.ruleBaseSizes = new int[mappers];
}
public DataBase getDataBase(){
return dataBase;
}
public int getInferenceType(){
return inferenceType;
}
public int getCompatibilityType(){
return compatibilityType;
}
public int getRuleWeight(){
return ruleWeight;
}
public String[] getNames(){
return names;
}
public String[] getClasses(){
return classes;
}
public int size(){
return ruleBase.size();
}
public void add(Rule r){
ruleBase.add(r);
}
public Rule get(int i){
return ruleBase.get(i);
}
public void setRuleBaseSize(int pos, int size){
ruleBaseSizes[pos]=size;
}
public int[] getRuleBaseSizes(){
return ruleBaseSizes;
}
/**
* It checks if a specific rule is already in the rule base
* @param r Rule the rule for comparison
* @return boolean true if the rule is already in the rule base, false in other case
*/
public boolean duplicated(Rule r) {
int i = 0;
boolean found = false;
while ((i < ruleBase.size()) && (!found)) {
found = ruleBase.get(i).comparison(r);
i++;
}
return found;
}
/**
* It checks if a specific rule is already in the rule base
* @param r Rule the rule for comparison
* @return boolean true if the rule is already in the rule base, false in other case
*/
/*
public boolean duplicated_reduce(Rule r) {
int i = 0, j = 0;
int averageWeight[] = new int[classes.length];
int numberRulesByClass[] = new int[classes.length];
boolean[] found = {false, false};
boolean[] found_ = {false, false};
while ((i < ruleBase.size()) && !(found[0]&&found[1])) {
found = ruleBase.get(i).comparison_reduce(r);
if(found[0]&&found[1]){
System.out.println("Entra");
while (j < ruleBase.size()){
found_ = ruleBase.get(j).comparison_reduce(r);
if(found_[0]){
averageWeight[ruleBase.get(j).getClas()] += ruleBase.get(j).getWeight();
numberRulesByClass[ruleBase.get(j).getClas()] += 1;
}
j++;
}
averageWeight[r.getClas()] += r.getWeight();
numberRulesByClass[r.getClas()] += 1;
for(int k = 0 ; k < averageWeight.length ; k++){
averageWeight[k] = averageWeight[k]/numberRulesByClass[k];
}
int higherWeight = averageWeight[0];
int newClass = 0;
for(int k = 1 ; k < averageWeight.length ; k++){
if(averageWeight[k] > higherWeight){
higherWeight = averageWeight[k];
newClass = k ;
}
}
r.setWeight(higherWeight);
r.setClass(newClass);
}
i++;
}
return found[0];
}*/
public boolean duplicated_reduce(Rule r) {
int i = 0, j = 0;
int averageWeight[] = new int[classes.length];
int numberRulesByClass[] = new int[classes.length];
boolean[] found = {false, false};
boolean[] found_ = {false, false};
while ((i < ruleBase.size()) && !found[0]) {
found = ruleBase.get(i).comparison_reduce(r);
if(found[0]){
while (j < ruleBase.size()){
found_ = ruleBase.get(j).comparison_reduce(r);
if(found_[0]){
averageWeight[ruleBase.get(j).getClas()] += ruleBase.get(j).getWeight();
numberRulesByClass[ruleBase.get(j).getClas()] += 1;
}
j++;
}
for(int k = 0 ; k < averageWeight.length ; k++){
if(numberRulesByClass[k] == 0)
averageWeight[k] = -9999;
else
averageWeight[k] = averageWeight[k]/numberRulesByClass[k];
}
int higherWeight = averageWeight[0];
int newClass = 0;
for(int k = 1 ; k < averageWeight.length ; k++){
if(averageWeight[k] > higherWeight){
higherWeight = averageWeight[k];
newClass = k ;
}
}
r.setWeight(higherWeight);
r.setClass(newClass);
}
i++;
}
return found[0];
}
/**
* Rule Learning Mechanism for the Chi et al.'s method
* @param train myDataset the training data-set
*//*
public void Generation(Data train, Context context) {
ArrayList<Rule> temporalRuleBase = new ArrayList<Rule>();;
Dataset dataset = train.getDataset();
for (int i = 0; i < train.size(); i++) {
context.progress();
Rule r = searchForBestAntecedent(train.get(i).get(), (int) dataset.getLabel(train.get(i)));
r.assingConsequent(train, ruleWeight);
temporalRuleBase.add(r);
}
for(int i = 0 ; i < temporalRuleBase.size() ; i++){
context.progress();
if ((temporalRuleBase.get(i).weight > 0)) {
if(ruleBase.size() == 0){
ruleBase.add(temporalRuleBase.get(i));
}
else if (!duplicated(temporalRuleBase.get(i))){
ruleBase.add(temporalRuleBase.get(i));
}
}
}
}*/
/**
* Rule Learning Mechanism for the Chi et al.'s method
* @param train myDataset the training data-set
*/
public void Generation(Data train, Context context) {
Dataset dataset = train.getDataset();
for (int i = 0; i < train.size(); i++) {
context.progress();
Rule r = searchForBestAntecedent(train.get(i).get(), (int) dataset.getLabel(train.get(i)));
r.assingConsequent(train, ruleWeight);
if ((!duplicated(r)) &&
(r.weight > 0)) {
ruleBase.add(r);
}
}
}
/**
* This function obtains the best fuzzy label for each variable of the example and assigns
* it to the rule
* @param example double[] the input example
* @param clas int the class of the input example
* @return Rule the fuzzy rule with the highest membership degree with the example
*/
private Rule searchForBestAntecedent(double[] example, int clas) {
Rule r = new Rule(n_variables, this.compatibilityType);
r.setClass(clas);
for (int i = 0; i < n_variables; i++) {
double max = 0.0;
int etq = -1;
double per;
for (int j = 0; j < n_labels; j++) {
per = dataBase.membershipFunction(i, j, example[i]);
if (per > max) {
max = per;
etq = j;
}
}
if (max == 0.0) {
System.err.println(
"There was an Error while searching for the antecedent of the rule");
System.err.println("Example: ");
for (int j = 0; j < n_variables; j++) {
System.err.print(example[j] + "\t");
}
System.err.println("Variable " + i);
System.exit(1);
}
r.antecedent[i] = dataBase.clone(i, etq);
}
return r;
}
/**
* Fuzzy Reasoning Method
* @param example double[] the input example
* @return int the predicted class label (id)
*/
public int FRM(double[] example) {
if (this.inferenceType == BuildModel.WINNING_RULE) {
return FRM_WR(example);
} else {
return FRM_AC(example);
}
}
/**
* Winning Rule FRM
* @param example double[] the input example
* @return int the class label for the rule with highest membership degree to the example
*/
private int FRM_WR(double[] example) {
int clas = -1;
double max = 0.0;
for (int i = 0; i < ruleBase.size(); i++) {
Rule r = ruleBase.get(i);
double produc = r.compatibility(example);
produc *= r.weight;
if (produc > max) {
max = produc;
clas = r.clas;
}
}
return clas;
}
/**
* Additive Combination FRM
* @param example double[] the input example
* @return int the class label for the set of rules with the highest sum of membership degree per class
*/
private int FRM_AC(double[] example) {
int clas = -1;
double[] class_degrees = new double[1];
for (int i = 0; i < ruleBase.size(); i++) {
Rule r = ruleBase.get(i);
double produc = r.compatibility(example);
produc *= r.weight;
if (r.clas > class_degrees.length - 1) {
double[] aux = new double[class_degrees.length];
for (int j = 0; j < aux.length; j++) {
aux[j] = class_degrees[j];
}
class_degrees = new double[r.clas + 1];
for (int j = 0; j < aux.length; j++) {
class_degrees[j] = aux[j];
}
}
class_degrees[r.clas] += produc;
}
double max = 0.0;
for (int l = 0; l < class_degrees.length; l++) {
if (class_degrees[l] > max) {
max = class_degrees[l];
clas = l;
}
}
return clas;
}
/**
* It prints the rule base into an string
* @return String an string containing the rule base
*/
public String printString() {
int i, j;
String cadena = "";
cadena += "@Number of rules: " + ruleBase.size() + "\n\n";
for (i = 0; i < ruleBase.size(); i++) {
Rule r = ruleBase.get(i);
cadena += (i + 1) + ": ";
for (j = 0; j < n_variables - 1; j++) {
cadena += names[j] + " IS " + r.antecedent[j].name + " AND ";
}
cadena += names[j] + " IS " + r.antecedent[j].name + ": " +
classes[r.clas] + " with Rule Weight: " + r.weight + "\n";
}
return (cadena);
}
public String rulePrintString(Rule r) {
int i;
String cadena = "";
for (i = 0; i < n_variables - 1; i++) {
cadena += names[i] + " IS " + r.antecedent[i].name + " AND ";
}
cadena += names[i] + " IS " + r.antecedent[i].name + ": " +
classes[r.clas] + " with Rule Weight: " + r.weight + "\n";
return (cadena);
}
/**
* Load the rule base from a single file or a directory of files
* @throws java.io.IOException
*/
public static RuleBase load(Configuration conf, Path fuzzy_ChiCSPath) throws IOException {
FileSystem fs = fuzzy_ChiCSPath.getFileSystem(conf);
Path[] files;
if (fs.getFileStatus(fuzzy_ChiCSPath).isDir()) {
files = Chi_RWUtils.listOutputFiles(fs, fuzzy_ChiCSPath);
} else {
files = new Path[]{fuzzy_ChiCSPath};
}
RuleBase rb = null;
for (Path path : files) {
FSDataInputStream dataInput = new FSDataInputStream(fs.open(path));
try {
if (rb == null) {
rb = read(dataInput);
} else {
rb.readFields(dataInput);
}
} finally {
Closeables.closeQuietly(dataInput);
}
}
return rb;
}
private static RuleBase read(DataInput dataInput) throws IOException {
RuleBase rb = new RuleBase();
rb.readFields(dataInput);
return rb;
}
/**
* predicts the label for the instance
*
*/
public double classify(Instance instance) {
//for classification:
return this.classificationOutput(instance.get());
}
/**
* It returns the algorithm classification output given an input example
* @param example double[] The input example
* @return String the output generated by the algorithm
*/
private double classificationOutput(double[] example) {
/**
Here we should include the algorithm directives to generate the
classification output from the input example
*/
int classOut = FRM(example);
if (classOut >= 0) {
return classOut;
}
else
return Double.NaN;
}
@Override
public void readFields(DataInput in) throws IOException {
// TODO Auto-generated method stub
n_variables = in.readInt();
n_labels = in.readInt();
ruleWeight = in.readInt();
inferenceType = in.readInt();
compatibilityType = in.readInt();
int names_size = in.readInt();
names = new String[names_size];
for (int i = 0 ; i < names_size ; i++){
names[i] = in.readUTF();
}
int classes_size = in.readInt();
classes = new String[classes_size];
for (int i = 0 ; i < classes_size ; i++){
classes[i] = in.readUTF();
}
dataBase = new DataBase();
dataBase.readFields(in);
int ruleBase_size = in.readInt();
ruleBase = new ArrayList<Rule>();
for (int i = 0 ; i < ruleBase_size ; i++){
Rule element = new Rule();
element.readFields(in);
ruleBase.add(i, element);
}
int ruleBaseSizes_size = in.readInt();
ruleBaseSizes = new int[ruleBaseSizes_size];
for (int i = 0 ; i < ruleBaseSizes_size ; i++){
ruleBaseSizes[i] = in.readInt();
}
}
@Override
public void write(DataOutput out) throws IOException {
// TODO Auto-generated method stub
out.writeInt(n_variables);
out.writeInt(n_labels);
out.writeInt(ruleWeight);
out.writeInt(inferenceType);
out.writeInt(compatibilityType);
out.writeInt(names.length);
for (int i = 0 ; i < names.length ; i++)
out.writeUTF(names[i]);
out.writeInt(classes.length);
for (int i = 0 ; i < classes.length ; i++)
out.writeUTF(classes[i]);
dataBase.write(out);
out.writeInt(ruleBase.size());
for (int i = 0 ; i < ruleBase.size() ; i++)
ruleBase.get(i).write(out);
out.writeInt(ruleBaseSizes.length);
for (int i = 0 ; i < ruleBaseSizes.length ; i++)
out.writeInt(ruleBaseSizes[i]);
}
}
|
923696375821ad22e5bebeca54feafe561c3aec6 | 5,903 | java | Java | src/main/java/com/ws/ogre/v2/commands/db2avro/Config.java | ogreflow/ogre | dbc934da85b9265d3a092e60b5fb1aef3f5e3f0f | [
"Apache-2.0"
] | 3 | 2019-09-23T15:10:27.000Z | 2019-09-24T06:07:37.000Z | src/main/java/com/ws/ogre/v2/commands/db2avro/Config.java | ogreflow/ogre | dbc934da85b9265d3a092e60b5fb1aef3f5e3f0f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ws/ogre/v2/commands/db2avro/Config.java | ogreflow/ogre | dbc934da85b9265d3a092e60b5fb1aef3f5e3f0f | [
"Apache-2.0"
] | null | null | null | 30.117347 | 114 | 0.578181 | 997,746 | package com.ws.ogre.v2.commands.db2avro;
import com.amazonaws.services.s3.model.StorageClass;
import com.ws.ogre.v2.aws.S3Url;
import com.ws.ogre.v2.db.JdbcDbHandler;
import com.ws.ogre.v2.db.JdbcDbHandlerBuilder;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import java.util.*;
/*
log4j.configuration = log4j.xml
types = apa, banan
<type>.sql =
src.db.type = mysql (optional, default mysql)
src.db.host = apa.mysql.com
src.db.port = 3306 (optional, default mysql - 3306, redshift - 5439)
src.db.database = apa
src.db.user = apa
src.db.password = banan
dst.s3.accessKeyId = ...
dst.s3.secretKey = ...
dst.s3.rootPath = s3://...
dst.s3.storageClass = (STANDARD, STANDARD_IA, REDUCED_REDUNDANCY, GLACIER - default is STANDARD_IA)
*/
public class Config {
public String log4jConf;
public String[] types;
public JdbcDbHandler.DbType srcDbType;
public String srcDbHost;
public Integer srcDbPort;
public String srcDbDatabase;
public String srcDbUser;
public String srcDbPassword;
public String srcDbStagingDir;
public String dstAccessKey;
public String dstSecret;
public S3Url dstRoot;
public String dstComponent;
public String dstSource;
public StorageClass dstStorageClass;
public StorageType dstStorageType;
public String localAvroRoot;
public Map<String, Sql> sqls = new HashMap<>();
public static Config load(String theFile) {
try {
return new Config(theFile);
} catch (ConfigurationException e) {
throw new ConfigException(e);
}
}
public Config(String theFile) throws ConfigurationException {
PropertiesConfiguration aConf = new PropertiesConfiguration(theFile);
log4jConf = aConf.getString("log4j.configuration");
srcDbType = JdbcDbHandler.DbType.valueOf(aConf.getString("src.db.type", "mysql").toUpperCase());
srcDbHost = aConf.getString("src.db.host");
srcDbPort = aConf.getInteger("src.db.port", null);
srcDbDatabase = aConf.getString("src.db.database");
srcDbUser = aConf.getString("src.db.user");
srcDbPassword = aConf.getString("src.db.password");
srcDbStagingDir = aConf.getString("src.db.stagingDir");
dstAccessKey = aConf.getString("dst.s3.accessKeyId");
dstSecret = aConf.getString("dst.s3.secretKey");
dstRoot = new S3Url(aConf.getString("dst.s3.rootPath"));
dstComponent = aConf.getString("dst.s3.component");
dstSource = aConf.getString("dst.s3.source");
dstStorageClass = StorageClass.fromValue(aConf.getString("dst.s3.storageClass", "STANDARD_IA"));
dstStorageType = StorageType.fromValue(aConf.getString("dst.s3.storageType", "avro"));
localAvroRoot = aConf.getString("local.avro.root");
types = aConf.getStringArray("types");
aConf.setDelimiterParsingDisabled(true);
aConf.refresh();
for (String aType : types) {
String aName = aType + ".sql";
Sql aSql = new Sql();
aSql.type = aType;
aSql.sql = aConf.getString(aName);
sqls.put(aType, aSql);
}
aConf.setDelimiterParsingDisabled(false);
aConf.refresh();
}
public Sql getSql(String theType) {
return sqls.get(theType);
}
public String getDstS3FullPath() {
return "s3://" + dstRoot.bucket + "/" + dstStorageType.getTypeId() + "/" + dstComponent + "/" + dstSource;
}
public JdbcDbHandlerBuilder.JdbcDbHandlerConfig getSrcDbConfig() {
return new JdbcDbHandlerBuilder.JdbcDbHandlerConfig() {
@Override
public JdbcDbHandler.DbType getDbType() {
return srcDbType;
}
@Override
public String getDbHost() {
return srcDbHost;
}
@Override
public Integer getDbPort() {
return srcDbPort;
}
@Override
public String getDbDatabaseName() {
return srcDbDatabase;
}
@Override
public String getDbUser() {
return srcDbUser;
}
@Override
public String getDbPassword() {
return srcDbPassword;
}
@Override
public String getDbStagingDir() {
return srcDbStagingDir;
}
};
}
public static class Sql {
String sql;
String type;
}
public static class ConfigException extends RuntimeException {
public ConfigException(Throwable theCause) {
super(theCause);
}
}
@Override
public String toString() {
return "Config{" +
"log4jConf=" + log4jConf +
", types=" + Arrays.toString(types) +
", srcDbType=" + srcDbType +
", srcDbHost=" + srcDbHost +
", srcDbPort=" + srcDbPort +
", srcDbDatabase=" + srcDbDatabase +
", srcDbUser=" + srcDbUser +
", srcDbPassword=" + "***" +
", srcDbStagingDir=" + srcDbStagingDir +
", dstAccessKey=" + dstAccessKey +
", dstSecret=" + "***" +
", dstRoot=" + dstRoot +
", dstComponent=" + dstComponent +
", dstSource=" + dstSource +
", dstStorageClass=" + dstStorageClass +
", dstStorageType=" + dstStorageType +
", localAvroRoot=" + localAvroRoot +
", sqls=" + sqls +
'}';
}
}
|
9236978abc481da8236018685b40c5cfb912821e | 1,790 | java | Java | stream-core/src/main/java/org/apache/kylin/stream/core/model/stats/ReceiverCubeRealTimeState.java | Pay-Baymax/kylin | d5a085c907d9786deee897c2f6e1ac9f6ee102ae | [
"Apache-2.0"
] | 3,402 | 2015-12-02T01:37:41.000Z | 2022-03-29T12:10:43.000Z | stream-core/src/main/java/org/apache/kylin/stream/core/model/stats/ReceiverCubeRealTimeState.java | UZi5136225/kylin | ae6120b849c499956a11814d817fb9506e6dd2d6 | [
"Apache-2.0"
] | 1,510 | 2015-12-10T00:22:45.000Z | 2022-03-29T12:17:08.000Z | stream-core/src/main/java/org/apache/kylin/stream/core/model/stats/ReceiverCubeRealTimeState.java | UZi5136225/kylin | ae6120b849c499956a11814d817fb9506e6dd2d6 | [
"Apache-2.0"
] | 1,811 | 2015-12-02T03:49:03.000Z | 2022-03-31T16:01:35.000Z | 37.291667 | 220 | 0.76257 | 997,747 | /*
* 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.kylin.stream.core.model.stats;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
public class ReceiverCubeRealTimeState {
@JsonProperty("receiver_state")
private ReceiverState.State state;
@JsonProperty("receiver_cube_stats")
private ReceiverCubeStats receiverCubeStats;
public ReceiverState.State getState() {
return state;
}
public void setState(ReceiverState.State state) {
this.state = state;
}
public ReceiverCubeStats getReceiverCubeStats() {
return receiverCubeStats;
}
public void setReceiverCubeStats(ReceiverCubeStats receiverCubeStats) {
this.receiverCubeStats = receiverCubeStats;
}
}
|
92369853705e4be30165cb865468a040f8c81016 | 4,005 | java | Java | zols-cms-plugin/src/main/java/org/zols/datastore/web/DataControler.java | techatpark/zols | 7dcf34108bb6a85a99827b6a458a4c237de8c898 | [
"Apache-2.0"
] | null | null | null | zols-cms-plugin/src/main/java/org/zols/datastore/web/DataControler.java | techatpark/zols | 7dcf34108bb6a85a99827b6a458a4c237de8c898 | [
"Apache-2.0"
] | 26 | 2020-04-29T22:55:27.000Z | 2022-01-20T04:40:31.000Z | zols-cms-plugin/src/main/java/org/zols/datastore/web/DataControler.java | techatpark/zols | 7dcf34108bb6a85a99827b6a458a4c237de8c898 | [
"Apache-2.0"
] | 2 | 2021-12-06T08:45:31.000Z | 2022-01-21T11:42:42.000Z | 45.511364 | 137 | 0.73633 | 997,748 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this jsonSchema file, choose Tools | JsonSchemas
* and open the jsonSchema in the editor.
*/
package org.zols.datastore.web;
import java.util.AbstractMap.SimpleEntry;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.zols.datastore.service.DataService;
import static org.zols.datastore.web.util.SpringConverter.getPage;
import org.zols.datatore.exception.DataStoreException;
/**
*
* @author sathish_ku
*/
@RestController
@RequestMapping(value = "/api/data/{schemaId}")
public class DataControler {
private static final Logger LOGGER = getLogger(DataControler.class);
@Autowired
private DataService dataService;
@RequestMapping(method = POST)
public Map<String, Object> create(@PathVariable(value = "schemaId") String schemaName,
@RequestBody Map<String, Object> jsonData, Locale loc) throws DataStoreException {
LOGGER.info("Creating new instance of {}", schemaName);
return dataService.create(schemaName, jsonData, loc);
}
@RequestMapping(value = "/{idname}/{id}", method = GET)
public Map<String, Object> read(@PathVariable(value = "schemaId") String schemaName,
@PathVariable(value = "idname") String idname, @PathVariable(value = "id") String id, Locale loc) throws DataStoreException {
LOGGER.info("Getting Data {} value {}", idname, id);
Optional<Map<String, Object>> optional = dataService.read(schemaName, loc, new SimpleEntry(idname, id));
return optional.orElse(null);
}
@RequestMapping(value = "/{idname}/{id}", method = PUT)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void update(@PathVariable(value = "schemaId") String schemaName,
@PathVariable(value = "idname") String idname,
@PathVariable(value = "id") String id,
@RequestBody Map<String, Object> jsonData, Locale loc) throws DataStoreException {
dataService.update(schemaName, jsonData, loc, new SimpleEntry(idname, id));
}
@RequestMapping(value = "/{idname}/{id}", method = DELETE)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(@PathVariable(value = "schemaId") String schemaName,
@PathVariable(value = "idname") String idname,
@PathVariable(value = "id") String id) throws DataStoreException {
LOGGER.info("Deleting jsonSchemas with id {} value {}", idname, id);
dataService.delete(schemaName, new SimpleEntry(idname, id));
}
@RequestMapping(method = GET)
public Page<Map<String, Object>> list(@PathVariable(value = "schemaId") String schemaName,
@RequestParam(value = "q", required = false) String queryString,
Pageable pageable, Locale loc) throws DataStoreException {
LOGGER.info("Getting Data for {}", schemaName);
return getPage(dataService.list(schemaName, queryString, pageable.getPageNumber(), pageable.getPageSize(), loc), pageable);
}
}
|
923698542ad28a6fccf48b1b7ba8064d886700dd | 7,215 | java | Java | src/main/java/com/cien/teleport/CienTeleport.java | CientistaVuador/NeoELC | 9ab25e3b84d12f5159db5e08f96e668ddac14224 | [
"Unlicense"
] | 3 | 2020-04-10T23:03:29.000Z | 2020-04-28T03:29:08.000Z | src/main/java/com/cien/teleport/CienTeleport.java | CientistaVuador/NeoELC | 9ab25e3b84d12f5159db5e08f96e668ddac14224 | [
"Unlicense"
] | null | null | null | src/main/java/com/cien/teleport/CienTeleport.java | CientistaVuador/NeoELC | 9ab25e3b84d12f5159db5e08f96e668ddac14224 | [
"Unlicense"
] | null | null | null | 27.43346 | 83 | 0.615385 | 997,749 | package com.cien.teleport;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.function.Function;
import com.cien.Module;
import com.cien.data.Properties;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
public class CienTeleport extends Module {
public static final CienTeleport TELEPORT = new CienTeleport();
public static final int DEFAULT_MAX_HOMES = 3;
private static String escape(String s) {
StringBuilder b = new StringBuilder();
for (char c:s.toCharArray()) {
switch (c) {
case ':':
case '\\':
b.append('\\');
}
b.append(c);
}
return b.toString();
}
private final Properties prop = Properties.getProperties("(Module)CienTeleport");
private final List<Home> homes = new ArrayList<>();
private final List<Warp> warps = new ArrayList<>();
private CienTeleport() {
super("CienTeleport");
}
@Override
public void start() {
load();
}
@Override
public void registerCommands(FMLServerStartingEvent event) {
event.registerServerCommand(new com.cien.teleport.commands.DelHome());
event.registerServerCommand(new com.cien.teleport.commands.DelWarp());
event.registerServerCommand(new com.cien.teleport.commands.GotoHome());
event.registerServerCommand(new com.cien.teleport.commands.Home());
event.registerServerCommand(new com.cien.teleport.commands.SetHome());
event.registerServerCommand(new com.cien.teleport.commands.SetMaxHomes());
event.registerServerCommand(new com.cien.teleport.commands.SetWarp());
event.registerServerCommand(new com.cien.teleport.commands.Warp());
event.registerServerCommand(new com.cien.teleport.commands.Tpa());
event.registerServerCommand(new com.cien.teleport.commands.Tprc());
event.registerServerCommand(new com.cien.teleport.commands.Tpac());
event.registerServerCommand(new com.cien.teleport.commands.Tphere());
event.registerServerCommand(new com.cien.teleport.commands.Tpp());
event.registerServerCommand(new com.cien.teleport.commands.Rtp());
}
public void load() {
Function<String, String[]> split = (String s) -> {
StringBuilder b = new StringBuilder(64);
boolean escape = false;
List<String> strings = new ArrayList<>();
for (char c:s.toCharArray()) {
if (escape) {
escape = false;
b.append(c);
continue;
}
if (c == '\\') {
escape = true;
continue;
}
if (c == ':') {
strings.add(b.toString());
b.setLength(0);
continue;
}
b.append(c);
}
if (b.length() != 0) {
strings.add(b.toString());
}
return strings.toArray(new String[strings.size()]);
};
for (Entry<String, String> entry:prop.getEntries()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || value == null) {
continue;
}
if (key.startsWith("HOME->")) {
try {
String[] home = split.apply(key.substring("HOME->".length()));
String[] positions = split.apply(value);
String name = home[0];
String owner = home[1];
String world = positions[0];
float x = Float.parseFloat(positions[1]);
float y = Float.parseFloat(positions[2]);
float z = Float.parseFloat(positions[3]);
float pitch = Float.parseFloat(positions[4]);
float yaw = Float.parseFloat(positions[5]);
Home h = new Home(name, owner, world, x, y, z, pitch, yaw);
addHome(h);
} catch (Exception ex) {
System.out.println("Erro ao carregar home '"+key+"': "+ex.getMessage());
}
} else if (key.startsWith("WARP->")) {
try {
String[] positions = split.apply(value);
String name = key.substring("WARP->".length());
String world = positions[0];
float x = Float.parseFloat(positions[1]);
float y = Float.parseFloat(positions[2]);
float z = Float.parseFloat(positions[3]);
float pitch = Float.parseFloat(positions[4]);
float yaw = Float.parseFloat(positions[5]);
Warp h = new Warp(name, world, x, y, z, pitch, yaw);
addWarp(h);
} catch (Exception ex) {
System.out.println("Erro ao carregar warp '"+key+"': "+ex.getMessage());
}
}
}
}
public Home[] getHomes(){
return homes.toArray(new Home[homes.size()]);
}
public Warp[] getWarps() {
return warps.toArray(new Warp[warps.size()]);
}
public Home[] getHomes(String owner) {
List<Home> homes = new ArrayList<>();
for (Home h:getHomes()) {
if (h.getOwner().equals(owner)) {
homes.add(h);
}
}
return homes.toArray(new Home[homes.size()]);
}
public Home getHome(String name, String owner) {
for (Home h:getHomes()) {
if (h.getName().equalsIgnoreCase(name) && h.getOwner().equals(owner)) {
return h;
}
}
return null;
}
public Warp getWarp(String name) {
for (Warp h:getWarps()) {
if (h.getName().equalsIgnoreCase(name)) {
return h;
}
}
return null;
}
public boolean containsHome(String name, String owner) {
for (Home h:getHomes()) {
if (h.getName().equalsIgnoreCase(name) && h.getOwner().equals(owner)) {
return true;
}
}
return false;
}
public boolean containsWarp(String name) {
for (Warp h:getWarps()) {
if (h.getName().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
public boolean addHome(Home h) {
if (homes.contains(h)) {
return false;
}
String name = "HOME->"+escape(h.getName())+":"+escape(h.getOwner());
String position =
h.getWorld() + ":" +
h.getX() + ":" +
h.getY() + ":" +
h.getZ() + ":" +
h.getPitch() + ":" +
h.getYaw()
;
prop.set(name, position);
homes.add(h);
return true;
}
public boolean removeHome(Home h) {
if (!homes.contains(h)) {
return false;
}
String name = "HOME->"+escape(h.getName())+":"+escape(h.getOwner());
prop.remove(name);
return homes.remove(h);
}
public boolean addWarp(Warp w) {
if (warps.contains(w)) {
return false;
}
String name = "WARP->"+escape(w.getName());
String position =
w.getWorld() + ":" +
w.getX() + ":" +
w.getY() + ":" +
w.getZ() + ":" +
w.getPitch() + ":" +
w.getYaw()
;
prop.set(name, position);
warps.add(w);
return true;
}
public boolean removeWarp(Warp w) {
if (!warps.contains(w)) {
return false;
}
String name = "WARP->"+escape(w.getName());
prop.remove(name);
return warps.remove(w);
}
public int getMaxHomes(String player) {
Properties prop = Properties.getProperties(player);
String homes = prop.get("maxHomes");
if (homes == null) {
return DEFAULT_MAX_HOMES;
}
try {
return Integer.parseInt(homes);
} catch (NumberFormatException ex) {
return DEFAULT_MAX_HOMES;
}
}
public void setMaxHomes(String player, int homes) {
Properties prop = Properties.getProperties(player);
prop.set("maxHomes", Integer.toString(homes));
}
public int getNumberOfHomes(String player) {
return getHomes(player).length;
}
}
|
923699cbf0c938cc1bfae0b30cb4b214f836bb5f | 16,321 | java | Java | pcgen/code/src/java/pcgen/rules/persistence/TokenLibrary.java | allardhoeve/pcgen-multiline-objects | 2643b8cde1b866121290b16c26d5c8bd7ad21cbc | [
"OML"
] | 1 | 2022-03-15T22:42:34.000Z | 2022-03-15T22:42:34.000Z | pcgen/code/src/java/pcgen/rules/persistence/TokenLibrary.java | allardhoeve/pcgen-multiline-objects | 2643b8cde1b866121290b16c26d5c8bd7ad21cbc | [
"OML"
] | null | null | null | pcgen/code/src/java/pcgen/rules/persistence/TokenLibrary.java | allardhoeve/pcgen-multiline-objects | 2643b8cde1b866121290b16c26d5c8bd7ad21cbc | [
"OML"
] | null | null | null | 30.018382 | 137 | 0.68071 | 997,750 | /*
* Copyright 2008 (C) Tom Parker <lyhxr@example.com>
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package pcgen.rules.persistence;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import pcgen.base.lang.UnreachableError;
import pcgen.base.util.CaseInsensitiveMap;
import pcgen.base.util.DoubleKeyMap;
import pcgen.base.util.TreeMapToList;
import pcgen.cdom.base.CDOMObject;
import pcgen.cdom.base.Loadable;
import pcgen.core.PCClass;
import pcgen.core.bonus.BonusObj;
import pcgen.persistence.lst.LstToken;
import pcgen.persistence.lst.prereq.PreMultParser;
import pcgen.persistence.lst.prereq.PrerequisiteParserInterface;
import pcgen.rules.persistence.token.CDOMCompatibilityToken;
import pcgen.rules.persistence.token.CDOMPrimaryToken;
import pcgen.rules.persistence.token.CDOMSecondaryToken;
import pcgen.rules.persistence.token.CDOMSubToken;
import pcgen.rules.persistence.token.CDOMToken;
import pcgen.rules.persistence.token.ClassWrappedToken;
import pcgen.rules.persistence.token.DeferredToken;
import pcgen.rules.persistence.token.PostDeferredToken;
import pcgen.rules.persistence.token.PreCompatibilityToken;
import pcgen.rules.persistence.token.PrimitiveToken;
import pcgen.rules.persistence.token.QualifierToken;
import pcgen.rules.persistence.util.TokenFamily;
import pcgen.system.PluginLoader;
import pcgen.util.Logging;
public class TokenLibrary implements PluginLoader
{
private static final Class<PCClass> PCCLASS_CLASS = PCClass.class;
private static final Class<CDOMObject> CDOMOBJECT_CLASS = CDOMObject.class;
private static final List<DeferredToken<? extends Loadable>> deferredTokens =
new ArrayList<DeferredToken<? extends Loadable>>();
private static final TreeMapToList<Integer, PostDeferredToken<? extends Loadable>> postDeferredTokens =
new TreeMapToList<Integer, PostDeferredToken<? extends Loadable>>();
private static final DoubleKeyMap<Class<?>, String, Class<? extends QualifierToken>> qualifierMap =
new DoubleKeyMap<Class<?>, String, Class<? extends QualifierToken>>();
private static final DoubleKeyMap<Class<?>, String, Class<PrimitiveToken<?>>> primitiveMap =
new DoubleKeyMap<Class<?>, String, Class<PrimitiveToken<?>>>();
private static final Set<TokenFamily> TOKEN_FAMILIES = new TreeSet<TokenFamily>();
private static final CaseInsensitiveMap<Class<? extends BonusObj>> BONUS_TAG_MAP = new CaseInsensitiveMap<Class<? extends BonusObj>>();
private static TokenLibrary instance = null;
static
{
reset();
}
public static void reset()
{
deferredTokens.clear();
postDeferredTokens.clear();
qualifierMap.clear();
primitiveMap.clear();
BONUS_TAG_MAP.clear();
TOKEN_FAMILIES.clear();
TokenFamily.CURRENT.clearTokens();
TOKEN_FAMILIES.add(TokenFamily.CURRENT);
TokenFamily.REV514.clearTokens();
TOKEN_FAMILIES.add(TokenFamily.REV514);
addToTokenMap(new PreMultParser());
}
private TokenLibrary()
{
// Don't instantiate utility class
}
public static <T> PrimitiveToken<T> getPrimitive(
Class<T> cl, String tokKey)
{
for (Iterator<PrimitiveToken<T>> it = new PrimitiveTokenIterator<T, PrimitiveToken<T>>(
cl, tokKey); it.hasNext();)
{
return it.next();
}
return null;
}
public static List<DeferredToken<? extends Loadable>> getDeferredTokens()
{
return new ArrayList<DeferredToken<? extends Loadable>>(
deferredTokens);
}
public static Collection<PostDeferredToken<? extends Loadable>> getPostDeferredTokens()
{
return postDeferredTokens.allValues();
}
public static void addToPrimitiveMap(PrimitiveToken<?> p)
{
Class<? extends PrimitiveToken> newTokClass = p.getClass();
if (PrimitiveToken.class.isAssignableFrom(newTokClass))
{
String name = p.getTokenName();
Class cl = ((PrimitiveToken) p).getReferenceClass();
Class<PrimitiveToken<?>> prev = primitiveMap.put(cl, name,
(Class<PrimitiveToken<?>>) newTokClass);
if (prev != null)
{
Logging.errorPrint("Found a second " + name + " Primitive for " + cl);
}
}
}
public static void addToQualifierMap(QualifierToken<?> p)
{
Class<? extends QualifierToken> newTokClass = p.getClass();
Class<?> cl = p.getReferenceClass();
String name = p.getTokenName();
Class<? extends QualifierToken> prev = qualifierMap.put(cl, name,
newTokClass);
if (prev != null)
{
Logging.errorPrint("Found a second " + name + " Primitive for " + cl);
}
}
public static void addToTokenMap(Object newToken)
{
if (newToken instanceof DeferredToken)
{
deferredTokens.add((DeferredToken<?>) newToken);
}
if (newToken instanceof PostDeferredToken)
{
PostDeferredToken<?> pdt = (PostDeferredToken<?>) newToken;
postDeferredTokens.addToListFor(pdt.getPriority(), pdt);
}
if (newToken instanceof CDOMPrimaryToken)
{
CDOMPrimaryToken<?> tok = (CDOMPrimaryToken<?>) newToken;
CDOMToken<?> existingToken = TokenFamily.CURRENT.putToken(tok);
if (existingToken != null)
{
Logging.errorPrint("Duplicate "
+ tok.getTokenClass().getSimpleName()
+ " Token found for token " + tok.getTokenName()
+ ". Classes were " + existingToken.getClass().getName()
+ " and " + newToken.getClass().getName());
}
if (PCCLASS_CLASS.equals(tok.getTokenClass()))
{
addToTokenMap(new ClassWrappedToken(
(CDOMPrimaryToken<PCClass>) tok));
}
}
if (newToken instanceof CDOMSecondaryToken)
{
CDOMSecondaryToken<?> tok = (CDOMSecondaryToken<?>) newToken;
CDOMSubToken<?> existingToken = TokenFamily.CURRENT.putSubToken(tok);
if (existingToken != null)
{
Logging.errorPrint("Duplicate "
+ tok.getTokenClass().getSimpleName()
+ " Token found for token " + tok.getParentToken() + ":"
+ tok.getTokenName() + ". Classes were "
+ existingToken.getClass().getName() + " and "
+ newToken.getClass().getName());
}
}
// if (newToken instanceof ChoiceSetToken)
// {
// TokenFamily.CURRENT.putChooseToken((ChoiceSetToken<?>) newToken);
// }
if (newToken instanceof PrerequisiteParserInterface)
{
PrerequisiteParserInterface prereqToken = (PrerequisiteParserInterface) newToken;
TokenFamily.CURRENT.putPrerequisiteToken(prereqToken);
for (String s : prereqToken.kindsHandled())
{
/*
* TODO Theoretically these belong in REV514, but put into
* current for unparse testing
*/
PreCompatibilityToken pos = new PreCompatibilityToken(s,
prereqToken, false);
if (TokenFamily.CURRENT.putToken(pos) != null)
{
Logging.errorPrint("Duplicate " + pos.getTokenClass().getSimpleName() +
" Token found for token " + pos.getTokenName());
}
if (TokenFamily.CURRENT.putSubToken(pos) != null)
{
Logging.errorPrint("Duplicate " + pos.getTokenClass().getSimpleName() +
" Token found for token " + pos.getParentToken() + ":" +
pos.getTokenName());
}
TokenFamily.CURRENT.putSubToken(pos);
PreCompatibilityToken neg = new PreCompatibilityToken(s,
prereqToken, true);
if (TokenFamily.CURRENT.putToken(neg) != null)
{
Logging.errorPrint("Duplicate " + neg.getTokenClass().getSimpleName() +
" Token found for token " + neg.getTokenName());
}
if (TokenFamily.CURRENT.putSubToken(neg) != null)
{
Logging.errorPrint("Duplicate " + neg.getTokenClass().getSimpleName() +
" Token found for token " + neg.getParentToken() + ":" +
neg.getTokenName());
}
}
}
if (newToken instanceof CDOMCompatibilityToken)
{
CDOMCompatibilityToken<?> tok = (CDOMCompatibilityToken<?>) newToken;
TokenFamily fam = TokenFamily.getConstant(tok.compatibilityLevel(),
tok.compatibilitySubLevel(), tok.compatibilityPriority());
if (fam.putToken(tok) != null)
{
Logging.errorPrint("Duplicate " + tok.getTokenClass().getSimpleName() +
" Compatibility Token found for token " + tok.getTokenName() +
" at compatibility level " + tok.compatibilityLevel() + "." +
tok.compatibilitySubLevel() + "." + tok.compatibilityPriority());
}
TOKEN_FAMILIES.add(fam);
if (fam.compareTo(TokenFamily.REV514) <= 0 && PCCLASS_CLASS.equals(tok.getTokenClass()))
{
addToTokenMap(new ClassWrappedToken(
(CDOMCompatibilityToken<PCClass>) tok));
}
}
// if (newToken instanceof CDOMCompatibilitySubToken)
// {
// CDOMCompatibilitySubToken<?> tok = (CDOMCompatibilitySubToken<?>)
// newToken;
// TokenFamily fam = TokenFamily.getConstant(tok.compatibilityLevel(),
// tok.compatibilitySubLevel(), tok.compatibilityPriority());
// fam.putSubToken(tok);
// tokenSources.add(fam);
// }
// if (newToken instanceof ChoiceSetCompatibilityToken)
// {
// ChoiceSetCompatibilityToken tok = (ChoiceSetCompatibilityToken)
// newToken;
// TokenFamily fam = TokenFamily.getConstant(tok.compatibilityLevel(),
// tok.compatibilitySubLevel(), tok.compatibilityPriority());
// fam.putChooseToken(tok);
// tokenSources.add(fam);
// }
}
public static TokenLibrary getInstance()
{
if (instance == null)
{
instance = new TokenLibrary();
}
return instance;
}
@Override
public void loadPlugin(Class<?> clazz) throws Exception
{
if (BonusObj.class.isAssignableFrom(clazz))
{
addBonusClass(clazz, clazz.getName());
}
Object token = clazz.newInstance();
if (LstToken.class.isAssignableFrom(clazz) ||
PrerequisiteParserInterface.class.isAssignableFrom(clazz))
{
addToTokenMap(token);
}
if (QualifierToken.class.isAssignableFrom(clazz))
{
addToQualifierMap((QualifierToken<?>) token);
}
if (PrimitiveToken.class.isAssignableFrom(clazz))
{
addToPrimitiveMap((PrimitiveToken<?>) token);
}
}
@Override
public Class[] getPluginClasses()
{
return new Class[]
{
LstToken.class,
BonusObj.class,
PrerequisiteParserInterface.class
};
}
abstract static class AbstractTokenIterator<C, T> implements Iterator<T>
{
// private static final Class<Object> OBJECT_CLASS = Object.class;
private final Class<C> rootClass;
private final String tokenKey;
private T nextToken = null;
private boolean needNewToken = true;
private Class<?> stopClass;
private final Iterator<TokenFamily> subIterator;
public AbstractTokenIterator(Class<C> cl, String key)
{
rootClass = cl;
subIterator = TOKEN_FAMILIES.iterator();
tokenKey = key;
}
@Override
public boolean hasNext()
{
setNextToken();
return !needNewToken;
}
protected void setNextToken()
{
while (needNewToken && subIterator.hasNext())
{
TokenFamily family = subIterator.next();
Class<?> actingClass = rootClass;
nextToken = grabToken(family, actingClass, tokenKey);
while (nextToken == null && actingClass != null && !actingClass.equals(stopClass))
{
actingClass = actingClass.getSuperclass();
nextToken = grabToken(family, actingClass, tokenKey);
}
if (stopClass == null)
{
stopClass = actingClass;
}
needNewToken = nextToken == null;
}
}
protected abstract T grabToken(TokenFamily family, Class<?> cl,
String key);
@Override
public T next()
{
setNextToken();
if (needNewToken)
{
throw new NoSuchElementException();
}
needNewToken = true;
return nextToken;
}
@Override
public void remove()
{
throw new UnsupportedOperationException(
"Iterator does not support remove");
}
}
static class TokenIterator<C extends Loadable, T extends CDOMToken<? super C>>
extends TokenLibrary.AbstractTokenIterator<C, T>
{
public TokenIterator(Class<C> cl, String key)
{
super(cl, key);
}
@Override
protected T grabToken(TokenFamily family, Class<?> cl, String key)
{
return (T) family.getToken(cl, key);
}
}
static class SubTokenIterator<C, T extends CDOMSubToken<? super C>> extends TokenLibrary.AbstractTokenIterator<C, T>
{
private final String subTokenKey;
public SubTokenIterator(Class<C> cl, String key, String subKey)
{
super(cl, key);
subTokenKey = subKey;
}
@Override
protected T grabToken(TokenFamily family, Class<?> cl, String key)
{
return (T) family.getSubToken(cl, key, subTokenKey);
}
}
static class QualifierTokenIterator<C extends CDOMObject, T extends QualifierToken<? super C>>
extends TokenLibrary.AbstractTokenIterator<C, T>
{
public QualifierTokenIterator(Class<C> cl, String key)
{
super(cl, key);
}
@Override
protected T grabToken(TokenFamily family, Class<?> cl, String key)
{
if (!TokenFamily.CURRENT.equals(family))
{
return null;
}
Class<? extends QualifierToken> cl1 = qualifierMap.get(cl, key);
if (cl1 == null)
{
return null;
}
try
{
return (T) cl1.newInstance();
}
catch (InstantiationException e)
{
throw new UnreachableError("new Instance on " + cl1 + " should not fail", e);
}
catch (IllegalAccessException e)
{
throw new UnreachableError("new Instance on " + cl1 +
" should not fail due to access", e);
}
}
}
static class PrimitiveTokenIterator<C, T extends PrimitiveToken<? super C>>
extends TokenLibrary.AbstractTokenIterator<C, T>
{
public PrimitiveTokenIterator(Class<C> cl, String key)
{
super(cl, key);
}
@Override
protected T grabToken(TokenFamily family, Class<?> cl, String key)
{
if (!TokenFamily.CURRENT.equals(family))
{
return null;
}
Class<? extends PrimitiveToken> cl1 = primitiveMap.get(cl, key);
if (cl1 == null)
{
return null;
}
try
{
return (T) cl1.newInstance();
}
catch (InstantiationException e)
{
throw new UnreachableError("new Instance on " + cl1 + " should not fail", e);
}
catch (IllegalAccessException e)
{
throw new UnreachableError("new Instance on " + cl1 +
" should not fail due to access", e);
}
}
}
static class PreTokenIterator
extends TokenLibrary.AbstractTokenIterator<CDOMObject, PrerequisiteParserInterface>
{
public PreTokenIterator(String key)
{
super(CDOMOBJECT_CLASS, key);
}
@Override
protected PrerequisiteParserInterface grabToken(TokenFamily family,
Class<?> cl, String key)
{
return family.getPrerequisiteToken(key);
}
}
/**
* Add a CLASS via a BONUS
*
* @param bonusClass
* @param bonusName
* @return true if successful
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static boolean addBonusClass(Class bonusClass,
String bonusName) throws InstantiationException, IllegalAccessException
{
if (BonusObj.class.isAssignableFrom(bonusClass))
{
final BonusObj bonusObj = (BonusObj) bonusClass.newInstance();
BONUS_TAG_MAP.put(bonusObj.getBonusHandled(), bonusClass);
return true;
}
return false;
}
public static Class<? extends BonusObj> getBonus(String bonusName)
{
return BONUS_TAG_MAP.get(bonusName);
}
}
|
92369a88a5f8ef6a84c8142bf885fe8af430b813 | 1,850 | java | Java | src/main/java/org/leo/wechat4j/wxmsg/msg/Msg4Location.java | xinlc/wechat4j | 0756dec44e7aed77dea3207e6a2452497cbfff4f | [
"MIT"
] | 1 | 2021-04-08T06:04:57.000Z | 2021-04-08T06:04:57.000Z | src/main/java/org/leo/wechat4j/wxmsg/msg/Msg4Location.java | xinlc/wechat4j | 0756dec44e7aed77dea3207e6a2452497cbfff4f | [
"MIT"
] | null | null | null | src/main/java/org/leo/wechat4j/wxmsg/msg/Msg4Location.java | xinlc/wechat4j | 0756dec44e7aed77dea3207e6a2452497cbfff4f | [
"MIT"
] | null | null | null | 20.32967 | 104 | 0.720541 | 997,751 | package org.leo.wechat4j.wxmsg.msg;
import org.leo.wechat4j.wxmsg.WXXmlElementName;
import org.w3c.dom.Document;
/**
* 地理位置消息
*/
public class Msg4Location extends Msg {
// 地理位置纬度
private String location_X;
// 地理位置经度
private String location_Y;
// 地图缩放大小
private String scale;
// 地理位置信息
private String label;
//消息id,64位整型
private String msgId;
/**
* 开发者调用
* */
public Msg4Location() {
this.head = new Msg4Head();
this.head.setMsgType(Msg.MSG_TYPE_LOCATION);
}
/**
* 程序内部调用
* */
public Msg4Location(Msg4Head head) {
this.head = head;
}
@Override
public void write(Document document) {
// TODO Auto-generated method stub
}
@Override
public void read(Document document) {
this.location_X = document.getElementsByTagName(WXXmlElementName.LOCATION_X).item(0).getTextContent();
this.location_Y = document.getElementsByTagName(WXXmlElementName.LOCATION_Y).item(0).getTextContent();
this.scale = document.getElementsByTagName(WXXmlElementName.SCALE).item(0).getTextContent();
this.label = document.getElementsByTagName(WXXmlElementName.LABEL).item(0).getTextContent();
this.msgId = document.getElementsByTagName(WXXmlElementName.MSG_ID).item(0).getTextContent();
}
public String getLocation_X() {
return location_X;
}
public void setLocation_X(String location_X) {
this.location_X = location_X;
}
public String getLocation_Y() {
return location_Y;
}
public void setLocation_Y(String location_Y) {
this.location_Y = location_Y;
}
public String getScale() {
return scale;
}
public void setScale(String scale) {
this.scale = scale;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
}
|
92369b1ce4c86ec0707cdb89e6ea774d72c9687a | 2,429 | java | Java | Android Application/app/src/main/java/com/example/wing_project_android_app/endpoints/BoardView.java | BranKein/AIFB_GIST_WING_2020 | ea71eb58c3dd65f9ec89f8a5140c2c20af6aeadb | [
"MIT"
] | null | null | null | Android Application/app/src/main/java/com/example/wing_project_android_app/endpoints/BoardView.java | BranKein/AIFB_GIST_WING_2020 | ea71eb58c3dd65f9ec89f8a5140c2c20af6aeadb | [
"MIT"
] | null | null | null | Android Application/app/src/main/java/com/example/wing_project_android_app/endpoints/BoardView.java | BranKein/AIFB_GIST_WING_2020 | ea71eb58c3dd65f9ec89f8a5140c2c20af6aeadb | [
"MIT"
] | null | null | null | 32.386667 | 98 | 0.669 | 997,752 | package com.example.wing_project_android_app.endpoints;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.wing_project_android_app.R;
import com.example.wing_project_android_app.methods.board.Board;
import com.example.wing_project_android_app.methods.board.BoardAdapter;
import com.example.wing_project_android_app.methods.board.Board_manager;
import java.util.ArrayList;
public class BoardView extends AppCompatActivity {
ListView board_listview;
BoardAdapter board_adapter;
ArrayList<String> board_name_list;
Board_manager board_manager;
Request_Thread request_thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.board_page);
board_manager = new Board_manager();
request_thread = new Request_Thread();
request_thread.start();
try{
request_thread.join();
} catch (InterruptedException e) {
}
board_listview = (ListView) findViewById(R.id.board_listview);
board_adapter = new BoardAdapter();
for (int i = 0; i < board_name_list.size(); i++) {
board_adapter.addItem(new Board(board_name_list.get(i)));
}
board_adapter.addItem(new Board("외전: 인공지능 체험해보기"));
board_listview.setAdapter(board_adapter);
board_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Board clicked_board = (Board) board_adapter.getItem(position);
Intent intent;
if (clicked_board.getBoard_str().equals("외전: 인공지능 체험해보기")) {
intent = new Intent(BoardView.this, AI_ExperienceView.class);
} else {
intent = new Intent(BoardView.this, ContentView.class);
intent.putExtra("boardname", clicked_board.getBoard_str());
}
startActivity(intent);
}
});
}
private class Request_Thread extends Thread {
public void run() {
board_name_list = board_manager.get_board_list();
}
}
}
|
92369fb1f143af7991a925005d869c1f681058b1 | 2,357 | java | Java | engine-spring/core/src/test/java/org/camunda/bpm/engine/spring/test/configuration/SpringProcessEngineInitializationTest.java | HardLOLMaster/camunda-bpm-platform | e8411f499a28bd9262045ae966283a786dce901d | [
"Apache-2.0"
] | null | null | null | engine-spring/core/src/test/java/org/camunda/bpm/engine/spring/test/configuration/SpringProcessEngineInitializationTest.java | HardLOLMaster/camunda-bpm-platform | e8411f499a28bd9262045ae966283a786dce901d | [
"Apache-2.0"
] | null | null | null | engine-spring/core/src/test/java/org/camunda/bpm/engine/spring/test/configuration/SpringProcessEngineInitializationTest.java | HardLOLMaster/camunda-bpm-platform | e8411f499a28bd9262045ae966283a786dce901d | [
"Apache-2.0"
] | null | null | null | 36.261538 | 114 | 0.76538 | 997,753 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.spring.test.configuration;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngines;
import org.camunda.bpm.engine.impl.util.ReflectUtil;
import org.camunda.bpm.engine.spring.SpringConfigurationHelper;
import org.junit.Test;
import java.net.URL;
import static org.junit.Assert.*;
public class SpringProcessEngineInitializationTest {
@Test
public void testSpringConfigurationContextInitializing() {
//given
URL resource = existActivitiContext();
//when
ProcessEngine processEngine = SpringConfigurationHelper.buildProcessEngine(resource);
//then
assertNotNull(processEngine);
assertEquals("activitiContextProcessName", processEngine.getName());
processEngine.close();
}
@Test
public void shouldInitializeProcessEngineFromActivitiContext() {
//given
existActivitiContext();
//when
ProcessEngine processEngine = ProcessEngines.getProcessEngine("activitiContextProcessName");
//then
assertNotNull(processEngine);
assertEquals("activitiContextProcessName", processEngine.getName());
processEngine.close();
}
//check exists activiti-context.xml in classpath without this check ProcessEngines will ignore parsing this file
private URL existActivitiContext() {
URL resource = ReflectUtil.getClassLoader().getResource("activiti-context.xml");
if (resource == null)
fail("activiti-context.xml not found on the classpath: " + System.getProperty("java.class.path"));
return resource;
}
}
|
9236a0a6f375d4ac408026c1f54aa8bf6ed30e40 | 17,831 | java | Java | src/test/java/io/induct/reflection/bpc/BeanPropertyControllerTestCase.java | esuomi/bean-property-controller | b3c58285ed291de34fb0639d284932428aedf16f | [
"MIT"
] | 1 | 2016-12-23T03:17:49.000Z | 2016-12-23T03:17:49.000Z | src/test/java/io/induct/reflection/bpc/BeanPropertyControllerTestCase.java | esuomi/bean-property-controller | b3c58285ed291de34fb0639d284932428aedf16f | [
"MIT"
] | null | null | null | src/test/java/io/induct/reflection/bpc/BeanPropertyControllerTestCase.java | esuomi/bean-property-controller | b3c58285ed291de34fb0639d284932428aedf16f | [
"MIT"
] | null | null | null | 43.918719 | 148 | 0.689529 | 997,754 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Esko Suomi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.induct.reflection.bpc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import io.induct.reflection.bpc.BeanPropertyController.ExtractionDepth;
import io.induct.reflection.bpc.instantiation.ClassInstantiator.InstantiationPolicy;
import io.induct.reflection.bpc.testbeans.ArrayBean;
import io.induct.reflection.bpc.testbeans.BooleanClass;
import io.induct.reflection.bpc.testbeans.BrokenBean;
import io.induct.reflection.bpc.testbeans.HiddenBean;
import io.induct.reflection.bpc.testbeans.IntegerBean;
import io.induct.reflection.bpc.testbeans.MultipleConstructorsBean;
import io.induct.reflection.bpc.testbeans.QuestimationBean;
import io.induct.reflection.bpc.testbeans.RecursionBean;
import io.induct.reflection.bpc.testbeans.SerializableBean;
import io.induct.reflection.bpc.testbeans.SingleValueBean;
import io.induct.reflection.bpc.testbeans.SomeClass;
import io.induct.reflection.bpc.testbeans.TraditionalBean;
import io.induct.reflection.bpc.testbeans.VaryingParametersBean;
public class BeanPropertyControllerTestCase extends TestCase {
private BeanPropertyController bpc;
private SingleValueBean<String> singleValueBean;
private IntegerBean intBean;
private ArrayBean arrayBean;
private double[] values;
private SomeClass valueClass;
private BooleanClass booleanClass;
private QuestimationBean questimationBean;
private RecursionBean recursionBean;
private TraditionalBean traditionalBean;
private VaryingParametersBean varyingParametersBean;
@Override
protected void setUp() throws Exception {
singleValueBean = new SingleValueBean<String>("testingValue");
intBean = new IntegerBean(3);
values = new double[3];
values[0] = 1.2;
values[1] = 3.4;
values[2] = 5.6;
arrayBean = new ArrayBean(values);
valueClass = new SomeClass("hidden dragon", "crouching tiger");
booleanClass = new BooleanClass(true);
questimationBean = new QuestimationBean("onlySetter", "onlyGetter");
recursionBean = new RecursionBean(singleValueBean);
traditionalBean = new TraditionalBean();
varyingParametersBean = new VaryingParametersBean();
}
public void testCreatesControllerObjectForGivenBean() throws Exception {
bpc = BeanPropertyController.of(singleValueBean);
assertEquals(singleValueBean, bpc.getObject());
}
public void testCanAccessNamedProperty() throws Exception {
bpc = BeanPropertyController.of(singleValueBean);
Object value = bpc.access("value");
assertEquals(singleValueBean.getValue(), value);
}
public void testCanMutateNamedProperty() throws Exception {
bpc = BeanPropertyController.of(singleValueBean);
bpc.mutate("value", "newValue");
assertEquals("newValue", bpc.access("value"));
}
public void testCanHandlePrimitiveIntegerType() throws Exception {
bpc = BeanPropertyController.of(intBean);
assertEquals(3, bpc.access("integer"));
bpc.mutate("integer", 10);
assertEquals(10, bpc.access("integer"));
}
public void testCanHandleArrays() throws Exception {
bpc = BeanPropertyController.of(arrayBean);
assertTrue("Expected "+Arrays.toString(values)+", but was "+Arrays.toString((double[]) bpc.access("values")),
Arrays.equals(values, (double[]) bpc.access("values")));
double[] newValues = new double[] { 9.8, 7.6, 5.4};
bpc.mutate("values", newValues);
assertTrue("Expected "+Arrays.toString(newValues)+", but was "+Arrays.toString((double[]) bpc.access("values")),
Arrays.equals(newValues, (double[]) bpc.access("values")));
}
public void testProvidesConvenienceMethodsForCheckingPropertysAttributes() throws Exception {
bpc = BeanPropertyController.of(arrayBean);
assertTrue(bpc.isArray("values"));
}
public void testAccessesFieldDirectlyIfAppropriateMethodsDontExistAndCorrectConstructorIsUsed() throws Exception {
bpc = BeanPropertyController.of(valueClass, ExtractionDepth.FIELDS);
assertEquals("crouching tiger", bpc.access("visible"));
bpc.mutate("visible", "still visible");
assertEquals("still visible", bpc.access("visible"));
}
public void testThrowsDescriptiveExceptionIfNamedPropertyIsntFound() throws Exception {
bpc = BeanPropertyController.of(valueClass);
try {
bpc.access("doughnuts");
} catch (NonexistentPropertyException e) {
assertEquals("Property 'doughnuts' doesn't exist for the specified class io.induct.reflection.bpc.testbeans.SomeClass", e.getMessage());
}
}
public void testCanAccessBooleanAccessorCorrectly() throws Exception {
bpc = BeanPropertyController.of(booleanClass);
assertEquals(Boolean.TRUE, bpc.access("boo"));
bpc.mutate("boo", false);
assertEquals(Boolean.FALSE, bpc.access("boo"));
}
public void testCanCombineDifferentMutatorsAndAccessorsIfQuestimationIsAllowedToConstructBeanPropertyObject() throws Exception {
bpc = BeanPropertyController.of(questimationBean, ExtractionDepth.QUESTIMATE);
assertEquals("onlySetter", bpc.access("onlySetter"));
assertEquals("onlyGetter", bpc.access("onlyGetter"));
bpc.mutate("onlySetter", "And that's fine");
bpc.mutate("onlyGetter", "because this class just doesn't care!");
assertEquals("And that's fine", bpc.access("onlySetter"));
assertEquals("because this class just doesn't care!", bpc.access("onlyGetter"));
}
public void testCanListAllAvailableMethodPropertiesForGivenObject() throws Exception {
bpc = BeanPropertyController.of(questimationBean, ExtractionDepth.METHODS);
String[] propertyNames = bpc.getPropertyNames();
assertEquals(0, propertyNames.length);
bpc = BeanPropertyController.of(traditionalBean);
propertyNames = bpc.getPropertyNames();
assertEquals(3, propertyNames.length);
}
public void testCanListAllAvailableMethodAndFieldPropertiesForGivenObject() throws Exception {
bpc = BeanPropertyController.of(valueClass, ExtractionDepth.FIELDS);
String[] propertyNames = bpc.getPropertyNames();
assertEquals(1, propertyNames.length);
assertEquals("visible", propertyNames[0]);
}
public void testCanListAllAvailablePropertiesOfAnyTypeForGivenObject() throws Exception {
bpc = BeanPropertyController.of(questimationBean, ExtractionDepth.QUESTIMATE);
List<String> propertyNames = Arrays.asList(removeUnitTestingLibraryProxyProperties(bpc.getPropertyNames()));
assertEquals(2, propertyNames.size());
assertTrue("onlyGetter not found", propertyNames.contains("onlyGetter"));
assertTrue("onlySetter not found", propertyNames.contains("onlySetter"));
}
public void testCanScanPropertiesFromRecursionBean() throws Exception {
bpc = BeanPropertyController.of(recursionBean);
Arrays.equals(bpc.getPropertyNames(), new String[] {"bean"});
Arrays.equals(bpc.getPropertyNames(), new String[] {"bean.value", "bean"});
bpc.mutate("bean.value", "generic hello");
assertEquals("generic hello", bpc.access("bean.value"));
}
private String[] removeUnitTestingLibraryProxyProperties(String[] propertyNames) {
List<String> actualProperties = new ArrayList<String>();
for (String property : propertyNames) {
actualProperties.add(property);
}
removeEclEMMAFields(actualProperties);
return actualProperties.toArray(new String[actualProperties.size()]);
}
/*
* Yes, this does happen. Apparently EclEMMA creates proxies to track coverage.
*/
private void removeEclEMMAFields(List<String> actualProperties) {
actualProperties.remove("$VRc");
actualProperties.remove("serialVersionUID");
}
public void testIsAbleToExtractPropertiesWithinProperties() throws Exception {
bpc = BeanPropertyController.of(recursionBean);
assertEquals("testingValue", bpc.access("bean.value"));
bpc.mutate("bean.value", "jou");
assertEquals("jou", bpc.access("bean.value"));
}
public void testCanBeSetToIgnorePropertiesWithinPropertiesOnConstruct() throws Exception {
bpc = BeanPropertyController.of(recursionBean, 0);
try {
bpc.access("bean.value");
fail("Should've thrown NonexistentPropertyException");
} catch (NonexistentPropertyException e) {
assertEquals("Property 'bean.value' doesn't exist for the specified class io.induct.reflection.bpc.testbeans.RecursionBean",
e.getMessage());
}
}
public void testCanDeterminePropertyTypeForSaferManipulation() throws Exception {
bpc = BeanPropertyController.of(questimationBean, ExtractionDepth.QUESTIMATE);
assertEquals(String.class, bpc.typeOf("onlySetter"));
}
public void testSupportsReadOnlyProperties() throws Exception {
bpc = BeanPropertyController.of(questimationBean);
assertTrue(bpc.isReadOnly("onlyGetter"));
assertEquals("onlyGetter", bpc.access("onlyGetter"));
bpc = BeanPropertyController.of(booleanClass);
assertFalse(bpc.isReadOnly("boo"));
}
public void testChecksForTheAmountOfParametersInMutators() throws Exception {
bpc = BeanPropertyController.of(varyingParametersBean);
bpc.mutate("value", "plap");
assertEquals("plap", bpc.access("value"));
}
public void testChecksThatAccessorsReturnTypeMatchesWithMutatorsParameter() throws Exception {
bpc = BeanPropertyController.of(BrokenBean.class, -1);
bpc.mutate("valid", "this property is valid");
assertEquals("this property is valid", bpc.access("valid"));
try {
bpc.access("invalid");
fail("Should've thrown NonMatchingAccessorAndMutatorException");
} catch (NonMatchingAccessorAndMutatorException e) {}
}
public void testCanApplyMultipleMutationsEasily() throws Exception {
Map<String, Object> newProps = new HashMap<String, Object>();
newProps.put("name", "John");
newProps.put("age", 36);
newProps.put("accountBalance", 3050);
BeanPropertyController c = BeanPropertyController.of(traditionalBean);
c.mutate(newProps);
assertEquals("John", traditionalBean.getName());
assertEquals(36, traditionalBean.getAge());
assertEquals(3050d, traditionalBean.getAccountBalance());
c.mutate("name", "Jill").mutate("age", 31).mutate("accountBalance", 32301295);
assertEquals("Jill", traditionalBean.getName());
assertEquals(31, traditionalBean.getAge());
assertEquals(32301295d, traditionalBean.getAccountBalance());
}
public void testAccessesOnlyPublicMethods() throws Exception {
bpc = BeanPropertyController.of(HiddenBean.class);
String[] properties = bpc.getPropertyNames();
assertEquals(0, properties.length);
}
public void testCanTransparentlyCreateAnObjectFromClassAndControlItAsIfItWasANormalObject() throws Exception {
bpc = BeanPropertyController.of(SingleValueBean.class, ExtractionDepth.METHODS);
assertNull(bpc.access("value"));
bpc.mutate("value", "newValue");
assertEquals("newValue", bpc.access("value"));
}
public void testCanTransparentlyCreateAnObjectWithArbitraryConstructorFromClassAndControlItAsIfItWasANormalObject() throws Exception {
bpc = BeanPropertyController.of(BooleanClass.class, InstantiationPolicy.NICE);
assertEquals(false, bpc.access("boo"));
bpc = BeanPropertyController.of(SomeClass.class, ExtractionDepth.FIELDS, InstantiationPolicy.NICE);
assertEquals("", bpc.access("visible"));
bpc = BeanPropertyController.of(IntegerBean.class, InstantiationPolicy.NICE);
assertEquals(0, bpc.access("integer"));
}
public void testUsesTheConstructorWithLeastAmountOfParametersWhenInstantiating() throws Exception {
bpc = BeanPropertyController.of(MultipleConstructorsBean.class, InstantiationPolicy.NICE);
assertEquals("single-arg", bpc.access("instantiatedWith"));
}
public void testThrowsExceptionIfNoArgsConstructorIsFound() throws Exception {
try {
bpc = BeanPropertyController.of(MultipleConstructorsBean.class);
fail("Should've thrown Exception!");
} catch (BeanInstantiationException e) {
assertEquals("Couldn't instantiate given class io.induct.reflection.bpc.testbeans.MultipleConstructorsBean", e.getMessage());
assertEquals(1, e.getExceptions().size());
}
}
public void testChangesActiveBeansProperties() throws Exception {
assertEquals(null, traditionalBean.getName());
bpc = BeanPropertyController.of(traditionalBean);
bpc.mutate("name", "Tsohn");
assertEquals("Tsohn", traditionalBean.getName());
}
public void testIsSerializableIfControlledObjectIsSerializable() throws Exception {
SerializableBean bean = new SerializableBean();
bean.setSerial("something else");
bpc = BeanPropertyController.of(bean);
byte[] objectAsBytes = serialize(bpc);
BeanPropertyController bpc = deserialize(objectAsBytes);
assertEquals(bean, bpc.getObject());
}
public void testIsSerializableIfControlledClassIsSerializable() throws Exception {
bpc = BeanPropertyController.of(SerializableBean.class);
bpc.mutate("serial", "original");
SerializableBean original = (SerializableBean) bpc.getObject();
byte[] objectAsBytes = serialize(bpc);
BeanPropertyController bpc = deserialize(objectAsBytes);
assertEquals(original, bpc.getObject());
}
/* TODO: Implement this.
public void testCanAccessSpecificObjectInArrayByIndex() throws Exception {
double[] doubles = {1.0, 2.0, 3.0};
arrayBean.setValues(doubles);
bpc = BeanPropertyController.of(arrayBean);
assertEquals(doubles[0], bpc.access("values[0]"));
assertEquals(doubles[1], bpc.access("values[1]"));
assertEquals(doubles[2], bpc.access("values[2]"));
}
*/
private BeanPropertyController deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(is);
return (BeanPropertyController) in.readObject();
}
private byte[] serialize(Object o) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(os);
out.writeObject(o);
System.out.println("Serialized to "+os.toByteArray().length+" bytes");
return os.toByteArray();
}
// TODO: Test JVM restart support
public void testCanBeUsedAsObjectFactory() throws Exception {
bpc = BeanPropertyController.of(TraditionalBean.class);
List<TraditionalBean> listOfBeans = new ArrayList<TraditionalBean>();
for (int i=0; i<10; i++) {
bpc.mutate("age", i);
TraditionalBean bean = (TraditionalBean) bpc.getObject();
listOfBeans.add(bean);
assertEquals(i, bean.getAge());
bpc.recycle();
}
assertEquals(10, listOfBeans.size());
// ages were set correctly
for (int i=0; i<listOfBeans.size(); i++) {
assertEquals(i, listOfBeans.get(i).getAge());
}
// all items are unique
List<TraditionalBean> checked = new ArrayList<TraditionalBean>();
for (TraditionalBean bean : listOfBeans) {
for (TraditionalBean checkedBean : checked) {
assertNotSame(bean, checkedBean);
}
checked.add(bean);
}
}
}
|
9236a111ae597d27b3593db5656f5d7eb251830d | 1,117 | java | Java | src/main/java/com/qlzw/smartwc/mapper/Dev_answerMapper.java | zzttwzq/deviceControl | 50c3eef6770116ed0624e7d59f3bc7fd503da821 | [
"MIT"
] | 1 | 2021-05-21T08:43:48.000Z | 2021-05-21T08:43:48.000Z | src/main/java/com/qlzw/smartwc/mapper/Dev_answerMapper.java | zzttwzq/deviceControl | 50c3eef6770116ed0624e7d59f3bc7fd503da821 | [
"MIT"
] | null | null | null | src/main/java/com/qlzw/smartwc/mapper/Dev_answerMapper.java | zzttwzq/deviceControl | 50c3eef6770116ed0624e7d59f3bc7fd503da821 | [
"MIT"
] | null | null | null | 38.517241 | 97 | 0.739481 | 997,755 | package com.qlzw.smartwc.mapper;
import com.qlzw.smartwc.model.Dev_answer;
import com.qlzw.smartwc.provider.Dev_answerProvider;
import org.apache.ibatis.annotations.*;
import java.util.List;
import org.springframework.stereotype.Component;
@Component(value = "dev_answerMapper")
@Mapper
public interface Dev_answerMapper {
@SelectProvider(type = Dev_answerProvider.class,method = "selectAll")
public List<Dev_answer> list(@Param("page") Integer page,@Param("size") Integer size);
@SelectProvider(type = Dev_answerProvider.class,method = "selectOne")
public Dev_answer show(@Param("id") Long id);
@InsertProvider(type = Dev_answerProvider.class,method = "insertOne")
@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")//加入该注解可以保持对象后,查看对象插入id
public Boolean insert(Dev_answer dev_answer);
@DeleteProvider(type = Dev_answerProvider.class,method = "deleteOne")
public Boolean delete(@Param("id") Long id);
@UpdateProvider(type = Dev_answerProvider.class,method = "updateOne")
public Boolean update(Dev_answer dev_answer);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.