blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
7231a184f1f1970af621b6bc3ccdd8b61017b5eb | Java | apk-spectrum/apk-scanner | /src/main/java/com/apkscanner/gui/action/ShowManifestAction.java | UTF-8 | 3,076 | 2.125 | 2 | [
"BSD-3-Clause",
"Apache-2.0",
"WTFPL",
"LGPL-2.0-or-later",
"GPL-3.0-only"
] | permissive | package com.apkscanner.gui.action;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JFileChooser;
import com.apkscanner.gui.MessageBoxPool;
import com.apkscanner.resource.RProp;
import com.apkspectrum.data.apkinfo.ApkInfo;
import com.apkspectrum.logback.Log;
import com.apkspectrum.swing.ApkActionEventHandler;
import com.apkspectrum.swing.ApkFileChooser;
import com.apkspectrum.tool.aapt.AaptNativeWrapper;
import com.apkspectrum.util.FileUtil;
import com.apkspectrum.util.SystemUtil;
public class ShowManifestAction extends AbstractApkScannerAction {
private static final long serialVersionUID = 5554614631873501903L;
public static final String ACTION_COMMAND = "ACT_CMD_SHOW_MANIFEST";
public ShowManifestAction(ApkActionEventHandler h) {
super(h);
}
@Override
public void actionPerformed(ActionEvent e) {
boolean withShift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
evtShowManifest(getWindow(e), withShift);
}
private void evtShowManifest(Window owner, boolean saveAs) {
ApkInfo apkInfo = getApkInfo();
if (apkInfo == null) {
Log.e("evtShowManifest() apkInfo is null");
MessageBoxPool.show(owner, MessageBoxPool.MSG_NO_SUCH_APK_FILE);
return;
}
try {
String manifestPath = null;
File manifestFile = null;
if (!saveAs) {
manifestPath = apkInfo.tempWorkPath + File.separator + "AndroidManifest.xml";
manifestFile = new File(manifestPath);
} else {
JFileChooser jfc = ApkFileChooser.getFileChooser(RProp.S.LAST_FILE_SAVE_PATH.get(),
JFileChooser.SAVE_DIALOG, new File("AndroidManifest.xml"));
if (jfc.showSaveDialog(owner) != JFileChooser.APPROVE_OPTION) return;
manifestFile = jfc.getSelectedFile();
if (manifestFile == null) return;
RProp.S.LAST_FILE_SAVE_PATH.set(manifestFile.getParentFile().getAbsolutePath());
manifestPath = manifestFile.getAbsolutePath();
}
if (saveAs || !manifestFile.exists()) {
if (!manifestFile.getParentFile().exists()) {
if (FileUtil.makeFolder(manifestFile.getParentFile().getAbsolutePath())) {
Log.d("sucess make folder");
}
}
String[] convStrings = AaptNativeWrapper.Dump.getXmltree(apkInfo.filePath,
new String[] {"AndroidManifest.xml"});
FileWriter fw = new FileWriter(new File(manifestPath));
fw.write(apkInfo.a2xConvert.convertToText(convStrings));
fw.close();
} else {
Log.e("already existed file : " + manifestPath);
}
if (!saveAs) SystemUtil.openEditor(manifestPath);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
| true |
540af28cf3e47e0bcba0e7c56459ff0b6f8c87fc | Java | codedeedope/JNativeLibLoader | /NativeLibLoader/src/main/java/de/dhbw/rahmlab/nativelibloader/maintenance/DeleteUnusedGluegenJavaFiles.java | UTF-8 | 1,123 | 2.265625 | 2 | [
"BSD-4-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause-No-Nuclear-Warranty",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.dhbw.rahmlab.nativelibloader.maintenance;
import com.thoughtworks.qdox.model.JavaClass;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author fabian
*/
public class DeleteUnusedGluegenJavaFiles {
public static void delete() {
List<JavaClass> unusedClasses = UnusedGluegenClasses.get_unusedGluegenClasses();
System.out.println("-------------");
System.out.println("---UnusedClasses:");
unusedClasses.forEach(cl -> System.out.println(cl.getCanonicalName()));
List<String> unusedPath = unusedClasses
.stream()
.map(cl -> cl.getSource().getURL().getPath())
.collect(Collectors.toCollection(ArrayList::new));
for (String path : unusedPath) {
File file = new File(path);
file.delete();
}
PatchGluegenClasses.patch();
}
}
| true |
46b1ea4800a2893be5cbe02bf8be2651fccf3766 | Java | bbilger/jrestless | /core/jrestless-core-container/src/main/java/com/jrestless/core/interceptor/ConditionalBase64WriteInterceptor.java | UTF-8 | 1,717 | 2.421875 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | /*
* Copyright 2017 Bjoern Bilger
*
* 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.jrestless.core.interceptor;
import java.io.IOException;
import java.util.Base64;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
/**
* Wraps the {@link WriterInterceptorContext context's} output stream with a
* base64 encoder (RFC4648; not URL-safe) if {@link #isBase64(WriterInterceptorContext)}
* returns true.
*
* @author Bjoern Bilger
*
*/
public abstract class ConditionalBase64WriteInterceptor implements WriterInterceptor {
@Override
public final void aroundWriteTo(WriterInterceptorContext context) throws IOException {
if (isBase64(context)) {
context.setOutputStream(Base64.getEncoder().wrap(context.getOutputStream()));
}
context.proceed();
}
/**
* Returns true if the {@link WriterInterceptorContext context's}
* output stream should be wrapped by a base64 encoder.
*
* @param context
* the response context
* @return {@code true} in case the context's output stream must be wrapped
* by a base64 encoder; {@code false} otherwise
*/
protected abstract boolean isBase64(WriterInterceptorContext context);
}
| true |
7e625459d173eac0d4d41877075d24a7aa955557 | Java | jahstreet/JCasino | /src/main/java/by/sasnouskikh/jcasino/command/impl/VerifyProfileCommand.java | UTF-8 | 2,306 | 2.375 | 2 | [] | no_license | package by.sasnouskikh.jcasino.command.impl;
import by.sasnouskikh.jcasino.command.Command;
import by.sasnouskikh.jcasino.command.PageNavigator;
import by.sasnouskikh.jcasino.entity.bean.Player;
import by.sasnouskikh.jcasino.manager.ConfigConstant;
import by.sasnouskikh.jcasino.manager.MessageManager;
import by.sasnouskikh.jcasino.service.PlayerService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import static by.sasnouskikh.jcasino.manager.ConfigConstant.*;
/**
* The class provides verifying profile for player.
*
* @author Sasnouskikh Aliaksandr
* @see Command
*/
public class VerifyProfileCommand implements Command {
/**
* <p>Provides verifying profile for player. <p>Passes {@link HttpServletRequest} attributes further to the Logic
* layer. <p>If Logic operation passed successfully navigates to {@link PageNavigator#REDIRECT_GOTO_VERIFICATION},
* else adds {@link ConfigConstant#ATTR_ERROR_MESSAGE} attribute to {@link HttpServletRequest#setAttribute(String,
* Object)} and navigates to {@link PageNavigator#FORWARD_PAGE_VERIFICATION}.
*
* @param request request from client to get parameters to work with
* @return {@link PageNavigator} with response parameters (contains 'query' and 'response type' data for {@link
* by.sasnouskikh.jcasino.controller.MainController})
* @see MessageManager
* @see PlayerService#verifyProfile(Player)
*/
@Override
public PageNavigator execute(HttpServletRequest request) {
HttpSession session = request.getSession();
String locale = (String) session.getAttribute(ATTR_LOCALE);
MessageManager messageManager = MessageManager.getMessageManager(locale);
PageNavigator navigator;
Player player = (Player) session.getAttribute(ATTR_PLAYER);
try (PlayerService playerService = new PlayerService()) {
if (playerService.verifyProfile(player)) {
navigator = PageNavigator.REDIRECT_GOTO_VERIFICATION;
} else {
request.setAttribute(ATTR_ERROR_MESSAGE, messageManager.getMessage(MESSAGE_VERIFY_PROFILE_ERROR));
navigator = PageNavigator.FORWARD_PAGE_VERIFICATION;
}
}
return navigator;
}
} | true |
74ad044bd02a716c98a332ea84061874f9def767 | Java | shimingxy/dbblazer | /blazer-trans/src/main/java/com/blazer/load/file/runner/TransDataLoadFile.java | UTF-8 | 14,928 | 2.0625 | 2 | [] | no_license | /**
*
*/
package com.blazer.load.file.runner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.sql.DataSource;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.blazer.db.ConnUtil;
import com.blazer.db.TableColumns;
/**
* 单数据文件导入
* @author mhshi
*
*/
public class TransDataLoadFile{
private static final Logger _logger = LoggerFactory.getLogger(TransDataLoadFile.class);
DataSource sourceDataSource;
int commitNumber = 2000;
int threadNumber =1;
int limitTextSize=0;
String tableName;
String loadFilePath;
String loadFileName;
String fileNameSuffix;
String terminatedString;
String fileType="csv";
boolean skipFirstRow=false;
String fromUrl;
String fromUser;
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = Float.valueOf(System.getProperty("java.specification.version"))<1.8?
manager.getEngineByName("javascript"):manager.getEngineByName("nashorn");
/**
* 转换代码 javascript 定义
*/
static String SCRIPT_CODE=
" var columns[%s''];"//当前行的数据数组
+ " var dataValue='%s';"//当前列的数据
+ " var returnValue=''; "//定义返回值
+ " %s ;";//用户定义javascript控制代码
//<!-- FULL 在插入前进行删除,默认 -->
//<!-- INCREMENT 先清除条件相关数据,然后按照条件进行增量插入 -->
String transType="FULL";
ArrayList<TableColumns> listTableColumns ;
public TransDataLoadFile() {
super();
// TODO Auto-generated constructor stub
}
public TransDataLoadFile(DataSource sourceDataSource,int commitNumber, int threadNumber,
String tableName, String loadFileName, String fileNameSuffix,
String terminatedString, String selectSqlString, String exportFilePath,int limitTextSize) {
super();
this.commitNumber = commitNumber;
this.threadNumber = threadNumber;
this.tableName = tableName;
this.loadFileName = loadFileName;
this.fileNameSuffix = fileNameSuffix;
this.terminatedString = terminatedString;
this.sourceDataSource=sourceDataSource;
this.limitTextSize=limitTextSize;
}
public void run() throws SQLException {
//未填写数据列,则自动读取数据库内容
if(listTableColumns==null) {
buildMetaData(tableName);
}
if(fileType.equalsIgnoreCase("csv")) {
runCsv();
}else {
runXlsx();
}
}
public void runCsv() throws SQLException {
Connection sourcConn=null;
PreparedStatement pstmt=null;
// TODO Auto-generated method stub
try {
String filePath=loadFilePath.replace("\\", "/")+""+loadFileName+fileNameSuffix;
_logger.info("---------------thread "+threadNumber+" "+filePath);
File txtFile=new File(filePath);
if(txtFile.exists()&&txtFile.length()>0){//文件不存在或者为空的情况
_logger.info("---------------thread "+threadNumber+" "+"file exists");
InputStreamReader read=new InputStreamReader(new FileInputStream(filePath));
BufferedReader bReader=new BufferedReader(read);
String lineText;
String insertSql=buildInsertSql();
sourcConn=sourceDataSource.getConnection();
sourcConn.setAutoCommit(false);
pstmt=sourcConn.prepareStatement(insertSql);
long insertNum=0;
long commitCount=0;
while((lineText=bReader.readLine())!=null){
if(skipFirstRow&&commitCount==0){commitCount++ ;continue;}//跳过第一行
lineText=lineText+" |+|";
_logger.debug("---------------lineText "+lineText);
String[] columnvalues=lineText.split("\\|\\+\\|");
_logger.debug("---------------length "+columnvalues.length);
for (String v :columnvalues) {
_logger.debug("---------------column value "+v);
}
//TODO:
/*
if(columnvalues.length<listTableColumns.size()) {
_logger.info("--------------- skip columnvalues "+columnvalues.length+" TableColumns "+listTableColumns.size());
continue;
}*/
setValue(columnvalues,pstmt);
commitCount++;
insertNum += 1;
if (insertNum >= this.commitNumber) {
insertNum = 0;
_logger.info("--thread "+threadNumber+"--Commit Count "+commitCount );
pstmt.executeBatch();
sourcConn.commit();
}
}
if (insertNum >0){
_logger.info("--thread "+threadNumber+"--Commit Count "+commitCount +" Complete .");
pstmt.executeBatch();
sourcConn.commit();
}
bReader.close();
}else if(txtFile.length()<=0){
_logger.info("---------------thread "+threadNumber+" "+"file length is 0");
}else {
_logger.info("---------------thread "+threadNumber+" "+"file not exists");
}
}catch(Exception e) {
_logger.info("---------------thread "+threadNumber+" "+"Exception");
_logger.info("---------------thread "+e.getMessage());
e.printStackTrace();
if(sourcConn!=null)sourcConn.rollback();
}finally {
ConnUtil.releaseConnection(sourcConn, null, pstmt, null);
}
}
public void runXlsx() throws SQLException {
Connection sourcConn=null;
PreparedStatement pstmt=null;
// TODO Auto-generated method stub
try {
String filePath=loadFilePath.replace("\\", "/")+""+loadFileName+fileNameSuffix;
_logger.info("---------------thread "+threadNumber+" "+filePath);
File excelFile=new File(filePath);
if(excelFile.exists()&&excelFile.length()>0){
_logger.info("---------------thread "+threadNumber+" "+"file exists");
FileInputStream fis= new FileInputStream(excelFile);
Workbook workbook=null;
//Workbook workbook=new HSSFWorkbook();
if(fileNameSuffix.indexOf("xlsx")>-1) {
workbook=new XSSFWorkbook(fis);
_logger.info("--thread "+threadNumber+" XSSFWorkbook ...");
}else {
workbook=new HSSFWorkbook(fis);
_logger.info("--thread "+threadNumber+" HSSFWorkbook ...");
}
Sheet sheet=workbook.getSheetAt(0);
String insertSql=buildInsertSql();
sourcConn=sourceDataSource.getConnection();
sourcConn.setAutoCommit(false);
pstmt=sourcConn.prepareStatement(insertSql);
;
long insertNum=0;
long commitCount=0;
for (Row rows : sheet) {
if(skipFirstRow&&commitCount==0){commitCount++ ;continue;}//跳过第一行
if(commitCount>sheet.getLastRowNum())break;
String[] columnvalues=new String [listTableColumns.size()];
_logger.debug("---------------length "+columnvalues.length);
//读取每行记录各列的值
for (int readColumn =0; readColumn<columnvalues.length;readColumn++) {
columnvalues[readColumn]=rows.getCell(readColumn).toString();
_logger.debug("---------------column value "+columnvalues[readColumn]);
}
setValue(columnvalues,pstmt);
commitCount++;
insertNum += 1;
if (insertNum >= this.commitNumber) {
insertNum = 0;
_logger.info("--thread "+threadNumber+"--Commit Count "+commitCount );
pstmt.executeBatch();
sourcConn.commit();
}
}
if (insertNum >0){
_logger.info("--thread "+threadNumber+"--Commit Count "+commitCount +" Complete .");
pstmt.executeBatch();
sourcConn.commit();
}
workbook.close();
fis.close();
}else if(excelFile.length()<=0){
_logger.info("---------------thread "+threadNumber+" "+"file length is 0");
}else {
_logger.info("---------------thread "+threadNumber+" "+"file not exists");
}
}catch(Exception e) {
_logger.info("---------------thread "+threadNumber+" "+"Exception");
_logger.info("---------------thread "+e.getMessage());
e.printStackTrace();
if(sourcConn!=null)sourcConn.rollback();
}finally {
ConnUtil.releaseConnection(sourcConn, null, pstmt, null);
}
}
public String buildInsertSql(){
String sql="";
String cols="";
String vals="";
int i=1;
for(TableColumns tc : listTableColumns) {
if(tc.isSkip()) {i++;continue;}//跳过
if(i==1) {
cols=tc.getColumnName();
if(tc.isFixed()) {
vals=" "+tc.getDefaultValue()+" ";
}else {
vals=" ? ";
}
}else {
cols=cols+" , "+tc.getColumnName();
if(tc.isFixed()) {
vals=vals+" , "+tc.getDefaultValue()+" ";
}else {
vals=vals+" , ? ";
}
}
_logger.debug("---------------thread "+threadNumber+" "+tc.getColumnName()+","+tc.getDataType());
i++;
}
sql="INSERT INTO "+this.tableName +" ("+cols+") VALUES ("+vals+")";
_logger.info("---------------thread "+threadNumber+" SQL "+sql);
return sql;
}
public void setValue(String []columnvalues,PreparedStatement pstmt) throws Exception{
//TODO:
int pos=1;
int columnPos=0;
for(TableColumns tc :listTableColumns){
if(tc.isSkip()||tc.isFixed()) {continue;}//跳过
//TODO:
String columnValue=columnvalues[columnPos++];
if(tc.getConvert()!=null) {
String columnsString="";
for(String cv : columnvalues) {
columnsString+="'"+cv+"',";
}
engine.eval(String.format(SCRIPT_CODE,columnsString,columnValue,tc.getConvert()));
columnValue=engine.get("returnValue").toString();//获取返js回值
}
_logger.trace("--column "+tc.getColumnName()+" , "+tc.getDataType() +" , value "+columnValue);
if(tc.getDataType().equalsIgnoreCase("VARCHAR2")||
tc.getDataType().equalsIgnoreCase("VARCHAR")||
tc.getDataType().equalsIgnoreCase("NVARCHAR2")||
tc.getDataType().equalsIgnoreCase("CHAR")||
tc.getDataType().equalsIgnoreCase("RAW")
){
pstmt.setString(pos, columnValue.trim());
}else if(tc.getDataType().equalsIgnoreCase("NUMBER")){
if(tc.getDataLength()==22&&tc.getDataScale()>0){//NUMBER
pstmt.setFloat(pos, Float.parseFloat(columnValue));
}else if(tc.getDataLength()==22&&tc.getDataScale()==0){//INTEGER
pstmt.setFloat(pos, Float.parseFloat(columnValue));
}else if(tc.getDataPrecision()==0||tc.getDataScale()==0||tc.getDataScale()==0){//LONG
pstmt.setFloat(pos, Float.parseFloat(columnValue));
}else{//DOUBLE
pstmt.setFloat(pos, Float.parseFloat(columnValue));
}
}else if(tc.getDataType().equalsIgnoreCase("blob")){
//stringBufferLines.append(getBlob(rs,tc.getColumnName()));
}else if(tc.getDataType().equalsIgnoreCase("clob")||tc.getDataType().equalsIgnoreCase("NCLOB")){
pstmt.setString(pos, columnValue);
}else if(tc.getDataType().equalsIgnoreCase("DATE")){
//stringBufferLines.append(rs.getDate(tc.getColumnName()));//targetPstmt.setDate(pos, rs.getDate(tc.getColumnName()));
}else{
pstmt.setString(pos, columnValue);
}
pos++;
}
pstmt.addBatch();
}
public String getClob(ResultSet sourceRs,String column) throws Exception{
oracle.sql.CLOB sb=(oracle.sql.CLOB)sourceRs.getClob(column);
if(sb==null)return "";
Reader is=sb.getCharacterStream();
char[]data=new char[(int)sb.length()];
is.read(data);
is.close();
return new String(data);
}
public String getBlob(ResultSet sourceRs,String column) throws Exception{
oracle.sql.BLOB sb=(oracle.sql.BLOB)sourceRs.getBlob(column);
if(sb==null)return "";
InputStream is=sb.getBinaryStream();
byte[]data=new byte[(int)sb.length()];
is.read(data);
is.close();
return new String(data);
}
public void buildMetaData(String tableName) throws SQLException{
Connection sourcConn=sourceDataSource.getConnection();
PreparedStatement pstmt=sourcConn.prepareStatement("SELECT * FROM "+tableName);
buildMetaData(pstmt.getMetaData());
pstmt.close();
sourcConn.close();
}
public void buildMetaData(ResultSet rs) throws SQLException{
ResultSetMetaData metaData = rs.getMetaData();
buildMetaData(metaData);
}
public void buildMetaData(ResultSetMetaData metaData) throws SQLException{
_logger.debug("--thread "+threadNumber+"--column Count "+metaData.getColumnCount() );
for (int i = 1; i <= metaData.getColumnCount(); i++) {
TableColumns tc=new TableColumns();
tc.setColumnName(metaData.getColumnName(i));
tc.setDataType(metaData.getColumnTypeName(i));
tc.setTableName(metaData.getTableName(i));
tc.setDataPrecision(metaData.getPrecision(i));
tc.setDataScale(metaData.getScale(i));
_logger.debug("--thread "+threadNumber+"--No. "+i+" , Column "+tc.getColumnName()+" , DataType "+tc.getDataType() );
listTableColumns.add(tc);
}
}
public DataSource getSourceDataSource() {
return sourceDataSource;
}
public void setSourceDataSource(DataSource sourceDataSource) {
this.sourceDataSource = sourceDataSource;
}
public int getCommitNumber() {
return commitNumber;
}
public void setCommitNumber(int commitNumber) {
this.commitNumber = commitNumber;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public int getLimitTextSize() {
return limitTextSize;
}
public void setLimitTextSize(int limitTextSize) {
this.limitTextSize = limitTextSize;
}
public String getFileNameSuffix() {
return fileNameSuffix;
}
public void setFileNameSuffix(String fileNameSuffix) {
this.fileNameSuffix = fileNameSuffix;
}
public String getTerminatedString() {
return terminatedString;
}
public void setTerminatedString(String terminatedString) {
this.terminatedString = terminatedString;
}
public ArrayList<TableColumns> getListTableColumns() {
return listTableColumns;
}
public void setListTableColumns(ArrayList<TableColumns> listTableColumns) {
this.listTableColumns = listTableColumns;
}
public String getLoadFileName() {
return loadFileName;
}
public void setLoadFileName(String loadFileName) {
this.loadFileName = loadFileName;
}
public String getLoadFilePath() {
return loadFilePath;
}
public void setLoadFilePath(String loadFilePath) {
this.loadFilePath = loadFilePath;
}
public int getThreadNumber() {
return threadNumber;
}
public void setThreadNumber(int threadNumber) {
this.threadNumber = threadNumber;
}
public String getTransType() {
return transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
public boolean isSkipFirstRow() {
return skipFirstRow;
}
public void setSkipFirstRow(boolean skipFirstRow) {
this.skipFirstRow = skipFirstRow;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
}
| true |
3a1cfd7577db6989a57d4e1fd0562c6746eaeae4 | Java | jarvcol/myTaxy | /src/test/java/test/clients/posts/BasePostClient.java | UTF-8 | 1,016 | 2.078125 | 2 | [] | no_license | package test.clients.posts;
import pojo.PostRequestBody;
import test.clients.BaseClient;
public abstract class BasePostClient extends BaseClient {
protected PostRequestBody postObject;
protected int postId;
protected int userId;
public BasePostClient(String baseUri) {
super(baseUri);
}
public abstract void getApiRun();
public int getPostId(){
return getApiResponseAsJsonObject().getInt("id");
}
public String getPostTitle(){
return getApiResponseAsJsonObject().getString("title");
}
public String getPostBody(){
return getApiResponseAsJsonObject().getString("body");
}
public int getUserId(){
return getApiResponseAsJsonObject().getInt("userId");
}
public void setPostObject(PostRequestBody postObject){
this.postObject = postObject;
}
public void setPostId(int postId){
this.postId = postId;
}
public void setUserId(int userId){
this.userId = userId;
}
}
| true |
67b4b1b4cf450a79b28cbc9515b9254efe620f91 | Java | Gekoncze/MgCompiler | /src/cz/mg/compiler/entities/logical/LogicalEntity.java | UTF-8 | 365 | 2.125 | 2 | [] | no_license | package cz.mg.compiler.entities.logical;
import cz.mg.compiler.utilities.debug.Trace;
import cz.mg.compiler.entities.Entity;
public abstract class LogicalEntity extends Entity {
private final Trace trace;
protected LogicalEntity(Trace trace) {
this.trace = trace;
}
@Override
public Trace getTrace() {
return trace;
}
}
| true |
7998b5703708be35e6d83bcfcfdd83801c21c171 | Java | fp1203/FASTUT | /src/main/java/fastut/coverage/data/ClassData.java | UTF-8 | 17,727 | 2.5625 | 3 | [] | no_license | package fastut.coverage.data;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* <p>
* ProjectData information is typically serialized to a file. An instance of this class records coverage information for
* a single class that has been instrumented.
* </p>
* <p>
* This class implements HasBeenInstrumented so that when cobertura instruments itself, it will omit this class. It does
* this to avoid an infinite recursion problem because instrumented classes make use of this class.
* </p>
*/
public class ClassData extends CoverageDataContainer implements Comparable<ClassData>, HasBeenInstrumented {
private static final long serialVersionUID = 5;
/**
* Each key is a line number in this class, stored as an Integer object. Each value is information about the line,
* stored as a LineData object.
*/
private Map<Integer, LineData> branches = new HashMap<Integer, LineData>();
private boolean containsInstrumentationInfo = false;
private Set<String> methodNamesAndDescriptors = new HashSet<String>();
private String name = null;
private String sourceFileName = null;
/**
* @param name In the format "net.sourceforge.cobertura.coveragedata.ClassData"
*/
public ClassData(String name){
if (name == null) throw new IllegalArgumentException("Class name must be specified.");
this.name = name;
}
public LineData addLine(int lineNumber, String methodName, String methodDescriptor) {
lock.lock();
try {
LineData lineData = getLineData(lineNumber);
if (lineData == null) {
lineData = new LineData(lineNumber);
// Each key is a line number in this class, stored as an Integer object.
// Each value is information about the line, stored as a LineData object.
children.put(new Integer(lineNumber), lineData);
}
lineData.setMethodNameAndDescriptor(methodName, methodDescriptor);
// methodName and methodDescriptor can be null when cobertura.ser with
// no line information was loaded (or was not loaded at all).
if (methodName != null && methodDescriptor != null) methodNamesAndDescriptors.add(methodName
+ methodDescriptor);
return lineData;
} finally {
lock.unlock();
}
}
/**
* This is required because we implement Comparable.
*/
public int compareTo(ClassData o) {
return this.name.compareTo(o.name);
}
public boolean containsInstrumentationInfo() {
lock.lock();
try {
return this.containsInstrumentationInfo;
} finally {
lock.unlock();
}
}
/**
* Returns true if the given object is an instance of the ClassData class, and it contains the same data as this
* class.
*/
public boolean equals(Object obj) {
if (this == obj) return true;
if ((obj == null) || !(obj.getClass().equals(this.getClass()))) return false;
ClassData classData = (ClassData) obj;
getBothLocks(classData);
try {
return super.equals(obj) && this.branches.equals(classData.branches)
&& this.methodNamesAndDescriptors.equals(classData.methodNamesAndDescriptors)
&& this.name.equals(classData.name) && this.sourceFileName.equals(classData.sourceFileName);
} finally {
lock.unlock();
classData.lock.unlock();
}
}
public String getBaseName() {
int lastDot = this.name.lastIndexOf('.');
if (lastDot == -1) {
return this.name;
}
return this.name.substring(lastDot + 1);
}
/**
* @return The branch coverage rate for a particular method.
*/
public double getBranchCoverageRate(String methodNameAndDescriptor) {
int total = 0;
int covered = 0;
lock.lock();
try {
for (Iterator<LineData> iter = branches.values().iterator(); iter.hasNext();) {
LineData next = (LineData) iter.next();
if (methodNameAndDescriptor.equals(next.getMethodName() + next.getMethodDescriptor())) {
total += next.getNumberOfValidBranches();
covered += next.getNumberOfCoveredBranches();
}
}
if (total == 0) return 1.0;
return ((double) covered) / total;
} finally {
lock.unlock();
}
}
public int getNumberOfValidBranches(String methodNameAndDescriptor) {
int total = 0;
lock.lock();
try {
for (Iterator<LineData> iter = branches.values().iterator(); iter.hasNext();) {
LineData next = (LineData) iter.next();
if (methodNameAndDescriptor.equals(next.getMethodName() + next.getMethodDescriptor())) {
total += next.getNumberOfValidBranches();
}
}
return total;
} finally {
lock.unlock();
}
}
public Collection<Integer> getBranches() {
lock.lock();
try {
return Collections.unmodifiableCollection(branches.keySet());
} finally {
lock.unlock();
}
}
/**
* @param lineNumber The source code line number.
* @return The coverage of the line
*/
public LineData getLineCoverage(int lineNumber) {
Integer lineObject = new Integer(lineNumber);
lock.lock();
try {
if (!children.containsKey(lineObject)) {
return null;
}
return (LineData) children.get(lineObject);
} finally {
lock.unlock();
}
}
/**
* @return The line coverage rate for particular method
*/
public double getLineCoverageRate(String methodNameAndDescriptor) {
int total = 0;
int hits = 0;
lock.lock();
try {
Iterator<CoverageData> iter = children.values().iterator();
while (iter.hasNext()) {
LineData next = (LineData) iter.next();
if (methodNameAndDescriptor.equals(next.getMethodName() + next.getMethodDescriptor())) {
total++;
if (next.getHits() > 0) {
hits++;
}
}
}
if (total == 0) return 1d;
return (double) hits / total;
} finally {
lock.unlock();
}
}
private LineData getLineData(int lineNumber) {
lock.lock();
try {
return (LineData) children.get(Integer.valueOf(lineNumber));
} finally {
lock.unlock();
}
}
public SortedSet<CoverageData> getLines() {
lock.lock();
try {
return new TreeSet<CoverageData>(this.children.values());
} finally {
lock.unlock();
}
}
public Collection<CoverageData> getLines(String methodNameAndDescriptor) {
Collection<CoverageData> lines = new HashSet<CoverageData>();
lock.lock();
try {
Iterator<CoverageData> iter = children.values().iterator();
while (iter.hasNext()) {
LineData next = (LineData) iter.next();
if (methodNameAndDescriptor.equals(next.getMethodName() + next.getMethodDescriptor())) {
lines.add(next);
}
}
return lines;
} finally {
lock.unlock();
}
}
/**
* @return The method name and descriptor of each method found in the class represented by this instrumentation.
*/
public Set<String> getMethodNamesAndDescriptors() {
lock.lock();
try {
return methodNamesAndDescriptors;
} finally {
lock.unlock();
}
}
public String getName() {
return name;
}
/**
* @return The number of branches in this class.
*/
public int getNumberOfValidBranches() {
int number = 0;
lock.lock();
try {
for (Iterator<LineData> i = branches.values().iterator(); i.hasNext(); number += (i.next()).getNumberOfValidBranches())
;
return number;
} finally {
lock.unlock();
}
}
/**
* @see net.sourceforge.cobertura.coveragedata.CoverageData#getNumberOfCoveredBranches()
*/
public int getNumberOfCoveredBranches() {
int number = 0;
lock.lock();
try {
for (Iterator<LineData> i = branches.values().iterator(); i.hasNext(); number += (i.next()).getNumberOfCoveredBranches())
;
return number;
} finally {
lock.unlock();
}
}
public String getPackageName() {
int lastDot = this.name.lastIndexOf('.');
if (lastDot == -1) {
return "";
}
return this.name.substring(0, lastDot);
}
/**
* Return the name of the file containing this class. If this class' sourceFileName has not been set (for whatever
* reason) then this method will attempt to infer the name of the source file using the class name.
*
* @return The name of the source file, for example net/sourceforge/cobertura/coveragedata/ClassData.java
*/
public String getSourceFileName() {
String baseName;
lock.lock();
try {
if (sourceFileName != null) baseName = sourceFileName;
else {
baseName = getBaseName();
int firstDollarSign = baseName.indexOf('$');
if (firstDollarSign == -1 || firstDollarSign == 0) baseName += ".java";
else baseName = baseName.substring(0, firstDollarSign) + ".java";
}
String packageName = getPackageName();
if (packageName.equals("")) return baseName;
return packageName.replace('.', '/') + '/' + baseName;
} finally {
lock.unlock();
}
}
public int hashCode() {
return this.name.hashCode();
}
/**
* @return True if the line contains at least one condition jump (branch)
*/
public boolean hasBranch(int lineNumber) {
lock.lock();
try {
return branches.containsKey(Integer.valueOf(lineNumber));
} finally {
lock.unlock();
}
}
/**
* Determine if a given line number is a valid line of code.
*
* @return True if the line contains executable code. False if the line is empty, or a comment, etc.
*/
public boolean isValidSourceLineNumber(int lineNumber) {
lock.lock();
try {
return children.containsKey(Integer.valueOf(lineNumber));
} finally {
lock.unlock();
}
}
public void addLineJump(int lineNumber, int branchNumber) {
lock.lock();
try {
LineData lineData = getLineData(lineNumber);
if (lineData != null) {
lineData.addJump(branchNumber);
this.branches.put(Integer.valueOf(lineNumber), lineData);
}
} finally {
lock.unlock();
}
}
public void addLineSwitch(int lineNumber, int switchNumber, int[] keys) {
lock.lock();
try {
LineData lineData = getLineData(lineNumber);
if (lineData != null) {
lineData.addSwitch(switchNumber, keys);
this.branches.put(Integer.valueOf(lineNumber), lineData);
}
} finally {
lock.unlock();
}
}
public void addLineSwitch(int lineNumber, int switchNumber, int min, int max) {
lock.lock();
try {
LineData lineData = getLineData(lineNumber);
if (lineData != null) {
lineData.addSwitch(switchNumber, min, max);
this.branches.put(Integer.valueOf(lineNumber), lineData);
}
} finally {
lock.unlock();
}
}
/**
* Merge some existing instrumentation with this instrumentation.
*
* @param coverageData Some existing coverage data.
*/
public void merge(CoverageData coverageData) {
ClassData classData = (ClassData) coverageData;
// If objects contain data for different classes then don't merge
if (!this.getName().equals(classData.getName())) return;
getBothLocks(classData);
try {
super.merge(coverageData);
// We can't just call this.branches.putAll(classData.branches);
// Why not? If we did a putAll, then the LineData objects from
// the coverageData class would overwrite the LineData objects
// that are already in "this.branches" And we don't need to
// update the LineData objects that are already in this.branches
// because they are shared between this.branches and this.children,
// so the object hit counts will be moved when we called
// super.merge() above.
for (Iterator<Integer> iter = classData.branches.keySet().iterator(); iter.hasNext();) {
Integer key = iter.next();
if (!this.branches.containsKey(key)) {
this.branches.put(key, classData.branches.get(key));
}
}
this.containsInstrumentationInfo |= classData.containsInstrumentationInfo;
this.methodNamesAndDescriptors.addAll(classData.getMethodNamesAndDescriptors());
if (classData.sourceFileName != null) this.sourceFileName = classData.sourceFileName;
} finally {
lock.unlock();
classData.lock.unlock();
}
}
public void removeLine(int lineNumber) {
Integer lineObject = Integer.valueOf(lineNumber);
lock.lock();
try {
children.remove(lineObject);
branches.remove(lineObject);
} finally {
lock.unlock();
}
}
public void setContainsInstrumentationInfo() {
lock.lock();
try {
this.containsInstrumentationInfo = true;
} finally {
lock.unlock();
}
}
public void setSourceFileName(String sourceFileName) {
lock.lock();
try {
this.sourceFileName = sourceFileName;
} finally {
lock.unlock();
}
}
/**
* Increment the number of hits for a particular line of code.
*
* @param lineNumber the line of code to increment the number of hits.
* @param hits how many times the piece was called
*/
public void touch(int lineNumber, int hits) {
lock.lock();
try {
LineData lineData = getLineData(lineNumber);
if (lineData == null) lineData = addLine(lineNumber, null, null);
lineData.touch(hits);
} finally {
lock.unlock();
}
}
/**
* Increments the number of hits for particular hit counter of particular branch on particular line number.
*
* @param lineNumber The line of code where the branch is
* @param branchNumber The branch on the line to change the hit counter
* @param branch The hit counter (true or false)
* @param hits how many times the piece was called
*/
public void touchJump(int lineNumber, int branchNumber, boolean branch, int hits) {
lock.lock();
try {
LineData lineData = getLineData(lineNumber);
if (lineData == null) lineData = addLine(lineNumber, null, null);
lineData.touchJump(branchNumber, branch, hits);
} finally {
lock.unlock();
}
}
/**
* Increments the number of hits for particular hit counter of particular switch branch on particular line number.
*
* @param lineNumber The line of code where the branch is
* @param switchNumber The switch on the line to change the hit counter
* @param branch The hit counter
* @param hits how many times the piece was called
*/
public void touchSwitch(int lineNumber, int switchNumber, int branch, int hits) {
lock.lock();
try {
LineData lineData = getLineData(lineNumber);
if (lineData == null) lineData = addLine(lineNumber, null, null);
lineData.touchSwitch(switchNumber, branch, hits);
} finally {
lock.unlock();
}
}
@Override
public void reset() {
lock.lock();
try {
for (Map.Entry<Integer, LineData> entry : branches.entrySet()) {
entry.getValue().reset();
}
Iterator<CoverageData> iter = children.values().iterator();
while (iter.hasNext()) {
LineData next = (LineData) iter.next();
next.reset();
}
} finally {
lock.unlock();
}
}
@Override
public String toString() {
return "ClassData [branches=" + branches + "]";
}
}
| true |
0f5de6853b73749b6dc327dd701a36cadb3aec7b | Java | Alsan/turing-chunk07 | /components/autoscaler/jvmagentclient/src/main/java/org/wso2/carbon/autoscaler/main/TestAgent.java | UTF-8 | 749 | 2.03125 | 2 | [] | no_license | package org.wso2.carbon.autoscaler.main;
import org.wso2.carbon.autoscaler.service.agent.clients.AgentServiceClient;
public class TestAgent {
private final static String AMS_BACKEND_URL ="http://localhost:9788/services/";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
AgentServiceClient asc = new AgentServiceClient(AMS_BACKEND_URL);
System.out.println(asc.registerInAgentManagementService());
System.out.println(asc.unregisterInAgentManagementService());
System.out.println(asc.unregisterInAgentManagementService());
System.out.println(asc.registerInAgentManagementService());
System.out.println(asc.unregisterInAgentManagementService());
}
}
| true |
6e7ee67511b93762dbac177f7d9995822b006604 | Java | Dmitriy886/mirea.java.homework | /practice05/PR5.java | UTF-8 | 785 | 2.921875 | 3 | [] | no_license | package ru.mirea.java.practice05;
public class PR5 {
public static void main(String[] args) {
SingletonFirst singletonOne = SingletonFirst.getInstance();
SingletonFirst singletonOne2 = SingletonFirst.getInstance();
SingletonSecond singletonTwo = SingletonSecond.getInstance();
SingletonSecond singletonTwo2 = SingletonSecond.getInstance();
SingletonThird singletonThree = SingletonThird.getInstance();
SingletonThird singletonThree2 = SingletonThird.getInstance();
System.out.println(singletonOne);
System.out.println(singletonOne2);
System.out.println(singletonTwo);
System.out.println(singletonTwo2);
System.out.println(singletonThree);
System.out.println(singletonThree2);
}
} | true |
cb1aa7a77e615c898df8aa5550702184b4ad9aff | Java | mviera89/tesis2015 | /vSpemWeb1.2/src/logica/dataTypes/TipoPlugin.java | UTF-8 | 3,773 | 1.929688 | 2 | [] | no_license | package logica.dataTypes;
import java.util.List;
public class TipoPlugin {
private String id;
private String name;
private String guid;
private String briefDescription;
private String authors;
private String changeDate;
private String changeDescription;
private String version;
private String lineProcessDir;
private String deliveryProcessDir;
private List<String> capabilityPatternsDir;
private String customCategoriesDir;
private List<String> tasksDir;
private List<String> workproductsDir;
private List<String> guidancesDir;
public TipoPlugin(String id, String name, String guid, String briefDescription, String authors, String changeDate, String changeDescription, String version,
String lineProcessDir, String deliveryProcessDir, List<String> capabilityPatternsDir, String customCategoriesDir,
List<String> tasksDir, List<String> workproductsDir, List<String> guidancesDir) {
this.id = id;
this.name = name;
this.guid = guid;
this.briefDescription = briefDescription;
this.authors = authors;
this.changeDate = changeDate;
this.changeDescription = changeDescription;
this.version = version;
this.lineProcessDir = lineProcessDir;
this.deliveryProcessDir = deliveryProcessDir;
this.capabilityPatternsDir = capabilityPatternsDir;
this.customCategoriesDir = customCategoriesDir;
this.tasksDir = tasksDir;
this.workproductsDir = workproductsDir;
this.guidancesDir = guidancesDir;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getBriefDescription() {
return briefDescription;
}
public void setBriefDescription(String briefDescription) {
this.briefDescription = briefDescription;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getChangeDate() {
return changeDate;
}
public void setChangeDate(String changeDate) {
this.changeDate = changeDate;
}
public String getChangeDescription() {
return changeDescription;
}
public void setChangeDescription(String changeDescription) {
this.changeDescription = changeDescription;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLineProcessDir() {
return lineProcessDir;
}
public void setLineProcessDir(String lineProcessDir) {
this.lineProcessDir = lineProcessDir;
}
public String getDeliveryProcessDir() {
return deliveryProcessDir;
}
public void setDeliveryProcessDir(String deliveryProcessDir) {
this.deliveryProcessDir = deliveryProcessDir;
}
public List<String> getCapabilityPatternsDir() {
return capabilityPatternsDir;
}
public void setCapabilityPatternsDir(List<String> capabilityPatternsDir) {
this.capabilityPatternsDir = capabilityPatternsDir;
}
public String getCustomCategoriesDir() {
return customCategoriesDir;
}
public void setCustomCategoriesDir(String customCategoriesDir) {
this.customCategoriesDir = customCategoriesDir;
}
public List<String> getTasksDir() {
return tasksDir;
}
public void setTasksDir(List<String> tasksDir) {
this.tasksDir = tasksDir;
}
public List<String> getWorkproductsDir() {
return workproductsDir;
}
public void setWorkproductsDir(List<String> workproductsDir) {
this.workproductsDir = workproductsDir;
}
public List<String> getGuidancesDir() {
return guidancesDir;
}
public void setGuidancesDir(List<String> guidancesDir) {
this.guidancesDir = guidancesDir;
}
}
| true |
1130bc515d9f0e62ee5d4cb2b612d2748bff57f1 | Java | sumityadav22/Java-Practice | /javaInput.java | UTF-8 | 276 | 3.265625 | 3 | [] | no_license | import java.util.Scanner;
class javaInput{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input_number;
System.out.println("Enter any number: ");
input_number = sc.nextInt();
System.out.println("You Entered: "+input_number);
}
} | true |
32bc2ec12ee641650c5d0c46c999e819b3661620 | Java | cuartz/Systematis | /ZiPlace/src/main/java/com/zeepoint/DAO/PmessageDAO.java | UTF-8 | 557 | 1.90625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.zeepoint.DAO;
import com.zeepoint.model.Pmessage;
import java.util.List;
/**
*
* @author cuartz
*/
public interface PmessageDAO extends DAO<Pmessage, Long> {
public List<Pmessage> getLastMessages(Long fromUserId,Long toUserId);
public List<Pmessage> getPreviousMessages(Long fromUserId,Long toUserId, Long lastMessageId);
}
| true |
5a4e8c9872fea98efdce53ac2b68a0ca5c37faaa | Java | LyricsRH/dahuashejimoshi | /src/抽象工厂模式/Department.java | UTF-8 | 96 | 2.265625 | 2 | [] | no_license | package 抽象工厂模式;
public interface Department {
void add();
void delete();
}
| true |
0e1dbd415b74932b0c4d2051fdc3d4d95637d777 | Java | gong9949/design-pattern | /src/main/java/com/gong/designpattern/abstractfactory/ComputerHuaWei.java | UTF-8 | 254 | 2.484375 | 2 | [] | no_license | package com.gong.designpattern.abstractfactory;
/**
* Created by gongls on 2019/3/9.
*/
public class ComputerHuaWei implements IComputer {
@Override
public ComputerInfo getComputer() {
return new ComputerInfo("华为",6999f);
}
}
| true |
edcd67c5f65c5de257d1c45a0d2a2b021b43bdb5 | Java | WheatVIVO/datasources | /datasources/src/main/java/org/wheatinitiative/vivo/datasource/LaunchIngest.java | UTF-8 | 9,903 | 2.078125 | 2 | [] | no_license | package org.wheatinitiative.vivo.datasource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wheatinitiative.vivo.datasource.connector.arc.ArcConnector;
import org.wheatinitiative.vivo.datasource.connector.cordis.Cordis;
import org.wheatinitiative.vivo.datasource.connector.cornell.Cornell;
import org.wheatinitiative.vivo.datasource.connector.florida.Florida;
import org.wheatinitiative.vivo.datasource.connector.grdc.GrdcConnector;
import org.wheatinitiative.vivo.datasource.connector.msracad.MicrosoftAcademicConnector;
import org.wheatinitiative.vivo.datasource.connector.openaire.OpenAire;
import org.wheatinitiative.vivo.datasource.connector.orcid.OrcidConnector;
import org.wheatinitiative.vivo.datasource.connector.prodinra.Prodinra;
import org.wheatinitiative.vivo.datasource.connector.rcuk.Rcuk;
import org.wheatinitiative.vivo.datasource.connector.tamu.Tamu;
import org.wheatinitiative.vivo.datasource.connector.upenn.Upenn;
import org.wheatinitiative.vivo.datasource.connector.usda.Usda;
import org.wheatinitiative.vivo.datasource.connector.wheatinitiative.WheatInitiative;
import org.wheatinitiative.vivo.datasource.normalizer.AuthorNameForSameAsNormalizer;
import org.wheatinitiative.vivo.datasource.normalizer.LiteratureNameForSameAsNormalizer;
import org.wheatinitiative.vivo.datasource.normalizer.OrganizationNameForSameAsNormalizer;
import org.wheatinitiative.vivo.datasource.postmerge.PostmergeDataSource;
import com.hp.hpl.jena.rdf.model.Model;
public class LaunchIngest {
private static final Log log = LogFactory.getLog(LaunchIngest.class);
public static void main(String[] args) {
if(args.length < 3) {
System.out.println("Usage: LaunchIngest"
+ " openaire|cordis|rcuk|msracad|prodinra|wheatinitiative|florida|arc|grdc|"
+ "normalizePerson|normalizeOrganization|normalizeLiterature|postmerge"
+ " outputfile"
+ " [endpointURI= endpointUpdateURI= username= password= dataDir= graph=]"
+ " queryTerm ... [queryTermN] [limit]");
return;
}
List<String> queryTerms = new LinkedList<String>(
Arrays.asList(args));
String connectorName = queryTerms.remove(0);
String outputFileName = queryTerms.remove(0);
int limit = getLimit(queryTerms);
if(limit < Integer.MAX_VALUE) {
log.info("Retrieving a limit of " + limit + " records");
}
DataSource connector = getConnector(connectorName);
SparqlEndpointParams endpointParameters = getEndpointParams("", queryTerms);
SparqlEndpointParams prodEndpointParameters = getEndpointParams("prod", queryTerms);
if(prodEndpointParameters != null) {
connector.getConfiguration().getParameterMap().put("prodEndpointParameters", prodEndpointParameters);
}
connector.getConfiguration().getParameterMap().put("dataDir", getDataDir(queryTerms));
connector.getConfiguration().setQueryTerms(queryTerms);
connector.getConfiguration().setEndpointParameters(endpointParameters);
connector.getConfiguration().setLimit(limit);
connector.getConfiguration().setResultsGraphURI(getResultsGraphURI(queryTerms));
connector.run();
Model result = connector.getResult();
if(result == null) {
log.warn("result is null");
} else {
File outputFile = new File(outputFileName);
FileOutputStream fos;
try {
log.info("Writing output to " + outputFile);
fos = new FileOutputStream(outputFile);
result.write(fos, "N3");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
private static DataSource getConnector(String connectorName) {
DataSource connector = null;
if ("cornell".equals(connectorName)) {
connector = new Cornell();
} else if ("cordis".equals(connectorName)) {
connector = new Cordis();
connector.getConfiguration().setServiceURI(
"https://cordis.europa.eu/search/result_en");
} else if("rcuk".equals(connectorName)) {
connector = new Rcuk();
connector.getConfiguration().setServiceURI(
"http://gtr.ukri.org/gtr/api/");
} else if ("msracad".equals(connectorName)) {
connector = new MicrosoftAcademicConnector();
} else if ("prodinra".equals(connectorName)) {
connector = new Prodinra();
connector.getConfiguration().setServiceURI(
"http://oai.prodinra.inra.fr/ft");
} else if ("usda".equals(connectorName)) {
connector = new Usda();
connector.getConfiguration().setServiceURI(
"http://vivo.usda.gov/");
} else if ("wheatinitiative".equals(connectorName)) {
connector = new WheatInitiative();
connector.getConfiguration().setServiceURI(
"http://www.wheatinitiative.org/administration/users/csv");
} else if ("arc".equals(connectorName)) {
connector = new ArcConnector();
} else if ("grdc".equals(connectorName)) {
connector = new GrdcConnector();
} else if ("openaire".equals(connectorName)) {
connector = new OpenAire();
connector.getConfiguration().setServiceURI(
"http://api.openaire.eu/oai_pmh");
} else if ("florida".equals(connectorName)) {
connector = new Florida();
connector.getConfiguration().setServiceURI(
"http://vivo.ufl.edu/");
} else if ("orcid".equals(connectorName)) {
connector = new OrcidConnector();
} else if ("upenn".equals(connectorName)) {
connector = new Upenn();
connector.getConfiguration().setServiceURI(
"http://vivo.upenn.edu/vivo/");
} else if ("tamu".equals(connectorName)) {
connector = new Tamu();
connector.getConfiguration().setServiceURI(
"http://scholars.library.tamu.edu/vivo/");
} else if ("normalizePerson".equals(connectorName)) {
connector = new AuthorNameForSameAsNormalizer();
} else if ("normalizeLiterature".equals(connectorName)) {
connector = new LiteratureNameForSameAsNormalizer();
} else if ("normalizeOrganization".equals(connectorName)) {
connector = new OrganizationNameForSameAsNormalizer();
} else if ("postmerge".equals(connectorName)) {
connector = new PostmergeDataSource();
} else {
throw new RuntimeException("Connector not found: "
+ connectorName);
}
connector.getConfiguration().getParameterMap().put(
"Vitro.defaultNamespace", "http://vivo.wheatinitiative.org/individual/");
return connector;
}
private static SparqlEndpointParams getEndpointParams(String endpointName,
List<String> queryTerms) {
SparqlEndpointParams params = new SparqlEndpointParams();
int toRemove = 0;
for (String queryTerm : queryTerms) {
if(queryTerm.startsWith(endpointName + "endpointURI=")) {
params.setEndpointURI(queryTerm.substring((endpointName + "endpointURI=").length()));
toRemove++;
} else if (queryTerm.startsWith(endpointName + "endpointUpdateURI=")) {
params.setEndpointUpdateURI(queryTerm.substring((endpointName + "endpointUpdateURI=").length()));
toRemove++;
} else if (queryTerm.startsWith(endpointName + "username=")) {
params.setUsername(queryTerm.substring((endpointName + "username=").length()));
toRemove++;
} else if (queryTerm.startsWith(endpointName + "password=")) {
params.setPassword(queryTerm.substring((endpointName + "password=").length()));
toRemove++;
}
}
for(int i = 0; i < toRemove; i++) {
queryTerms.remove(0);
}
if(toRemove > 0) {
return params;
} else {
log.info("Endpoint parameters not found");
return null;
}
}
private static String getDataDir(List<String> queryTerms) {
if(queryTerms.get(0).startsWith("dataDir=")) {
String dataDir = queryTerms.get(0).substring("dataDir=".length());
queryTerms.remove(0);
return dataDir;
} else {
return null;
}
}
private static String getResultsGraphURI(List<String> queryTerms) {
if(!queryTerms.isEmpty() && queryTerms.get(0).startsWith("graph=")) {
String graphParam = queryTerms.remove(0);
return graphParam.substring("graph=".length());
} else {
log.info("Graph parameter not found");
return null;
}
}
private static int getLimit(List<String> queryTerms) {
if(!queryTerms.isEmpty()) {
String possibleLimit = queryTerms.get(queryTerms.size() - 1);
try {
int limit = Integer.parseInt(possibleLimit, 10);
queryTerms.remove(queryTerms.size() - 1);
return limit;
} catch (NumberFormatException e) {
// no limit argument present; move on
}
}
return Integer.MAX_VALUE;
}
}
| true |
530917226cb17ea3d39811f6b9d4c44423b6626e | Java | MayYk/SwordOffer | /src/chapter3/No21ReorderArray.java | UTF-8 | 1,705 | 3.546875 | 4 | [] | no_license | package chapter3;
import java.time.temporal.Temporal;
import java.util.Arrays;
import java.util.Scanner;
/**
* Description: SwordOffer
* time: 2019-08-29 21:22
*/
//输入一个整数数组,调整数组中数字位置,使奇数位于数组的前半部分,偶数位于数组的后半部分
public class No21ReorderArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if (n<=0){
scanner.close();
return;
}
int[] arr = new int[n];
for (int i=0;i<n;i++){
arr[i] = scanner.nextInt();
}
No21ReorderArray no21ReorderArray = new No21ReorderArray();
int[] ss = no21ReorderArray.Reorder(arr);
for (int i=0;i<n;i++){
System.out.print(ss[i]);
}
scanner.close();
}
private int[] Reorder(int[] arr){
int head = 0;
int tail = arr.length-1;
while (head < tail){
while (arr[head] % 2 != 0 && head < tail){
head++;
}
while (arr[tail] % 2 == 0 && head < tail){
tail--;
}
if(head < tail){
int tem = arr[head];
arr[head] = arr[tail];
arr[tail] = tem;
}
}
return arr;
}
public void reOrderArray(int [] array) {
if (array == null || array.length < 2) {
return;
}
Integer[] bak = new Integer[array.length];
Arrays.setAll(bak, i -> array[i]);
Arrays.sort(bak, (x, y) -> (y & 1) - (x & 1));
Arrays.setAll(array, i -> bak[i]);
}
}
| true |
aad6a7934b915ce69f794641ee65f413634ea00d | Java | c1earlove7/demo1 | /src/day9/Search.java | UTF-8 | 1,165 | 3.203125 | 3 | [] | no_license | package day9;
public class Search {
boolean isSearchFound = false;
public void searchById(Student[] array,Integer stuID) {
for (int i = 0; i < array.length; i++) {
if(stuID == array[i].getId()) {
System.out.println(array[i]);
isSearchFound = true;
}
}
isSearch();
}
public void searchByName(Student[] array,String stuName) {
for (int i = 0; i < array.length; i++) {
if(array[i].getName().equals(stuName)) {
System.out.println(array[i]);
isSearchFound = true;
}
}
isSearch();
}
public void searchByGender(Student[] array,String stuGender) {
for (int i = 0; i < array.length; i++) {
if(array[i].getGender().equals(stuGender)) {
System.out.println(array[i]);
isSearchFound = true;
}
}
isSearch();
}
public void searchByAge(Student[] array,Integer stuAge) {
for (int i = 0; i < array.length; i++) {
if(array[i].getAge() == stuAge) {
System.out.println(array[i]);
isSearchFound = true;
}
}
isSearch();
}
public void isSearch() {
if (isSearchFound == false) {
System.out.println("没有找到符合条件的学生");
} else {
isSearchFound = false;
}
}
}
| true |
53892c02f87c7c15a449c478fd0123d0d7eaa9fe | Java | BananaPirate/BPBrewingStandLib | /src/main/java/org/sijbesma/bp/bpbrewingstandlib/event/listeners/WorldEventListener.java | UTF-8 | 1,902 | 2.390625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.sijbesma.bp.bpbrewingstandlib.event.listeners;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.sijbesma.bp.bpbrewingstandlib.managers.BrewingManager;
import static org.sijbesma.bp.utils.DebugLogger.debug;
/**
*
* @author JJS
*/
public class WorldEventListener implements Listener {
private static BrewingManager brewingManager;
public WorldEventListener(BrewingManager brewingManager) {
this.brewingManager = brewingManager;
}
@EventHandler
public void onChunkLoadEvent(ChunkLoadEvent event) {
Chunk chunk = event.getChunk();
World world = chunk.getWorld();
int X = chunk.getX();
int Z = chunk.getZ();
Location location = new Location(world, X, 0, Z);
if (brewingManager.chunkHasTasks(location)) {
debug("onChunkLoadEvent", true);
brewingManager.resumeTasksInChunk(location);
debug("End of Event", true);
}
}
@EventHandler
public void onChunkUnloadEvent(ChunkUnloadEvent event) {
Chunk chunk = event.getChunk();
World world = chunk.getWorld();
int X = chunk.getX();
int Z = chunk.getZ();
Location location = new Location(world, X, 0, Z);
if (brewingManager.chunkHasTasks(location)) {
debug("onChunkUnloadEvent", true);
brewingManager.pauseTasksInChunk(location);
debug("End of Event", true);
}
}
}
| true |
22c20323df99dc5441af4937bfd3e73633bf08c8 | Java | lharriott/AndroidCrochetProject-2014 | /CrochetGuideForBeginers/src/com/example/crochetguideforbeginers/Resources.java | UTF-8 | 6,410 | 2.515625 | 3 | [] | no_license | //File Name: Resources.Java
//Author: Lisa Harriott
//Date Modified: 12/13/2014
//Purpose: Connects the expandable list and it's adaptor and handles the
// click events for the items in the expandable list.
package com.example.crochetguideforbeginers;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;
public class Resources extends Activity{
@Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.resources_content);
ExpandableListView expListResc=(ExpandableListView)findViewById(R.id.expandableListView1);
//connects the exp list and it's adaptor class
expListResc.setAdapter((ExpandableListAdapter)new expListAdapterResc(this));
//sets up a listener for child clicks
expListResc.setOnChildClickListener(new OnChildClickListener(){
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//switch statement checks for the parent position
switch(groupPosition){
case 0: //abbrev
if(childPosition == 1){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.craftyarncouncil.com/crochet.html")));
} else {
break;}
break;
case 1: //basic skills
switch(childPosition){
case 0: //hold
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/ss/how-to-hold-a-crochet-hook.htm")));
break;
case 1: //casting
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/ss/Crochet_Slip_Knot.htm")));
break;
case 2: //yarn
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.dummies.com/how-to/content/how-to-yarn-over-in-crochet.html")));
break;
case 3: //count
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.simplycrochetmag.co.uk/2014/07/10/how-to-count-your-stitches/")));
break;
case 4: //turn
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.dummies.com/how-to/content/how-to-turn-crochet-work.html")));
break;
}
break;
case 2: //basic stitch
switch(childPosition){
case 1: //chain
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/ss/Chain_Stitch.htm")));
break;
case 2: //single
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/ss/Single_Crochet.htm")));
break;
case 3: //double
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/ss/DoubleCrochet.htm")));
break;
case 4: //half double
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/tp/half-double-crochet-stitch.htm")));
break;
case 5: //triple
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/tp/how-to-treble-crochet-free-stitch-tutorial-and-instructions.htm")));
break;
case 6: //slip stitch
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/tp/how-to-slip-stitch-in-crochet.htm")));
break;
case 7: //starter video 1
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=eqca00LdmAc")));
break;
case 8: //starter video 2
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=DlTdOMTDkug")));
break;
}
break;
case 3: //adv. tech.
switch(childPosition){
case 0: //magic ring
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.craftsy.com/blog/2013/09/demystifying-the-magic-ring/")));
break;
case 1: //new skien
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.dummies.com/how-to/content/how-to-join-yarn-in-crochet.html")));
break;
case 2: //new color
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/skillstechniques/tp/Changing_Colors_SC.htm")));
break;
case 3: //even border
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=5OVxqbI62-E")));
break;
case 4: //even border
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/?gws_rd=ssl")));
break;
}
break;
case 4: //hooks and yarn
switch(childPosition){
case 0:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/crochethooks/tp/Crochet-Hooks.htm")));
break;
case 1:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.craftyarncouncil.com/weight.html")));
break;
case 2:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/od/learntocrochet/a/Beginner-Crochet-Yarn.htm")));
break;
case 3:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.craftyarncouncil.com/top10qa.html")));
break;
}
break;
case 5: //pattern resc.
switch(childPosition){
case 1: //about
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://crochet.about.com/")));
break;
case 2: //redheart
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.redheart.com/free-patterns")));
case 3: //lionbrand
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://freecrochetpatterns.lionbrand.com/")));
}
break;
}//end check parent position
return false;
}//end onChildClick
});
}
}
| true |
d8d43568b9641ff1601f3f05a4a3d6d1d5ba7d25 | Java | Bkm016/TrChat | /src/main/java/me/arasple/mc/trchat/TrChatFiles.java | UTF-8 | 1,478 | 1.953125 | 2 | [] | permissive | package me.arasple.mc.trchat;
import io.izzel.taboolib.module.config.TConfig;
import io.izzel.taboolib.module.inject.TFunction;
import io.izzel.taboolib.module.inject.TInject;
import me.arasple.mc.trchat.chat.ChatFormats;
import me.arasple.mc.trchat.filter.ChatFilter;
import me.arasple.mc.trchat.func.ChatFunctions;
import org.bukkit.Bukkit;
/**
* @author Arasple
* @date 2019/11/30 9:59
*/
public class TrChatFiles {
@TInject("settings.yml")
private static TConfig settings;
@TInject("formats.yml")
private static TConfig formats;
@TInject("filter.yml")
private static TConfig filter;
@TInject("function.yml")
private static TConfig function;
@TInject("channels.yml")
private static TConfig channels;
@TFunction.Init
public static void init() {
filter.listener(() -> ChatFilter.loadFilter(false, Bukkit.getConsoleSender())).runListener();
formats.listener(() -> ChatFormats.loadFormats(Bukkit.getConsoleSender())).runListener();
function.listener(() -> ChatFunctions.loadFunctions(Bukkit.getConsoleSender())).runListener();
}
public static TConfig getSettings() {
return settings;
}
public static TConfig getFormats() {
return formats;
}
public static TConfig getFilter() {
return filter;
}
public static TConfig getFunction() {
return function;
}
public static TConfig getChannels() {
return channels;
}
}
| true |
26a6aa86cc183975a0366d53bf98971b5938b912 | Java | byr068/test | /src/com/company/delete.java | UTF-8 | 4,720 | 4 | 4 | [] | no_license | package com.company;
import java.util.*;
public class delete {
/**
* 一个长方体纸箱由六个面构成。
*
* 现在给出六块纸板的长和宽,请你判断能否用这六块纸板构成一个长方体纸箱。
* @param args
*/
public static void main(String[] args) {
test2 t = new test2();
// System.out.println(t.toString(123456789));
int[] arr = {1,4,5,6,7,3};
t.quickSort(arr,0,arr.length-1);
for(int s :arr){ System.out.println(s); }
}
}
class test2{
public String toString(int num){
String str = "";
String sb = num + "";
String[] arr = new String[sb.length()];
for(int i=0;i<arr.length;i++){
arr[i] = String.valueOf(sb.charAt(i));
}
for(int i=arr.length-1,j=0;i>=0;i-=4,j++){
if(i-1>=0){
arr[i-1] = arr[i-1]+"十";
}
if(i-2>=0){
arr[i-2] = arr[i-2]+"百";
}
if(i-3>=0){
arr[i-3] = arr[i-3] +"千";
}
switch (j){
case 1:
arr[i] = arr[i]+"万";
break;
case 2:
arr[i] = arr[i]+"亿";
}
}
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<arr.length;i++){
stringBuffer.append(arr[i]);
}
str = stringBuffer.toString();
str = str.replaceAll("1","一");
str = str.replaceAll("2","二");
str = str.replaceAll("3","三");
str = str.replaceAll("4","四");
str = str.replaceAll("5","五");
str = str.replaceAll("6","六");
str = str.replaceAll("7","七");
str = str.replaceAll("8","八");
str = str.replaceAll("9","九");
return str;
}
/**
* 快排
*/
public void quickSort(int[] arr,int l,int r){
int i = l;
int j = r;
int privot = arr[(i+j)/2];
while(i<j){
while(arr[i]<privot){
i++;
}
while(arr[j]>privot){
j--;
}
if(i>=j)break;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
if(arr[i]==privot){
j-=1;
}
if(arr[j]==privot){
i+=1;
}
}
if(i==j){
i++;
j--;
}
if(l<j){
quickSort(arr,l,j);
}
if(i<r){
quickSort(arr,i,r);
}
}
}
class test1{
/**
* 根据输入的数字,转化为相应的字符串;如 123456 ---> 一十二万三千四百五十六圆
* @param number
* @return
*/
public String getString(int number){
//将 number 转化为字符串数组
String str=number+"";
String[] array=new String[str.length()];
for(int i=0;i<str.length();i++){
array[i]=str.substring(i,i+1);
System.out.println(array[i]);
}
//处理字符串,加上相应的 万,亿, 圆,千,百 字
for(int i=array.length-1,j=1;i>=0;i-=4,j++){
if(i-1>=0){
array[i-1]=array[i-1]+"十";
}
if(i-2>=0){
array[i-2]=array[i-2]+"百";
}
if(i-3>=0){
array[i-3]=array[i-3]+"千";
}
switch(j){
// case 1:
// array[i]=array[i]+"圆";
// break;
case 2:
array[i]=array[i]+"万";
break;
case 3:
array[i]=array[i]+"亿";
}
}
//将 字符串数组 转化为字符串
StringBuffer sb=new StringBuffer();
for(int i = 0; i < array.length; i++){
sb.append(array[i]);
}
str=sb.toString();
//将数字 转化为 汉字
str=str.replaceAll("1", "一");
str=str.replaceAll("2", "二");
str=str.replaceAll("3", "三");
str=str.replaceAll("4", "四");
str=str.replaceAll("5", "五");
str=str.replaceAll("6", "六");
str=str.replaceAll("7", "七");
str=str.replaceAll("8", "八");
str=str.replaceAll("9", "九");
return str;
}
}
class Solution {
public Solution(){
System.out.println("父亲构造方法");
}
public void fu(){
System.out.println("父亲普通方法");
}
}
class Test extends Solution{
public Test(){
System.out.println("子构造方法");
}
} | true |
169d51d14d2ab9985308f52f9e77428726aa9879 | Java | geralex/SWG-NGE | /dsrc/sku.0/sys.server/compiled/game/script/theme_park/nym/kusak_nyms_themepark.java | UTF-8 | 13,559 | 2.09375 | 2 | [] | no_license | package script.theme_park.nym;
import script.*;
import script.base_class.*;
import script.combat_engine.*;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import script.base_script;
import script.library.ai_lib;
import script.library.chat;
import script.library.group;
import script.library.groundquests;
import script.library.hue;
import script.library.trial;
import script.library.utils;
public class kusak_nyms_themepark extends script.base_script
{
public kusak_nyms_themepark()
{
}
public static final int RADIUS = 100;
public static final int MIN_DIST = 25;
public static final String DISTANCE_CHECK = "distance_check";
public int OnAttach(obj_id self) throws InterruptedException
{
messageTo(self, "moveCreatureToWaypoint", null, 1, false);
return SCRIPT_CONTINUE;
}
public int OnAboutToBeIncapacitated(obj_id self, obj_id killer) throws InterruptedException
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnAboutToBeIncapacitated() Boss Mob " + self + " incapacitated by: " + killer);
if (!hasObjVar(self, "theme_park_boss"))
{
return SCRIPT_CONTINUE;
}
if (!hasObjVar(self, "theme_park_boss_slot"))
{
return SCRIPT_CONTINUE;
}
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnAboutToBeIncapacitated() Boss Mob has boss slot and quest name data");
String bossQuest = getStringObjVar(self, "theme_park_boss");
if (bossQuest == null || bossQuest.length() <= 0)
{
return SCRIPT_CONTINUE;
}
String bossQuestSlot = getStringObjVar(self, "theme_park_boss_slot");
if (bossQuestSlot == null || bossQuestSlot.length() <= 0)
{
return SCRIPT_CONTINUE;
}
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnAboutToBeIncapacitated() Boss Mob slot and quest name data validated");
obj_id[] attackerList = utils.getObjIdBatchScriptVar(self, "creditForKills.attackerList.attackers");
if (attackerList != null && attackerList.length > 0)
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnAboutToBeIncapacitated() Boss Mob attackerList = " + attackerList.length);
for (int i = 0; i < attackerList.length; i++)
{
if (!isIdValid(attackerList[i]))
{
continue;
}
if (group.isGroupObject(attackerList[i]))
{
obj_id[] members = getGroupMemberIds(attackerList[i]);
for (int j = 0, k = members.length; j < k; j++)
{
if (isIdValid(members[j]))
{
if (!groundquests.isQuestActive(attackerList[i], bossQuest))
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnAboutToBeIncapacitated() Boss Mob attacker: " + attackerList[i] + " did not have boss quest: " + bossQuest);
continue;
}
if (hasCompletedCollectionSlot(attackerList[i], bossQuestSlot))
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnAboutToBeIncapacitated() Boss Mob attacker: " + attackerList[i] + " has already attained: " + bossQuestSlot);
continue;
}
if (!hasCompletedCollectionSlotPrereq(attackerList[i], bossQuestSlot))
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnAboutToBeIncapacitated() Boss Mob attacker: " + attackerList[i] + " hasn't fulfilled the prerequisite for boss slot/: " + bossQuestSlot);
continue;
}
modifyCollectionSlotValue(attackerList[i], bossQuestSlot, 1);
}
}
}
else
{
if (!groundquests.isQuestActive(attackerList[i], bossQuest))
{
continue;
}
if (hasCompletedCollectionSlot(attackerList[i], bossQuestSlot))
{
continue;
}
if (!hasCompletedCollectionSlotPrereq(attackerList[i], bossQuestSlot))
{
continue;
}
modifyCollectionSlotValue(attackerList[i], bossQuestSlot, 1);
}
}
}
return SCRIPT_CONTINUE;
}
public int OnEnteredCombat(obj_id self) throws InterruptedException
{
if (!isIdValid(self))
{
return SCRIPT_CONTINUE;
}
if (hasObjVar(self, "shuttle"))
{
return SCRIPT_CONTINUE;
}
int maxDist = getIntObjVar(self, DISTANCE_CHECK);
if (maxDist <= 0)
{
maxDist = MIN_DIST;
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnEnteredCombat() maximum distance from creation location for boss mob (" + self + ") was invalid or NULL.");
}
obj_id playerEnemy = utils.getObjIdScriptVar(self, "waveEventPlayer");
if (!isIdValid(playerEnemy) || !exists(playerEnemy))
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnEnteredCombat() Mob found player but player was not part of owners group.");
return SCRIPT_CONTINUE;
}
obj_id[] players = getPlayerCreaturesInRange(self, maxDist);
if (players != null && players.length > 0)
{
for (int i = 0; i < players.length; i++)
{
if (!isIdValid(players[i]) && !exists(players[i]) || isIncapacitated(players[i]) || !isDead(players[i]))
{
continue;
}
addHate(self, players[i], 1000.0f);
startCombat(self, players[i]);
}
}
messageTo(self, "handleBossDistanceCheck", null, 3, false);
return SCRIPT_CONTINUE;
}
public int OnIncapacitateTarget(obj_id self, obj_id victim) throws InterruptedException
{
if (!isIdValid(self))
{
return SCRIPT_CONTINUE;
}
if (ai_lib.isDead(self))
{
return SCRIPT_CONTINUE;
}
if (hasObjVar(self, "shuttle"))
{
return SCRIPT_CONTINUE;
}
obj_id parent = getObjIdObjVar(self, trial.PARENT);
if (!isIdValid(parent) || !exists(parent))
{
destroyObject(self);
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnIncapacitateTarget() FAILED to find parent object.");
return SCRIPT_CONTINUE;
}
if (getRandomCombatTarget(self, parent))
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.OnIncapacitateTarget() Boss Mob has found someone in the player's group.");
return SCRIPT_CONTINUE;
}
dictionary webster = trial.getSessionDict(parent);
messageTo(parent, "defaultEventReset", webster, 2, false);
return SCRIPT_CONTINUE;
}
public int OnExitedCombat(obj_id self) throws InterruptedException
{
if (!isIdValid(self))
{
return SCRIPT_CONTINUE;
}
if (ai_lib.isDead(self))
{
return SCRIPT_CONTINUE;
}
if (hasObjVar(self, "shuttle"))
{
return SCRIPT_CONTINUE;
}
obj_id parent = getObjIdObjVar(self, trial.PARENT);
if (!isIdValid(parent) || !exists(parent))
{
destroyObject(self);
CustomerServiceLog("quest", "dynamic_mob_opponent.OnExitedCombat() FAILED to find parent object.");
return SCRIPT_CONTINUE;
}
if (getRandomCombatTarget(self, parent))
{
return SCRIPT_CONTINUE;
}
dictionary webster = trial.getSessionDict(parent);
messageTo(parent, "defaultEventReset", webster, 2, false);
return SCRIPT_CONTINUE;
}
public int handleBossDistanceCheck(obj_id self, dictionary params) throws InterruptedException
{
if (!isValidId(self) || !exists(self))
{
return SCRIPT_CONTINUE;
}
location currentLoc = getLocation(self);
if (currentLoc == null)
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.handleBossDistanceCheck() current boss mob (" + self + ") location NULL.");
return SCRIPT_CONTINUE;
}
location creationLoc = aiGetHomeLocation(self);
if (creationLoc == null)
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.handleBossDistanceCheck() creation location for boss mob (" + self + ") was NULL.");
return SCRIPT_CONTINUE;
}
float distanceCheck = utils.getDistance2D(currentLoc, creationLoc);
int maxDist = getIntObjVar(self, DISTANCE_CHECK);
if (maxDist <= 0)
{
maxDist = MIN_DIST;
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.handleBossDistanceCheck() maximum distance from creation location for boss mob (" + self + ") was invalid or NULL.");
}
obj_id parent = getObjIdObjVar(self, trial.PARENT);
if (!isIdValid(parent) || !exists(parent))
{
destroyObject(self);
CustomerServiceLog("quest", "dynamic_mob_opponent.handleBossDistanceCheck() FAILED to find parent object.");
return SCRIPT_CONTINUE;
}
if (distanceCheck > maxDist)
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.handleBossDistanceCheck() boss mob (" + self + ") has moved too far from creation location. Moving back to creation location.");
dictionary webster = trial.getSessionDict(parent);
messageTo(parent, "defaultEventReset", webster, 2, false);
}
else
{
messageTo(self, "handleBossDistanceCheck", null, 3, false);
}
return SCRIPT_CONTINUE;
}
public boolean getRandomCombatTarget(obj_id self, obj_id parent) throws InterruptedException
{
if (!isIdValid(self) || !exists(self))
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.getRandomCombatTarget() FAILED to find self.");
return false;
}
if (!isIdValid(parent) || !exists(parent))
{
destroyObject(self);
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.getRandomCombatTarget() FAILED to find parent object.");
return false;
}
int maxDist = getIntObjVar(self, DISTANCE_CHECK);
if (maxDist <= 0)
{
maxDist = MIN_DIST;
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.getRandomCombatTarget() maximum distance from creation location for boss mob (" + self + ") was invalid or NULL.");
}
obj_id[] targets = trial.getValidTargetsInRadiusIgnoreLOS(self, maxDist);
if (targets == null || targets.length == 0)
{
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.getRandomCombatTarget() no targets for boss (" + self + ") is: " + maxDist);
dictionary webster = trial.getSessionDict(parent);
messageTo(parent, "defaultEventReset", webster, 2, false);
return false;
}
for (int i = 0; i < targets.length; i++)
{
if (!isIdValid(targets[i]))
{
continue;
}
startCombat(self, targets[i]);
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.getRandomCombatTarget(): Player " + targets[i] + " was found as a valid target. Boss Mob: " + self + " attacking player.");
return true;
}
CustomerServiceLog("nyms_themepark", "boss_nyms_themepark.getRandomCombatTarget(): Boss Mob: " + self + " failed to find a player to attack.");
dictionary webster = trial.getSessionDict(parent);
messageTo(parent, "defaultEventReset", webster, 2, false);
return false;
}
public int moveCreatureToWaypoint(obj_id self, dictionary params) throws InterruptedException
{
if (!isValidId(self) || !exists(self))
{
return SCRIPT_CONTINUE;
}
if (!hasObjVar(self, "arena") && !hasObjVar(self, "shuttle"))
{
return SCRIPT_CONTINUE;
}
if (hasObjVar(self, "arena"))
{
location startPos = new location(472.5f, 34.4f, 4815.6f, "lok", null);
setLocation(self, startPos);
aiSetHomeLocation(self, startPos);
setYaw(self, 160.0f);
}
if (hasObjVar(self, "shuttle"))
{
location locCenter = new location(473.0f, 12.0f, 4868.0f, "lok", null);
location locDestination = utils.getRandomLocationInRing(locCenter, 4.0f, 6.0f);
setLocation(self, locDestination);
aiSetHomeLocation(self, locDestination);
}
return SCRIPT_CONTINUE;
}
}
| true |
d9c7546e00f82fd498625ddec8cdfa063140905b | Java | JAlexisH254/res22-08 | /Pokedex/app/src/main/java/com/example/pokedex/Adaptadores/AdaptadorPokedex.java | UTF-8 | 1,204 | 2.578125 | 3 | [] | no_license | package com.example.pokedex.Adaptadores;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.pokedex.Pokemon;
import java.util.List;
public class AdaptadorPokedex extends RecyclerView.Adapter<PokedexHolder> {
Context context;
int layout;
List<Pokemon> datos;
LayoutInflater layoutInflater;
public AdaptadorPokedex(Context context, int layout, List<Pokemon> datos) {
this.context = context;
this.layout = layout;
this.datos = datos;
layoutInflater = LayoutInflater.from(context);
}
@NonNull
@Override
public PokedexHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = layoutInflater.inflate(layout,parent, false);
return new PokedexHolder(v,context);
}
@Override
public void onBindViewHolder(@NonNull PokedexHolder holder, int position) {
holder.nombrePokemon.setText(datos.get(position).getName());
}
@Override
public int getItemCount() {
return datos.size();
}
}
| true |
c8da920a6990a245ace774dceb2a5866aaf516ca | Java | poav/POAVnew | /poa_core/PeopleOnboardingCore/src/main/java/com/sapient/statestreetscreeningapplication/utils/converter/RoleNewConverter.java | UTF-8 | 2,176 | 2.75 | 3 | [] | no_license | package com.sapient.statestreetscreeningapplication.utils.converter;
import java.util.HashSet;
import java.util.Set;
import com.sapient.statestreetscreeningapplication.model.entity.Role;
import com.sapient.statestreetscreeningapplication.ui.bean.RoleBean;
import com.sapient.statestreetscreeningapplication.utils.CustomLoggerUtils;
// TODO: Auto-generated Javadoc
/**
* The Class RoleNewConverter.
*/
public class RoleNewConverter {
/**
* Role entity to bean.
*
* @param role the role
* @return the sets the
*/
public static Set<RoleBean> roleEntityToBean(Set<Role> role) {
CustomLoggerUtils.INSTANCE.log.info("Inside roleEntityToBean method in RoleNewConverter");
Set<RoleBean> roleBeanSet=new HashSet<RoleBean>();
for (Role roleEntity : role) {
roleBeanSet.add(convertEntityToBean(roleEntity));
}
CustomLoggerUtils.INSTANCE.log.info("Returing the following set from roleEntityToBean method in RoleNewConverter"+roleBeanSet);
return roleBeanSet;
}
/**
* Convert entity to bean.
*
* @param role the role
* @return the role bean
*/
public static RoleBean convertEntityToBean(Role role) {
RoleBean roleBean=new RoleBean();
roleBean.setIsActive(role.isActive());
roleBean.setRoleId(role.getRoleId());
roleBean.setRoleName(role.getRoleName());
return roleBean;
}
/**
* Role bean to entity set.
*
* @param role the role
* @return the sets the
*/
public static Set<Role> roleBeanToEntitySet(Set<RoleBean> role) {
CustomLoggerUtils.INSTANCE.log.info("Inside roleBeanToEntity method in RoleNewConverter");
Set<Role> roleSet=new HashSet<Role>();
for (RoleBean roleBean : role) {
roleSet.add(convertBeanToEntity(roleBean));
}
CustomLoggerUtils.INSTANCE.log.info("Returing the following set from roleBeanToEntity method in RoleNewConverter"+roleSet);
return roleSet;
}
/**
* Convert bean to entity.
*
* @param roleBean the role bean
* @return the role
*/
public static Role convertBeanToEntity(RoleBean roleBean) {
Role role=new Role();
role.setIsActive(roleBean.getIsActive());
role.setRoleId(roleBean.getRoleId());
role.setRoleName(roleBean.getRoleName());
return role;
}
}
| true |
aaa3ded71713326e84ee507951ee2955d4577433 | Java | mczal/Profile-Matching | /src/main/java/com/spk/model/Criteria.java | UTF-8 | 1,317 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.spk.model;
import com.spk.base.McnBaseEntity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Gl552 on 4/25/2017.
*/
@Entity
public class Criteria extends McnBaseEntity {
private static final long serialVersionUID = -8985277390452938447L;
@Column
private Double CFWeight;
@Column
private Double SFWeight;
@Column
private String name;
@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
mappedBy = "criteria")
private List<Subcriteria> subcriterias = new ArrayList<>();
@Column
private Double weight;
public Double getCFWeight() {
return CFWeight;
}
public void setCFWeight(Double CFWeight) {
this.CFWeight = CFWeight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSFWeight() {
return SFWeight;
}
public void setSFWeight(Double SFWeight) {
this.SFWeight = SFWeight;
}
public List<Subcriteria> getSubcriterias() {
return subcriterias;
}
public void setSubcriterias(List<Subcriteria> subcriterias) {
this.subcriterias = subcriterias;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
}
| true |
e43241c865c81699b1aac42062ab2d6957545b78 | Java | abernardi597/pop-sim | /src/net/popsim/src/util/config/JsonConfigLoader.java | UTF-8 | 1,746 | 2.703125 | 3 | [
"MIT"
] | permissive | package net.popsim.src.util.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
// Todo: Document
public class JsonConfigLoader {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
private final Class<? extends Target> mType;
public JsonConfigLoader(Class<? extends Target> type) {
mType = type;
}
public Target load(File source) throws ConfigException {
Target target;
try (FileReader reader = new FileReader(source)) {
target = GSON.fromJson(reader, mType);
target.postLoad();
// Reader is closed automatically
} catch (FileNotFoundException e) {
throw new ConfigException("Unable to locate file: " + source.getAbsolutePath(), e);
} catch (Exception e) {
throw new ConfigException("Error while loading file", e);
}
return target;
}
public void save(File destination, Target target) throws ConfigException {
try (FileWriter writer = new FileWriter(destination)) {
GSON.toJson(target, writer);
// Writer is closed automatically
} catch (Exception e) {
throw new ConfigException("Error while saving file", e);
}
}
public interface Target {
/**
* Called on the Target after it is parsed from JSON.
*
* @throws Exception if some error arises.
*/
void postLoad() throws Exception;
}
public static class ConfigException extends Exception {
public ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
}
| true |
7f2fe5911f139ef3d0ddebd0a8aaad98ff8bfe33 | Java | noman9k/Pharmacy_javaFx | /src/controller/UpdatePurchaseController.java | UTF-8 | 6,230 | 2.34375 | 2 | [] | no_license | package controller;
import Classes.dbDataBase;
import Classes.purchase;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyEvent;
import org.controlsfx.control.textfield.TextFields;
public class UpdatePurchaseController {
@FXML
private JFXTextField productName;
@FXML
private JFXTextField productQuantity;
@FXML
private JFXButton updatePurchase;
@FXML
private TableView productTableView;
@FXML private TableColumn<purchase,String> productIDColumn;
@FXML private TableColumn<purchase,String> productNameColumn;
@FXML private TableColumn<purchase,String> productCostPriceColumn;
@FXML private TableColumn<purchase,String> productSellingPriceColumn;
@FXML private TableColumn<purchase,String> productExpiryDateColumn;
@FXML private TableColumn<purchase,String> productProductionDateColumn;
@FXML private TableColumn<purchase,String> productPlaceColumn;
@FXML private TableColumn<purchase,String> productCompanyColumn;
@FXML private TableColumn<purchase,String> productPackColumn;
@FXML private TableColumn<purchase,String> productQin_One_packColumn;
@FXML private TableColumn<purchase,String> productStockColumn;
ObservableList<purchase> dataList;
public void initialize(){
System.out.println("table render update purchase ");
TextFields.bindAutoCompletion(productName,dbDataBase.getPurchaseNameColumn());
renderTable();
}
public void updatePurchase(ActionEvent event) {
if (productName.getText().trim().isEmpty() ||productQuantity.getText().trim().isEmpty()){
Alert alert = new Alert(Alert.AlertType.ERROR, " Text Field Must Non Empty "
, ButtonType.CLOSE);
alert.setHeaderText("Error");
alert.setTitle("Error");
alert.show();
return;
}
String id=dbDataBase.findSearchID(productName.getText());
dbDataBase.updatePurchase(id,productQuantity.getText());
productTableView.getItems().clear();
renderTable();
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Data Uprated"
, ButtonType.CLOSE);
alert.setHeaderText("Updated");
alert.setTitle("Updated");
alert.show();
}
private void renderTable(){
System.out.println("Purchase table rendering ");
this.productIDColumn.setCellValueFactory(new PropertyValueFactory<>("productID"));
this.productNameColumn.setCellValueFactory(new PropertyValueFactory<>("ProductName"));
this.productCostPriceColumn.setCellValueFactory(new PropertyValueFactory<>("productCostPrice"));
this.productSellingPriceColumn.setCellValueFactory(new PropertyValueFactory<>("productSellingPrice"));
this.productExpiryDateColumn.setCellValueFactory(new PropertyValueFactory<>("productExpiryDate"));
this.productProductionDateColumn.setCellValueFactory(new PropertyValueFactory<>("productProductionDate"));
this.productPlaceColumn.setCellValueFactory(new PropertyValueFactory<>("productPlace"));
this.productCompanyColumn.setCellValueFactory(new PropertyValueFactory<>("productCompanyID"));
this.productPackColumn.setCellValueFactory(new PropertyValueFactory<>("productPack"));
this.productQin_One_packColumn.setCellValueFactory(new PropertyValueFactory<>("productQuantity"));
this.productStockColumn.setCellValueFactory(new PropertyValueFactory<>("productInStock"));
dataList=dbDataBase.getDataPurchase();
productTableView.getItems().addAll(dataList);
}
public void searchPurchase(KeyEvent event) {
// dataList=dbDataBase.getDataPurchase();
// this.productIDColumn.setCellValueFactory(new PropertyValueFactory<>("productID"));
// this.productNameColumn.setCellValueFactory(new PropertyValueFactory<>("ProductName"));
// this.productCostPriceColumn.setCellValueFactory(new PropertyValueFactory<>("productCostPrice"));
// this.productSellingPriceColumn.setCellValueFactory(new PropertyValueFactory<>("productSellingPrice"));
// this.productExpiryDateColumn.setCellValueFactory(new PropertyValueFactory<>("productExpiryDate"));
// this.productProductionDateColumn.setCellValueFactory(new PropertyValueFactory<>("productProductionDate"));
// this.productPlaceColumn.setCellValueFactory(new PropertyValueFactory<>("productPlace"));
// this.productCompanyColumn.setCellValueFactory(new PropertyValueFactory<>("productCompany"));
// this.productPackColumn.setCellValueFactory(new PropertyValueFactory<>("productPack"));
// this.productQin_One_packColumn.setCellValueFactory(new PropertyValueFactory<>("productQuantity"));
// this.productStockColumn.setCellValueFactory(new PropertyValueFactory<>("productInStock"));
// dataList = dbDataBase.getDataPurchase();
//// productTableView.setItems(dataList);
// FilteredList<purchase> filteredList = new FilteredList<>(dataList, search -> true);
//
// productName.textProperty().addListener((observable, oldValue, newValue) -> {
// filteredList.setPredicate(product -> {
// if (newValue == null || newValue.isEmpty()) {
// return true;
// }
// String lowerCaseFilter = newValue.toLowerCase();
// if (product.getProductName().toLowerCase().indexOf(lowerCaseFilter) != -1) {
// return true;}
// else
// return false;
//
// });
// });
// SortedList<purchase> employeeSortedList = new SortedList<>(filteredList);
// employeeSortedList.comparatorProperty().bind(productTableView.comparatorProperty());
// productTableView.setItems(employeeSortedList);
////
//
//
//
}
}
| true |
2c869f02c7831581a1651e15e52cf671ee4a5d1f | Java | zamboOlino/iTrySQL | /src/main/java/de/kuehweg/sqltool/dialog/component/achievement/SingleAchievement.java | UTF-8 | 4,879 | 2.4375 | 2 | [
"BSD-2-Clause"
] | permissive | /*
* Copyright (c) 2017, Michael Kühweg
* 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.
*
* 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 HOLDER 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.
*/
package de.kuehweg.sqltool.dialog.component.achievement;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
/**
* Komponente zur Darstellung eines einzelnen Achievements.
*
* @author Michael Kühweg
*/
public class SingleAchievement {
private static final int LABEL_LOGO_FIXED_WIDTH = 64;
private static final double HBOX_SPACING = 0.0;
private static final double VBOX_LABEL_SPACING = 2.0;
private static final double DESCRIPTION_LABEL_MAX_WIDTH = 333.0;
private boolean achieved;
private String name;
private String description;
private String hint;
private String logoCharacter;
private int points;
private double percentageAchieved;
/**
* Baut einen Knoten für den Scene-Graph auf, der die visuelle Darstellung
* des einzelnen Achievements repräsentiert.
*
* @return Knoten für den Scene-Graph.
*/
public Node buildVisual() {
final VBox nameAndDescription = new VBox(VBOX_LABEL_SPACING, nodeForName(), nodeForDescription());
final HBox box = new HBox(HBOX_SPACING, nodeForLogo(), nameAndDescription);
// Punkte bringen im Moment keinen Mehrwert, daher nicht angezeigt
nameAndDescription.setAlignment(Pos.BOTTOM_LEFT);
box.setAlignment(Pos.BOTTOM_LEFT);
return box;
}
public boolean isAchieved() {
return achieved;
}
public void setAchieved(final boolean achieved) {
this.achieved = achieved;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getHint() {
return hint;
}
public void setHint(final String hint) {
this.hint = hint;
}
public String getLogoCharacter() {
return logoCharacter;
}
public void setLogoCharacter(final String logoCharacter) {
this.logoCharacter = logoCharacter;
}
public int getPoints() {
return points;
}
public void setPoints(final int points) {
this.points = points;
}
public double getPercentageAchieved() {
return percentageAchieved;
}
public void setPercentageAchieved(final double percentageAchieved) {
this.percentageAchieved = percentageAchieved;
}
private Node nodeForName() {
final Label label = new Label(name);
label.getStyleClass().add("itrysql-achievement-label-name");
return label;
}
private Node nodeForDescription() {
final Label label = new Label(achieved ? description : hint);
label.setWrapText(true);
label.setMaxWidth(DESCRIPTION_LABEL_MAX_WIDTH);
label.getStyleClass().add("itrysql-achievement-label-description");
return label;
}
private Node nodeForLogo() {
return achieved ? nodeForAchieved() : nodeForPercentage();
}
private Node nodeForAchieved() {
final Label label = new Label(logoCharacter);
label.getStyleClass().add("itrysql-achievement-logo");
label.setPrefWidth(LABEL_LOGO_FIXED_WIDTH);
label.setMinWidth(LABEL_LOGO_FIXED_WIDTH);
label.setMaxWidth(LABEL_LOGO_FIXED_WIDTH);
return label;
}
private Node nodeForPercentage() {
final ProgressIndicator progress = new ProgressIndicator(percentageAchieved);
progress.getStyleClass().add("itrysql-achievement-progress");
progress.setPrefWidth(LABEL_LOGO_FIXED_WIDTH);
progress.setMinWidth(LABEL_LOGO_FIXED_WIDTH);
progress.setMaxWidth(LABEL_LOGO_FIXED_WIDTH);
return progress;
}
}
| true |
feee3a9178f8796bdf7416545788a29b38c122c4 | Java | wprogLK/Ursuppe | /Ursuppe/src/gameObjectsASCII/PlayerASCII.java | UTF-8 | 612 | 2.78125 | 3 | [] | no_license | package gameObjectsASCII;
import java.util.Date;
import enums.EColor;
import templates.PlayerTemplate;
/**
* ascii player for the ascii game
* @author Lukas Keller
* @version 1.0.0
*/
public class PlayerASCII extends PlayerTemplate
{
/**
* creates a default player
*
* <br/> for head and tail player
* @see PlayerTemplate
*/
public PlayerASCII()
{
super();
}
/**
* creates a concrete player with name, age and color
* @param name
* @param age
* @param color
*/
public PlayerASCII(String name, Date birthday, int age, EColor color)
{
super(name,birthday, age,color);
}
}
| true |
ba87f33c38175469a415e2c65e4f4020a22f6a96 | Java | cybernetics/javaslang | /src/main/java/javaslang/lambda/Functions.java | UTF-8 | 8,132 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | /** / \____ _ ______ _____ / \____ ____ _____
* / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang
* _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014 Daniel Dietrich
* /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.lambda;
import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Supplier;
import javaslang.Tuples;
public interface Functions {
@FunctionalInterface
static interface Function0<R> extends Supplier<R>, Serializable {
default Function0<R> curried() {
return this;
}
default Function0<R> tupled() {
return this;
}
}
/**
* A function with one argument which implements Serializable in order to obtain runtime type information about the
* lambda via {@link javaslang.lambda.Lambdas#getLambdaSignature(Serializable)}.
*
* @param <T1> The parameter type of the function.
* @param <R> The return type of the function.
*/
@FunctionalInterface
static interface Function1<T1, R> extends Function<T1, R>, Serializable {
@Override
R apply(T1 t1);
default Function1<T1, R> curried() {
return t1 -> apply(t1);
}
default Function1<Tuples.Tuple1<T1>, R> tupled() {
return t -> apply(t._1);
}
}
@FunctionalInterface
static interface Function2<T1, T2, R> extends Serializable {
R apply(T1 t1, T2 t2);
default Function1<T1, Function1<T2, R>> curried() {
return t1 -> t2 -> apply(t1, t2);
}
default Function1<Tuples.Tuple2<T1, T2>, R> tupled() {
return t -> apply(t._1, t._2);
}
}
@FunctionalInterface
static interface Function3<T1, T2, T3, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3);
default Function1<T1, Function1<T2, Function1<T3, R>>> curried() {
return t1 -> t2 -> t3 -> apply(t1, t2, t3);
}
default Function1<Tuples.Tuple3<T1, T2, T3>, R> tupled() {
return t -> apply(t._1, t._2, t._3);
}
}
@FunctionalInterface
static interface Function4<T1, T2, T3, T4, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, R>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> apply(t1, t2, t3, t4);
}
default Function1<Tuples.Tuple4<T1, T2, T3, T4>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4);
}
}
@FunctionalInterface
static interface Function5<T1, T2, T3, T4, T5, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, R>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> apply(t1, t2, t3, t4, t5);
}
default Function1<Tuples.Tuple5<T1, T2, T3, T4, T5>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5);
}
}
@FunctionalInterface
static interface Function6<T1, T2, T3, T4, T5, T6, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, R>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> apply(t1, t2, t3, t4, t5, t6);
}
default Function1<Tuples.Tuple6<T1, T2, T3, T4, T5, T6>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6);
}
}
@FunctionalInterface
static interface Function7<T1, T2, T3, T4, T5, T6, T7, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, R>>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> t7 -> apply(t1, t2, t3, t4, t5, t6, t7);
}
default Function1<Tuples.Tuple7<T1, T2, T3, T4, T5, T6, T7>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6, t._7);
}
}
@FunctionalInterface
static interface Function8<T1, T2, T3, T4, T5, T6, T7, T8, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, R>>>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> t7 -> t8 -> apply(t1, t2, t3, t4, t5, t6, t7, t8);
}
default Function1<Tuples.Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6, t._7, t._8);
}
}
@FunctionalInterface
static interface Function9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, Function1<T9, R>>>>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> t7 -> t8 -> t9 -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9);
}
default Function1<Tuples.Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6, t._7, t._8, t._9);
}
}
@FunctionalInterface
static interface Function10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, Function1<T9, Function1<T10, R>>>>>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> t7 -> t8 -> t9 -> t10 -> apply(t1, t2, t3, t4, t5, t6, t7, t8,
t9, t10);
}
default Function1<Tuples.Tuple10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6, t._7, t._8, t._9, t._10);
}
}
@FunctionalInterface
static interface Function11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, Function1<T9, Function1<T10, Function1<T11, R>>>>>>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> t7 -> t8 -> t9 -> t10 -> t11 -> apply(t1, t2, t3, t4, t5, t6,
t7, t8, t9, t10, t11);
}
default Function1<Tuples.Tuple11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6, t._7, t._8, t._9, t._10, t._11);
}
}
@FunctionalInterface
static interface Function12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, Function1<T9, Function1<T10, Function1<T11, Function1<T12, R>>>>>>>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> t7 -> t8 -> t9 -> t10 -> t11 -> t12 -> apply(t1, t2, t3, t4, t5,
t6, t7, t8, t9, t10, t11, t12);
}
default Function1<Tuples.Tuple12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6, t._7, t._8, t._9, t._10, t._11, t._12);
}
}
@FunctionalInterface
static interface Function13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, R> extends Serializable {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13);
default Function1<T1, Function1<T2, Function1<T3, Function1<T4, Function1<T5, Function1<T6, Function1<T7, Function1<T8, Function1<T9, Function1<T10, Function1<T11, Function1<T12, Function1<T13, R>>>>>>>>>>>>> curried() {
return t1 -> t2 -> t3 -> t4 -> t5 -> t6 -> t7 -> t8 -> t9 -> t10 -> t11 -> t12 -> t13 -> apply(t1, t2, t3,
t4, t5, t6, t7, t8, t9, t10, t11, t12, t13);
}
default Function1<Tuples.Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>, R> tupled() {
return t -> apply(t._1, t._2, t._3, t._4, t._5, t._6, t._7, t._8, t._9, t._10, t._11, t._12, t._13);
}
}
}
| true |
8206105b81845d8122a81e971bbdc2b039148f02 | Java | zehrakonca/hrms.project | /hrms/src/main/java/com/aberimen/hrms/jobposting/dto/JobPostingDTO.java | UTF-8 | 635 | 1.929688 | 2 | [] | no_license | package com.aberimen.hrms.jobposting.dto;
import java.time.LocalDate;
import javax.validation.constraints.NotEmpty;
import com.aberimen.hrms.jobposting.EmploymentType;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Data
public class JobPostingDTO {
@JsonIgnore
private long id;
private int jobPositionId;
@NotEmpty
private String jobDescription;
private int locationId;
private int minSalary;
private int maxSalary;
private int openPositions;
private LocalDate deadline;
private int employerId;
private EmploymentType employmentType;
private boolean workRemotely;
}
| true |
1a4ae30bd2f8c948b51fd3ae6b9ad4ad0d6cc6ff | Java | davealgie/JavaSol | /DataTypes.java | UTF-8 | 310 | 2.28125 | 2 | [] | no_license | package com.qa.helloworld;
public class DataTypes {
// PRIMITIVE DATA TYPES
boolean bool = true;
byte bytes = 8;
char character = 'A';
short number = 16;
int anotherNumber = 32;
long aLongNumber = 64L;
float decimalNumber = 3.2f;
double anotherDecimalNumber = 6.4d;
String text = "Hello";
}
| true |
c7f0ebc4fc9a0251bb628ea6073f004d28b5170b | Java | Valsaa/compilateur | /src/backend/Code.java | UTF-8 | 596 | 2.71875 | 3 | [] | no_license | package backend;
public class Code extends Code3a{
private static boolean error = false;
public Code (){
super ();
}
public Code(Inst3a i){
super(i);
}
public static Code genVar(Operand3a t){
Inst3a i= new Inst3a(Inst3a.TAC_VAR, t, null, null);
return new Code(i);
}
public static Code genBinOp(int op, Expratt exp1, Expratt exp2, Operand3a temp){
Code cod = exp1.code;
cod.append(exp2.code);
cod.append(genVar(temp));
Inst3a i = new Inst3a(op, temp, exp1.place, exp2.place);
cod.append(new Code(i));
return cod;
}
} // Code ***
| true |
bc0baef94bd0334651af08ba177884300c246ec3 | Java | HPI-Information-Systems/metanome-algorithms | /ducc/ducc_algorithm/src/main/java/de/metanome/algorithms/ducc/DuccAlgorithm.java | UTF-8 | 2,219 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | package de.metanome.algorithms.ducc;
import com.google.common.collect.ImmutableList;
import de.metanome.algorithm_helper.data_structures.ColumnCombinationBitset;
import de.metanome.algorithm_helper.data_structures.PositionListIndex;
import de.metanome.algorithm_integration.AlgorithmExecutionException;
import de.metanome.algorithm_integration.result_receiver.UniqueColumnCombinationResultReceiver;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class DuccAlgorithm {
public int found;
protected String relationName;
protected List<String> columnNames;
protected UniqueColumnCombinationResultReceiver uccReceiver = null;
protected UccGraphTraverser graphTraverser;
protected long desiredRawKeyError = 0;
public DuccAlgorithm(String relationName, List<String> columnNames,
UniqueColumnCombinationResultReceiver uccReceiver) {
this.uccReceiver = uccReceiver;
this.relationName = relationName;
this.columnNames = columnNames;
graphTraverser = new UccGraphTraverser();
}
public DuccAlgorithm(String relationName, List<String> columnNames,
UniqueColumnCombinationResultReceiver uccReceiver, Random random) {
this(relationName, columnNames, uccReceiver);
graphTraverser = new UccGraphTraverser(random);
}
/**
* Method that sets the desired raw key error for unique checks. Default is 0. If set to a value
* different to 0, partial uniques are found.
*/
public void setRawKeyError(long keyError) {
this.desiredRawKeyError = keyError;
this.graphTraverser.setDesiredKeyError(keyError);
}
public void run(List<PositionListIndex> pliList) throws AlgorithmExecutionException {
this.found = 0;
this.graphTraverser.init(pliList, this.uccReceiver, this.relationName, this.columnNames);
this.found = this.graphTraverser.traverseGraph();
}
public ImmutableList<ColumnCombinationBitset> getMinimalUniqueColumnCombinations() {
return ImmutableList.copyOf(this.graphTraverser.getMinimalPositiveColumnCombinations());
}
public Map<ColumnCombinationBitset, PositionListIndex> getCalculatedPlis() {
return this.graphTraverser.getCalculatedPlis();
}
}
| true |
eaeb68cc109e492510049903037580cad9e3d315 | Java | FrancescaPascalau/design-patterns | /src/main/java/com/francesca/pascalau/designpatterns/structural/bridge/BlueCircle.java | UTF-8 | 287 | 3.03125 | 3 | [] | no_license | package com.francesca.pascalau.designpatterns.structural.bridge;
public class BlueCircle extends Circle {
public BlueCircle(ShapeColor shapeColor) {
super(shapeColor);
}
@Override
public void applyColor() {
System.out.println("Applying blue");
}
}
| true |
cc517d20fbae70631000293309cff296933531dd | Java | ipl-adm/ForgeScratch | /ForgeScratch/forge/src/main/java/org/golde/forge/scratchforge/base/common/world/AbstractCommand.java | UTF-8 | 1,106 | 2.3125 | 2 | [] | no_license | package org.golde.forge.scratchforge.base.common.world;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
public abstract class AbstractCommand implements ICommand {
public abstract void run(EntityPlayer player, String[] args);
@Override
public int compareTo(Object arg0) {
return 0;
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "/" + getCommandName();
}
@Override
public List getCommandAliases() {
return new ArrayList<String>();
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if(sender instanceof EntityPlayer) {
run((EntityPlayer)sender, args);
}
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender sender) {
return true;
}
@Override
public List addTabCompletionOptions(ICommandSender sender, String[] args) {
return new ArrayList<String>();
}
@Override
public boolean isUsernameIndex(String[] p_82358_1_, int index) {
return false;
}
}
| true |
2015ba68c2af03c6e78e101a255356aa783c1c03 | Java | shisongWjj/java18 | /src/main/java/com/ss/design/pattern/creational/prototype/Test.java | UTF-8 | 4,340 | 3.203125 | 3 | [] | no_license | package com.ss.design.pattern.creational.prototype;
import com.ss.design.pattern.creational.singleton.HungrySingleton;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* CamelUtils
*
* @author shisong
* @date 2019/1/9
*/
public class Test {
/*public static void main(String[] args) {
*//**
* 打印结果:
* 向姓名0同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名1同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名2同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名3同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名4同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名5同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名6同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名7同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名8同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
向姓名9同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
存储originMail记录,originMail:恭喜您,中奖了
我们发现,我们应该要保存下来的原始模板发生变化了,其实按照我们想要的,应该是原始模板不改变,所以我们需要对mail类进行修改
*//*
Mail mail = new Mail();
mail.setContent("初始化模板");
for(int i = 0;i<10;i++){
mail.setName("姓名"+i);
mail.setContent("姓名"+i+"@163.com");
mail.setContent("恭喜您,中奖了");
MailUitl.sendMessage(mail);
}
MailUitl.saveOriginMailRecord(mail);
}*/
/* public static void main(String[] args) throws CloneNotSupportedException {
*/
/**
* 向姓名0同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名1同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名2同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名3同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名4同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名5同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名6同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名7同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名8同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 向姓名9同学,邮件地址:null,邮件内容:恭喜您,中奖了 发送邮件成功
* 存储originMail记录,originMail:初始化模板
*//*
Mail mail = new Mail();
mail.setContent("初始化模板");
for(int i = 0;i<10;i++){
Mail mailtemp = (Mail) mail.clone();
mailtemp.setName("姓名"+i);
mailtemp.setContent("姓名"+i+"@163.com");
mailtemp.setContent("恭喜您,中奖了");
MailUitl.sendMessage(mailtemp);
}
MailUitl.saveOriginMailRecord(mail);
}*/
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//克隆破坏单列模式
/**
* com.ss.design.pattern.creational.singleton.HungrySingleton@6f75e721
com.ss.design.pattern.creational.singleton.HungrySingleton@69222c14
发现不是同一个对象了,那么怎么修改呢,
第一:就是不让他克隆
第二:重写克隆方法
*/
HungrySingleton hungrySingleton = HungrySingleton.getInstance();
Method declaredMethod = hungrySingleton.getClass().getDeclaredMethod("clone");
declaredMethod.setAccessible(true);
HungrySingleton invoke = (HungrySingleton) declaredMethod.invoke(hungrySingleton);
System.out.println(hungrySingleton);
System.out.println(invoke);
}
}
| true |
9f2618fcbde90384452c16fc743aad8fd2f963bc | Java | ozankyncu/Parser | /src/main/java/Modules/Article.java | UTF-8 | 2,096 | 2.171875 | 2 | [] | no_license | package Modules;
public class Article {
private String article_name;
private String authors;
private String article_title;
private int article_number;
private String abst;
private String mdurl;
private String pdf;
private int spage;
private int epage;
private String doi;
private String issn;
private String isbn;
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public int getArticle_number() {
return article_number;
}
public void setArticle_number(int article_number) {
this.article_number = article_number;
}
public String getArticle_name() {
return article_name;
}
public void setArticle_name(String article_name) {
this.article_name = article_name;
}
public String getAbst() {
return abst;
}
public void setAbst(String abst) {
this.abst = abst;
}
public String getMdurl() {
return mdurl;
}
public void setMdurl(String mdurl) {
this.mdurl = mdurl;
}
public String getPdf() {
return pdf;
}
public void setPdf(String pdf) {
this.pdf = pdf;
}
public int getSpage() {
return spage;
}
public void setSpage(int spage) {
this.spage = spage;
}
public int getEpage() {
return epage;
}
public void setEpage(int epage) {
this.epage = epage;
}
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
public String getIssn() {
return issn;
}
public void setIssn(String issn) {
this.issn = issn;
}
public String getIsbn() {
return isbn;
}
public String getArticle_title() {
return article_title;
}
public void setArticle_title(String article_title) {
this.article_title = article_title;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
}
| true |
085c0e116efbf456ac8af9fb08def36c67c7a359 | Java | scmanjarrez/RestFul-UPMSocial | /UPMSocial/src/rest/model/post/Post.java | UTF-8 | 2,180 | 2.546875 | 3 | [] | no_license | package rest.model.post;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.text.SimpleDateFormat;
import java.util.Date;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType (propOrder={"id","author_username","content","creation_date"})
public class Post {
private int id;
@XmlElement (name = "author")
private String author_username;
private String content;
@XmlJavaTypeAdapter(DateFormatterAdapter.class)
private Date creation_date;
public Post(){
}
public Post(int id, String author_username, String content, Date creation_date) {
super();
this.id = id;
this.author_username = author_username;
this.content = content;
this.creation_date = creation_date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor_username() {
return author_username;
}
public void setAuthor_username(String author_username) {
this.author_username = author_username;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreation_date() {
return creation_date;
}
public void setCreation_date(Date creation_date) {
this.creation_date = creation_date;
}
@Override
public String toString() {
return "Post [id=" + id + ", author_username=" + author_username + ", content=" + content + ", creation_date="
+ creation_date + "]";
}
private static class DateFormatterAdapter extends XmlAdapter<String, Date> {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
@Override
public Date unmarshal(final String v) throws Exception {
return dateFormat.parse(v);
}
@Override
public String marshal(final Date v) throws Exception {
return dateFormat.format(v);
}
}
}
| true |
322da26ed7a33c7d9a994f8251ab3f28f370698d | Java | jkb2922/PlaceSencer | /app/src/main/java/envyandroid/org/graduationproject/MainActivity.java | UTF-8 | 9,117 | 1.828125 | 2 | [] | no_license | package envyandroid.org.graduationproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import java.util.ArrayList;
import envyandroid.org.graduationproject.Community.CommunityFragment;
import envyandroid.org.graduationproject.Home.HomeFragment;
import envyandroid.org.graduationproject.Plan.PlanFragment;
import envyandroid.org.graduationproject.Plan.PlanMapFragment;
import envyandroid.org.graduationproject.Settings.SettingsFavoriteFragment;
import envyandroid.org.graduationproject.Settings.SettingsFragment;
import envyandroid.org.graduationproject.Settings.SettingsNoticeFragment;
public class MainActivity extends AppCompatActivity {
// 하단메뉴바
private BottomNavigationView bottomNavigationView;
// 하단 메뉴바 아이템 선택용
private ArrayList<String> menuHistory;
//
//public String ServerIP = "http://3.16.183.218/";
/* public String getServerIP(){
return ServerIP;
}*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Log 예시 (kosh 20.03.27)
//if(PlaceConfig.DEBUG) Log.d(PlaceConfig.TAG + this.getLocalClassName(),"OnCreate();");
PlaceConfig.WriteLog(this,"onCreate()");
//by kosh 200329 firbase cloud message add
/*FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
//Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
// String token = task.getResult().getToken();
// Log and toast
//String msg = getString(R.string.msg_token_fmt, token);
//Log.d("PlaceSensor_", token);
//Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
}
});*/
menuHistory = new ArrayList<>();
//-------------------
// 하단메뉴바 등록
//-------------------
bottomNavigationView = findViewById(R.id.bottomNavi);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.Main_Frame, HomeFragment.newInstance()).commit();
// menuHistory에 menu_home 기본 등록
menuHistory.add(PlaceConfig.Main_bottom_menu_home);
}
//-----------------------------
// 하단 메뉴바 리스너 선언
//-----------------------------
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_home: // 홈으로 이동
replaceFragment(HomeFragment.newInstance());
menuHistory.add(PlaceConfig.Main_bottom_menu_home);
return true;
case R.id.menu_community: // 커뮤니티로 이동
replaceFragment(CommunityFragment.newInstance());
menuHistory.add(PlaceConfig.Main_bottom_menu_community);
return true;
case R.id.menu_plan: // 계획으로 이동
replaceFragment(PlanFragment.newInstance());
menuHistory.add(PlaceConfig.Main_bottom_menu_plan);
return true;
case R.id.menu_settings: // 설정으로 이동
replaceFragment(SettingsFragment.newInstance());
menuHistory.add(PlaceConfig.Main_bottom_menu_settings);
return true;
}
return false;
}
};
//----------------------
// 프래그먼트 갈아끼우기
//-----------------------
private void replaceFragment(Fragment fragment) {
final FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.Main_Frame, fragment).addToBackStack(null).commit();
}
//-------------------------
// 뒤로가기 버튼 기능
//-------------------------
@Override
public void onBackPressed() {
int historyCount = menuHistory.size();
if (historyCount == 1) {
// menuHistory에 값이 main_home밖에 없으면 다음 메세지 출력
new AlertDialog.Builder(this)
.setMessage(getString(R.string.main_end_msg)) // String.xml 에서 불러오게 수정 by kosh 2020.03.27
.setCancelable(false)
.setPositiveButton("Yes", (dialog, id) -> finish())
.setNegativeButton("No", null)
.show();
} else {
if (historyCount > 1) {
// 프래그먼트 현재 스택 제거, menuHistory 최상단 제거
getSupportFragmentManager().popBackStack();
menuHistory.remove(historyCount-1);
// menuHistory 최상단 switch
switch(menuHistory.get(historyCount-2)){
case PlaceConfig.Main_bottom_menu_home: // 홈으로 이동
bottomNavigationView.getMenu().getItem(0).setChecked(true);
break;
case PlaceConfig.Main_bottom_menu_community: // 커뮤니티로 이동
bottomNavigationView.getMenu().getItem(1).setChecked(true);
break;
case PlaceConfig.Main_bottom_menu_plan: // 여행계획으로 이동
bottomNavigationView.getMenu().getItem(2).setChecked(true);
break;
case PlaceConfig.Main_bottom_menu_settings : // 설정으로 이동
bottomNavigationView.getMenu().getItem(3).setChecked(true);
break;
}
} else {
super.onBackPressed();
}
}
}
/* */
//-------------------------------------------------
// 프래그먼트 내에서 다른 프래그먼트로 갈아끼우기용
//-------------------------------------------------
public void changeCommunityFragment(){
menuHistory.add(PlaceConfig.Main_bottom_menu_community);
bottomNavigationView.getMenu().getItem(1).setChecked(true);
}
public void changePlanMapFragment(){
menuHistory.add(PlaceConfig.Main_bottom_menu_plan);
bottomNavigationView.getMenu().getItem(2).setChecked(true);
replaceFragment(PlanMapFragment.newInstance());
}
public void changeNoticeFragment(){
menuHistory.add(PlaceConfig.Main_bottom_menu_settings);
bottomNavigationView.getMenu().getItem(3).setChecked(true);
replaceFragment(SettingsNoticeFragment.newInstance());
}
public void changeFavoriteFragment(){
menuHistory.add(PlaceConfig.Main_bottom_menu_settings);
bottomNavigationView.getMenu().getItem(3).setChecked(true);
replaceFragment(SettingsFavoriteFragment.newInstance());
}
/* */
//---------------------
// 여행계획용, 실험중
//---------------------
public void planSetMode(boolean mode){
TextView planUpdate = findViewById(R.id.planUpdate);
TextView planRemove = findViewById(R.id.planRemove);
if(!mode){
planUpdate.setVisibility(View.VISIBLE);
planRemove.setVisibility(View.VISIBLE);
}else{
planUpdate.setVisibility(View.GONE);
planRemove.setVisibility(View.GONE);
}
}
}
| true |
e63e7e1e82d8311dbe1ccf5b9c3503fa7a511007 | Java | duwei205057/JavaWork | /src/com/dw/Test3.java | UTF-8 | 4,446 | 2.515625 | 3 | [] | no_license | package com.dw;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;
public class Test3 {
public static void main(String[] args) {
try {
isANRFileContainIMEInfo(new File("src/emoji.xml"));
ByteArrayOutputStream bao = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(bao, "UTF-16LE");
// OutputStreamWriter osw = new OutputStreamWriter(bao, "UTF-16LE");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("你好");
bw.close();
byte[] out = bao.toByteArray();
for(byte b : out) {
System.out.println(Integer.toHexString(b & 0xff));
}
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:S");
System.out.println(df.format(date));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update("adc".getBytes());//md.getDigest() 输出1
md.update("def".getBytes());//md.getDigest() 输出1
md.update("adc".getBytes());//md.getDigest() 输出1
System.out.println(bytesToHexString(md.digest()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
uuid();
}
public static String bytesToHexString(byte[] bArr) {
StringBuffer sb = new StringBuffer(bArr.length);
String sTmp;
for (int i = 0; i < bArr.length; i++) {
sTmp = Integer.toHexString(0xFF & bArr[i]);
if (sTmp.length() < 2)
sb.append(0);
sb.append(sTmp.toUpperCase());
}
return sb.toString();
}
public static boolean isANRFileContainIMEInfo(File anrFile) {
System.out.println(anrFile.getAbsolutePath());
if (anrFile == null || !anrFile.exists()) {
return false;
}
FileInputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
inputStream = new FileInputStream(anrFile);
bufferedInputStream = new BufferedInputStream(inputStream);
byte[] buffer = new byte[1024];
int len = -1;
int imeLineNumber = 0;
int ANR_MAX_IME_LINE_NUMBER = 10;
StringBuilder stringBuilder = new StringBuilder();
while((len = bufferedInputStream.read(buffer)) != -1) {
stringBuilder.append(new String(buffer, 0 , len));
String tmp = stringBuilder.toString();
System.out.println(tmp.contains("fadfdfggdgeg"));
imeLineNumber ++;
if (imeLineNumber > ANR_MAX_IME_LINE_NUMBER){
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return false;
}
private static void uuid() {
byte[] data = new byte[]{117,117,105,100,61,72,2,-17,-65,-67,37,36,-17,-65,-67,-17,-65,-67,-54,-106,-17
,-65,-67,36,43,-17,-65,-67,64,42,74,72,5,-17,-65,-67,21,99,-17,-65,-67,-23,-95,-89,88,105,-17,-65,-67,-17,-65,-67,-17,-65,-67,44,74};
// [117 117 105 100 61 72 2 239 191 189 37 36 239 191 189 239 191 189 202 150 239 191 189 36 43 239 191 189
// 64 42 74 72 5 239 191 189 21 99 239 191 189 233 161 167 88 105 239 191 189 239 191 189 239 191 189 44 74]
try {
System.out.println(new String(data, "UTF-8"));
System.out.println(new String(data, "GBK"));
System.out.println(bytesToHexString(data));
System.out.println(bytesToHexString("uuid=H\u0002�%$��ʖ�$+�@*JH\u0005�\u0015c�顧Xi���,J".getBytes()));
System.out.println(Arrays.toString("705ce31c29c5b469a6ee73d13f4ea2a8".getBytes()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
| true |
b9e5ceac3c6fb3722bd42086fed09986b89343c5 | Java | lapivoinerouge/lab-wizard-app | /src/main/java/com/lab/wizard/repository/PatientRepository.java | UTF-8 | 629 | 2.09375 | 2 | [] | no_license | package com.lab.wizard.repository;
import com.lab.wizard.domain.user.Patient;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Transactional
@Repository
public interface PatientRepository extends CrudRepository<Patient, Long> {
@Override
List<Patient> findAll();
@Override
Optional<Patient> findById(Long id);
Optional<Patient> findByPesel(String pesel);
@Override
Patient save(Patient patient);
@Override
void deleteById(Long id);
}
| true |
12868a682afc00def1f3d77916428a878b0ce8a5 | Java | Fachschaft07/fs-rest | /common/src/main/java/edu/hm/cs/fs/common/model/Meal.java | UTF-8 | 938 | 2.453125 | 2 | [] | no_license | package edu.hm.cs.fs.common.model;
import java.util.Date;
import java.util.List;
import edu.hm.cs.fs.common.constant.Additive;
import edu.hm.cs.fs.common.constant.MealType;
/**
* Created by Fabio on 18.02.2015.
*/
public class Meal {
private Date date;
private MealType type;
private String name;
private List<Additive> additives;
public Date getDate() {
return date;
}
public void setDate(final Date date) {
this.date = date;
}
public MealType getType() {
return type;
}
public void setType(final MealType type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<Additive> getAdditives() {
return additives;
}
public void setAdditives(List<Additive> additives) {
this.additives = additives;
}
}
| true |
57398c3f14c0709be2a081f8b3f3eda1dbe501b4 | Java | dimitrisli/SpringHibernateMySQL | /src/main/java/com/dimitrisli/springHibernateMySQL/dao/PersonORMDao.java | UTF-8 | 301 | 2.296875 | 2 | [] | no_license | package com.dimitrisli.springHibernateMySQL.dao;
import com.dimitrisli.springHibernateMySQL.model.Person;
public interface PersonORMDao {
public void create(Person person);
public Person read(String name, String surname);
public void update(Person person);
public void delete(Person person);
}
| true |
92d2537e1ae8f0bb43c4084e3d316046274ad0b3 | Java | nevoezov/Bluffer | /server/src/server/QuestionAndAnswer.java | UTF-8 | 902 | 3.03125 | 3 | [] | no_license | package server;
import java.util.ArrayList;
import java.util.Collections;
public class QuestionAndAnswer {
private String question;
private ArrayList<PlayerAnswer> answers;
private String realAnswer;
public QuestionAndAnswer(String question, String realAnswer) {
this.question = question;
this.answers = new ArrayList<PlayerAnswer>();
this.realAnswer = realAnswer;
answers.add(new PlayerAnswer(null, realAnswer));
}
public String getQuestion() {
return question;
}
public void addAnswer(Player player, String answer) {
answers.add(new PlayerAnswer(player, answer));
}
public ArrayList<PlayerAnswer> getAnswers() {
return answers;
}
public ArrayList<PlayerAnswer> getShuffledAnswers() {
ArrayList<PlayerAnswer> temp = new ArrayList<PlayerAnswer>(answers);
Collections.shuffle(temp);
return temp;
}
public String getRealAnswer() {
return this.realAnswer;
}
}
| true |
1a7b8955ff066d29d6a7a60c755ac0914b40f631 | Java | GreckiD/YouTubePlayListDownloader | /src/main/java/VideoConverter.java | UTF-8 | 1,809 | 2.453125 | 2 | [] | no_license | import com.jayway.jsonpath.JsonPath;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import java.io.*;
import java.net.URL;
import static io.restassured.RestAssured.given;
public class VideoConverter {
private RequestSpecification requestSpec;
private String projectDIR = System.getProperty("user.dir");
public VideoConverter() {
RestAssured.baseURI = "https://toquemp3.com/";
requestSpec = new RequestSpecBuilder()
.addHeader("content-type", "application/json; charset=UTF-8")
.setRelaxedHTTPSValidation()
.build();
}
private String getMP3DownloadUrl(String videoId) {
Response response = given()
.spec(requestSpec)
.get("/en/@api/json/mp3/" + videoId);
String downloadURL = JsonPath.parse(response.getBody().asString()).read("$.vidInfo.0.dloadUrl");
return downloadURL;
}
public void downloadMP3File(String videoId, String title) {
String downloadURL = getMP3DownloadUrl(videoId);
title = title.replace("/", "");
try (BufferedInputStream inputStream = new BufferedInputStream(new URL("https:" + downloadURL).openStream());
FileOutputStream mp3File = new FileOutputStream(projectDIR + "/target/files/" + title + ".mp3")) {
byte data[] = new byte[1024];
int byteContent;
while ((byteContent = inputStream.read(data, 0, 1024)) != -1) {
mp3File.write(data, 0, byteContent);
}
System.out.println("Downloaded: " + title);
} catch (IOException e) {
System.out.println(e);
}
}
}
| true |
6eb265479065ca656a7318a7575259433b641010 | Java | Matkurbanova/SalonGoBack | /src/main/java/kg/salongo/SalonGoBack/jdbc/ServiceSalonJdbc.java | UTF-8 | 4,752 | 2.0625 | 2 | [] | no_license | package kg.salongo.SalonGoBack.jdbc;
import kg.salongo.SalonGoBack.data.ServiceBySubCat;
import kg.salongo.SalonGoBack.entity.Category;
import kg.salongo.SalonGoBack.entity.ServiceMaster;
import kg.salongo.SalonGoBack.entity.ServiceSalon;
import kg.salongo.SalonGoBack.entity.SubCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class ServiceSalonJdbc {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
WorkTimeJdbc workTimeJdbc;
public List<ServiceSalon> findAll() {
return jdbcTemplate.query("SELECT*FROM ServiceSalon",
new BeanPropertyRowMapper<>(ServiceSalon.class));
}
public ServiceSalon findById(int id) {
return jdbcTemplate.queryForObject("SELECT*FROM ServiceSalon WHERE id=?", new Object[]{id}, new BeanPropertyRowMapper<>(ServiceSalon.class));
}
public int deleteById(int id) {
return jdbcTemplate.update("DELETE FROM ServiceSalon WHERE id=?",
new Object[]{id});
}
public int save(ServiceSalon sSalon) {
return jdbcTemplate.update("INSERT INTO ServiceSalon (SalonId, SubCategoryId,Price,Description,Image) " +
"VALUES (?,?,?,?,?)",
sSalon.getSalonId(),
sSalon.getSubCategoryId(),
sSalon.getPrice(),
sSalon.getDescription(),
sSalon.getImage());
}
public List<ServiceSalon> findBySalonId(int SalonId) {
return jdbcTemplate.query("SELECT * FROM ServiceSalon WHERE SalonId = ?", new Object[]{SalonId},
new BeanPropertyRowMapper<>(ServiceSalon.class));
}
public List<ServiceBySubCat> findBySubCategory(int SalonId) {
List<ServiceBySubCat> resList = jdbcTemplate.query("SELECT ss.*, us.NAME, us.ADDRESS, us.PHONE,us.status FROM ServiceSalon ss " +
" JOIN users us ON ss.SALONID = us.ID " +
" WHERE SubCategoryId = ? ", new Object[]{SalonId},
new BeanPropertyRowMapper<>(ServiceBySubCat.class));
for (ServiceBySubCat servSubCat : resList) {
servSubCat.setWorkTimes(workTimeJdbc.findBSalonId(servSubCat.getSalonId()));
}
return resList;
}
public List<Category> findByUserSalon(int SalonId) {
List<Category> resList = jdbcTemplate.query("select c.* from servicesalon ss " +
"LEFT JOIN subcategory sc ON sc.Id = ss.SubcategoryId " +
"LEFT JOIN category c ON c.Id = sc.CategoryId " +
"WHERE ss.SalonId = ? " +
"group by c.Id; ", new Object[]{SalonId},
new BeanPropertyRowMapper<>(Category.class));
return resList;
}
public List<SubCategory> findByCategoryId(int SalonId, int CategoryId) {
List<SubCategory> resList = jdbcTemplate.query("select sc.* from servicesalon ss " +
"LEFT JOIN subcategory sc ON sc.Id = ss.SubcategoryId " +
"WHERE ss.SalonId = ? AND sc.CategoryId = ? " +
"group by sc.Id; ", new Object[]{SalonId,CategoryId},
new BeanPropertyRowMapper<>(SubCategory.class));
return resList;
}
public List<ServiceSalon>findBySubCategoryId(int salonId,int subcategoryId){
List<ServiceSalon>resList=jdbcTemplate.query(
"SELECT * FROM servicesalon WHERE SalonId = ? AND subcategoryId = ? ",
new Object[]{salonId,subcategoryId} ,
new BeanPropertyRowMapper<>(ServiceSalon.class));
return resList;
}
// public List<MoreServiceBySubCat>findBySubCategoryId(int SalonId) {
// List<MoreServiceBySubCat> resList = jdbcTemplate.query(" SELECT mss.*, mus.NAME, mus.ADDRESS, mus.PHONE,mus.typeStatus FROM ServiceSalon mss\n" +
// "JOIN USERSALON mus ON mss.SALONID = mus.ID\n" +
// "WHERE SubcategoryId = ?", new Object[]{SalonId},
// new BeanPropertyRowMapper<>(MoreServiceBySubCat.class));
//
// for (MoreServiceBySubCat moreservSubCat : resList) {
// moreservSubCat.setWorkTimes(workTimeJdbc.findBSalonId(moreservSubCat.getSalonId()));
//
// }
// return resList;
//
//
// }
public ServiceSalon findByToken(String token) {
return jdbcTemplate.queryForObject("SELECT * FROM ServiceSalon WHERE token = ? ", new Object[]{token},
new BeanPropertyRowMapper<>(ServiceSalon.class));
}
}
| true |
c906b10ec256256b9dc452ad01db128b210365f2 | Java | Rishi74744/MyPractice | /src/com/java/concepts/crack/code/interview/questions/chapter3/SortStack.java | UTF-8 | 1,787 | 3.859375 | 4 | [] | no_license | package com.java.concepts.crack.code.interview.questions.chapter3;
import java.util.Scanner;
import java.util.Stack;
public class SortStack {
static Stack<Integer> mainStack = new Stack<>();
static void push(int data) {
if (mainStack.isEmpty()) {
mainStack.push(data);
} else {
int msTop = mainStack.peek();
if (msTop > data) {
mainStack.push(data);
} else {
Stack<Integer> tempStack = new Stack<>();
msTop = mainStack.pop();
while (msTop < data) {
tempStack.push(msTop);
if (!mainStack.isEmpty()) {
msTop = mainStack.pop();
} else {
break;
}
}
if (msTop > data) {
mainStack.push(msTop);
}
mainStack.push(data);
while (!tempStack.isEmpty()) {
mainStack.push(tempStack.pop());
}
}
}
}
static int pop() {
if (mainStack.isEmpty()) {
return -1;
} else {
return mainStack.pop();
}
}
static int peek() {
if (mainStack.isEmpty()) {
return -1;
} else {
return mainStack.peek();
}
}
static boolean isEmpty() {
return mainStack.isEmpty();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of elements you want to insert in stack : ");
int total = scanner.nextInt();
System.out.println("Enter stack elements : ");
for (int i = 0; i < total; i++) {
int data = scanner.nextInt();
push(data);
}
System.out.println("Enter number of elements you want to fetch from stack : ");
total = scanner.nextInt();
for (int i = 0; i < total; i++) {
int result = pop();
if (result == -1) {
System.out.println("Stack Underflow");
} else {
System.out.println(result);
}
}
System.out.println("Top Of Stack after pop : " + peek());
scanner.close();
}
} | true |
010cd318f1362d7ab91bb79c152053df21903967 | Java | yarodinD/climathon_2019 | /src/main/java/de/climathon/extremeweather/mawarning/infra/converter/WaterLevelTrendConverter.java | UTF-8 | 1,330 | 2.296875 | 2 | [] | no_license | package de.climathon.extremeweather.mawarning.infra.converter;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import de.climathon.extremeweather.mawarning.domain.model.WaterLevelTrend;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.jackson.JsonComponent;
@JsonComponent
public class WaterLevelTrendConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(WaterLevelTrendConverter.class);
public static class Deserialize extends JsonDeserializer<WaterLevelTrend> {
@Override
public WaterLevelTrend deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
String valueAsString = jsonParser.getValueAsString();
try {
Integer value = Integer.valueOf(valueAsString);
return WaterLevelTrend.byValue(value);
} catch (NumberFormatException e) {
LOGGER.warn("Unknown value for WaterLevelTrend: {}", valueAsString);
return null;
}
}
}
}
| true |
21b58c3933ea0095b3a35cba0cc816e1ec03eba5 | Java | danielannan17/StarSailor | /gameLogic/Resources.java | UTF-8 | 9,697 | 2.6875 | 3 | [] | no_license | package gameLogic;
/**
*
*
*
*/
public class Resources {
private String type;
private PlayerStats playerStats;
private int level,increment;
private long id;
private int amountPerHour;
private int[] LVL,storageAvailablePerLevel,populationAvailablePerLevelofRecruitmentAgency, waterAvailablePerLevel, moneyPerLevel;
public Resources(String _type,int level, long id, int amountPerHour){
this.type = _type;
this.level = level;
this.id = id;
this.amountPerHour = amountPerHour;
LVL = new int[] {45,53,62,71,83,96,111,129,150,176,204,237,276,321,374,434,506,587,683,800};
storageAvailablePerLevel = new int[] {1000,1230,1550,1860,2285,2810,3454,4247,5222,6420,7883, 9715, 11942, 14670, 18037, 22177, 27266, 33573, 41017, 50000};
populationAvailablePerLevelofRecruitmentAgency = new int[] {240, 281, 329, 386, 452, 530, 622, 729, 854, 1002, 1174, 1376, 1613, 1891, 2216, 2598, 3045, 3569, 4183, 5000};
waterAvailablePerLevel = new int[] {53,62,71,83,96,111,129,150,176,204,237,276,321,374,434,506,587,673,785,900};
moneyPerLevel = new int[] {90,106,124,142,166,192,222,258,300,351,408,474,532,642,748,868,1012,1174,1366,1600};
}
/**
* Upgrade the resource
* @param level the level you want to reach
*/
public void upgradeResources(int level){
setAmountPerHour("" + level);
this.level = level;
}
/**
* Set how many resource the player is going to receive according on the level the building is
* @param level the level of the resource
*/
public void setAmountPerHour(String level){
switch(this.type){
case "money":
switch(level){
case "1" : this.amountPerHour = moneyPerLevel[0]; break;
case "2" : this.amountPerHour = moneyPerLevel[1]; break;
case "3" : this.amountPerHour = moneyPerLevel[2]; break;
case "4" : this.amountPerHour = moneyPerLevel[3]; break;
case "5" : this.amountPerHour = moneyPerLevel[4]; break;
case "6" : this.amountPerHour = moneyPerLevel[5]; break;
case "7" : this.amountPerHour = moneyPerLevel[6]; break;
case "8" : this.amountPerHour = moneyPerLevel[7]; break;
case "9" : this.amountPerHour = moneyPerLevel[8]; break;
case "10" : this.amountPerHour = moneyPerLevel[9]; break;
case "11" : this.amountPerHour = moneyPerLevel[10]; break;
case "12" : this.amountPerHour = moneyPerLevel[11]; break;
case "13" : this.amountPerHour = moneyPerLevel[12]; break;
case "14" : this.amountPerHour = moneyPerLevel[13]; break;
case "15" : this.amountPerHour = moneyPerLevel[14]; break;
case "16" : this.amountPerHour = moneyPerLevel[15]; break;
case "17" : this.amountPerHour = moneyPerLevel[16]; break;
case "18" : this.amountPerHour = moneyPerLevel[17]; break;
case "19" : this.amountPerHour = moneyPerLevel[18]; break;
case "20" : this.amountPerHour = moneyPerLevel[19]; break;
}
case "water":
if(this.type == "money") break;
switch(level){
case "1" : this.amountPerHour = waterAvailablePerLevel[0]; break;
case "2" : this.amountPerHour = waterAvailablePerLevel[1]; break;
case "3" : this.amountPerHour = waterAvailablePerLevel[2]; break;
case "4" : this.amountPerHour = waterAvailablePerLevel[3]; break;
case "5" : this.amountPerHour = waterAvailablePerLevel[4]; break;
case "6" : this.amountPerHour = waterAvailablePerLevel[5]; break;
case "7" : this.amountPerHour = waterAvailablePerLevel[6]; break;
case "8" : this.amountPerHour = waterAvailablePerLevel[7]; break;
case "9" : this.amountPerHour = waterAvailablePerLevel[8]; break;
case "10" : this.amountPerHour = waterAvailablePerLevel[9]; break;
case "11" : this.amountPerHour = waterAvailablePerLevel[10]; break;
case "12" : this.amountPerHour = waterAvailablePerLevel[11]; break;
case "13" : this.amountPerHour = waterAvailablePerLevel[12]; break;
case "14" : this.amountPerHour = waterAvailablePerLevel[13]; break;
case "15" : this.amountPerHour = waterAvailablePerLevel[14]; break;
case "16" : this.amountPerHour = waterAvailablePerLevel[15]; break;
case "17" : this.amountPerHour = waterAvailablePerLevel[16]; break;
case "18" : this.amountPerHour = waterAvailablePerLevel[17]; break;
case "19" : this.amountPerHour = waterAvailablePerLevel[18]; break;
case "20" : this.amountPerHour = waterAvailablePerLevel[19]; break;
}
case "population":
if(this.type == "water" || this.type == "money") break;
switch(level){
case "1" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[0]; break;
case "2" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[1]; break;
case "3" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[2]; break;
case "4" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[3]; break;
case "5" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[4]; break;
case "6" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[5]; break;
case "7" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[6]; break;
case "8" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[7]; break;
case "9" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[8]; break;
case "10" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[9]; break;
case "11" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[10]; break;
case "12" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[11]; break;
case "13" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[12]; break;
case "14" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[13]; break;
case "15" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[14]; break;
case "16" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[15]; break;
case "17" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[16]; break;
case "18" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[17]; break;
case "19" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[18]; break;
case "20" : this.amountPerHour = populationAvailablePerLevelofRecruitmentAgency[19]; break;
}
case "storage":
if(this.type == "population" || this.type == "water" || this.type == "money") break;
switch(level){
case "1" : this.amountPerHour = storageAvailablePerLevel[0]; break;
case "2" : this.amountPerHour = storageAvailablePerLevel[1]; break;
case "3" : this.amountPerHour = storageAvailablePerLevel[2]; break;
case "4" : this.amountPerHour = storageAvailablePerLevel[3]; break;
case "5" : this.amountPerHour = storageAvailablePerLevel[4]; break;
case "6" : this.amountPerHour = storageAvailablePerLevel[5]; break;
case "7" : this.amountPerHour = storageAvailablePerLevel[6]; break;
case "8" : this.amountPerHour = storageAvailablePerLevel[7]; break;
case "9" : this.amountPerHour = storageAvailablePerLevel[8]; break;
case "10" : this.amountPerHour = storageAvailablePerLevel[9]; break;
case "11" : this.amountPerHour = storageAvailablePerLevel[10]; break;
case "12" : this.amountPerHour = storageAvailablePerLevel[11]; break;
case "13" : this.amountPerHour = storageAvailablePerLevel[12]; break;
case "14" : this.amountPerHour = storageAvailablePerLevel[13]; break;
case "15" : this.amountPerHour = storageAvailablePerLevel[14]; break;
case "16" : this.amountPerHour = storageAvailablePerLevel[15]; break;
case "17" : this.amountPerHour = storageAvailablePerLevel[16]; break;
case "18" : this.amountPerHour = storageAvailablePerLevel[17]; break;
case "19" : this.amountPerHour = storageAvailablePerLevel[18]; break;
case "20" : this.amountPerHour = storageAvailablePerLevel[19]; break;
}
default:
if(this.type == "storage" || this.type == "population" || this.type == "water" || this.type == "money") break;
switch(level){
case "1" : this.amountPerHour = LVL[0]; break;
case "2" : this.amountPerHour = LVL[1]; break;
case "3" : this.amountPerHour = LVL[2]; break;
case "4" : this.amountPerHour = LVL[3]; break;
case "5" : this.amountPerHour = LVL[4]; break;
case "6" : this.amountPerHour = LVL[5]; break;
case "7" : this.amountPerHour = LVL[6]; break;
case "8" : this.amountPerHour = LVL[7]; break;
case "9" : this.amountPerHour = LVL[8]; break;
case "10" : this.amountPerHour = LVL[9]; break;
case "11" : this.amountPerHour = LVL[10]; break;
case "12" : this.amountPerHour = LVL[11]; break;
case "13" : this.amountPerHour = LVL[12]; break;
case "14" : this.amountPerHour = LVL[13]; break;
case "15" : this.amountPerHour = LVL[14]; break;
case "16" : this.amountPerHour = LVL[15]; break;
case "17" : this.amountPerHour = LVL[16]; break;
case "18" : this.amountPerHour = LVL[17]; break;
case "19" : this.amountPerHour = LVL[18]; break;
case "20" : this.amountPerHour = LVL[19]; break;
}
}
}
/**
* Get the type of the resource
* @return the type of the resource
*/
public String getType(){
return this.type;
}
/**
* Get the level of the resource
* @return the level of the resource
*/
public int getLevel(){
return this.level;
}
/**
* Get the ID of the resource
* @return the ID of the resource
*/
public long getId(){
return this.id;
}
/**
* Get the amount a certain resource is producing/giving to the player
* @return the amount a certain resource is producing/giving to the player
*/
public long getAmountPerHour(){
return this.amountPerHour;
}
public void setLevel(int level) {
this.level = level;
}
}
| true |
9f7c77185ff03f0e9a5c718aafd2f3c3d3a075db | Java | liwenwei/logconverge | /logconverge/src/main/java/com/moment/logconverge/entity/BusinessLog.java | UTF-8 | 1,164 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | package com.moment.logconverge.entity;
import com.alibaba.fastjson.JSON;
import com.moment.logconverge.parse.ParseToJson;
import java.util.Map;
/**
* Created by moment on 2018/1/10.
*/
public class BusinessLog implements ParseToJson {
// 业务日志类型
private Map<String, Object> businessLog;
public Map<String, Object> getBusinessLog() {
return businessLog;
}
public void setBusinessLog(Map<String, Object> businessLog) {
this.businessLog = businessLog;
}
@Override
public String toJson() {
String json = JSON.toJSONString(this);
return (json == null || json.equals("{}")) ? "{\"error\":\"json parse error\"}" : JSON.toJSONString(this);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{");
for (Map.Entry<String, Object> entry : businessLog.entrySet()) {
builder.append("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
builder.append("}");
return "BusinessLog{" +
"commonLog=" + builder.toString() +
'}';
}
}
| true |
4fab3ba7363fe0568e5e15d15895f44622fb8b2c | Java | hungwen0425/cloudmall | /cloudmall-admin/src/main/java/io/renren/modules/sys/service/SysConfigService.java | UTF-8 | 1,154 | 2.046875 | 2 | [] | no_license | /**
* Copyright (c) 2016-2019 人人開源 All rights reserved.
*
* https://www.renren.io
*
* 版權所有,侵權必究!
*/
package io.renren.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import io.renren.common.utils.PageUtils;
import io.renren.modules.sys.entity.SysConfigEntity;
import java.util.Map;
/**
* 系统設定備註
*
* @author hungwen.tseng@gmail.com
*/
public interface SysConfigService extends IService<SysConfigEntity> {
PageUtils queryPage(Map<String, Object> params);
/**
* 保存設定備註
*/
public void saveConfig(SysConfigEntity config);
/**
* 更新設定備註
*/
public void update(SysConfigEntity config);
/**
* 根據key,更新value
*/
public void updateValueByKey(String key, String value);
/**
* 删除設定備註
*/
public void deleteBatch(Long[] ids);
/**
* 根據key,取得設定的value值
*
* @param key key
*/
public String getValue(String key);
/**
* 根據key,取得value的Object物件
* @param key key
* @param clazz Object物件
*/
public <T> T getConfigObject(String key, Class<T> clazz);
}
| true |
a2437a63811fb005606b120ca62ac50545368401 | Java | cat-ding/SimpleTweet | /app/src/main/java/com/codepath/apps/restclienttemplate/TimelineActivity.java | UTF-8 | 9,488 | 1.929688 | 2 | [
"Apache-2.0",
"MIT"
] | permissive | package com.codepath.apps.restclienttemplate;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.codepath.apps.restclienttemplate.databinding.ActivityTimelineBinding;
import com.codepath.apps.restclienttemplate.databinding.ActivityTweetDetailBinding;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.codepath.apps.restclienttemplate.models.TweetDao;
import com.codepath.apps.restclienttemplate.models.TweetWithUser;
import com.codepath.apps.restclienttemplate.models.User;
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler;
import com.google.android.material.tabs.TabLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.parceler.Parcels;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Headers;
public class TimelineActivity extends AppCompatActivity implements ComposeFragment.OnFinishEditDialog {
public static final String TAG = "TimelineActivity";
private final int REQUEST_CODE = 40;
TweetDao tweetDao;
TwitterClient client;
RecyclerView rvTweets;
List<Tweet> tweets;
TweetsAdapter adapter;
SwipeRefreshLayout swipeContainer;
EndlessRecyclerViewScrollListener scrollListener;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Apply View Binding library
final ActivityTimelineBinding binding = ActivityTimelineBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
client = TwitterApp.getRestClient(this);
tweetDao = ((TwitterApp) getApplicationContext()).getMyDatabase().tweetDao();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
progressBar = binding.progressBar;
swipeContainer = binding.swipeContainer;
binding.swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
Log.i(TAG, "fetching new data!");
populateHomeTimeline();
}
});
// Configure the refreshing colors
binding.swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R. color.holo_orange_light,
android.R.color.holo_red_light);
// Find the recycler view
rvTweets = binding.rvTweets;
// Init the list of tweets and the adapter
tweets = new ArrayList<>();
adapter = new TweetsAdapter(this, tweets);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// Recycler view set up: layout manager and the adapter
binding.rvTweets.setLayoutManager(layoutManager);
binding.rvTweets.setAdapter(adapter);
scrollListener = new EndlessRecyclerViewScrollListener(layoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount) {
Log.i(TAG, "onLoadMore: " + page);
progressBar.setVisibility(View.VISIBLE);
loadMoreData();
}
};
// Adds the scroll listener to RecyclerView
binding.rvTweets.addOnScrollListener(scrollListener);
// Query for existing tweets in the DB
AsyncTask.execute(new Runnable() {
@Override
public void run() {
Log.i(TAG, "Showing data from database");
List <Tweet> tweetsFromDB = TweetWithUser.getTweetList(tweetDao.recentItems());
adapter.clear();
adapter.addAll(tweetsFromDB);
progressBar.setVisibility(View.INVISIBLE);
}
});
binding.progressBar.setVisibility(View.VISIBLE);
populateHomeTimeline();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// coming back from TweetDetailActivity
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
Parcelable updatedTweetParcel = data.getParcelableExtra("updatedTweet");
if (updatedTweetParcel != null) {
Tweet updatedTweet = Parcels.unwrap(updatedTweetParcel);
// find adapter position (where the tweet was)
int position = -1;
for (int i = 0; i < tweets.size(); i++) {
if (tweets.get(i).id == updatedTweet.id) {
position = i;
break;
}
}
tweets.remove(position);
tweets.add(position, updatedTweet);
adapter.notifyItemChanged(position);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.compose) {
// Compose icon has been selected
// Navigate to the compose dialog fragment
ComposeFragment dialog = ComposeFragment.newInstance("");
dialog.show(getSupportFragmentManager(), "ComposeFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadMoreData() {
// 1. Send an API request to retrieve appropriate paginated data
client.getNextPageOfTweets(new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Headers headers, JSON json) {
Log.i(TAG, "onSuccess for loadMoreData! " + json.toString());
// 2. Deserialize and construct new model objects from the API response
JSONArray jsonArray = json.jsonArray;
try {
List<Tweet> tweets = Tweet.fromJsonArray(jsonArray);
// 3. Append the new data objects to the existing set of items inside the array of items
// 4. Notify the adapter of the new items made with `notifyItemRangeInserted()`
adapter.addAll(tweets);
progressBar.setVisibility(View.INVISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) {
Log.e (TAG, "onFailure for loadMoreData!", throwable);
progressBar.setVisibility(View.INVISIBLE);
}
}, tweets.get(tweets.size() - 1).id);
}
private void populateHomeTimeline() {
client.getHomeTimeline(new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Headers headers, JSON json) {
Log.i(TAG, "onSuccess! " + json.toString());
JSONArray jsonArray = json.jsonArray;
try {
final List<Tweet> tweetsFromNetwork = Tweet.fromJsonArray(jsonArray);
adapter.clear();
adapter.addAll(tweetsFromNetwork);
// Signal refresh has finished
swipeContainer.setRefreshing(false);
progressBar.setVisibility(View.INVISIBLE);
AsyncTask.execute(new Runnable() {
@Override
public void run() {
Log.i(TAG, "Saving data into database");
// insert users first
List<User> usersFromNetwork = User.fromJsonTweetArray(tweetsFromNetwork);
tweetDao.insertModel(usersFromNetwork.toArray(new User[0]));
// insert tweets next
tweetDao.insertModel(tweetsFromNetwork.toArray(new Tweet[0]));
}
});
} catch (JSONException e) {
Log.e(TAG, "Json exception", e);
}
}
@Override
public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) {
Log.e(TAG, "onFailure! " + response, throwable);
}
});
}
@Override
public void sendTweet(Tweet tweet) {
tweets.add(0, tweet);
// Update the adapter
adapter.notifyItemInserted(0);
rvTweets.smoothScrollToPosition(0);
}
} | true |
0d68c1c9761e08a665f3e50f02bdb9932a938131 | Java | bigMiscellaneous/summer | /src/main/java/com/interfacedemo/zoo/Fish.java | UTF-8 | 229 | 3.09375 | 3 | [] | no_license | package com.interfacedemo.zoo;
public class Fish implements Animal {
public void eat(){
System.out.println("鱼爱吃蚯蚓");
}
public void sleep(){
System.out.println("鱼在水里睡觉");
}
}
| true |
6fd79e321346efd68cdb58e5668aa14b30276c9c | Java | kmgill/com.apoapsys.astronomy | /src/main/com/apoapsys/astronomy/geo/exception/MapProjectionException.java | UTF-8 | 309 | 1.882813 | 2 | [] | no_license | package com.apoapsys.astronomy.geo.exception;
@SuppressWarnings("serial")
public class MapProjectionException extends Exception
{
public MapProjectionException(String message)
{
super(message);
}
public MapProjectionException(String message, Throwable thrown)
{
super(message, thrown);
}
}
| true |
4375b8262c4df5bf4850823baf324b0576c137bf | Java | DZ-Wong/AboutJavaBase | /src/main/java/T0308/AccessControl/AccessDemo.java | UTF-8 | 470 | 3.03125 | 3 | [] | no_license | package T0308.AccessControl;
/**
* Created by vip on 2018/3/21.
*/
public class AccessDemo extends Cookie {
public AccessDemo() {
System.out.println("AccessDemo Constructor");
}
public void chomp() {
bite();//这时和Cookie还在同一个package下,能够调用,在其他包下时报错。
sing();
}
public static void main(String[] args) {
AccessDemo demo = new AccessDemo();
demo.chomp();
}
}
| true |
f6550681ae218f93d1916b6bd8eacadf7f0fdcc7 | Java | KevinChanDev/raccoons-tda | /raccoons-tda-auth/src/main/java/com/raccoons/tda/auth/model/OAuth2AccessTokenResponse.java | UTF-8 | 2,446 | 2.65625 | 3 | [] | no_license | package com.raccoons.tda.auth.model;
import java.util.Map;
public class OAuth2AccessTokenResponse {
private boolean valid;
private String accessToken;
private String refreshToken;
private String tokenType;
private long expiresIn;
private long refreshTokenExpiresIn;
private OAuth2AccessTokenResponse(boolean valid) {
this.valid = valid;
}
private OAuth2AccessTokenResponse(final Map<String, Object> values) {
try {
final String accessToken = (String) values.get("access_token");
final String refreshToken = (String) values.get("refresh_token");
final String tokenType = (String) values.get("token_type");
final Object refreshTokenExpiresIn = values.get("refresh_token_expires_in");
final Object expiresIn = values.get("expires_in");
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.tokenType = tokenType;
if (expiresIn instanceof Integer) {
this.expiresIn = ((Integer) expiresIn).longValue();
} else if (expiresIn instanceof Long) {
this.expiresIn = (long) expiresIn;
} else {
valid = false;
}
if (refreshTokenExpiresIn instanceof Integer) {
this.refreshTokenExpiresIn = ((Integer) refreshTokenExpiresIn).longValue();
} else if (refreshTokenExpiresIn instanceof Long) {
this.refreshTokenExpiresIn = (long) refreshTokenExpiresIn;
} else {
valid = false;
}
valid = true;
} catch (Exception e) {
e.printStackTrace();
valid = false;
}
}
public String getAccessToken() {
return accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public long getExpiresIn() {
return expiresIn;
}
public long getRefreshTokenExpiresIn() {
return refreshTokenExpiresIn;
}
public String getTokenType() {
return tokenType;
}
public boolean isValid() {
return valid;
}
public static OAuth2AccessTokenResponse of(Map<String, Object> values) {
return new OAuth2AccessTokenResponse(values);
}
public static OAuth2AccessTokenResponse failed() {
return new OAuth2AccessTokenResponse(false);
}
}
| true |
c2c021cb329fa2440bdf4e488aace323c3b1c412 | Java | rvladi/pentago_game | /src/student_player/Node.java | UTF-8 | 4,443 | 3.140625 | 3 | [] | no_license | package student_player;
import java.util.Iterator;
import java.util.List;
import boardgame.Board;
import pentago_swap.PentagoBoardState;
import pentago_swap.PentagoMove;
public class Node implements Iterable<Node> {
private static final PentagoHeuristic HEURISTIC = getHeuristic();
private final PentagoMove previousMove;
private final PentagoBoardState boardState;
private final int studentPlayerID;
private final List<PentagoMove> legalMoves;
private final int depthLimit;
public Node(PentagoMove previousMove, PentagoBoardState boardState, int studentPlayerID) {
this.previousMove = previousMove;
this.boardState = boardState;
this.studentPlayerID = studentPlayerID;
legalMoves = boardState.getAllLegalMoves();
depthLimit = calculateDepthLimit(legalMoves.size());
}
private static PentagoHeuristic getHeuristic() {
CompositePentagoHeuristic heuristic = new CompositePentagoHeuristic();
heuristic.add(new PentagoHeuristic4And1EmptyOr5());
heuristic.add(new PentagoHeuristic3And2Empty());
return heuristic;
}
private static int calculateDepthLimit(int numLegalMoves) {
if (numLegalMoves <= 4 * 6) {
// 4 or fewer pieces left to play
return 4;
}
if (numLegalMoves <= 10 * 6) {
// 10 or fewer pieces left to play
return 3;
}
return 2;
}
/**
* @return the board state associated with this node
*/
public PentagoBoardState getBoardState() {
return boardState;
}
/**
* @return true if the board state associated with this node corresponds to an
* ended game (student player win, opponent win or draw); otherwise
* false
*/
public boolean isTerminal() {
return boardState.getWinner() != Board.NOBODY;
}
/**
* @return the score of the board state associated with this node; if the node
* is terminal, the score is 1 for student player win, 0 for opponent
* win and 0.5 for draw; otherwise it is calculated using heuristics
*/
public double getScore() {
int winner = boardState.getWinner();
if (winner == Board.NOBODY) {
return HEURISTIC.calculateScore(boardState, studentPlayerID);
}
if (winner == Board.DRAW) {
return 0.5;
}
return (winner == studentPlayerID) ? 1 : 0;
}
/**
* @return the move that generated the board state associated with this node
*/
public PentagoMove getPreviousMove() {
return previousMove;
}
/**
* @return the next best move for the student player
*/
public PentagoMove getNextMove() {
Pair<Node, Double> maxScore = alphaBetaSearch();
return maxScore.key.getPreviousMove();
}
private Pair<Node, Double> alphaBetaSearch() {
double alpha = Double.NEGATIVE_INFINITY;
double beta = Double.POSITIVE_INFINITY;
return maxScore(0, alpha, beta);
}
private Pair<Node, Double> maxScore(int depth, double alpha, double beta) {
if (depth >= depthLimit || isTerminal()) {
return new Pair<>(this, getScore());
}
Pair<Node, Double> maxScore = new Pair<>(null, Double.NEGATIVE_INFINITY);
for (Node child : this) {
Pair<Node, Double> childScore = child.minScore(depth + 1, alpha, beta);
if (childScore.value > maxScore.value) {
maxScore.value = childScore.value;
maxScore.key = child;
}
if (maxScore.value > alpha) {
alpha = maxScore.value;
}
if (alpha >= beta) {
break;
}
}
return maxScore;
}
private Pair<Node, Double> minScore(int depth, double alpha, double beta) {
if (depth >= depthLimit || isTerminal()) {
return new Pair<>(this, getScore());
}
Pair<Node, Double> minScore = new Pair<>(null, Double.POSITIVE_INFINITY);
for (Node child : this) {
Pair<Node, Double> childScore = child.maxScore(depth + 1, alpha, beta);
if (childScore.value < minScore.value) {
minScore.value = childScore.value;
minScore.key = child;
}
if (minScore.value < beta) {
beta = minScore.value;
}
if (alpha >= beta) {
break;
}
}
return minScore;
}
@Override
public Iterator<Node> iterator() {
return new NodeIterator();
}
private class NodeIterator implements Iterator<Node> {
private final Iterator<PentagoMove> movesIter = legalMoves.iterator();
@Override
public boolean hasNext() {
return movesIter.hasNext();
}
@Override
public Node next() {
PentagoMove move = movesIter.next();
PentagoBoardState state = (PentagoBoardState) boardState.clone();
state.processMove(move);
return new Node(move, state, studentPlayerID);
}
}
}
| true |
6a783384c4d3da4fce23cdf03907ec171d40bd47 | Java | xcking/recruit01 | /Recruit01/src/com/cx/dao/DriverDao.java | GB18030 | 519 | 2.046875 | 2 | [] | no_license | package com.cx.dao;
import com.cx.entity.Driver;
import com.cx.entity.Driverdetails;
public interface DriverDao {
public Driver findDriverById(int driverId); // idѯû
public Driver findDriverByAccount(String driverAccount); //˻ѯû
public void addDriver(Driver driver);
public void deleteDriver(int driverId);
public void updateDriver(Driver driver);
public void updateDriverDetails(Driverdetails driverdetails,int driverId); //ûϸϢ
}
| true |
2eb1ffde7f3bcefbc2747a10a7e802d6b6c03f4e | Java | osmanaldiyar/Encharity-v1-Client-Android- | /app/src/main/java/com/encharity/encharity_v1/fragments/UrgentPatientsFragment.java | UTF-8 | 4,665 | 2.0625 | 2 | [] | no_license | package com.encharity.encharity_v1.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.encharity.encharity_v1.R;
import com.encharity.encharity_v1.UrgentPatientDetailsActivity;
import com.encharity.encharity_v1.api.APIUtils;
import com.encharity.encharity_v1.api.UrgentPatientService;
import com.encharity.encharity_v1.entities.UrgentPatient;
import com.encharity.encharity_v1.recyclerViewAdapter.UrgentPatientsAdapter;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* A simple {@link Fragment} subclass.
*/
public class UrgentPatientsFragment extends Fragment {
private List<UrgentPatient> urgentPatientList;
public UrgentPatientsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView urgentPatientsRecycler = (RecyclerView)inflater.inflate(R.layout.fragment_urgent, container,
false);
urgentPatientList = new ArrayList<>();
/*String[] cities = new String[UrgentPatient.URGENT_PATIENTS.length];
String[] daysLeft = new String[UrgentPatient.URGENT_PATIENTS.length];
String[] fundsPercentage = new String[UrgentPatient.URGENT_PATIENTS.length];
String[] totalTenge = new String[UrgentPatient.URGENT_PATIENTS.length];
String[] adultsDescription = new String[UrgentPatient.URGENT_PATIENTS.length];
String[] adultsCategory = new String[UrgentPatient.URGENT_PATIENTS.length];
String[] adultsNames = new String[UrgentPatient.URGENT_PATIENTS.length];
int[] adultsImages = new int[UrgentPatient.URGENT_PATIENTS.length];
for(int i = 0; i < UrgentPatient.URGENT_PATIENTS.length; i++){
adultsNames[i] = UrgentPatient.URGENT_PATIENTS[i].getFullname();
adultsImages[i] = UrgentPatient.URGENT_PATIENTS[i].getPhotoId();
adultsCategory[i] = UrgentPatient.URGENT_PATIENTS[i].getCategory();
adultsDescription[i] = UrgentPatient.URGENT_PATIENTS[i].getDescription();
totalTenge[i] = UrgentPatient.URGENT_PATIENTS[i].getTotalTenge();
fundsPercentage[i] = UrgentPatient.URGENT_PATIENTS[i].getFundedPercent();
daysLeft[i] = UrgentPatient.URGENT_PATIENTS[i].getDaysLeft();
cities[i] = UrgentPatient.URGENT_PATIENTS[i].getCity();
}*/
UrgentPatientService urgentPatientService = APIUtils.getUrgentPatientService();
Call<List<UrgentPatient>> repos = urgentPatientService.getAllUrgentPatients();
final UrgentPatientsAdapter adapter = new UrgentPatientsAdapter(urgentPatientList/*adultsNames,adultsImages,adultsCategory,
adultsDescription,totalTenge,fundsPercentage,daysLeft,cities*/);
repos.enqueue(new Callback<List<UrgentPatient>>() {
@Override
public void onResponse(Call<List<UrgentPatient>> call, Response<List<UrgentPatient>> response) {
Toast.makeText(getActivity(), String.format("OK"), Toast.LENGTH_SHORT).show();
if(response.isSuccessful()) {
urgentPatientList = response.body();
adapter.setUrgentPatientsList(urgentPatientList);
}
}
@Override
public void onFailure(Call<List<UrgentPatient>> call, Throwable t) {
Toast.makeText(getActivity(), String.format("Please, check internet connection."), Toast.LENGTH_SHORT).show();
}
});
urgentPatientsRecycler.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
urgentPatientsRecycler.setLayoutManager(layoutManager);
adapter.setListener(new UrgentPatientsAdapter.Listener() {
@Override
public void onClick(int position) {
Intent intent = new Intent(getActivity(),UrgentPatientDetailsActivity.class);
intent.putExtra(UrgentPatientDetailsActivity.EXTRA_URGENT_PATIENT_ID, position);
getActivity().startActivity(intent);
}
});
return urgentPatientsRecycler;
}
}
| true |
95225f143f7f37c5547b71af219195759254740c | Java | zhaohangbo/LeetCode | /src/main/java/P191_Numberof1Bits.java | UTF-8 | 344 | 2.671875 | 3 | [] | no_license |
public class P191_Numberof1Bits {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count =0;
while(n!=0){
count +=(n & 1);
n=n>>>1;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// int a = 2147483648;
}
}
| true |
eea52ccded79ad5b470def7fa043b9a641252385 | Java | Nata8/Bioinformatics_toolbox_2nd | /src/msa/model/BlosumMatrix.java | UTF-8 | 2,398 | 3.28125 | 3 | [] | no_license | package msa.model;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class BlosumMatrix {
private List<List<Integer>> matrix;
/**
* load data from txt file and save them to list
* @throws IOException
*/
public void loadMatrix() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("matrix.txt"));
this.matrix = new ArrayList<>();
String st = null;
int row = 0;
while((st = br.readLine()) != null) {
String[] numbers = st.split(" ");
this.matrix.add(new ArrayList<>());
for (int i = 0; i < numbers.length; i++) {
if (!numbers[i].equals(""))
this.matrix.get(row).add(Integer.parseInt(numbers[i]));
}
row++;
}
int b = 0;
}
/**
* @param a
* @return index of amino acid
*/
private Integer getIndex(char a) {
switch ((String.valueOf(a)).toUpperCase().charAt(0)) {
case 'A': return 0;
case 'R': return 1;
case 'N': return 2;
case 'D': return 3;
case 'C': return 4;
case 'Q': return 5;
case 'E': return 6;
case 'G': return 7;
case 'H': return 8;
case 'I': return 9;
case 'L': return 10;
case 'K': return 11;
case 'M': return 12;
case 'F': return 13;
case 'P': return 14;
case 'S': return 15;
case 'T': return 16;
case 'W': return 17;
case 'Y': return 18;
case 'V': return 19;
default: return null;
}
}
public List<List<Integer>> getMatrix() {
return matrix;
}
/**
* @param i
* @param j
* @return matrix score for two amino acids
*/
private Integer getDistance(int i, int j) {
return (i >= 0 && i < matrix.size()) && (j >= 0 && j < matrix.size()) ? matrix.get(i).get(j) : null;
}
/**
* @param a1
* @param a2
* @return matrix score for two amino acids
*/
public Integer getDistance(char a1, char a2) {
return getIndex(a1) != null && getIndex(a2) != null ? getDistance(getIndex(a1),getIndex(a2)) : null;
}
}
| true |
106d53700efd9b18c512c37e9e30b69bc81306e7 | Java | swathibandi173/Ecommerce | /OrderService/src/main/java/com/orderservice/application/model/CartDetails.java | UTF-8 | 1,060 | 2.078125 | 2 | [] | no_license | package com.orderservice.application.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name="cart_details")
public class CartDetails
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="cartdetails_id")
private long cartDetailsId;
@Column(name="quantity")
private int quantity;
@JoinColumn(name="product_id")
private String productId;
@Column(name="price")
private double price;
@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name="cart_id")
private Cart cart;
}
| true |
c63374aae2c0477919064b188bbf2466785b6db7 | Java | rura6502/repo.rura6502.github.io | /Spring-jpa Projects/jpa_01_repository_04_exception/src/main/java/io/github/rura6502/jpa_01_repository_04_exception/TestObjDao.java | UTF-8 | 258 | 1.882813 | 2 | [
"MIT"
] | permissive | package io.github.rura6502.jpa_01_repository_04_exception;
import java.util.Optional;
/**
* TestObjDao
*/
public interface TestObjDao {
TestObj save(TestObj testObj);
Optional<TestObj> findById(Long testObjId);
TestObj findByName(String name);
} | true |
587d31a547599716534000d2a9c32b9459a8b312 | Java | GreedyWang/sdaac | /src/sdaac/wym/app/Dao/hr/OrganizationStructureDao.java | UTF-8 | 866 | 2.0625 | 2 | [] | no_license | package sdaac.wym.app.Dao.hr;
import java.util.List;
import sdaac.wym.app.entity.hr.OrganizationStructure;
import common.dao.impl.CommonSpringDAOImpl;
public class OrganizationStructureDao extends CommonSpringDAOImpl<OrganizationStructure> implements IOrganizationStructure {
public OrganizationStructureDao(String className)
throws InstantiationException, IllegalAccessException {
super(className);
// TODO Auto-generated constructor stub
}
public List<Integer[]> getPostion() {
// TODO Auto-generated method stub
String hql="select os.postionAx,os.postionAy from OrganizationStructure as os";
return this.getHibernateTemplate().find(hql);
}
public List<String[]> getNames() {
// TODO Auto-generated method stub
String hql="select os.id,os.context from OrganizationStructure as os";
return this.getHibernateTemplate().find(hql);
}
}
| true |
6344f4b0bdcafe5560840508cfcdfa3d513044fe | Java | chaws/sanshack | /SantaGram/SantaGram_4.2.src/android/support/v7/widget/ab.java | UTF-8 | 2,402 | 1.679688 | 2 | [] | no_license | package android.support.v7.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.support.v4.j.ac;
import android.util.AttributeSet;
import android.widget.TextView;
public class ab
extends TextView
implements ac
{
private m a = m.a();
private h b = new h(this, this.a);
private z c;
public ab(Context paramContext)
{
this(paramContext, null);
}
public ab(Context paramContext, AttributeSet paramAttributeSet)
{
this(paramContext, paramAttributeSet, 16842884);
}
public ab(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(ay.a(paramContext), paramAttributeSet, paramInt);
this.b.a(paramAttributeSet, paramInt);
this.c = z.a(this);
this.c.a(paramAttributeSet, paramInt);
this.c.a();
}
protected void drawableStateChanged()
{
super.drawableStateChanged();
if (this.b != null) {
this.b.c();
}
if (this.c != null) {
this.c.a();
}
}
public ColorStateList getSupportBackgroundTintList()
{
if (this.b != null) {
return this.b.a();
}
return null;
}
public PorterDuff.Mode getSupportBackgroundTintMode()
{
if (this.b != null) {
return this.b.b();
}
return null;
}
public void setBackgroundDrawable(Drawable paramDrawable)
{
super.setBackgroundDrawable(paramDrawable);
if (this.b != null) {
this.b.a(paramDrawable);
}
}
public void setBackgroundResource(int paramInt)
{
super.setBackgroundResource(paramInt);
if (this.b != null) {
this.b.a(paramInt);
}
}
public void setSupportBackgroundTintList(ColorStateList paramColorStateList)
{
if (this.b != null) {
this.b.a(paramColorStateList);
}
}
public void setSupportBackgroundTintMode(PorterDuff.Mode paramMode)
{
if (this.b != null) {
this.b.a(paramMode);
}
}
public void setTextAppearance(Context paramContext, int paramInt)
{
super.setTextAppearance(paramContext, paramInt);
if (this.c != null) {
this.c.a(paramContext, paramInt);
}
}
}
/* Location: /home/cdo/tmp/sanshack/SantaGram_4.2-dex2jar.jar!/android/support/v7/widget/ab.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
87325a443d42bd969fa9fc974d70e99a0ea9ea35 | Java | cha63506/CompSecurity | /GoogleWallet_source/src/com/google/common/collect/ImmutableBiMap.java | UTF-8 | 2,158 | 2.359375 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.common.collect;
import java.util.Collection;
// Referenced classes of package com.google.common.collect:
// ImmutableMap, BiMap, EmptyImmutableBiMap, SingletonImmutableBiMap,
// ImmutableSet, ImmutableCollection, RegularImmutableBiMap
public abstract class ImmutableBiMap extends ImmutableMap
implements BiMap
{
public static final class Builder extends ImmutableMap.Builder
{
public final ImmutableBiMap build()
{
switch (size)
{
default:
return new RegularImmutableBiMap(size, entries);
case 0: // '\0'
return ImmutableBiMap.of();
case 1: // '\001'
return ImmutableBiMap.of(entries[0].getKey(), entries[0].getValue());
}
}
public final volatile ImmutableMap build()
{
return build();
}
public final Builder put(Object obj, Object obj1)
{
super.put(obj, obj1);
return this;
}
public final volatile ImmutableMap.Builder put(Object obj, Object obj1)
{
return put(obj, obj1);
}
public Builder()
{
}
}
private static final java.util.Map.Entry EMPTY_ENTRY_ARRAY[] = new java.util.Map.Entry[0];
ImmutableBiMap()
{
}
public static Builder builder()
{
return new Builder();
}
public static ImmutableBiMap of()
{
return EmptyImmutableBiMap.INSTANCE;
}
public static ImmutableBiMap of(Object obj, Object obj1)
{
return new SingletonImmutableBiMap(obj, obj1);
}
private ImmutableSet values()
{
return inverse().keySet();
}
public abstract ImmutableBiMap inverse();
public final volatile ImmutableCollection values()
{
return values();
}
public volatile Collection values()
{
return values();
}
}
| true |
aad23d0551c85b01215eaef58b4abb660da58931 | Java | rodrigogregorioneri/MyFilmesClient | /app/src/main/java/model/AutenticarModel.java | UTF-8 | 681 | 2.140625 | 2 | [] | no_license | package model;
import java.util.HashMap;
import java.util.Map;
public class AutenticarModel {
private Boolean success;
private String expiresAt;
private String requestToken;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(String expiresAt) {
this.expiresAt = expiresAt;
}
public String getRequestToken() {
return requestToken;
}
public void setRequestToken(String requestToken) {
this.requestToken = requestToken;
}
}
| true |
99233ce1fbb24dc89888377eaba65d8837d57831 | Java | LuizRC/springboot | /paginacao/src/main/java/br/org/estudos/backend/repository/FotoRepository.java | UTF-8 | 220 | 1.601563 | 2 | [] | no_license | package br.org.estudos.backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import br.org.estudos.backend.model.Foto;
public interface FotoRepository extends JpaRepository<Foto, Long>{
}
| true |
302814996e08cbc628d83a1196b116ec4cda9d11 | Java | yawkat/Columbus | /src/main/java/at/yawk/columbus/Lighter.java | UTF-8 | 1,582 | 2.609375 | 3 | [] | no_license | package at.yawk.columbus;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Value;
import org.apache.mahout.math.map.AbstractIntObjectMap;
import org.apache.mahout.math.map.OpenIntObjectHashMap;
/**
* Object that stores data about different block IDs and their properties, particularly light values.
*/
@Getter(AccessLevel.PRIVATE)
public class Lighter {
/**
* Known block data.
*/
private final AbstractIntObjectMap<BlockLightData> blocks = new OpenIntObjectHashMap<>();
private final int[] lightUpdateBlockList = new int[32768];
/**
* Return either the light data for the given ID or the default light data if it is unknown.
*/
private BlockLightData lookup(int id) {
return this.getBlocks().containsKey(id) ? this.getBlocks().get(id) : BlockLightData.DEFAULT;
}
/**
* Set the lighting data for the given block ID.
*/
public void putBlockLightData(int blockId, int opacity, int brightness) {
this.getBlocks().put(blockId, new BlockLightData(opacity, brightness));
}
/**
* Returns the opacity of the given block ID.
*/
public int getOpacity(int blockId) {
return this.lookup(blockId).getOpacity();
}
/**
* Insert the default lighting values.
*/
public void putDefaultBlockLightData() {
Tables.putDefaultLightValues(this);
}
@Value
private static final class BlockLightData {
private static final BlockLightData DEFAULT = new BlockLightData(0, 0);
int opacity;
int brightness;
}
}
| true |
a0f720b3de62850940be368ff3fc92c8f427e648 | Java | AdhamNour/ThreeTierPowerStationMonitoringApplication | /models/powerstation/Sensor.java | UTF-8 | 508 | 3.015625 | 3 | [] | no_license | package models.powerstation;
import java.util.*;
public class Sensor {
private float maxReading;
private Random rand;
public Sensor(float MaxReading){
this.maxReading = MaxReading;
rand = new Random();
}
public float getSensorReading(){
return rand.nextFloat()*maxReading;
}
public float getMaxReading() {
return maxReading;
}
public void setMaxReading(float MaxReading){
this.maxReading =Math.max(MaxReading, 2);
}
}
| true |
8b44d425392cf1af53a0394978b7cc9996fa30be | Java | iAnimo/mycodes | /mprojects/m052.java | UTF-8 | 595 | 2.59375 | 3 | [] | no_license | package mprojects;
import utils.ListNode;
public class m052 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode indexA = headA;
ListNode indexB = headB;
while ( indexA != indexB ) {
if ( indexA == null ) {
indexA = headB;
} else {
indexA = indexA.next;
}
if ( indexB == null ) {
indexB = headA;
} else {
indexB = indexB.next;
}
}
return indexA;
}
}
| true |
ebf63d5bc5bc634a86f173a37fbf09eff0e96890 | Java | shallshadow/CodeingInterviewGuide | /src/main/java/dp/JumpGame.java | UTF-8 | 824 | 3.875 | 4 | [] | no_license |
package dp;
/**
* @fun 问题描述:给定数组arr,arr[i]==k代表可以从位置i向右跳1~k个距离。如果从位置0出发,返回最少跳几次能跳到arr最后的位置上。
* @author shadow
* @Date 2016年9月17日下午8:01:39
* @version 1.0
* @since
**/
public class JumpGame {
public static void main(String[] args) {
int[] arr = {3,2,3,1,1,4,5,6,1,1,2,1};
System.out.println("Jump " + new JumpGame().jump(arr));
}
/**
* 核心思想就是使跳跃范围最大。
* @param arr
* @return
*/
public int jump(int[] arr){
if(arr == null || arr.length == 0){
return 0;
}
int jump = 0;
int cur = 0;
int next = 0;
for(int i = 0; i < arr.length; i++){
if(cur < i){
jump++;
cur = next;
}
next = Math.max(next, i + arr[i]);
}
return jump;
}
}
| true |
eccae53f7ee56e8667956051371cea8bca141e44 | Java | xxc2016/ETime_Server | /E_TimeServer/src/service/PostDetailService.java | GB18030 | 10,981 | 2.234375 | 2 | [] | no_license | package service;
import java.sql.Statement;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.sql.ResultSet;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import bean.PostDetailBean;
import bean.TraceBean;
import bean.TraceBean.Trace;
import database.JDBCConn;
public class PostDetailService {
public Statement Statement = null;//Э preparedStatement Statement ƹܸısql
public PreparedStatement preparedStatement = null;
public ResultSet resultSet = null;
static private final Object PostLock = new Object();
public PostDetailBean upStorePostDetailService(String userId,String title,String content,String time
,String pic,String date,List<String> imagePath,List<String> imagePath_src)
{
String sql_i_image = "insert into PostDetailPic(detailId,picId,url) values(?,?,?)";
String sql_i_pic = "insert into picSrcList(srcPic,compressPic) values(?,?)";
synchronized(PostLock)
{
boolean isSuccess = false;
if(userId!=null)
{
userId = "'"+userId+"'";
}
if(title!=null)
{
title = "'"+title+"'";
}
if(content!=null)
{
content = "'"+content+"'";
}
if(time!=null)
{
time = "'"+time+"'";
}
if(pic!=null)
{
pic = "'"+pic+"'";
}
if(date!=null)
{
date = "'"+date+"'";
}
String sql_i = " insert into PostDetail(userId,title,pic,time,content,date)"
+ " values( "+userId+","
+ title + ","
+pic+ ","
+time+","
+content+","
+date+")";
String sql_q = " SELECT SCOPE_IDENTITY() ";
Connection conn = JDBCConn.getConnection();
try
{
System.out.println(sql_i);
Statement = conn.createStatement();
Statement.execute(sql_i);
resultSet = Statement.executeQuery(sql_q);
int index;
int watch = 0;
int remark = 0;
if(resultSet.next())
{
index = resultSet.getInt(1);
System.out.println("index:"+index);
String sql_i_detail = "insert into Post(detailId,watch,remark) values("
+index+","
+watch+","
+remark+")";
Statement.execute(sql_i_detail);
if(imagePath!=null)
{
for(int i=0;i<imagePath.size();i++)
{
String picPath = imagePath.get(i);
String picPath_src = imagePath_src.get(i);
preparedStatement = conn.prepareStatement(sql_i_image);
preparedStatement.setInt(1, index);
preparedStatement.setInt(2, i);
preparedStatement.setString(3, picPath);
preparedStatement.execute();
preparedStatement = conn.prepareStatement(sql_i_pic);
preparedStatement.setString(1,picPath_src);
preparedStatement.setString(2,picPath);
preparedStatement.execute();
preparedStatement.close();
}
}
}
isSuccess = true;
Statement.close();
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
PostDetailBean askPostDetailBean = new PostDetailBean();
if(isSuccess)
{
askPostDetailBean.setResponseCode(PostDetailBean.POST_DETAIL_UP_STORE_RESPONSE_SUCCESSED);
}
else
{
askPostDetailBean.setResponseCode(PostDetailBean.POST_DETAIL_UP_STORE_RESPONSE_FAILED);
}
return askPostDetailBean;
}
}
public PostDetailBean downLoadPostDetailService(int DetailId)
{
boolean isSuccess = false;
String sql_q = "select * from PostDetail where detailId = ?";
String sql_q_user = "select * from userImage where userId = ?";
String sql_q_remark = "select * from Remark where detailId = ?";
String sql_q_image = "select * from PostDetailPic where detailId = ? order by picId asc";
String sql_u = "update Post set watch = watch+1 where detailId = ?";
String sql_q_post = "select * from Post where detailId = ?";
String sql_q_remark_image = "select * from RemarkPic where remarkId = ?";
PostDetailBean askPostDetailBean = new PostDetailBean();
try
{
Connection conn = JDBCConn.getConnection();
preparedStatement = conn.prepareStatement(sql_u);
preparedStatement.setInt(1, DetailId);
preparedStatement.execute();//ۿһ
preparedStatement = conn.prepareStatement(sql_q);
preparedStatement.setInt(1,DetailId);
resultSet = preparedStatement.executeQuery();
if(resultSet.next())//postDetail
{
String userId = resultSet.getString("userId");
String title = resultSet.getString("title");
String pic = resultSet.getString("pic");
String time = resultSet.getString("time");
String date = resultSet.getString("date");
String content = resultSet.getString("content");
askPostDetailBean.setDetailId(DetailId);
askPostDetailBean.setTitle(title);
askPostDetailBean.setTime(time);
askPostDetailBean.setContent(content);
askPostDetailBean.setDate(date);
PostDetailBean.Remark.User user = new PostDetailBean.Remark.User();
askPostDetailBean.user = user;
LinkedList<PostDetailBean.Remark> remarkList = new LinkedList<PostDetailBean.Remark>();
askPostDetailBean.setRemarkList(remarkList);
LinkedList<String> bitmapPath = new LinkedList<String>();
askPostDetailBean.setBitmapPath(bitmapPath);
preparedStatement = conn.prepareStatement(sql_q_image);
preparedStatement.setInt(1,DetailId);
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
String picPath = resultSet.getString("url");
bitmapPath.add(picPath);
}
preparedStatement = conn.prepareStatement(sql_q_post);
preparedStatement.setInt(1,DetailId);
resultSet = preparedStatement.executeQuery();
if(resultSet.next())//postId
{
int postId = resultSet.getInt("postId");
askPostDetailBean.setPostId(postId);
}
preparedStatement = conn.prepareStatement(sql_q_user);
preparedStatement.setString(1,userId);
resultSet = preparedStatement.executeQuery();
if(resultSet.next())//userImage
{
String nickName = resultSet.getString("userName");
String head = resultSet.getString("userImagePath");
user.account = userId;
user.head = head;
user.nickName = nickName;
askPostDetailBean.user = user;
preparedStatement = conn.prepareStatement(sql_q_remark);
preparedStatement.setInt(1,DetailId);
resultSet = preparedStatement.executeQuery();
while(resultSet.next())//remark
{
PostDetailBean.Remark r = new PostDetailBean.Remark();
String userId_r = resultSet.getString("userId");
int remarkId_r = resultSet.getInt("remarkId");
String time_r = resultSet.getString("time");
String date_r = resultSet.getString("date");
String content_r = resultSet.getString("content");
r.content = content_r;
r.detailId = DetailId;
r.remarkId = remarkId_r;
r.time = time_r;
r.date = date_r;
PostDetailBean.Remark.User user_r = new PostDetailBean.Remark.User();
user_r.account = userId_r;
r.user =user_r;
remarkList.add(r);
}
int length = remarkList.size();
for(int i=0;i<length;i++)//remarkеuserImage
{
String userId_r_u = remarkList.get(i).user.account;
preparedStatement = conn.prepareStatement(sql_q_user);
preparedStatement.setString(1,userId_r_u);
resultSet = preparedStatement.executeQuery();
if(resultSet.next())
{
String nickName_r_u = resultSet.getString("userName");
String head_r_u = resultSet.getString("userImagePath");
remarkList.get(i).user.head = head_r_u;
remarkList.get(i).user.nickName = nickName_r_u;
}
}
for(int i=0;i<length;i++)
{
int remarkId = remarkList.get(i).remarkId;
LinkedList<String> remarkPicList = new LinkedList<String>();
remarkList.get(i).bitmapPath = remarkPicList;
preparedStatement = conn.prepareStatement(sql_q_remark_image);
preparedStatement.setInt(1, remarkId);
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
String picPath = resultSet.getString("url");
remarkPicList.add(picPath);
}
}
isSuccess = true;
}
}
preparedStatement.close();
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
if(isSuccess)
{
askPostDetailBean.setResponseCode(PostDetailBean.POST_DETAIL_DOWN_LOAD_RESPONSE_SUCCESSED);
}
else
{
askPostDetailBean.setResponseCode(PostDetailBean.POST_DETAIL_DOWN_LOAD_RESPONSE_FAILED);
}
return askPostDetailBean;
}
public PostDetailBean deletePostDetailService(int DetailId)
{
boolean isSuccess = false;
String sql_d_postDetail = "delete from PostDetail where detailId = ?";
String sql_d_remark = "delete from Remark where detailId = ?";
String sql_d_post = "delete from Post where detailId = ?";
String sql_d_image = "delete from PostDetailPic where detailId = ?";
PostDetailBean askPostDetailBean = new PostDetailBean();
try
{
Connection conn = JDBCConn.getConnection();
preparedStatement = conn.prepareStatement(sql_d_post);
preparedStatement.setInt(1,DetailId);
preparedStatement.execute();
preparedStatement = conn.prepareStatement(sql_d_image);
preparedStatement.setInt(1,DetailId);
preparedStatement.execute();
preparedStatement = conn.prepareStatement(sql_d_remark);
preparedStatement.setInt(1,DetailId);
preparedStatement.execute();
preparedStatement = conn.prepareStatement(sql_d_postDetail);
preparedStatement.setInt(1,DetailId);
preparedStatement.execute();
isSuccess = true;
preparedStatement.close();
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
if(isSuccess)
{
askPostDetailBean.setResponseCode(PostDetailBean.POST_DETAIL_DELETE_RESPONSE_SUCCESSED);
}
else
{
askPostDetailBean.setResponseCode(PostDetailBean.POST_DETAIL_DELETE_RESPONSE_FAILED);
}
return askPostDetailBean;
}
}
| true |
261f58bab525e9a0eb8e9a32b0e650063aa3a5ca | Java | wuzhenping/crm | /back/src/main/java/com/msy/plus/util/Config.java | UTF-8 | 4,715 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | package com.msy.plus.util;
import com.google.common.collect.Maps;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import javax.servlet.ServletContext;
import java.text.MessageFormat;
import java.util.Map;
import java.util.Properties;
public class Config {
/**
* 当前对象实例
*/
private static Config CONFIG = new Config();
/**
* 保存全局属性值
*/
private static Map<String, String> map = Maps.newHashMap();
/**
* 属性文件加载对象
*/
private static PropertiesLoader loader;
/**
* 上传文件基础虚拟路径
*/
public static final String USERFILES_BASE_URL = "/userfiles/";
private static boolean inited = false;
private static String path = "classpath*:*.properties";
public static void init() {
if (!inited) {
map = Maps.newHashMap();
loader = new PropertiesLoader(path);
inited = true;
}
}
/**
* 获取当前对象实例
*/
public static Config getInstance() {
return CONFIG;
}
/**
* 获取配置
*/
public static String get(String key) {
init();
Validate.notNull(map);
String value = map.get(key);
if (value == null) {
Validate.notNull(loader);
value = loader.getProperty(key);
map.put(key, value != null ? value : StringUtils.EMPTY);
}
return value;
}
public static String get(String key, Object...args) {
return MessageFormat.format(get(key), args);
}
/**
* 获取管理端根路径
*/
public static String getAdminPath() {
return get("adminPath");
}
/**
* 获取前端根路径
*/
public static String getFrontPath() {
return get("frontPath");
}
/**
* 获取URL后缀
*/
public static String getUrlSuffix() {
return get("urlSuffix");
}
/**
* 是否是演示模式,演示模式下不能修改用户、角色、密码、菜单、授权
*/
public static Boolean isDemoMode() {
String dm = get("demoMode");
return "true".equals(dm) || "1".equals(dm);
}
/**
* 在修改系统用户和角色时是否同步到Activiti
*/
public static Boolean isSynActivitiIndetity() {
String dm = get("activiti.isSynActivitiIndetity");
return "true".equals(dm) || "1".equals(dm);
}
/**
* 页面获取常量
*/
public static Object getConst(String field) {
try {
return Config.class.getField(field).get(null);
} catch (Exception e) {
// 异常代表无配置,这里什么也不做
}
return null;
}
/**
* 获取上传文件的根目录
*
* @return
*/
public static String getUserfilesBaseDir() {
String dir = get("userfiles.basedir");
if (StringUtils.isBlank(dir)) {
try {
// dir = ServletContextFactory.getServletContext().getRealPath("/");
dir = getServletContext().getRealPath("/");
} catch (Exception e) {
return "";
}
}
dir = FilenameUtils.normalize(dir, true);
if (!dir.endsWith("/")) {
dir += "/";
}
// System.out.println("userfiles.basedir: " + dir);
return dir;
}
/**
* 获取工程路径
*
* @return
*/
public static String getProjectPath() {
// 如果配置了工程路径,则直接返回,否则自动获取。
String projectPath = System.getProperty("");
return projectPath;
}
/**
* 是否生产环境
*/
public static boolean isProdMode() {
return "prod".equals(get("spring.profiles.env"));
}
/**
* 是否测试环境
*/
public static boolean isTestMode() {
return "test".equals(get("spring.profiles.env"));
}
/**
* 是否开发环境
*/
public static boolean isDevMode() {
return "dev".equals(get("spring.profiles.env"));
}
private ServletContext servletContext;
public static String contextPath() {
return getServletContext().getContextPath();
}
public static ServletContext getServletContext() {
return CONFIG.servletContext;
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public static Properties getPrperties() {
init();
return Config.loader.getProperties();
}
}
| true |
df62c8d1b08aee7e88d2eea35244005341a99490 | Java | tangguoqiang/htwebExtra | /src/main/java/com/ht/extra/pojo/comm/TableMaintRec.java | UTF-8 | 1,444 | 2.03125 | 2 | [] | no_license | package com.ht.extra.pojo.comm;
public class TableMaintRec extends TableMaintRecKey {
private String tableChineseName;
private String contentBeforeMaint;
private String contentAfterMaint;
private String correlativeSoftware;
private String memo;
public String getTableChineseName() {
return tableChineseName;
}
public void setTableChineseName(String tableChineseName) {
this.tableChineseName = tableChineseName == null ? null : tableChineseName.trim();
}
public String getContentBeforeMaint() {
return contentBeforeMaint;
}
public void setContentBeforeMaint(String contentBeforeMaint) {
this.contentBeforeMaint = contentBeforeMaint == null ? null : contentBeforeMaint.trim();
}
public String getContentAfterMaint() {
return contentAfterMaint;
}
public void setContentAfterMaint(String contentAfterMaint) {
this.contentAfterMaint = contentAfterMaint == null ? null : contentAfterMaint.trim();
}
public String getCorrelativeSoftware() {
return correlativeSoftware;
}
public void setCorrelativeSoftware(String correlativeSoftware) {
this.correlativeSoftware = correlativeSoftware == null ? null : correlativeSoftware.trim();
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo == null ? null : memo.trim();
}
} | true |
682441cd34ca611431e866df788a43d383b9a888 | Java | samsularifin1993/bilibili-angular-spring | /src/main/java/com/core/web/service/storage/FileSystemStorageService.java | UTF-8 | 3,822 | 2.453125 | 2 | [] | no_license | package com.core.web.service.storage;
import com.core.web.error.storage.StorageException;
import com.core.web.error.storage.StorageFileNotFoundException;
import com.core.web.util.FastestHash;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
import java.util.stream.Stream;
@Service
class FileSystemStorageService implements StorageService {
private final StorageProperties storageProperties;
public FileSystemStorageService(StorageProperties properties) {
this.storageProperties = properties;
this.init();
}
@Override
public String store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
final String extension = FilenameUtils.getExtension(filename);
// get system temporary directory
final Path temp = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
try (InputStream inputStream = file.getInputStream()) {
final FastestHash hashGenerator = new FastestHash();
Files.copy(new InputStream() {
@Override
public int read() throws IOException {
int retVal = inputStream.read();
if (retVal > -1) {
hashGenerator.digest((byte) retVal);
}
return retVal;
}
}, temp, StandardCopyOption.REPLACE_EXISTING);
filename = String.valueOf(Long.toHexString(hashGenerator.hash())) + "." + extension;
Files.move(temp, this.storageProperties.getLocation().resolve(filename));
return filename;
}
} catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.storageProperties.getLocation(), 1)
.filter(path -> !path.equals(this.storageProperties.getLocation()))
.map(this.storageProperties.getLocation()::relativize);
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
public Path load(String filename) {
return this.storageProperties.getLocation().resolve(filename);
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new StorageFileNotFoundException("Could not read file: " + filename);
}
} catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
public void init() {
try {
Files.createDirectories(this.storageProperties.getLocation());
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
| true |
135810402b9f8c7d069c29230a6a676986ed7752 | Java | gordonhtfu/LearnCantonese | /libcommonui/src/main/java/com/blackberry/common/ui/tree/TreeViewList.java | UTF-8 | 7,235 | 1.851563 | 2 | [] | no_license | /*
* Copyright (c) 2011, Polidea
*
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.
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 HOLDER 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.
https://github.com/Polidea/tree-view-list-android/blob/master/LICENCE.txt
*/
package com.blackberry.common.ui.tree;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.blackberry.common.ui.R;
/**
* Tree view, expandable multi-level.
*
* <pre>
* attr ref com.blackberry.ui.R.styleable#TreeViewList_collapsible
* attr ref com.blackberry.ui.R.styleable#TreeViewList_src_expanded
* attr ref com.blackberry.ui.R.styleable#TreeViewList_src_collapsed
* attr ref com.blackberry.ui.R.styleable#TreeViewList_indent_width
* attr ref com.blackberry.ui.R.styleable#TreeViewList_indicator_gravity
* attr ref com.blackberry.ui.R.styleable#TreeViewList_indicator_background
* attr ref com.blackberry.ui.R.styleable#TreeViewList_row_background
* </pre>
*/
public class TreeViewList extends ListView {
private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed;
private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded;
private static final int DEFAULT_INDENT = 0;
private static final int DEFAULT_GRAVITY = Gravity.START | Gravity.CENTER_VERTICAL;
private Drawable mExpandedDrawable;
private Drawable mCollapsedDrawable;
private Drawable mRowBackgroundDrawable;
private Drawable mIndicatorBackgroundDrawable;
private int mIndentWidth = 0;
private int mIndicatorGravity = 0;
private AbstractTreeViewAdapter<?> mTreeAdapter;
private boolean mCollapsible;
public TreeViewList(Context context) {
this(context, null);
}
public TreeViewList(Context context, AttributeSet attrs) {
this(context, attrs, R.style.TreeViewListStyle);
}
public TreeViewList(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
parseAttributes(context, attrs);
}
private void parseAttributes(final Context context, final AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TreeViewList);
mExpandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded);
if (mExpandedDrawable == null) {
mExpandedDrawable = context.getResources().getDrawable(DEFAULT_EXPANDED_RESOURCE);
}
mCollapsedDrawable = a.getDrawable(R.styleable.TreeViewList_src_collapsed);
if (mCollapsedDrawable == null) {
mCollapsedDrawable = context.getResources().getDrawable(DEFAULT_COLLAPSED_RESOURCE);
}
mIndentWidth = a.getDimensionPixelSize(R.styleable.TreeViewList_indent_width,
DEFAULT_INDENT);
mIndicatorGravity = a.getInteger(R.styleable.TreeViewList_indicator_gravity,
DEFAULT_GRAVITY);
mIndicatorBackgroundDrawable = a.getDrawable(R.styleable.TreeViewList_indicator_background);
mRowBackgroundDrawable = a.getDrawable(R.styleable.TreeViewList_row_background);
mCollapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true);
a.recycle();
}
@Override
public void setAdapter(final ListAdapter adapter) {
if (!(adapter instanceof AbstractTreeViewAdapter)) {
throw new TreeConfigurationException(
"The adapter is not of TreeViewAdapter type");
}
mTreeAdapter = (AbstractTreeViewAdapter<?>) adapter;
syncAdapter();
super.setAdapter(mTreeAdapter);
}
private void syncAdapter() {
mTreeAdapter.setCollapsedDrawable(mCollapsedDrawable);
mTreeAdapter.setExpandedDrawable(mExpandedDrawable);
mTreeAdapter.setIndicatorGravity(mIndicatorGravity);
mTreeAdapter.setIndentWidth(mIndentWidth);
mTreeAdapter.setIndicatorBackgroundDrawable(mIndicatorBackgroundDrawable);
mTreeAdapter.setRowBackgroundDrawable(mRowBackgroundDrawable);
mTreeAdapter.setCollapsible(mCollapsible);
}
public void setExpandedDrawable(final Drawable expandedDrawable) {
mExpandedDrawable = expandedDrawable;
syncAdapter();
mTreeAdapter.refresh();
}
public void setCollapsedDrawable(final Drawable collapsedDrawable) {
mCollapsedDrawable = collapsedDrawable;
syncAdapter();
mTreeAdapter.refresh();
}
public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) {
mRowBackgroundDrawable = rowBackgroundDrawable;
syncAdapter();
mTreeAdapter.refresh();
}
public void setIndicatorBackgroundDrawable(
final Drawable indicatorBackgroundDrawable) {
mIndicatorBackgroundDrawable = indicatorBackgroundDrawable;
syncAdapter();
mTreeAdapter.refresh();
}
public void setIndentWidth(final int indentWidth) {
this.mIndentWidth = indentWidth;
syncAdapter();
mTreeAdapter.refresh();
}
public void setIndicatorGravity(final int indicatorGravity) {
mIndicatorGravity = indicatorGravity;
syncAdapter();
mTreeAdapter.refresh();
}
public void setCollapsible(final boolean collapsible) {
mCollapsible = collapsible;
syncAdapter();
mTreeAdapter.refresh();
}
public Drawable getExpandedDrawable() {
return mExpandedDrawable;
}
public Drawable getCollapsedDrawable() {
return mCollapsedDrawable;
}
public Drawable getRowBackgroundDrawable() {
return mRowBackgroundDrawable;
}
public Drawable getIndicatorBackgroundDrawable() {
return mIndicatorBackgroundDrawable;
}
public int getIndentWidth() {
return mIndentWidth;
}
public int getIndicatorGravity() {
return mIndicatorGravity;
}
public boolean isCollapsible() {
return mCollapsible;
}
}
| true |
2c7ebdc31fb7881ec9a292ea5ca0b65568a08697 | Java | worldpotato-university/Netzwerke_Uebungen_1 | /uebung7/Sender/src/de/gruppe1/sender/IState.java | UTF-8 | 179 | 1.804688 | 2 | [] | no_license | package de.gruppe1.sender;
import java.io.IOException;
public interface IState {
boolean handle(StateMachine stateMachine, byte[][] data, int counter) throws IOException;
}
| true |
9984fbb2c48c8a7e7e0ad733123c4604458d6639 | Java | ccl-organization/ccl | /ccl-api/src/main/java/com/ccl/config/CommonConfig.java | UTF-8 | 678 | 1.914063 | 2 | [] | no_license | package com.ccl.config;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
/**
* Created by IntelliJ IDEA.
* User: yahui
* Date: 2018/5/2
* To change this template use File | Settings | File Templates.
**/
@Configuration
public class CommonConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(1024L * 1024L);
return factory.createMultipartConfig();
}
}
| true |
09a77f78bdea8e14dc86ef2285278b5a7c22ea06 | Java | KingStormCold/dsa-web | /src/main/java/vn/easycredit/response/CheckCreatePasswordResponse.java | UTF-8 | 726 | 2.03125 | 2 | [] | no_license | package vn.easycredit.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CheckCreatePasswordResponse extends ResultResponse{
@JsonProperty("redirect_code")
@SerializedName("redirect_code")
private String redirectCode;
@JsonProperty("user_name")
@SerializedName("user_name")
private String userName;
public CheckCreatePasswordResponse(String result, String message, String redirectCode, String userName) {
super(result, message);
this.redirectCode = redirectCode;
this.userName = userName;
}
}
| true |
6a107fa922a42a84d7e088760684de616a83935e | Java | maszqara/AiSD | /lista1/Zadania.java | UTF-8 | 2,056 | 3.75 | 4 | [
"Apache-2.0"
] | permissive | import java.io.IOException;
import java.util.Scanner;
public class Zadania {
public int menu() {
System.out.println();
System.out.println(" ****************************************");
System.out.println(" * MENU *");
System.out.println(" ****************************************");
System.out.println(" 1. Pełna Lista");
System.out.println(" 2. Zmień ocenę");
System.out.println(" 3. Średnia ocen zaliczonych");
System.out.println(" 4. Nie zaliczyli kursu");
System.out.println(" 5. Zaliczyli kurs");
System.out.println(" 6. Dopisz studenta");
System.out.println(" 7. Usuń studenta");
System.out.println(" 8. Uporządkuj według ocen");
System.out.println(" 0. Koniec");
Scanner in = new Scanner(System.in);
int w = in.nextInt();
return w;
}
public Zadania(Database db) throws IOException {
Scanner in = new Scanner(System.in);
int wybor = menu();
while (wybor != 0) {
switch (wybor) {
case 1:
db.pelnaLista();
break;
case 2:
db.zmiana();
break;
case 3:
db.srednia();
break;
case 4:
db.nieZal();
break;
case 5:
db.zal();
break;
case 6:
db.dopisz();
break;
case 7:
db.usun();
break;
case 8:
db.sort(false);
break;
}
System.out.println("\nWciśnij Enter, aby kontynuować...");
System.in.read();
wybor = menu();
}
System.out.println("\n Koniec programu\n\n");
}
}
| true |
e202d32a81eecfd048fe80fea69ceefcbf9ecb19 | Java | Lucaziki/WeFlow | /ReferenceProject/MiShare1_0/src/com/cmmobi/looklook/common/gson/HttpRequestUtils.java | UTF-8 | 3,738 | 2.640625 | 3 | [] | no_license | package com.cmmobi.looklook.common.gson;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.util.Log;
public class HttpRequestUtils {
private static final String TAG = "HTTPManageer";
public String sendPostRequest(String url, String json){
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("requestapp", json));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (httpResponse!=null && httpResponse.getStatusLine().getStatusCode() == 200) {
// 第3步:使用getEntity方法获得返回结果
String result = null;
try {
result = EntityUtils.toString(httpResponse.getEntity());
return result;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格
//tvQueryResult.setText(result.replaceAll("\r", ""));
}else if(httpResponse==null){
Log.e(TAG, "httpResponse error: null");
}else{
Log.e(TAG, "httpResponse error:" + httpResponse.getStatusLine().getStatusCode());
}
return null;
}
/* public <T> T sendPostRequest(String url, String json,
Class<T> classOfT) {
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("request", json));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 第3步:使用getEntity方法获得返回结果
String result = null;
try {
result = EntityUtils.toString(httpResponse.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格
//tvQueryResult.setText(result.replaceAll("\r", ""));
Gson gson = new Gson();
T target = gson.fromJson(result, classOfT);
return target;
}else{
Log.e(TAG, "httpResponse error:" + httpResponse.getStatusLine().getStatusCode());
}
return null;
}*/
}
| true |
12b70677081c11b77690c9af2786d88220a33266 | Java | vominhtan/TheBang | /BangWorkSpace/MyBang/src/com/vominhtan1988/mybang/background/BackgroundFXRenderer.java | UTF-8 | 1,097 | 2.5625 | 3 | [] | no_license | package com.vominhtan1988.mybang.background;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.vominhtan1988.mybang.Resources;
public class BackgroundFXRenderer {
SpriteBatch backgroundFXBatch;
SpriteBatch backgroundBatch;
Sprite background;
public BackgroundFXRenderer() {
backgroundFXBatch = new SpriteBatch();
backgroundFXBatch.getProjectionMatrix().setToOrtho2D(0, 0, 800, 480);
background = Resources.getInstance().background;
backgroundBatch = new SpriteBatch();
backgroundBatch.getProjectionMatrix().setToOrtho2D(0, 0, 1024, 1024);
}
float stateTime = 0;
public void render() {
backgroundBatch.begin();
background.draw(backgroundBatch);
backgroundBatch.end();
backgroundFXBatch.begin();
backgroundFXBatch.end();
}
public void resize(int width, int height) {
backgroundFXBatch.getProjectionMatrix().setToOrtho2D(0, 0, width, height);
}
public void dispose() {
backgroundFXBatch.dispose();
backgroundBatch.dispose();
}
}
| true |
4972e18e52b71d3161c366b9e06fca7b389de433 | Java | AllenCVI/myLocku | /common/src/main/java/com/lockulockme/locku/base/beans/requestbean/PageRequestBean.java | UTF-8 | 406 | 1.875 | 2 | [] | no_license | package com.lockulockme.locku.base.beans.requestbean;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class PageRequestBean {
@SerializedName("pcuajtgbce")
public int pageNo;
@SerializedName("sheikbztqe")
public int sizePerPage;
public PageRequestBean(int page, int size) {
this.pageNo = page;
this.sizePerPage = size;
}
}
| true |
023ce74ac2dc7cede4940b9d1dbe493ada5a0ad6 | Java | AyaOsamaAhmed/ClientsOffline | /app/src/main/java/app/aya/clientsoffline/ListViewAdapterClientTracks.java | UTF-8 | 3,944 | 2 | 2 | [] | no_license | package app.aya.clientsoffline;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.android.volley.VolleyLog.TAG;
/**
* Created by aya on 11/1/2016.
*/
public class ListViewAdapterClientTracks extends BaseAdapter {
// Declare Variables
Activity context;
String ls_username ,ls_client_id , ls_phone , ls_card ,ls_remaind , ls_position;
ArrayList<HashMap<String, String>> list_clientTracks ;
Integer list_position = 0 ;
public ListViewAdapterClientTracks(Activity context,
ArrayList<HashMap<String, String>> list_clientTracks, String username,String position ,String phone , String card , String remaind ) {
this.context = context;
ls_username = username;
ls_card=card;
ls_phone=phone;
ls_remaind = remaind;
ls_position=position;
this.list_clientTracks = list_clientTracks;
// resultp = list_clients.get(0);
}
@Override
public int getCount() {
return list_clientTracks.size();
}
@Override
public Object getItem(int position) {
return list_clientTracks.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertview, ViewGroup viewGroup) {
// Declare Variables
TextView last_paid , last_buy , last_date ;
ImageButton img_details ;
//---- customer inside
LayoutInflater inflater = context.getLayoutInflater();
View listViewClient = inflater.inflate(R.layout.customer_detail_inside, null, true);
// Locate the TextViews
last_paid = (TextView) listViewClient.findViewById(R.id.last_paid);
last_buy = (TextView) listViewClient.findViewById(R.id.last_buy);
last_date = (TextView) listViewClient.findViewById(R.id.last_date);
img_details = (ImageButton) listViewClient.findViewById(R.id.img_details);
//------- position
final HashMap<String, String> dataPaid = list_clientTracks.get(position);
//----- set Text
String x = dataPaid.get(" cash");
Log.d(TAG, "getView: cash:"+x);
last_paid.setText(dataPaid.get(" cash"));
last_buy.setText(dataPaid.get(" buy"));
last_date.setText(dataPaid.get("{date"));
listViewClient.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
// Toast.makeText(context, "long click--"+position, Toast.LENGTH_SHORT).show();
return false;
}
});
img_details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent( context ,ClientsPaid.class);
intent.putExtra("details",true);
intent.putExtra("username",ls_username);
intent.putExtra("clientname",ls_username);
intent.putExtra("phone",ls_phone);
intent.putExtra("card",ls_card);
intent.putExtra("remaind",ls_remaind);
intent.putExtra("position",ls_position);
intent.putExtra("paid",dataPaid.get(" cash"));
intent.putExtra("buy",dataPaid.get(" buy"));
intent.putExtra("date",dataPaid.get("{date"));
intent.putExtra("buy_details",dataPaid.get(" buy_details"));
context.startActivity(intent);
}
});
return listViewClient;
}
}
| true |
b37cdaee39c8511b4157fcd7949b86c1a9517dc1 | Java | mptokwe/Weather | /InstantWeather/app/src/main/java/com/mpho/instantweather/WeatherInfoActivity.java | UTF-8 | 4,780 | 2.3125 | 2 | [] | no_license | package com.mpho.instantweather;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
public class WeatherInfoActivity extends AppCompatActivity implements InternetVerifierBroadcastReceiver.ConnectivityReceiverListener{
TextView txtv_location, txtv_temp, txtv_max_temp, txtv_min_temp, txtv_humidity;
ImageView weather_icon_imgv;
Double lat, lon;
private String TAG = "WeatherInfoActivity: ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
txtv_location=(TextView) findViewById(R.id.txtv_location_value);
txtv_temp=(TextView) findViewById(R.id.txtv_temp_value);
txtv_max_temp=(TextView) findViewById(R.id.txtv_max_temp_value);
txtv_min_temp=(TextView) findViewById(R.id.txtv_min_temp_value);
txtv_humidity=(TextView) findViewById(R.id.txtv_humidity_value);
weather_icon_imgv=(ImageView) findViewById(R.id.weather_icon_imageView);
Bundle ext=getIntent().getExtras();
if(ext != null){
lat=ext.getDouble("lattitude");
lon=ext.getDouble("longitude");
Log.i(TAG,"creating Asynctask and calling JSONWeatherParse method");
//create asynttask and pass the coordinates
new JSONWeatherParse(lat, lon, weather_icon_imgv, txtv_location, txtv_temp, txtv_max_temp, txtv_min_temp, txtv_humidity).execute();
Log.i(TAG,"JSONWeatherParse compeleted execution");
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab == null) throw new AssertionError();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Please ensure that you are connected to the internet and you've turned your location settings on.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
protected void onResume(){
Log.i(TAG,"application resumed");
super.onResume();
Log.i(TAG,"registering the connection status listener");
WeatherApp.getInstance().setConnectivityListener(this);
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
if(!isConnected) {
//show a No Internet Alert or Dialog
AlertDialog.Builder b=new AlertDialog.Builder(this);
b.setMessage("Internet connection required to get location information");
b.setCancelable(false);
b.setTitle("Please switch connect to the internet");
b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog The dialog that received the click.
* @param which The button that was clicked (e.g.
* {@link DialogInterface#BUTTON1}) or the position
*/
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.android.phone", "com.android.phone.NetworkSetting");
startActivity(intent);
}
});
b.setNegativeButton("EXIT",new DialogInterface.OnClickListener(
) {
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog The dialog that received the click.
* @param which The button that was clicked (e.g.
* {@link DialogInterface#BUTTON1}) or the position
*/
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
} );
b.show();
}else{
// dismiss the dialog or refresh the activity
return;
}
}
}
| true |
7edd5782d1644322097d30906cbe32bf4c052714 | Java | owenmather/random-joke-app | /src/main/java/com/mather/inventions/jokeapp/test/TestController.java | UTF-8 | 366 | 1.703125 | 2 | [] | no_license | package com.mather.inventions.jokeapp.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping
public String test(){
return "test"; //this is the randomJoke.html page from templates auto pulled by spring
}
}
| true |
c3a1e7e2e0b3a75fe929bcf9dd71f9acdbb9bdee | Java | lalitch/frontlinesystems | /src/main/java/com/plessentials/frontlinesystems/FrontlinesystemsApplication.java | UTF-8 | 357 | 1.609375 | 2 | [] | no_license | package com.plessentials.frontlinesystems;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FrontlinesystemsApplication {
public static void main(String[] args) {
SpringApplication.run(FrontlinesystemsApplication.class, args);
}
}
| true |
e41119b99b8c07467d94b6065e00163c81ca1995 | Java | Areeb2016/JAVA | /BurgurShop/src/BurgurShop/UpdateGuiC.java | UTF-8 | 3,528 | 2.671875 | 3 | [] | no_license | package BurgurShop;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class UpdateGuiC extends JFrame{
JPanel p1, p2;
JButton b1, b2;
JLabel l1, l2;
JTextField t1, t2;
UpdateGuiC(){
p1 = new JPanel();
p2 = new JPanel();
l1 = new JLabel("Name");
t1 = new JTextField();
l2 = new JLabel("Bill");
t2 = new JTextField();
b1 = new JButton("Update");
b2 = new JButton("Back");
p1.setLayout(new GridLayout(2,2));
p2.setLayout(new FlowLayout());
b1.addActionListener(new MyActionListener11());
b2.addActionListener(new MyActionListener11());
setSize(600,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.SOUTH);
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p2.add(b1);
p2.add(b2);
}
class MyActionListener11 implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(b1)){
try{
boolean qw = false;
String l = t1.getText();
double d = Double.parseDouble(t2.getText());
ObjectOutputStream output = null;
try{
ArrayList<CustomerRecord> list = readAllData();
for(int i = 0; i<list.size(); i++)
if(list.get(i).getName().equals(l)){
list.get(i).setBill(d);
qw = true;
}
if(qw == false){
JOptionPane.showMessageDialog (null, "Nothing Found");
dispose();
UpdateGuiC bnm = new UpdateGuiC();
}
else{
output = new ObjectOutputStream(new FileOutputStream("Customer.ser"));
for(int i = 0 ; i<list.size() ; i++)
output.writeObject(list.get(i));
JOptionPane.showMessageDialog (null,"record saved", "Information", JOptionPane.INFORMATION_MESSAGE);
RecordMenuC rmc = new RecordMenuC();
setVisible(false);
}
}
catch(IOException ex) {
System.out.println("IO Exception while opening file");
}
}
catch(InputMismatchException ex){
return;
}
}
else{
RecordMenuC rmc = new RecordMenuC();
setVisible(false);
}
}
public ArrayList<CustomerRecord> readAllData () {
ArrayList<CustomerRecord> List = new ArrayList<CustomerRecord>(0);
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream("Customer.ser"));
boolean EOF = false;
while(!EOF) {
try {
CustomerRecord myObj = (CustomerRecord) input.readObject();
List.add(myObj);
}
catch (ClassNotFoundException e) {
}
catch (EOFException end) {
EOF = true;
}
}
}
catch(FileNotFoundException e) {
}
catch (IOException e) {
}
finally {
try {
if(input != null)
input.close( );
}
catch (IOException e){
System.out.println("IO Exception while closing file");
}
}
return List;
}
}
}
| true |
49ba9153602a20294c641dc95e04d16f79c4b4f8 | Java | UreshaSew/TestNG | /src/test/java/VerifySign_OrangeHRM.java | UTF-8 | 1,794 | 2.140625 | 2 | [] | no_license | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class VerifySign_OrangeHRM {
WebDriver driver;
@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver", "E:\\QA\\TestNG\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/");
System.out.println("1. Open Chrome & Application");
}
@Test()
public void Login(){
driver.findElement(By.id("txtUsername")).sendKeys("Admin");
driver.findElement(By.id("txtPassword")).sendKeys("admin123");
driver.findElement(By.id("btnLogin")).click();
// Assert.assertEquals(true,true,"The Welcome Link Is Not Correct On The Home Page");
// Assert.assertFalse(false,"The Admin Tab Is Not Displayed On The Home Page");
// Assert.assertTrue(true,"The Dashboard Is Not Correct On The Home Page");
Assert.assertEquals(true, false, "The Welcome Link Is Not Correct On The Home Page");
Assert.assertFalse(false, "The Admin Tab Is Not Displayed On The Home Page");
Assert.assertTrue(false, "The Dashboard Is Not Correct On The Home Page");
}
public void SignOut(){
driver.findElement(By.id("welcome")).click();
driver.findElement(By.xpath("//div[@id='welcome-menu']/descendant::a[contains(@href,'logout')]")).click();
}
@AfterClass
public void tearDown ()
{
System.out.println("5. Close Chrome & Application");
driver.quit();
}
}
| true |
4d282e2cfda3bde6893f62fac4c0c5b2be6dbb81 | Java | Fr4ncx/asweng | /src/Data_Analysis/impl/ExportDataTaskImpl.java | UTF-8 | 3,580 | 1.835938 | 2 | [] | no_license | /**
*/
package Data_Analysis.impl;
import Data_Analysis.Data_AnalysisPackage;
import Data_Analysis.ExportDataTask;
import Data_Analysis.FormatType;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Export Data Task</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link Data_Analysis.impl.ExportDataTaskImpl#getFormat <em>Format</em>}</li>
* </ul>
*
* @generated
*/
public class ExportDataTaskImpl extends TaskImpl implements ExportDataTask {
/**
* The default value of the '{@link #getFormat() <em>Format</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFormat()
* @generated
* @ordered
*/
protected static final FormatType FORMAT_EDEFAULT = FormatType.JSON;
/**
* The cached value of the '{@link #getFormat() <em>Format</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFormat()
* @generated
* @ordered
*/
protected FormatType format = FORMAT_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ExportDataTaskImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Data_AnalysisPackage.Literals.EXPORT_DATA_TASK;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FormatType getFormat() {
return format;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFormat(FormatType newFormat) {
FormatType oldFormat = format;
format = newFormat == null ? FORMAT_EDEFAULT : newFormat;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Data_AnalysisPackage.EXPORT_DATA_TASK__FORMAT, oldFormat, format));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Data_AnalysisPackage.EXPORT_DATA_TASK__FORMAT:
return getFormat();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Data_AnalysisPackage.EXPORT_DATA_TASK__FORMAT:
setFormat((FormatType)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Data_AnalysisPackage.EXPORT_DATA_TASK__FORMAT:
setFormat(FORMAT_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Data_AnalysisPackage.EXPORT_DATA_TASK__FORMAT:
return format != FORMAT_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (format: ");
result.append(format);
result.append(')');
return result.toString();
}
} //ExportDataTaskImpl
| true |
fa18f8d5f20cc4c7825f9b3bfe01eecd827caade | Java | Theosakamg-Archive/ros2_java | /rcljava/src/test/java/org/ros2/rcljava/SubscriptionTest.java | UTF-8 | 2,045 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | /* Copyright 2016 Esteve Fernandez <esteve@apache.org>
* Copyright 2016-2017 Mickael Gaillard <mick.gaillard@gmail.com>
*
* 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.ros2.rcljava;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.apache.log4j.BasicConfigurator;
import org.junit.BeforeClass;
import org.junit.Test;
import org.ros2.rcljava.node.NativeNode;
import org.ros2.rcljava.node.topic.SubscriptionCallback;
import std_msgs.msg.String;
import org.ros2.rcljava.node.topic.NativeSubscription;
public class SubscriptionTest {
@BeforeClass
public static void beforeClass() {
BasicConfigurator.resetConfiguration();
BasicConfigurator.configure();
}
@Test
public final void testCreate() {
RCLJava.rclJavaInit();
NativeNode node = (NativeNode) RCLJava.createNode("test_node");
NativeSubscription<std_msgs.msg.String> subscription =
(NativeSubscription<String>) node.<std_msgs.msg.String>createSubscription(
std_msgs.msg.String.class, "test_topic", new SubscriptionCallback<std_msgs.msg.String>() {
public void dispatch(final std_msgs.msg.String msg) {
}
});
assertEquals(node.getNodeHandle(), subscription.getNode().getNodeHandle());
assertNotEquals(0, subscription.getNode().getNodeHandle());
assertNotEquals(0, subscription.getSubscriptionHandle());
subscription.dispose();
node.dispose();
RCLJava.shutdown();
}
}
| true |
46e7f4e4ebeb2f80aa8305a9aae52790519f0f7c | Java | minimalistdev/reclameaqui | /src/main/java/com/minimalistdev/reclameaqui/exception/LocaleNotFoundException.java | UTF-8 | 449 | 2.25 | 2 | [] | no_license | package com.minimalistdev.reclameaqui.exception;
import org.springframework.http.HttpStatus;
public class LocaleNotFoundException extends RuntimeException{
private final String message;
public LocaleNotFoundException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public HttpStatus getHttpStatus() {
return HttpStatus.NO_CONTENT;
}
}
| true |
24137a359b928aa22aba2a1f2f6570866cdce410 | Java | monipriya/k | /2d.java | UTF-8 | 582 | 2.96875 | 3 | [] | no_license | import java.util.Scanner;
public class matrix {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[][]=new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
a[i][j]=sc.nextInt();
}
}
int c1=0,c2=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j]==0){
c1=i;
c2=j;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==c1 ||j==c2){
a[i][j]=0;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
| true |
a16eb7a2ff1f52ce449a0d517753e4c4b9dd6bb2 | Java | sasensio1/ProyectoCasosEmergenciasCompleto | /casosEmergenciasBulkApi/src/main/java/com/casosemergencias/dao/vo/FieldLabelVO.java | UTF-8 | 1,459 | 2.265625 | 2 | [] | no_license | package com.casosemergencias.dao.vo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Where;
import com.casosemergencias.model.FieldLabel;
@Entity
@Table(name = "salesforce.fieldlabel")
@Where(clause = "objeto='Case'")
public class FieldLabelVO extends ObjectVO implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "objeto")
private String objeto;
@Column(name = "campo")
private String campo;
@Column(name = "label")
private String label;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getObjeto() {
return objeto;
}
public void setObjeto(String objeto) {
this.objeto = objeto;
}
public String getCampo() {
return campo;
}
public void setCampo(String campo) {
this.campo = campo;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Override
public Object instantiateTargetLogic() {
FieldLabel fieldLabel = new FieldLabel();
return fieldLabel;
}
}
| true |
0be2377890f73f1921fbf02ff2e0894f25357cb0 | Java | chj199619/PetShop | /src/main/java/org/lanqiao/service/CatServiceDao.java | UTF-8 | 203 | 1.84375 | 2 | [] | no_license | package org.lanqiao.service;
import org.lanqiao.domain.Cat;
import java.sql.SQLException;
import java.util.List;
public interface CatServiceDao {
public List<Cat> catList() throws SQLException;
}
| true |
617af7baf519e8562fd86fccdf22b6269d2fef9f | Java | crpdev/mssc-oil-order-service | /src/main/java/com/crpdev/msscoilorder/web/mapper/OilOrderMapper.java | UTF-8 | 369 | 1.960938 | 2 | [] | no_license | package com.crpdev.msscoilorder.web.mapper;
import com.crpdev.factory.oil.model.OilOrderDto;
import com.crpdev.msscoilorder.domain.OilOrder;
import org.mapstruct.Mapper;
@Mapper(uses = {DateMapper.class, OilOrderLineMapper.class})
public interface OilOrderMapper {
OilOrderDto toOilOrderDto(OilOrder oilOrder);
OilOrder toOilOrder(OilOrderDto oilOrderDto);
}
| true |
2a9de2eb4eeda44dbd5ca19a5e0cee87dbe93c25 | Java | mcarebridge/mCareClientAndroid | /app/src/androidTest/java/android/ade/phr/com/careclient/ServiceTest.java | UTF-8 | 544 | 1.742188 | 2 | [] | no_license | package android.ade.phr.com.careclient;
import android.app.Service;
import android.test.ServiceTestCase;
import com.phr.ade.connector.CareXMLReader;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ServiceTest extends ServiceTestCase<Service> {
public ServiceTest() {
super(Service.class);
try {
CareXMLReader.bindXML("");
assertEquals(true, true);
} catch (Exception e) {
e.printStackTrace();
}
}
} | true |