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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
966c821aa9add26c7f6ca91d4c8d7bd096f9ab10 | Java | mailru/jira-plugins-mrimsender | /src/main/java/ru/mail/jira/plugins/myteam/myteam/dto/parts/Forward.java | UTF-8 | 558 | 1.9375 | 2 | [] | no_license | /* (C)2020 */
package ru.mail.jira.plugins.myteam.myteam.dto.parts;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import ru.mail.jira.plugins.myteam.myteam.dto.Message;
@SuppressWarnings("NullAway")
@ToString
public class Forward extends Part<Forward.Data> {
public Message getMessage() {
return this.getPayload().message;
}
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Data {
public Message message;
}
}
| true |
c87778e8517132ceabe057f25cf32597ef9e2745 | Java | mrAlexGiroux/SchoolWork | /OOP/javaOOP/Cours04/src/ca/csf/dfc/classes/CompteInteret.java | UTF-8 | 763 | 2.84375 | 3 | [] | no_license | package ca.csf.dfc.classes;
public class CompteInteret extends CompteBancaire {
public CompteInteret(double p_Solde)
{
super(p_Solde);
}
@Override
public void Deposer(double p_Amount)
{
if (super.getSolde() < (p_Amount - FRAIS_TRANSACTION)) {
throw new IllegalArgumentException("Le compte de peut etre negatif");
}
super.Deposer(p_Amount - FRAIS_TRANSACTION);
}
@Override
public void Retirer(double p_Amount)
{
if (super.getSolde() < (p_Amount + FRAIS_TRANSACTION)) {
throw new IllegalArgumentException("Le compte de peut etre negatif");
}
else
{
super.Retirer(p_Amount + FRAIS_TRANSACTION);
}
}
}
| true |
2b68f71cbd59c9e91ab5718517762bbe6dd0772d | Java | fallstool/ktw | /KTW_WMS/src/main/java/com/core/scpwms/server/util/FileUtil4Jp.java | UTF-8 | 21,298 | 2.515625 | 3 | [] | no_license | package com.core.scpwms.server.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.CsvListWriter;
import org.supercsv.prefs.CsvPreference;
/**
* <p>
* Title: file manager
* </p>
* <p>
* Description: <br>
* </p>
*
* @author 陳彬彬 2010/10/13
* @version 1.0
*/
public abstract class FileUtil4Jp {
/** 编码:MS932 */
public static final String ENCODE_MS932 = "MS932";
/** 编码:ISO-8859-1 */
public static final String ENCODE_ISO88591 = "ISO-8859-1";
/** 编码:UTF-8 */
public static final String ENCODE_UTF8 = "UTF-8";
/** CSV后缀名 */
public static final String NAME_EXTENSION = ".csv";
/** Response Head Name */
private static final String HEAD_NAME = "Content-disposition";
/** Response Head Value */
private static final String HEAD_VALUE = "attachment;filename=";
/** Response Content Type */
private static final String CONTENT_TYPE = "application/csv";
/**
*
* <p>新建目录</p>
*
* @param path
* @return
*/
public static boolean createPath(String path) {
if (path == null || "".equals(path)) {
return false;
}
File file = new File(path);
file.mkdirs();
return true;
}
/**
*
* <p>递归新建目录</p>
*
* @param path
* @return
*/
public static boolean createMultiPath(String path) {
if (path == null || "".equals(path)) {
return false;
}
StringTokenizer st = new StringTokenizer(path, File.separator);
String path1 = st.nextToken() + File.separator;
if( path.startsWith("/") ){
path1 = "/" + path1;
}
String path2 = path1;
while (st.hasMoreTokens()) {
path1 = st.nextToken() + File.separator;
path2 += path1;
File inbox = new File(path2);
if (!inbox.exists())
inbox.mkdir();
}
return true;
}
/**
*
* <p>新建文件</p>
* @param source
*/
public static void CreateFile(String source) {
File file = new File(source);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
*
* <p>移动文件位置</p>
*
* @param source
* @param desc
* @return
*/
public static boolean move(String source, String desc) {
File file = new File(source);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
files[i].renameTo(new File(desc + "/" + files[i].getName()));
}
}
return true;
}
/**
*
* <p>该目录下是否有文件存在</p>
*
* @param path
* @return
*/
public static boolean hasFile(String path) {
File file = new File(path);
return file.exists();
}
/**
*
* <p>删除该目录和该目录下所有文件</p>
*
* @param path
* @return
*/
public static boolean deleteAll(String path) {
File file = new File(path);
if (file.exists()) {
if (!file.isDirectory()) {
file.delete();
} else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteAll(files[i].getPath());
if (files[i].exists()) {
files[i].delete();
}
}
}
}
return true;
}
/**
*
* <p>判断该文件是否是CSV文件(通过后缀名)</p>
*
* @param argFileName
* @return
*/
public static boolean IsCSVFile(String argFileName) {
String str = argFileName.substring(argFileName.length() - NAME_EXTENSION.length());
return str.equalsIgnoreCase(NAME_EXTENSION);
}
/**
*
* <p>解析CSV文件(标准CSV格式)</p>
*
* @param strFileName
* @param encode
* @return
*/
public static String[][] readCSVFile(String strFileName, String encode, CsvPreference csvPreference) {
FileInputStream fis = null;
InputStreamReader isr = null;
String[][] cells = new String[0][0];
try {
fis = new FileInputStream(strFileName);
isr = new InputStreamReader(fis, encode);
CsvListReader clr = new CsvListReader(isr, csvPreference == null ? CsvPreference.STANDARD_PREFERENCE : csvPreference);
List<String[]> allLines = new Vector<String[]>();
List<String> oneLineData = null;
int cols = -1;
while ((oneLineData = clr.read()) != null) {
cols = cols < oneLineData.size() ? oneLineData.size() : cols;
allLines.add(oneLineData.toArray(new String[0]));
}
clr.close();
if (allLines.size() != 0) {
cells = new String[allLines.size()][cols];
for (int i = 0; i < allLines.size(); i++) {
cells[i] = allLines.get(i);
}
}
} catch (Exception e) {
// empty
} finally {
closeFileInputStream(fis);
closeInputStreamReader(isr);
}
return cells;
}
/**
*
* <p>解析Excel文件,生成2维List</p>
*
* @param strFileName
* @param encode
* @return
*/
public static List<List<String>> readExcelFile(String strFileName) {
List<List<String>> excel = null;
try {
// 打开文件
Workbook book = Workbook.getWorkbook(new File(strFileName));
// 取得第一个sheet
Sheet sheet = book.getSheet(0);
// 取得行数
int rows = sheet.getRows();
if (rows > 0) {
excel = new ArrayList<List<String>>(rows);
for (int i = 0; i < rows; i++) {
// 行
Cell[] cell = sheet.getRow(i);
List<String> excelRow = new ArrayList<String>(cell.length);
for (int j = 0; j < cell.length; j++) {
// 设置单元格内容
excelRow.add(cell[j].getContents().trim());
}
excel.add(excelRow);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return excel;
}
/**
*
* <p>解析CSV文件(指定CSV格式)</p>
*
* @param cpr
* @param strFileName
* @param encode
* @return
*/
public static String[][] readCSVFile(CsvPreference cpr, String strFileName, String encode) {
FileInputStream fis = null;
InputStreamReader isr = null;
String[][] cells = new String[0][0];
try {
fis = new FileInputStream(strFileName);
isr = new InputStreamReader(fis, encode);
CsvListReader clr = new CsvListReader(isr, cpr);
List<String[]> allLines = new Vector<String[]>();
List<String> oneLineData = null;
int cols = -1;
while ((oneLineData = clr.read()) != null) {
cols = cols < oneLineData.size() ? oneLineData.size() : cols;
allLines.add(oneLineData.toArray(new String[0]));
}
clr.close();
if (allLines.size() != 0) {
cells = new String[allLines.size()][cols];
for (int i = 0; i < allLines.size(); i++) {
cells[i] = allLines.get(i);
}
}
} catch (Exception e) {
// empty
} finally {
closeFileInputStream(fis);
closeInputStreamReader(isr);
}
return cells;
}
/**
*
* <p>解析CSV文件(标准CSV格式,从画面直接导入)</p>
*
* @param is
* @param encode
* @return
*/
public static String[][] readCSVFile(InputStream is, String encode) {
InputStreamReader isr = null;
String[][] cells = new String[0][0];
try {
isr = new InputStreamReader(is, encode);
CsvListReader clr = new CsvListReader(isr, CsvPreference.STANDARD_PREFERENCE);
List<String[]> allLines = new Vector<String[]>();
List<String> oneLineData = null;
int cols = -1;
while ((oneLineData = clr.read()) != null) {
cols = cols < oneLineData.size() ? oneLineData.size() : cols;
allLines.add(oneLineData.toArray(new String[0]));
}
clr.close();
if (allLines.size() != 0) {
cells = new String[allLines.size()][cols];
for (int i = 0; i < allLines.size(); i++) {
cells[i] = allLines.get(i);
}
}
} catch (Exception e) {
// empty
} finally {
closeInputStreamReader(isr);
}
return cells;
}
/**
*
* <p>解析CSV文件(指定CSV格式,从画面直接导入)</p>
*
* @param cpr
* @param is
* @param encode
* @return
*/
public static String[][] readCSVFile(CsvPreference cpr, InputStream is, String encode) {
InputStreamReader isr = null;
String[][] cells = new String[0][0];
try {
isr = new InputStreamReader(is, encode);
CsvListReader clr = new CsvListReader(isr, cpr);
List<String[]> allLines = new Vector<String[]>();
List<String> oneLineData = null;
int cols = -1;
while ((oneLineData = clr.read()) != null) {
cols = cols < oneLineData.size() ? oneLineData.size() : cols;
allLines.add(oneLineData.toArray(new String[0]));
}
clr.close();
if (allLines.size() != 0) {
cells = new String[allLines.size()][cols];
for (int i = 0; i < allLines.size(); i++) {
cells[i] = allLines.get(i);
}
}
} catch (Exception e) {
// empty
} finally {
closeInputStreamReader(isr);
}
return cells;
}
/**
* <p>生成CSV文件(标准格式)</p>
*
* @param contents
* @param strFileName
* @param encode
*/
public static void writeCSVFile(String[][] contents, String strFileName, String encode) {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
fos = new FileOutputStream(strFileName);
osw = new OutputStreamWriter(fos, encode);
CsvListWriter clw = new CsvListWriter(osw, CsvPreference.STANDARD_PREFERENCE);
for (int i = 0; i < contents.length; i++) {
List<String> lst = Arrays.asList(contents[i]);
removeListNull(lst);
clw.write(lst);
}
clw.close();
} catch (Exception e) {
// empty
} finally {
closeFileOutputStream(fos);
closeOutputStreamWriter(osw);
}
}
/**
* <p>生成CSV文件(指定格式)</p>
*
* @param cpr
* @param contents
* @param strFileName
* @param encode
*/
public static void writeCSVFile(CsvPreference cpr, String[][] contents, String strFileName, String encode) {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
fos = new FileOutputStream(strFileName);
osw = new OutputStreamWriter(fos, encode);
CsvListWriter clw = new CsvListWriter(osw, cpr);
for (int i = 0; i < contents.length; i++) {
List<String> lst = Arrays.asList(contents[i]);
removeListNull(lst);
clw.write(lst);
}
clw.close();
} catch (Exception e) {
// empty
} finally {
closeFileOutputStream(fos);
closeOutputStreamWriter(osw);
}
}
/**
* <p>生产CSV文件到Response</p>
*
* @param response
* @param strFileName
* @param Content
* @param encode
* @throws UnsupportedEncodingException
*/
public static void writeCSVStream(HttpServletResponse response, String strFileName, String[][] Content,
String encode) throws UnsupportedEncodingException {
response.reset();
response.setContentType(CONTENT_TYPE);
response.setHeader(HEAD_NAME, HEAD_VALUE + new String(strFileName.getBytes(ENCODE_MS932), ENCODE_ISO88591));
ByteArrayOutputStream baos = getCSVStreamWithNoTitle(Content, encode);
try {
baos.writeTo(response.getOutputStream());
baos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
*
* <p>解析TXT文件</p>
*
* @param fileName
* @param encode
* @return
*/
public static String[][] readTXTFile(String fileName, String encode) {
FileInputStream fis = null;
InputStreamReader isr = null;
String[][] cells = new String[0][0];
try {
fis = new FileInputStream(fileName);
isr = new InputStreamReader(fis, encode);
BufferedReader br = new BufferedReader(isr);
List<String[]> allLines = new Vector<String[]>();
String[] oneLineData = null;
while (br.ready()) {
oneLineData = new String[] { br.readLine() };
allLines.add(oneLineData);
}
br.close();
if (allLines.size() != 0) {
cells = new String[allLines.size()][1];
for (int i = 0; i < allLines.size(); i++) {
cells[i] = allLines.get(i);
}
}
} catch (Exception e) {
// empty
} finally {
closeFileInputStream(fis);
closeInputStreamReader(isr);
}
return cells;
}
/**
*
* <p>解析TXT文件(从画面导入)</p>
*
* @param is
* @param encode
* @return
*/
public static String[][] readTXTFile(InputStream is, String encode) {
InputStreamReader isr = null;
String[][] cells = new String[0][0];
try {
isr = new InputStreamReader(is, encode);
BufferedReader br = new BufferedReader(isr);
List<String[]> allLines = new Vector<String[]>();
String[] oneLineData = null;
while (br.ready()) {
oneLineData = new String[] { br.readLine() };
allLines.add(oneLineData);
}
br.close();
if (allLines.size() != 0) {
cells = new String[allLines.size()][1];
for (int i = 0; i < allLines.size(); i++) {
cells[i] = allLines.get(i);
}
}
} catch (Exception e) {
// empty
} finally {
closeInputStreamReader(isr);
}
return cells;
}
/**
* <p>生产TXT文件到Response</p>
*
* @param response
* @param strFileName
* @param Content
* @param encode
* @throws UnsupportedEncodingException
*/
public static void writeTXTStream(HttpServletResponse response, String strFileName, String[][] Content, String encode) throws UnsupportedEncodingException {
response.reset();
response.setContentType(CONTENT_TYPE);
response.setHeader(HEAD_NAME, HEAD_VALUE + new String(strFileName.getBytes(ENCODE_MS932), ENCODE_ISO88591));
ByteArrayOutputStream baos = getTXTStream(Content, encode);
try {
baos.writeTo(response.getOutputStream());
baos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* <p>生成CSV文件(标准格式)</p>
*
* @param contents
* @param strFileName
* @param encode
*/
public static void writeTXTStream(String[][] contents, String strFileName, String encode) {
FileOutputStream fos = null;
ByteArrayOutputStream baos = null;
try {
fos = new FileOutputStream(strFileName);
baos = getTXTStream(contents, encode);
baos.writeTo(fos);
baos.close();
} catch (Exception e) {
// empty
} finally {
closeFileOutputStream(fos);
}
}
/**
* <p>文件上传</p>
*
* @param is
* @param encode
* @param path
* @param fileName
*/
public static void uploadFile(InputStream is, String encode, String path, String fileName) {
InputStreamReader isr = null;
FileOutputStream fos = null;
try {
isr = new InputStreamReader(is, encode);
BufferedReader br = new BufferedReader(isr);
String fileFullPath = path;
if (fileFullPath.lastIndexOf(File.separator) != fileFullPath.length()) {
fileFullPath += File.separator;
}
fileFullPath += fileName;
fos = new FileOutputStream(fileFullPath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, encode));
while (br.ready()) {
bw.write(br.readLine());
bw.write("\r\n");
}
bw.flush();
bw.close();
br.close();
} catch (Exception e) {
// empty
} finally {
closeInputStreamReader(isr);
if (fos != null) {
closeFileOutputStream(fos);
}
}
}
private static void closeFileOutputStream(FileOutputStream fos) {
try {
fos.close();
} catch (Exception e) {
// empty
}
}
private static void closeOutputStreamWriter(OutputStreamWriter osw) {
try {
osw.close();
} catch (Exception e) {
// empty
}
}
private static void closeStringWriter(StringWriter sw) {
try {
sw.close();
} catch (Exception e) {
// empty
}
}
private static void removeListNull(List<String> list) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == null) {
list.set(i, "");
}
}
}
private static ByteArrayOutputStream getCSVStreamWithNoTitle(String[][] contents, String encode) {
StringWriter sw = new StringWriter();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
CsvListWriter clw = new CsvListWriter(sw, CsvPreference.STANDARD_PREFERENCE);
for (int i = 0; i < contents.length; i++) {
List<String> lst = Arrays.asList(contents[i]);
removeListNull(lst);
clw.write(lst);
}
clw.close();
sw.flush();
baos.write(sw.toString().getBytes(encode));
} catch (Exception e) {
// empty
} finally {
closeStringWriter(sw);
}
return baos;
}
private static ByteArrayOutputStream getTXTStream(String[][] contents, String encode) {
StringWriter sw = new StringWriter();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
for (int i = 0; i < contents.length; i++) {
sw.write(contents[i][0]);
sw.write("\r\n");
}
sw.flush();
baos.write(sw.toString().getBytes(encode));
} catch (Exception e) {
// empty
} finally {
closeStringWriter(sw);
}
return baos;
}
private static void closeFileInputStream(FileInputStream fis) {
try {
fis.close();
} catch (Exception e) {
// empty
}
}
private static void closeInputStreamReader(InputStreamReader isr) {
try {
isr.close();
} catch (Exception e) {
// empty
}
}
} | true |
d9ec5572846263cb3ba1716649ab17b36ac8cff1 | Java | Cardman/projects | /desktop/applis/apps/gui/gui_games/pokemongui/src/main/java/aiki/gui/threads/DrawingAnimation.java | UTF-8 | 671 | 2.8125 | 3 | [] | no_license | package aiki.gui.threads;
import aiki.game.fight.animations.AnimationInt;
import aiki.gui.components.fight.Battle;
public final class DrawingAnimation implements Runnable {
private Battle battle;
private AnimationInt animation;
private boolean initial;
public DrawingAnimation(Battle _battle, AnimationInt _animation,
boolean _initial) {
battle = _battle;
animation = _animation;
initial = _initial;
}
@Override
public void run() {
if (initial) {
battle.drawAnimationInstantInitial(animation);
} else {
battle.drawAnimationInstant(animation);
}
}
}
| true |
c7e038a621cd0f4f49a59d9e5e7481c4d4e4fd30 | Java | paillardf/PeerSync | /PeerSync/src/com/peersync/network/behaviour/DiscoveryBehaviour.java | UTF-8 | 3,995 | 1.992188 | 2 | [] | no_license | package com.peersync.network.behaviour;
import java.io.IOException;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.impl.endpoint.EndpointUtils;
import net.jxta.impl.protocol.RdvAdv;
import net.jxta.impl.rendezvous.RendezVousServiceImpl;
import net.jxta.protocol.PeerAdvertisement;
import net.jxta.protocol.RouteAdvertisement;
import com.peersync.models.PeerGroupEvent;
import com.peersync.network.group.BasicPeerGroup;
import com.peersync.tools.Log;
public class DiscoveryBehaviour extends AbstractBehaviour{
private static final long UPDATE_RDV_DELAY = 8*60*1000;
private static final long VALIDITY_RDV_ADV = 9*60*1000;
private long lastRDVPublishTime = 0;
private RdvAdv peerRDVAdv;
public DiscoveryBehaviour(BasicPeerGroup myPeerGroup) {
super(myPeerGroup);
}
@Override
protected int action() {
findRDVAdvertisement();
//findRDVAdvertisement();
// if(peerView!=null){
// peerView.seed();
// }
Log.d("IS RENDEZ VOUS "+ myPeerGroup.getPeerGroup().isRendezvous(), myPeerGroup.getPeerGroupID().toString());
Log.d( "IS CONNECT TO RENDEZ VOUS "+ myPeerGroup.getPeerGroup().getRendezVousService().isConnectedToRendezVous(), myPeerGroup.getPeerGroupID().toString());
if(System.currentTimeMillis() - lastRDVPublishTime > UPDATE_RDV_DELAY&&myPeerGroup.getPeerGroup().isRendezvous()){
sendRDVAdvertisement();
}
return 10000;
}
private void sendRDVAdvertisement(){
try {
if(peerRDVAdv==null){
PeerAdvertisement padv = myPeerGroup.getPeerGroup().getPeerAdvertisement();
RdvAdv rdvAdv = (RdvAdv) AdvertisementFactory.newAdvertisement(RdvAdv.getAdvertisementType());
rdvAdv.setServiceName(((RendezVousServiceImpl)myPeerGroup.getRendezVousService()).getAssignedID().toString() + myPeerGroup.getPeerGroupID().getUniqueValue().toString());
rdvAdv.setGroupID(padv.getPeerGroupID());
rdvAdv.setName(padv.getName());
rdvAdv.setPeerID(padv.getPeerID());
RouteAdvertisement ra = EndpointUtils.extractRouteAdv(padv);
rdvAdv.setRouteAdv(ra);
rdvAdv.sign(myPeerGroup.getPSECredential(), true, true);
peerRDVAdv = rdvAdv;
}
myPeerGroup.getNetPeerGroup().getDiscoveryService().publish(peerRDVAdv,VALIDITY_RDV_ADV,VALIDITY_RDV_ADV);
myPeerGroup.getNetPeerGroup().getDiscoveryService().remotePublish(peerRDVAdv,VALIDITY_RDV_ADV);
Log.d(myPeerGroup.getPeerGroupName(), "--- SEND RDV ADVERTISEMENT ---");
lastRDVPublishTime = System.currentTimeMillis();
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void findRDVAdvertisement() {
Log.d("Trying to find RDV advertisement...", myPeerGroup.getPeerGroup().getPeerGroupName());
try {
secureDiscovery(myPeerGroup.getNetPeerGroup().getDiscoveryService().getLocalAdvertisements(DiscoveryService.ADV, RdvAdv.GroupIDTag, myPeerGroup.getPeerGroupID().toString()));
} catch (IOException e) {
e.printStackTrace();
}
myPeerGroup.getNetPeerGroup().getDiscoveryService().getRemoteAdvertisements( null,
DiscoveryService.ADV, RdvAdv.GroupIDTag, myPeerGroup.getPeerGroupID().toString(),
10, this );
}
protected void parseAdvertisement(Advertisement foundAdv) {
if(foundAdv.getAdvType().compareTo(RdvAdv.getAdvertisementType())==0){
RdvAdv rdvAdv = (RdvAdv) foundAdv;
if(!rdvAdv.getPeerID().equals(myPeerGroup.getPeerGroup().getPeerID())){
Log.d("Found RDV Advertisement", myPeerGroup.getPeerGroupID().toString());
try {
myPeerGroup.getDiscoveryService().publish(rdvAdv);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void notifyPeerGroup(PeerGroupEvent event) {
if(myPeerGroup.getNetPeerGroup().getPeerGroupID().toString().equals(event.getPeerGroupID().toString())){
//NETPEERGROUPEVENT
switch (event.getID()) {
case PeerGroupEvent.RDV_CONNECTION:
lastRDVPublishTime = 0;
break;
}
}else{
}
}
}
| true |
d3ed87c572c440e708483cbb9bc43c17e4a616d7 | Java | Automattic/elasticsearch-statsd-plugin | /src/main/java/com/automattic/elasticsearch/statsd/StatsdReporterNodeStats.java | UTF-8 | 10,641 | 1.929688 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | package com.automattic.elasticsearch.statsd;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.http.HttpStats;
import org.elasticsearch.index.stats.IndexingPressureStats;
import org.elasticsearch.monitor.fs.FsInfo;
import org.elasticsearch.monitor.jvm.JvmStats;
import org.elasticsearch.monitor.os.OsStats;
import org.elasticsearch.monitor.process.ProcessStats;
import org.elasticsearch.threadpool.ThreadPoolStats;
import org.elasticsearch.transport.TransportStats;
public class StatsdReporterNodeStats extends StatsdReporter {
private final NodeStats nodeStats;
private final String nodeName;
private final Boolean statsdReportFsDetails;
private final Boolean reportIndexBackPressure;
public StatsdReporterNodeStats(NodeStats nodeStats, String nodeName, Boolean statsdReportFsDetails,Boolean reportIndexBackPressure) {
this.nodeStats = nodeStats;
this.nodeName = nodeName;
this.statsdReportFsDetails = statsdReportFsDetails;
this.reportIndexBackPressure = reportIndexBackPressure;
}
public void run() {
try {
this.sendNodeFsStats(this.nodeStats.getFs());
this.sendNodeJvmStats(this.nodeStats.getJvm());
this.sendNodeOsStats(this.nodeStats.getOs());
this.sendNodeProcessStats(this.nodeStats.getProcess());
this.sendNodeHttpStats(this.nodeStats.getHttp());
this.sendNodeTransportStats(this.nodeStats.getTransport());
this.sendNodeThreadPoolStats(this.nodeStats.getThreadPool());
if(reportIndexBackPressure){
this.sendIndexingBackPressureStats(this.nodeStats.getIndexingPressureStats());
}
} catch (Exception e) {
this.logException(e);
}
}
private void sendNodeThreadPoolStats(ThreadPoolStats threadPoolStats) {
String prefix = this.getPrefix("thread_pool");
for (ThreadPoolStats.Stats stats : threadPoolStats) {
String threadPoolType = prefix + "." + stats.getName();
this.sendGauge(threadPoolType, "threads", stats.getThreads());
this.sendGauge(threadPoolType, "queue", stats.getQueue());
this.sendGauge(threadPoolType, "active", stats.getActive());
this.sendGauge(threadPoolType, "rejected", stats.getRejected());
this.sendGauge(threadPoolType, "largest", stats.getLargest());
this.sendGauge(threadPoolType, "completed", stats.getCompleted());
}
}
private void sendIndexingBackPressureStats(IndexingPressureStats indexingPressureStats){
String prefix = this.getPrefix("indexing_pressure");
this.sendGauge(prefix,"primary_rejections",indexingPressureStats.getPrimaryRejections());
this.sendGauge(prefix,"replica_rejections",indexingPressureStats.getReplicaRejections());
this.sendGauge(prefix,"coordinating_rejections",indexingPressureStats.getCoordinatingRejections());
this.sendGauge(prefix,"memory.current.primary",indexingPressureStats.getCurrentPrimaryBytes());
this.sendGauge(prefix,"memory.current.replica",indexingPressureStats.getCurrentReplicaBytes());
this.sendGauge(prefix,"memory.current.coordinating",indexingPressureStats.getTotalCoordinatingBytes());
this.sendGauge(prefix,"memory.current.all",indexingPressureStats.getCurrentCombinedCoordinatingAndPrimaryBytes());
this.sendGauge(prefix,"memory.total.coordinating",indexingPressureStats.getTotalCoordinatingBytes());
this.sendGauge(prefix,"memory.total.primary",indexingPressureStats.getTotalPrimaryBytes());
this.sendGauge(prefix,"memory.total.replica",indexingPressureStats.getTotalReplicaBytes());
this.sendGauge(prefix,"memory.total.all",indexingPressureStats.getTotalCombinedCoordinatingAndPrimaryBytes());
}
private void sendNodeTransportStats(TransportStats transportStats) {
String prefix = this.getPrefix("transport");
this.sendGauge(prefix, "server_open", transportStats.serverOpen());
this.sendGauge(prefix, "rx_count", transportStats.rxCount());
this.sendGauge(prefix, "rx_size_in_bytes", transportStats.rxSize().getBytes());
this.sendGauge(prefix, "tx_count", transportStats.txCount());
this.sendGauge(prefix, "tx_size_in_bytes", transportStats.txSize().getBytes());
}
private void sendNodeProcessStats(ProcessStats processStats) {
String prefix = this.getPrefix("process");
this.sendGauge(prefix, "open_file_descriptors", processStats.getOpenFileDescriptors());
if (processStats.getCpu() != null) {
this.sendGauge(prefix + ".cpu", "percent", processStats.getCpu().getPercent());
this.sendGauge(prefix + ".cpu", "total_in_millis", processStats.getCpu().getTotal().millis());
}
if (processStats.getMem() != null) {
this.sendGauge(prefix + ".mem", "total_virtual_in_bytes", processStats.getMem().getTotalVirtual().getBytes());
}
}
private void sendNodeOsStats(OsStats osStats) {
String prefix = this.getPrefix("os");
this.sendGauge(prefix + ".load_average", "1m", osStats.getCpu().getLoadAverage()[0]);
this.sendGauge(prefix + ".load_average", "5m", osStats.getCpu().getLoadAverage()[1]);
this.sendGauge(prefix + ".load_average", "15m", osStats.getCpu().getLoadAverage()[2]);
this.sendGauge(prefix, "cpu_percent", osStats.getCpu().getPercent());
if (osStats.getMem() != null) {
this.sendGauge(prefix + ".mem", "free_in_bytes", osStats.getMem().getFree().getBytes());
this.sendGauge(prefix + ".mem", "used_in_bytes", osStats.getMem().getUsed().getBytes());
this.sendGauge(prefix + ".mem", "free_percent", osStats.getMem().getFreePercent());
this.sendGauge(prefix + ".mem", "used_percent", osStats.getMem().getUsedPercent());
}
if (osStats.getSwap() != null) {
this.sendGauge(prefix + ".swap", "free_in_bytes", osStats.getSwap().getFree().getBytes());
this.sendGauge(prefix + ".swap", "used_in_bytes", osStats.getSwap().getUsed().getBytes());
}
if (osStats.getCgroup() != null) {
this.sendGauge(prefix + ".cgroup", "cpuacct.usage", osStats.getCgroup().getCpuAcctUsageNanos());
this.sendGauge(prefix + ".cgroup", "cpu.cfs_period_micros", osStats.getCgroup().getCpuCfsPeriodMicros());
this.sendGauge(prefix + ".cgroup", "cpu.cfs_quota_micros", osStats.getCgroup().getCpuCfsQuotaMicros());
if (osStats.getCgroup().getCpuStat() != null) {
this.sendGauge(prefix + ".cgroup.cpu.stat", "number_of_elapsed_periods", osStats.getCgroup().getCpuStat().getNumberOfElapsedPeriods());
this.sendGauge(prefix + ".cgroup.cpu.stat", "number_of_times_throttled", osStats.getCgroup().getCpuStat().getNumberOfTimesThrottled());
this.sendGauge(prefix + ".cgroup.cpu.stat", "time_throttled_nanos", osStats.getCgroup().getCpuStat().getTimeThrottledNanos());
}
}
}
private void sendNodeJvmStats(JvmStats jvmStats) {
String prefix = this.getPrefix("jvm");
// mem
this.sendGauge(prefix + ".mem", "heap_used_percent", jvmStats.getMem().getHeapUsedPercent());
this.sendGauge(prefix + ".mem", "heap_used_in_bytes", jvmStats.getMem().getHeapUsed().getBytes());
this.sendGauge(prefix + ".mem", "heap_committed_in_bytes", jvmStats.getMem().getHeapCommitted().getBytes());
this.sendGauge(prefix + ".mem", "non_heap_used_in_bytes", jvmStats.getMem().getNonHeapUsed().getBytes());
this.sendGauge(prefix + ".mem", "non_heap_committed_in_bytes", jvmStats.getMem().getNonHeapCommitted().getBytes());
for (JvmStats.MemoryPool memoryPool : jvmStats.getMem()) {
String memoryPoolType = prefix + ".mem.pools." + memoryPool.getName();
this.sendGauge(memoryPoolType, "max_in_bytes", memoryPool.getMax().getBytes());
this.sendGauge(memoryPoolType, "used_in_bytes", memoryPool.getUsed().getBytes());
this.sendGauge(memoryPoolType, "peak_used_in_bytes", memoryPool.getPeakUsed().getBytes());
this.sendGauge(memoryPoolType, "peak_max_in_bytes", memoryPool.getPeakMax().getBytes());
}
// threads
this.sendGauge(prefix + ".threads", "count", jvmStats.getThreads().getCount());
this.sendGauge(prefix + ".threads", "peak_count", jvmStats.getThreads().getPeakCount());
// garbage collectors
for (JvmStats.GarbageCollector collector : jvmStats.getGc()) {
String gcCollectorType = prefix + ".gc.collectors." + collector.getName();
this.sendGauge(gcCollectorType, "collection_count", collector.getCollectionCount());
this.sendGauge(gcCollectorType, "collection_time_in_millis", collector.getCollectionTime().millis());
}
// TODO: buffer pools
}
private void sendNodeHttpStats(HttpStats httpStats) {
if( httpStats != null ) {
String prefix = this.getPrefix("http");
this.sendGauge(prefix, "current_open", httpStats.getServerOpen());
this.sendGauge(prefix, "total_opened", httpStats.getTotalOpen());
}
}
private void sendNodeFsStats(FsInfo fs) {
// Send total
String prefix = this.getPrefix("fs");
this.sendNodeFsStatsInfo(prefix + ".total", fs.getTotal());
// Maybe send details
if (this.statsdReportFsDetails) {
for (FsInfo.Path info : fs) {
this.sendNodeFsStatsInfo(prefix + ".data", info);
}
}
}
private void sendNodeFsStatsInfo(String prefix, FsInfo.Path info) {
// Construct detailed path
String prefixAppend = "";
if (info.getPath() != null)
prefixAppend += "." + info.getPath();
if (info.getMount() != null)
prefixAppend += "." + info.getMount();
if (info.getAvailable().getBytes() != -1)
this.sendGauge(prefix + prefixAppend, "available_in_bytes", info.getAvailable().getBytes());
if (info.getTotal().getBytes() != -1)
this.sendGauge(prefix + prefixAppend, "total_in_bytes", info.getTotal().getBytes());
if (info.getFree().getBytes() != -1)
this.sendGauge(prefix + prefixAppend, "free_in_bytes", info.getFree().getBytes());
}
private String getPrefix(String prefix) {
return this.buildMetricName("node." + this.nodeName + "." + prefix);
}
}
| true |
59a31748d984b88c5b2b51650ece0a00c20d7c6f | Java | randyp/jdbj | /src/test/java/io/github/randyp/jdbj/db/h2_1_4/QueriesTest.java | UTF-8 | 2,041 | 2.03125 | 2 | [
"CC0-1.0"
] | permissive | package io.github.randyp.jdbj.db.h2_1_4;
import io.github.randyp.jdbj.student.StudentTest;
import io.github.randyp.jdbj.test.query.*;
import org.junit.ClassRule;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import javax.sql.DataSource;
@RunWith(Enclosed.class)
public class QueriesTest {
@ClassRule
public static final H2Rule db = StudentTest.dbRule();
public static class BatchedExecuteInsert extends BatchedExecuteInsertTest {
@Override
public DataSource db() {
return db;
}
}
public static class BatchedExecuteUpdate extends BatchedExecuteUpdateTest {
@Override
public DataSource db() {
return db;
}
}
public static class ExecuteInsert extends ExecuteInsertTest {
@Override
public DataSource db() {
return db;
}
}
public static class ExecuteQuery extends ExecuteQueryTest {
@Override
public DataSource db() {
return db;
}
}
public static class ExecuteQueryRunnable extends ExecuteQueryRunnableTest {
@Override
public DataSource db() {
return db;
}
}
public static class ExecuteScript extends ExecuteScriptTest {
@Override
public DataSource db() {
return db;
}
}
public static class ExecuteStatement extends ExecuteStatementTest {
@Override
public DataSource db() {
return db;
}
}
public static class ExecuteUpdate extends ExecuteUpdateTest {
@Override
public DataSource db() {
return db;
}
}
public static class Transaction extends TransactionTest {
@Override
public DataSource db() {
return db;
}
}
public static class ReturningTransaction extends ReturningTransactionTest {
@Override
public DataSource db() {
return db;
}
}
}
| true |
98959b2151ce4a5d54430a475afc496cb5e9f944 | Java | priyojit1993/gintaa-actions | /src/main/java/com/asconsoft/gintaa/actions/repository/ActionModeRepository.java | UTF-8 | 313 | 1.625 | 2 | [] | no_license | package com.asconsoft.gintaa.actions.repository;
import com.asconsoft.gintaa.actions.model.ActionMode;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ActionModeRepository extends JpaRepository<ActionMode, String> {
}
| true |
84f66d351e8ee42cd331d88dd62a273a476a0321 | Java | Amit-Khobragade/ToDoLists | /com.sample.control/src/com/sample/control/Controls.java | UTF-8 | 8,613 | 2.46875 | 2 | [
"MIT"
] | permissive | package com.sample.control;
import javafx.scene.control.*;
import javafx.fxml.FXML;
import javafx.scene.text.Font;
import javafx.beans.value.ObservableValue;
import javafx.scene.input.*;
import javafx.scene.layout.BorderPane;
import javafx.fxml.FXMLLoader;
import javafx.event.Event;
import javafx.event.ActionEvent;
import javafx.scene.paint.Color;
import javafx.collections.transformation.SortedList;
import javafx.collections.transformation.FilteredList;
import com.sample.storage.*;
import java.util.Optional;
import java.time.LocalDate;
import java.util.function.Predicate;
import java.time.format.DateTimeFormatter;
public class Controls {
public void initialize() {
Font f = new Font( "bold", 10 );
timePeriod.setFont( f );
status.setFont( f );
description.setFont( new Font( "bold", 13 ) );
ContextMenu onList = new ContextMenu();
MenuItem deleteItem = new MenuItem( "delete" );
deleteItem.setOnAction( (ActionEvent e) -> {
handleDeleteItem();
});
onList.getItems().addAll( deleteItem );
title.setContextMenu( onList );
filterAll.setSelected( true );
allSelected = ( Item i ) -> { return true; };
todaySelected = ( Item i ) -> { return i.getDueDate().equals(LocalDate.now());};
tomorrowSelected = ( Item i ) -> { return i.getDueDate().equals(LocalDate.now().plusDays(1));};
dueSelected = ( Item i ) -> { return i.getDueDate().isBefore(LocalDate.now()) && !i.isComplete();};
doneSelected = ( Item i ) -> { return i.isComplete(); };
filteredList = new FilteredList<Item>( StoreData.getInstance().getItems(), allSelected );
SortedList<Item> list = new SortedList< Item >( filteredList, ( Item i1, Item i2 ) -> {
if( i1.isComplete() && !i2.isComplete() ){
return 1;
} else if( !i1.isComplete() && i2.isComplete()) {
return -1;
}
if( i1.getDueDate().equals( i2.getDueDate() )){
return 0;
} else if( i1.getDueDate().isBefore( i2.getDueDate() )) {
return -1;
} else {
return 1;
}
});
title.setItems( list );
title.getSelectionModel().setSelectionMode( SelectionMode.SINGLE );
title.getSelectionModel().selectedItemProperty().addListener(
( ObservableValue<? extends Item> observable, Item oldItem, Item newItem ) -> {
if( newItem != null ){
updateScene();
}
});
title.setOnKeyPressed(
(KeyEvent e) -> {
if( e.getCode().equals( KeyCode.DELETE )){
handleDeleteItem();
}
});
status.setOnMouseClicked( ( MouseEvent e ) -> {
Item it = title.getSelectionModel().getSelectedItem();
it.setStatus( !it.isComplete() );
String s = "status: " +( (it.isComplete())? "completed" : "not completed");
status.setText( s );
StoreData.getInstance().remove( it );
StoreData.getInstance().add( it );
title.getSelectionModel().select( it );
});
if(!list.isEmpty()){
title.getSelectionModel().selectFirst();
}
title.setCellFactory( ( ListView<Item> it ) -> {
ListCell<Item> toRet = new ListCell<Item>() {
@Override
protected void updateItem( Item item, boolean empty ){
super.updateItem( item, empty );
if( empty ){
setText( null );
setStyle( null );
} else {
setText( item.getTitle() );
if( item.isComplete() ){
setStyle( "-fx-background-color: springgreen");
} else {
setStyle( null);
if( item.getDueDate().equals(LocalDate.now())){
setTextFill( Color.RED );
} else if( item.getDueDate().isBefore(LocalDate.now()) ){
setTextFill( Color.BLACK );
setStyle( "-fx-background-color: red");
} else if( item.getDueDate().equals( LocalDate.now().plusDays(1)) && !item.isComplete() ){
setTextFill( Color.BROWN );
setStyle( "-fx-Underline: true");
} else {
setTextFill( Color.BLACK );
}
}
}
}
};
return toRet;
});
}
@FXML
public void handleMouseClick( Event e ){
boolean isButton = newButton.equals( e.getSource() ) || edit.equals( e.getSource() );
boolean isTime = timePeriod.equals( e.getSource() );
if( !isButton && !isTime ){
System.out.println( "Error in the click handler" );
return;
}
Dialog<ButtonType> dialog = new Dialog<>();
FXMLLoader fxmlLoader = new FXMLLoader();
dialog.initOwner( borderPane.getScene().getWindow() );
if( isButton ){
if( ((Button)e.getSource()).equals(newButton)){
dialog.setTitle( "New Item" );
dialog.setHeaderText("add new item");
fxmlLoader.setLocation( getClass().getResource( "/rscr/newItem.fxml") );
} else {
if( title.getItems().isEmpty() ){
return;
}
dialog.setTitle( "edit Item" );
dialog.setHeaderText("edit item");
fxmlLoader.setLocation( getClass().getResource( "/rscr/newItem.fxml") );
}
} else {
dialog.setTitle( "Due Date" );
fxmlLoader.setLocation( getClass().getResource( "/rscr/DueDateDialog.fxml") );
}
try{
dialog.getDialogPane().setContent( fxmlLoader.load() );
if( isButton && ((Button)e.getSource()).equals(edit)){
((NewItem)fxmlLoader.getController()).editMode(title.getSelectionModel().getSelectedItem());
}
}
catch( Exception ex ){
ex.printStackTrace();
return;
}
dialog.getDialogPane().getButtonTypes().add( ButtonType.OK );
dialog.getDialogPane().getButtonTypes().add( ButtonType.CANCEL );
Optional<ButtonType> val = dialog.showAndWait();
if( val.isPresent() && val.get() == ButtonType.OK ){
Item it = title.getSelectionModel().getSelectedItem();
if( isButton ){
it = ((NewItem)fxmlLoader.getController()).saveItem();
if(!((Button)e.getSource()).equals(newButton) && it != null ){
StoreData.getInstance().remove( title.getSelectionModel().getSelectedItem());
}
} else {
LocalDate newDate = ((DateDialogControls) fxmlLoader.getController()).saveDate();
it.setDueDate( newDate );
StoreData.getInstance().remove( it );
StoreData.getInstance().add( it );
}
if( it != null ){
title.getSelectionModel().select( it );
} else {
title.getSelectionModel().selectFirst();
}
}
}
@FXML
public void handleDeleteItem() {
if( title.getItems().isEmpty() ){
return;
}
Item it = title.getSelectionModel().getSelectedItem();
Alert askDelete = new Alert( Alert.AlertType.CONFIRMATION );
askDelete.setTitle( "deletion??" );
askDelete.setHeaderText( "do you want to delete:: " + it.getTitle() );
Optional<ButtonType> val = askDelete.showAndWait();
if( val.isPresent() && val.get() == ButtonType.OK ){
StoreData.getInstance().remove( title.getSelectionModel().getSelectedItem() );
}
updateScene();
}
private void updateScene(){
if( title.getItems().isEmpty() ){
description.setText( null );
timePeriod.setText( null );
status.setText( null );
return;
}
Item it = title.getSelectionModel().getSelectedItem();
if( it.getDescription().isEmpty() ){
description.setText( null );
} else {
description.setText( it.getDescription() );
}
String s = df.format(it.getCreationDate()) + " -- " +
df.format(it.getDueDate());
timePeriod.setText( s );
s = "status: " +( (it.isComplete())? "completed" : "not completed");
status.setText( s );
}
@FXML
public void handleFilters( ActionEvent e ){
if( filterToday.isSelected() ) {
filteredList.setPredicate( todaySelected );
} else if( filterTomorrow.isSelected() ) {
filteredList.setPredicate( tomorrowSelected );
} else if( filterAlreadyDue.isSelected() ) {
filteredList.setPredicate( dueSelected );
} else if( filterCompleted.isSelected() ) {
filteredList.setPredicate( doneSelected );
} else {
filteredList.setPredicate( allSelected );
}
if( !title.getItems().isEmpty() ){
title.getSelectionModel().selectFirst();
}
updateScene();
}
@FXML
private RadioMenuItem filterToday;
@FXML
private RadioMenuItem filterTomorrow;
@FXML
private RadioMenuItem filterAlreadyDue;
@FXML
private RadioMenuItem filterCompleted;
@FXML
private RadioMenuItem filterAll;
@FXML
private ListView<Item> title;
@FXML
private Label timePeriod;
@FXML
private Label status;
@FXML
private TextArea description;
@FXML
private BorderPane borderPane;
@FXML
private Button newButton;
@FXML
private Button edit;
private final DateTimeFormatter df = DateTimeFormatter.ofPattern( "MMMM d, YYYY");
private FilteredList<Item> filteredList;
private Predicate<Item> allSelected;
private Predicate<Item> todaySelected;
private Predicate<Item> tomorrowSelected;
private Predicate<Item> dueSelected;
private Predicate<Item> doneSelected;
}
| true |
5ba065780ebb52006443427f07f3e8965ad451c6 | Java | nandhugigaappz/Wishil | /app/src/main/java/com/wishill/wishill/activity/profile/UserFollowingList.java | UTF-8 | 7,394 | 2 | 2 | [] | no_license | package com.wishill.wishill.activity.profile;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wishill.wishill.R;
import com.wishill.wishill.activity.CollegeDetailsActivity;
import com.wishill.wishill.activity.SchoolDetails;
import com.wishill.wishill.adapter.FollowingListAdapter;
import com.wishill.wishill.api.recommendedColleges.userfollowing.UserFollowingData;
import com.wishill.wishill.api.recommendedColleges.userfollowing.UserFollowingListAPI;
import com.wishill.wishill.api.recommendedColleges.userfollowing.UserFollowingResponse;
import com.wishill.wishill.utilities.APILinks;
import com.wishill.wishill.utilities.DialogProgress;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class UserFollowingList extends AppCompatActivity {
RecyclerView rvList;
LinearLayoutManager linearLayoutManager;
HttpLoggingInterceptor interceptor;
Gson gson;
Retrofit retrofit;
OkHttpClient client;
DialogProgress dialogProgress;
ProgressBar progress;
TextView tvNoItem;
TextView tvToolbarTitle;
SharedPreferences sharedPreferences;
String userId;
List<UserFollowingData> followingLIst;
FollowingListAdapter followingListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_following_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
sharedPreferences = getApplicationContext().getSharedPreferences("wishill", MODE_PRIVATE);
userId = sharedPreferences.getString("userId", "");
tvToolbarTitle = findViewById(R.id.toolbar_title);
interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient
.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(interceptor).build();
gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
retrofit = new Retrofit.Builder()
.baseUrl(APILinks.API_LINK)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
rvList = findViewById(R.id.rv_list);
//linearLayoutManager =new GridLayoutManager(UserFollowingList.this, 2);
linearLayoutManager =new LinearLayoutManager(UserFollowingList.this);
rvList.setLayoutManager(linearLayoutManager);
dialogProgress = new DialogProgress(UserFollowingList.this);
tvNoItem = findViewById(R.id.tv_no_item);
tvNoItem.setVisibility(View.GONE);
progress = findViewById(R.id.progress);
}
private void getList() {
retrofit.create(UserFollowingListAPI.class).post(userId)
.enqueue(new Callback<UserFollowingResponse>() {
@Override
public void onResponse(Call<UserFollowingResponse> call, Response<UserFollowingResponse> response) {
if (response.isSuccessful()) {
progress.setVisibility(View.GONE);
if (response.body().getStatus() == 1) {
followingLIst = response.body().getDataList();
if (followingLIst == null || followingLIst.size() == 0) {
tvNoItem.setVisibility(View.VISIBLE);
rvList.setVisibility(View.GONE);
tvToolbarTitle.setText("0 Following");
} else {
tvToolbarTitle.setText(followingLIst.size() + " Following");
tvNoItem.setVisibility(View.GONE);
rvList.setVisibility(View.VISIBLE);
followingListAdapter = new FollowingListAdapter(false, followingLIst, UserFollowingList.this, new FollowingListAdapter.ItemClickAdapterListener() {
@Override
public void itemClick(View v, int position) {
if(followingLIst.get(position).getTypeID().equals("1")){
Intent in = new Intent(UserFollowingList.this, CollegeDetailsActivity.class);
in.putExtra("collegeID", followingLIst.get(position).getItemID());
startActivity(in);
}else if(followingLIst.get(position).getTypeID().equals("2")){
Intent in=new Intent(UserFollowingList.this,SchoolDetails.class);
in.putExtra("schoolID",followingLIst.get(position).getItemID());
startActivity(in);
}
}
@Override
public void itemCall(View v, int position) {
}
@Override
public void itemSendEnq(View v, int position) {
}
});
rvList.setAdapter(followingListAdapter);
}
} else {
tvNoItem.setVisibility(View.VISIBLE);
}
} else {
}
}
@Override
public void onFailure(Call<UserFollowingResponse> call, Throwable t) {
}
});
}
@Override
protected void onResume() {
super.onResume();
getList();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
e2d46344bfb7b9e5ff98425da45bde67760470db | Java | romanticstxj/kafkatest | /kafkatest/src/test/java/michael/kafkatest/controller/TestControllerTest.java | UTF-8 | 4,080 | 2.546875 | 3 | [] | no_license | package michael.kafkatest.controller;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class TestControllerTest {
private static final int SIZE = 10;
@Test
public void test() throws InterruptedException{
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();
final HttpGet request = new HttpGet("http://localhost:8080/services/media/list");
System.out.println(" caller thread is: " + Thread.currentThread());
// ExecutorService es = Executors.newCachedThreadPool();
for(int i=0; i<SIZE; i++){
httpclient.execute(request, new FutureCallback<HttpResponse>() {
@Override
public void completed(final HttpResponse response) {
System.out.println(" callback thread id is : " + Thread.currentThread());
System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
try {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
// System.out.println(" response content is : " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(final Exception ex) {
System.out.println(request.getRequestLine() + "->" + ex);
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
}
@Override
public void cancelled() {
System.out.println(request.getRequestLine() + " cancelled");
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
}
});
}
Thread.sleep(10000);
try {
httpclient.close();
} catch (IOException ignore) {
}
}
public static void main(String[] argv) {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();
final CountDownLatch latch = new CountDownLatch(1);
final int a=0;
final HttpGet request = new HttpGet("http://localhost:8080/services/media/list");
System.out.println(" caller thread is: " + Thread.currentThread().getId());
// ExecutorService es = Executors.newCachedThreadPool();
// for(int i=0; i<SIZE; i++){
httpclient.execute(request, new FutureCallback<HttpResponse>() {
@Override
public void completed(final HttpResponse response) {
latch.countDown();
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
try {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
// System.out.println(" response content is : " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(request.getRequestLine() + "->" + ex);
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(request.getRequestLine() + " cancelled");
System.out.println(" callback thread id is : " + Thread.currentThread().getId());
}
});
// }
try {
System.out.println("latch await");
latch.await();
System.out.println("latch await completed");
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
httpclient.close();
} catch (IOException ignore) {
}
}
}
| true |
a6aded6614004ab60e46897c9b2be97f9ede3dff | Java | leleron/fsas | /platforms/android/src/com/phonegap/plugins/fileOperate/FileOperate.java | UTF-8 | 2,625 | 2.1875 | 2 | [] | no_license | package com.phonegap.plugins.fileOperate;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
/**
* This class echoes a string called from JavaScript.
*/
public class FileOperate extends CordovaPlugin {
/**
* Constructor.
*/
public FileOperate() {
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
String tp = args.getString(0);
Bitmap bitmap = null;
byte[] bitmapArray;
String[] btp = tp.split(",");
bitmapArray = Base64.decode(btp[1], Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,bitmapArray.length);
if (action.equals("savepng")) {
saveImageToGallery(this.cordova.getActivity().getApplicationContext(),bitmap);
callbackContext.success();
return true;
}
return false;
}
public static void saveImageToGallery(Context context, Bitmap bmp) {
File appDir = new File(Environment.getExternalStorageDirectory(), "flyco");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".png";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
}
} | true |
2368bcdf34217cd8172f0b49a96129b7e5423a72 | Java | ZoranLi/thunder | /com/taobao/tao/remotebusiness/listener/MtopFinishListenerImpl.java | UTF-8 | 4,137 | 1.625 | 2 | [] | no_license | package com.taobao.tao.remotebusiness.listener;
import com.taobao.tao.remotebusiness.IRemoteParserListener;
import com.taobao.tao.remotebusiness.MtopBusiness;
import com.taobao.tao.remotebusiness.a;
import com.taobao.tao.remotebusiness.auth.RemoteAuth;
import com.taobao.tao.remotebusiness.login.RemoteLogin;
import mtopsdk.common.util.j;
import mtopsdk.mtop.common.e;
import mtopsdk.mtop.common.i;
import mtopsdk.mtop.common.k;
import mtopsdk.mtop.util.b;
import mtopsdk.mtop.util.h;
class MtopFinishListenerImpl extends b implements e {
private static final String TAG = "mtop.rb-FinishListener";
public MtopFinishListenerImpl(MtopBusiness mtopBusiness, k kVar) {
super(mtopBusiness, kVar);
}
public void onFinished(i iVar, Object obj) {
j.b(this.mtopBusiness.getSeqNo(), "Mtop onFinish event received.");
if (this.mtopBusiness.isTaskCanceled() != null) {
j.a(this.mtopBusiness.getSeqNo(), "The request of RemoteBusiness is canceled.");
return;
}
obj = iVar.a;
if (obj == null) {
j.a(this.mtopBusiness.getSeqNo(), "The MtopResponse is null.");
} else if (obj.isSessionInvalid() && this.mtopBusiness.request.isNeedEcode() && this.mtopBusiness.getRetryTime() == 0) {
a.a(this.mtopBusiness);
RemoteLogin.login(this.mtopBusiness.isShowLoginUI(), obj);
} else {
String retCode = obj.getRetCode();
if (("FAIL_SYS_ACCESS_TOKEN_EXPIRED".equalsIgnoreCase(retCode) || "FAIL_SYS_ILLEGAL_ACCESS_TOKEN".equalsIgnoreCase(retCode)) && this.mtopBusiness.isNeedAuth() && this.mtopBusiness.getRetryTime() < 3) {
a.a(this.mtopBusiness);
RemoteAuth.authorize(this.mtopBusiness.authParam, this.mtopBusiness.request.getKey(), c.a(obj.getHeaderFields(), "x-act-hint"), this.mtopBusiness.showAuthUI);
return;
}
long j;
h mtopStat;
long currentTimeMillis = System.currentTimeMillis();
if (this.listener instanceof IRemoteParserListener) {
((IRemoteParserListener) this.listener).parseResponse(iVar.a);
}
iVar = com.taobao.tao.remotebusiness.a.a.a(this.listener, iVar, this.mtopBusiness);
iVar.e = obj;
long currentTimeMillis2 = System.currentTimeMillis();
mtopsdk.mtop.domain.a aVar = null;
if (obj != null) {
if (!obj.isApiSuccess() || this.mtopBusiness.clazz == null) {
j = currentTimeMillis2;
} else {
Class cls = this.mtopBusiness.clazz;
if (cls != null) {
if (obj != null) {
aVar = b.a(obj.getBytedata(), cls);
iVar.c = aVar;
j = System.currentTimeMillis();
}
}
j.e("outClass is null or response is null");
iVar.c = aVar;
j = System.currentTimeMillis();
}
mtopStat = obj.getMtopStat();
if (mtopStat == null) {
mtopStat = new h();
obj.setMtopStat(mtopStat);
}
} else {
mtopStat = null;
j = currentTimeMillis2;
}
this.mtopBusiness.onBgFinishTime = System.currentTimeMillis();
if (mtopStat != null) {
obj = mtopStat.h();
obj.b = this.mtopBusiness.sendStartTime - this.mtopBusiness.reqStartTime;
obj.a = currentTimeMillis - this.mtopBusiness.sendStartTime;
obj.c = this.mtopBusiness.onBgFinishTime - currentTimeMillis;
obj.f = currentTimeMillis2 - currentTimeMillis;
obj.e = j - currentTimeMillis2;
obj.d = this.mtopBusiness.onBgFinishTime - this.mtopBusiness.reqStartTime;
}
com.taobao.tao.remotebusiness.a.a.a().obtainMessage(3, iVar).sendToTarget();
}
}
}
| true |
93367e0483ff6ff44da31c9cc5443d66cd8da59d | Java | JohnnyPron/PO_Projekt1_ProniewiczJan | /main/java/agh/cs/project/main_objects/Jungle.java | UTF-8 | 3,719 | 3.09375 | 3 | [] | no_license | package agh.cs.project.main_objects;
import agh.cs.project.secondary_objects.Vector2d;
import agh.cs.project.interfaces.IWorldMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
public class Jungle {
private final Vector2d bottomLeftCorner;
private final Vector2d upperRightCorner;
private int width;
private int height;
private IWorldMap map;
private Map<Vector2d, Grass> grass = new LinkedHashMap<Vector2d, Grass>();
public Vector2d getBottomLeftCorner() { return bottomLeftCorner; }
public Vector2d getUpperRightCorner() { return upperRightCorner; }
public int getWidth() { return width; }
public int getHeight() { return height; }
public Map<Vector2d, Grass> getGrass() { return grass; }
public Jungle(IWorldMap map, Vector2d bottomLeftCorner, Vector2d upperRightCorner, int tufts){
this.map = map;
this.bottomLeftCorner = bottomLeftCorner;
this.upperRightCorner = upperRightCorner;
this.width = bottomLeftCorner.xRange(upperRightCorner);
this.height = bottomLeftCorner.yRange(upperRightCorner);
if(tufts > width * height) tufts = width * height;
for(int t = 0; t < tufts; t++){
Vector2d new_v = null; // utworzenie pustego wektora dla kępki trawy 't'
while (new_v == null) {
int rand_x = new Random().nextInt(upperRightCorner.getX() + 1 - bottomLeftCorner.getX()) +
bottomLeftCorner.getX();
int rand_y = new Random().nextInt(upperRightCorner.getY() + 1 - bottomLeftCorner.getY()) +
bottomLeftCorner.getY();
new_v = new Vector2d(rand_x, rand_y); // przypisanie wektorowi konkretnej wartości
// jeśli się okaże, że trawa na tej pozycji już występuje, wektor staje się pusty
Grass existingGrass = grass.get(new_v);
if(existingGrass != null){ new_v = null; }
}
grass.put(new_v, new Grass(new_v));
}
}
public Grass growGrass(){
Grass newTuft = null;
// sprawdzenie, czy wszystkie pola dżungli są zajęte (czy to przez trawę lub zwierzęta)
int occupiedPlaces = 0;
for(int i = bottomLeftCorner.getX(); i <= upperRightCorner.getX(); i++){
for(int j = bottomLeftCorner.getY(); j <= upperRightCorner.getY(); j++){
Vector2d vectorToCheck = new Vector2d(i, j);
if(map.isOccupied(vectorToCheck)){
occupiedPlaces++;
}
}
}
// jeśli nie, algorytm losuje / poszukuje wolnego miejsca dla nowej kępki trawy
if(occupiedPlaces != this.height * this.width){
Vector2d new_v = null;
while (new_v == null) {
int rand_x = new Random().nextInt(upperRightCorner.getX() + 1 - bottomLeftCorner.getX()) +
bottomLeftCorner.getX();
int rand_y = new Random().nextInt(upperRightCorner.getY() + 1 - bottomLeftCorner.getY()) +
bottomLeftCorner.getY();
new_v = new Vector2d(rand_x, rand_y);
// jeśli miejsce na mapie jest zajęte przez inną trawę lub zwierzę, pozycja jest resetowana
if(map.isOccupied(new_v)){ new_v = null; }
}
newTuft = new Grass(new_v);
grass.put(new_v, newTuft);
}
// zwrócenie kępki trawy dla mapy
return newTuft;
}
public void removeGrass(Vector2d grassPosition){ this.grass.remove(grassPosition); }
}
| true |
295ed10f811644f58284a2333c253ec976ebccd6 | Java | yisusxp90/AngularSpringBootappBackend | /src/main/java/com/yisusxp/spring/backend/api/repository/IFacturaRepository.java | UTF-8 | 305 | 1.632813 | 2 | [] | no_license | package com.yisusxp.spring.backend.api.repository;
import com.yisusxp.spring.backend.api.model.Factura;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface IFacturaRepository extends CrudRepository<Factura, Long> {
}
| true |
5c999b51b28d6ce5e3b6dbcd4e9a28cec224038d | Java | raidcraft/rcfarms | /src/main/java/de/raidcraft/rcfarms/tables/TFarm.java | UTF-8 | 3,563 | 2.21875 | 2 | [] | no_license | package de.raidcraft.rcfarms.tables;
import de.raidcraft.RaidCraft;
import de.raidcraft.rcfarms.RCFarmsPlugin;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.World;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* @author Philip Urban
*/
@Setter
@Getter
@Entity
@Table(name = "rcfarms_farms")
public class TFarm {
@Id
private int id;
private String name;
private Timestamp creationDate;
private UUID creatorId;
private String creator;
private String world;
@OneToMany(cascade = CascadeType.REMOVE)
@JoinColumn(name = "farm_id")
private Set<TMaterial> materials;
@OneToMany(cascade = CascadeType.REMOVE)
@JoinColumn(name = "farm_id")
private Set<TFarmLocation> keyPoints;
private Timestamp lastRegeneration;
private boolean allMaterials;
// in seconds
private long explicitRegenerationInterval;
public void addMaterial(TMaterial tMaterial) {
if (materials == null) {
materials = new HashSet<>();
}
materials.add(tMaterial);
}
public TFarmLocation[] getKeyPointArray() {
return keyPoints.toArray(new TFarmLocation[keyPoints.size()]);
}
public void addKeyPoint(TFarmLocation keyPoint) {
if (keyPoints == null) {
keyPoints = new HashSet<>();
}
keyPoints.add(keyPoint);
}
public void loadChildren() {
materials = RaidCraft.getDatabase(RCFarmsPlugin.class).find(TMaterial.class).where().eq("farm_id", id).findSet();
keyPoints = RaidCraft.getDatabase(RCFarmsPlugin.class).find(TFarmLocation.class).where().eq("farm_id", id).findSet();
}
public World getBukkitWorld() {
TFarmLocation[] keyPoints = getKeyPointArray();
return Bukkit.getWorld(keyPoints[0].getWorld());
}
@Deprecated
public String getCreator() {
return creator;
}
@Deprecated
public void setCreator(String creator) {
this.creator = creator;
}
public String getWorld() {
return world;
}
public Timestamp getCreationTime() {
return creationDate;
}
public String getCreatorName() {
return creator;
}
public String getWorldName() {
return world;
}
public Timestamp getLastRegenerationTime() {
return lastRegeneration;
}
public boolean isAllMaterialFarm() {
return allMaterials;
}
public boolean isPlayerInside() {
// TODO: finish it
// TODO check take to much time
// TFarmLocation[] kp = getKeyPointArray();
//
// for(Player player : Bukkit.getOnlinePlayers()) {
// Location loc = player.getLocation();
// if(loc.getBlockX() >= Math.min(kp[0].getX(), kp[1].getX()) && loc.getBlockX() <= Math.max(kp[0].getX(), kp[1].getX())
// && loc.getBlockY() >= Math.min(kp[0].getY(), kp[1].getY()) && loc.getBlockY() <= Math.max(kp[0].getY(), kp[1].getY())
// && loc.getBlockZ() >= Math.min(kp[0].getZ(), kp[1].getZ()) && loc.getBlockZ() <= Math.max(kp[0].getZ(), kp[1].getZ())) {
// return true;
// }
// }
return false;
}
}
| true |
f3d99eed4bc377e1edd5cf828e3527ade1538aea | Java | sudha-shanker/CustomExtendingViews | /app/src/main/java/com/example/customextendingviews/CustomViewFan.java | UTF-8 | 1,495 | 2.671875 | 3 | [] | no_license | package com.example.customextendingviews;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
public class CustomViewFan extends View {
Paint p;
int x=100;
public CustomViewFan(Context context)
{
super(context);
init();
}
public void init() {
p = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.RED);
p.setColor(Color.YELLOW);
canvas.drawRect(100,100,500,500,p);
p.setColor(Color.GREEN);
canvas.drawArc(500,500,800,800,x,30,
true,p);
canvas.drawArc(500,500,800,800,x+120,
30,true,p);
canvas.drawArc(500,500,800,800, x+240,
30,true,p);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
for(int i=0;i<=50000;i++) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startFan();
break;
case MotionEvent.ACTION_UP:
stopFan();
break;
}
}
return true;
}
public void stopFan() {
}
public void startFan() {
x = x+5;
// invalidate() means redraw on screen and results to a call of the view's onDraw() method
invalidate();
}
}
| true |
93a9ca5053827f0069984414bbe4693250c502b7 | Java | lauren-dai/FinancialRecorder | /FinancialRecorderServer/src/main/java/com/financial/tools/recorderserver/business/FinancialManager.java | UTF-8 | 3,110 | 2.46875 | 2 | [] | no_license | package com.financial.tools.recorderserver.business;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.financial.tools.recorderserver.entity.FinancialRecord;
import com.financial.tools.recorderserver.entity.User;
import com.financial.tools.recorderserver.payload.FinancialRecordListResponse;
import com.financial.tools.recorderserver.payload.FinancialRecordRequest;
import com.financial.tools.recorderserver.payload.UserFinancialInfoResponse;
import com.financial.tools.recorderserver.store.FinancialRecordStore;
import com.financial.tools.recorderserver.store.UserStore;
import com.google.common.collect.Lists;
public class FinancialManager {
private UserStore userStore;
private FinancialRecordStore financialRecordStore;
public long updateUserBalance(long userId, long amount) {
User user = userStore.getUser(userId);
long balance = user.getBalance() + amount;
userStore.updateBalance(user.getId(), balance);
return balance;
}
public long createFinancialRecord(FinancialRecordRequest financialRecordRequest) {
List<User> userList = Lists.newArrayList();
for (Long userId : financialRecordRequest.getUserIdList()) {
userList.add(userStore.getUser(userId));
}
FinancialRecord financialRecord = new FinancialRecord();
financialRecord.setName(financialRecordRequest.getName());
financialRecord.setTotalFee(financialRecordRequest.getTotalFee());
financialRecord.setUserList(userList);
return financialRecordStore.createFinancialRecord(financialRecord);
}
public List<FinancialRecordListResponse> listFinancialRecords() {
List<FinancialRecordListResponse> recordList = Lists.newArrayList();
List<FinancialRecord> financialRecordList = financialRecordStore.listFinancialRecords();
for (FinancialRecord financialRecord : financialRecordList) {
FinancialRecordListResponse record = new FinancialRecordListResponse();
record.setName(financialRecord.getName());
record.setTotalFee(financialRecord.getTotalFee());
List<String> userNameList = Lists.newArrayList();
for (User user : financialRecord.getUserList()) {
userNameList.add(user.getName());
}
record.setUserNameList(userNameList);
recordList.add(record);
}
return recordList;
}
public void updateFinance(long financialRecordId) {
FinancialRecord financialRecord = financialRecordStore.getFinancialRecord(financialRecordId);
long totalFee = financialRecord.getTotalFee();
List<User> userList = financialRecord.getUserList();
long feePerUser = totalFee / userList.size();
for (User user : userList) {
userStore.updateBalance(user.getId(), user.getBalance() - feePerUser);
}
}
public UserFinancialInfoResponse getUserFinancialInfo(long userId) {
User user = userStore.getUser(userId);
return new UserFinancialInfoResponse(user.getName(), user.getBalance());
}
@Autowired
public void setUserStore(UserStore userStore) {
this.userStore = userStore;
}
@Autowired
public void setFinancialRecordStore(FinancialRecordStore financialRecordStore) {
this.financialRecordStore = financialRecordStore;
}
}
| true |
a0bc96cce96753202fe4fc65a60093162cf5ac6b | Java | cckmit/iot-6 | /src/main/java/com/dsw/iot/controller/rpc/VideoRpc.java | UTF-8 | 2,097 | 2.140625 | 2 | [] | no_license | package com.dsw.iot.controller.rpc;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dsw.iot.dto.FaceBaseInfoRequest;
import com.dsw.iot.dto.FaceHeadInfoDto;
import com.dsw.iot.manager.FaceManager;
import com.dsw.iot.manager.VideoManager;
import com.dsw.iot.model.AttachDo;
import com.dsw.iot.util.BizException;
import com.dsw.iot.util.PageResult;
import com.dsw.iot.vo.FaceBaseInfoVo;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* 视频抓拍rpc
*
* @author huangt
* @create 2018-01-18 8:40
**/
@RestController
@RequestMapping("/Video")
public class VideoRpc {
protected static final Logger logger = Logger.getLogger(VideoRpc.class);
@Autowired
private VideoManager videoManager;
@Autowired
private FaceManager faceManager;
/**
* 根据通道号进行抓拍
* 实验室 47通道号
*
* @param type
* @return
*/
@RequestMapping("/captureByChannel")
public AttachDo captureByChannel(String type) throws BizException {
return videoManager.capture(type);
}
/**
* 消息订阅-接收云从报警信息
*/
@RequestMapping("/subscribeFaceMsg")
public void subscribeFaceMsg(HttpServletRequest request) {
try {
String body = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
FaceHeadInfoDto faceHeadInfoDto = JSONObject.parseObject(body, new TypeReference<FaceHeadInfoDto>() {
});
faceManager.saveFaceInfo(faceHeadInfoDto);
} catch (Exception e) {
logger.error("云从报警信息接口异常", e);
}
}
@RequestMapping("/queryPage")
public PageResult<FaceBaseInfoVo> queryPage(FaceBaseInfoRequest request) {
return faceManager.queryPage(request);
}
}
| true |
3d1d006c30e6815233f1a6a7bc63b1426f0db9e9 | Java | cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | /ast_results/tejado_Authorizer/lib/src/main/java/net/tjado/passwdsafe/lib/view/GuiUtilsFroyo.java | UTF-8 | 1,458 | 1.976563 | 2 | [] | no_license | // isComment
package net.tjado.passwdsafe.lib.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.view.View;
/**
* isComment
*/
@TargetApi(isIntegerConstant)
public final class isClassOrIsInterface {
/**
* isComment
*/
public static class isClassOrIsInterface implements DialogInterface.OnShowListener, Runnable {
private final View isVariable;
private final Context isVariable;
/**
* isComment
*/
public isConstructor(View isParameter, Context isParameter) {
isNameExpr = isNameExpr;
isNameExpr = isNameExpr;
}
/*isComment*/
public void isMethod(DialogInterface isParameter) {
isMethod();
}
@Override
public void isMethod() {
isNameExpr.isMethod();
isNameExpr.isMethod(isNameExpr, isNameExpr, true);
}
}
/**
* isComment
*/
public static void isMethod(View isParameter, Context isParameter) {
isNameExpr.isMethod(new KeyboardViewer(isNameExpr, isNameExpr));
}
/**
* isComment
*/
@SuppressWarnings("isStringConstant")
public static Drawable isMethod(Resources isParameter, int isParameter) {
return isNameExpr.isMethod(isNameExpr);
}
}
| true |
924337d58668bd9845c9e1e2a6c660e4af2f8be6 | Java | abirahmeds/CSE114 | /Labs/Lab18.java | UTF-8 | 1,992 | 3.75 | 4 | [] | no_license | package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows and columns in the array: ");
int r = sc.nextInt();
int c = sc.nextInt();
double[][] x = new double[r][c];
System.out.println("Enter the array: ");
for (int i = 0; i < x.length; i++){
for (int j = 0; j < x[i].length; j++){
x[i][j] = sc.nextDouble();
}
}
int[] loca = locateLargest(x);
System.out.println("The location of the largest element is at (" +
loca[0] + ", " + loca[1] + ")");
double[][] ma = new double[3][3];
System.out.println("\nEnter a 3-by-3 matrix row by row: ");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
ma[i][j] = sc.nextDouble();
}
}
if(isMarkovMatrix(ma)){
System.out.println("It is a Markov matrix");
}
else{
System.out.println("It is not a Markov matrix");
}
}
public static int[] locateLargest(double[][] a) {
int[] loc = new int[2];
double max = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] > max){
loc[0] = i;
loc[1] = j;
max = a[i][j];
}
}
}
return loc;
}
public static boolean isMarkovMatrix(double[][] m){
for (int j = 0; j < m[0].length; j++) {
double sum = 0;
for (int i = 0; i < m.length; i++) {
double num = m[i][j];
if (num < 0)
return false;
sum += num;
}
if (sum != 1)
return false;
}
return true;
}
}
| true |
561230ee53654752f3b5edc3c3d1a6f7d4a723ed | Java | himanshu-rana1/SomeAlgorithms | /MergeSort.java | UTF-8 | 529 | 3.3125 | 3 | [] | no_license | package TopAlgorithms;
import java.util.Scanner;
public class MergeSort {
public void mSort(int[] a, int p, int q){
if(p<q){
}
}
public static void main(String[] args) {
System.out.println("Enter Size");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] a = new int[size];
for(int i=0; i<size; i++){
a[i] = sc.nextInt();
}
MergeSort mergeSort = new MergeSort();
mergeSort.mSort(a, 0, size-1);
}
}
| true |
c80b55ee0f133b07128d4be793e6e7e5c75a3675 | Java | aportolan/kps | /kps/src/main/java/hr/aportolan/kps/entity/Subscribers.java | UTF-8 | 1,851 | 2.296875 | 2 | [] | no_license | package hr.aportolan.kps.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Subscribers {
public Subscribers(String id, String name, String type, Routes route, Routes parentRoute) {
super();
this.id = id;
this.name = name;
this.type = type;
this.route = route;
this.parentRoute = parentRoute;
}
public Subscribers() {
}
@Id
private String id;
private String name;
private String type;
private Routes route;
private Routes parentRoute;
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 getType() {
return type;
}
public void setType(String type) {
this.type = type; // TODO Auto-generated constructor stub
}
public Routes getRoute() {
return route;
}
public void setRoute(Routes route) {
this.route = route;
}
public Routes getParentRoute() {
return parentRoute;
}
public void setParentRoute(Routes parentRoute) {
this.parentRoute = parentRoute;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Subscribers other = (Subscribers) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Subscribers [id=" + id + ", name=" + name + ", type=" + type + ", route=" + route + ", parentRoute="
+ parentRoute + "]";
}
}
| true |
1b85edbe84c448df2eda0dc9ac98d1cbc07f3b8c | Java | elkana911/b2b-big2 | /src/main/java/com/big/web/b2b_big2/booking/model/BookingFlightVO.java | UTF-8 | 17,203 | 1.632813 | 2 | [] | no_license | package com.big.web.b2b_big2.booking.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlTransient;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.jfree.util.Log;
import org.springframework.util.StringUtils;
import com.big.web.b2b_big2.booking.BOOK_STATUS;
import com.big.web.b2b_big2.finance.cart.pojo.FlightCart;
import com.big.web.b2b_big2.flight.Airline;
import com.big.web.b2b_big2.flight.pojo.FareInfo;
import com.big.web.b2b_big2.flight.pojo.PNR;
import com.big.web.b2b_big2.util.Utils;
import com.big.web.model.User;
@Entity
@Table(name="booking_flight")
public class BookingFlightVO implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4028860626048504341L;
public static final String TABLE_NAME = "booking_flight";
// public static final int INSURANCE_COMMISSION_IDR = 8000;
// public static final int INSURANCE_FARE_IDR = 32000;
private String id;
private String code;
private String status; //BOOK_STATUS.java
private String groupCode; //gabungan code-code
private String ccy; //currency
private BigDecimal insurance;
private BigDecimal insuranceCommission;
private String insurance_flag; //Y or N/Null
private BigDecimal serviceFee; //bisa plus bisa minus, sangat tergantung dr promo. biasanya null
private BigDecimal serviceFeeCommission; //sub agent bisa menambah sesukanya
private String service_flag; //Y or N/Null
private BigDecimal nta; //disini harga tiket sudah termasuk pajak
private BigDecimal ntaCommission;
private Date createdDate;
private Date lastUpdate;
private Date issuedDate;
private User user;
private String originIata;
private String destinationIata;
private Date departure_date;
private Date return_date;
private String return_flag;
private String agentId; // agent dr airline bersangkutan. bukan agent yg login aplikasi berleha.
private String radio_id;
private String airlines_iata;
private String cust_name;
private String cust_phone1;
private String cust_phone2;
private Date timeToPay; //waktu remaining utk pembeli melakukan pembayaran
private BigDecimal book_balance; //kayanya: jika book_balance=normal_sales itu brarti belum dibayar sama sekali,
private BigDecimal amount; //diisi SETELAH booking via airline
private String promo_code;
private String journey_sell_key;
private String updateCode;
private String reff_no;
private String radioid_return;
/* dipindah ke booking_flight_trans
private BigDecimal total_basefare;
private BigDecimal total_commission;
private BigDecimal total_tax;
private BigDecimal total_issued;
private BigDecimal total_psc;
private BigDecimal total_iwjr;
private BigDecimal total_surchargefee;
*/
//dipakai utk display saja
//private FlightItinerary itineraries;
private List<FareInfo> itineraries;
private List<PNR> pnr;
private BookingFlightTransVO detailTransaction; //transient, for report only
public BookingFlightVO() {
setId(java.util.UUID.randomUUID().toString());
}
public BookingFlightVO(FlightCart cart) {
this();
setOriginIata(cart.getOriginIata());
setDestinationIata(cart.getDestinationIata());
setReturn_flag(String.valueOf(cart.getTripMode()));
setDeparture_date(cart.getDepartDate());
setReturn_date(cart.getTripMode() == 0 ? null : cart.getReturnDate());
/*
* terkait bu fini minta dipisahin radioid yg return
if (cart.getRadioIds() != null){
try {
setRadio_id(StringUtils.arrayToCommaDelimitedString(cart.getDepartFlightItinerary().getRadioIds()));
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
try {
setRadioid_return(StringUtils.arrayToCommaDelimitedString(cart.getReturnFlightItinerary().getRadioIds()));
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
}
*/
if (cart.getDepartFlightItinerary() != null){
try {
String[] _b1 = cart.getDepartFlightItinerary().getRadioIds();
if (!Utils.isEmpty(_b1))
setRadio_id(StringUtils.arrayToCommaDelimitedString(_b1));
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
}
if (cart.getReturnFlightItinerary() != null){
try {
String[] _b1 = cart.getReturnFlightItinerary().getRadioIds();
if (!Utils.isEmpty(_b1))
setRadioid_return(StringUtils.arrayToCommaDelimitedString(_b1));
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
}
setInsurance_flag(cart.isUseInsurance() ? "Y" : "N");
setServiceFee(BigDecimal.ZERO);
setServiceFeeCommission(BigDecimal.ZERO);
setInsurance(BigDecimal.ZERO);
setInsuranceCommission(BigDecimal.ZERO);
}
@Id
@XmlTransient
@JsonIgnore
@Column(name="ID", length=40, nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(length=10)
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(length=15)
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Column(length=20)
public String getGroupCode() {
return groupCode;
}
public void setGroupCode(String groupCode) {
this.groupCode = groupCode;
}
@Column(length=3)
public String getCcy() {
return ccy;
}
public void setCcy(String ccy) {
this.ccy = ccy;
}
public BigDecimal getInsurance() {
return insurance;
}
public void setInsurance(BigDecimal insurance) {
this.insurance = insurance;
}
@Column(name = "ins_commission")
public BigDecimal getInsuranceCommission(){
return insuranceCommission;// new BigDecimal(INSURANCE_COMMISSION_IDR);
}
public void setInsuranceCommission(BigDecimal insuranceCommission) {
this.insuranceCommission = insuranceCommission;
}
@Column(length=1)
public String getInsurance_flag() {
return insurance_flag;
}
public void setInsurance_flag(String insurance_flag) {
this.insurance_flag = insurance_flag;
}
@Transient
public boolean isInsuranced(){
return insurance_flag == null ? false : insurance_flag.equalsIgnoreCase("Y");
}
@Transient
public boolean isService(){
return service_flag == null ? false : service_flag.equalsIgnoreCase("Y");
}
public BigDecimal getNta() {
return nta;
}
public void setNta(BigDecimal nta) {
this.nta = nta;
}
@Column(name="nta_commission")
public BigDecimal getNtaCommission() {
return ntaCommission;
}
public void setNtaCommission(BigDecimal ntaCommission) {
this.ntaCommission = ntaCommission;
}
public BigDecimal getServiceFee() {
return serviceFee;
}
public void setServiceFee(BigDecimal serviceFee) {
this.serviceFee = serviceFee;
}
@Column(name="svc_commission")
public BigDecimal getServiceFeeCommission() {
return serviceFeeCommission;
}
public void setServiceFeeCommission(BigDecimal serviceFeeCommission) {
this.serviceFeeCommission = serviceFeeCommission;
}
@Column(length=1)
public String getService_flag() {
return service_flag;
}
public void setService_flag(String service_flag) {
this.service_flag = service_flag;
}
/* table descriptions of amunts
NTSA COMMISSION PAX PAID
TICKET 9,643,250 269,250 9,912,500
INSURANCE 32,000 8,000 40,000
SERVICE FEE 0 10,000 10,000
TOTAL 9,675,250 287,250 9,962,500
*/
@Transient
public BigDecimal getAmountNTAServiceInsurance() { //9,962,500
BigDecimal sum = BigDecimal.ZERO;
return sum.add(getAmountNTA())
.add(serviceFee == null ? BigDecimal.ZERO : serviceFee)
.add(getInsurancePax());
}
@Transient
public BigDecimal getNtaAmount(){
BigDecimal sum = BigDecimal.ZERO;
return sum.add(getNta() == null ? BigDecimal.ZERO : getNta())
.add(serviceFee == null ? BigDecimal.ZERO : serviceFee)
.add(insurance == null ? BigDecimal.ZERO : insurance);
}
/**
* harga NTSA plus Commission
* @return
*/
@Transient
public BigDecimal getAmountNTA(){ //9,912,500
BigDecimal sum = BigDecimal.ZERO;
return sum.add(nta == null ? BigDecimal.ZERO : nta)
.add(ntaCommission == null ? BigDecimal.ZERO : ntaCommission)
;
}
/**
* harga insurance utk NTSA plus harga insurance utk commission
* @return
*/
@Transient
public BigDecimal getInsurancePax(){ //40,000
BigDecimal sum = BigDecimal.ZERO;
if (isInsuranced()){
sum = sum.add(getInsurance() == null ? BigDecimal.ZERO : getInsurance())
.add(getInsuranceCommission() == null ? BigDecimal.ZERO : getInsuranceCommission() )
;
}
return sum;
}
@Transient
public BigDecimal getServicePax(){ //40,000
BigDecimal sum = BigDecimal.ZERO;
if (isService()){
sum = sum.add(getServiceFee() == null ? BigDecimal.ZERO : getServiceFee() )
.add( getServiceFeeCommission() == null ? BigDecimal.ZERO : getServiceFeeCommission())
;
}
return sum;
}
@ManyToOne
@JoinColumn(name="userid")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
@Column(name = "issued_date")
public Date getIssuedDate() {
return issuedDate;
}
public void setIssuedDate(Date issuedDate) {
this.issuedDate = issuedDate;
}
@Column(name="origin", length=3)
public String getOriginIata() {
return originIata;
}
public void setOriginIata(String originIata) {
this.originIata = originIata;
}
@Column(name="destination", length=3)
public String getDestinationIata() {
return destinationIata;
}
public void setDestinationIata(String destinationIata) {
this.destinationIata = destinationIata;
}
public Date getDeparture_date() {
return departure_date;
}
public void setDeparture_date(Date departure_date) {
this.departure_date = departure_date;
}
public Date getReturn_date() {
return return_date;
}
public void setReturn_date(Date return_date) {
this.return_date = return_date;
}
@Column(length=1)
public String getReturn_flag() {
return return_flag;
}
public void setReturn_flag(String return_flag) {
this.return_flag = return_flag;
}
@Column(length=40)
public String getAgentId() {
return agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
@Column(length = 700)
public String getRadio_id() {
return radio_id;
}
public void setRadio_id(String radio_id) {
this.radio_id = radio_id;
}
@Column(length=30)
public String getAirlines_iata() {
return airlines_iata;
}
public void setAirlines_iata(String airlines_iata) {
this.airlines_iata = airlines_iata;
}
@Transient public Airline[] getAirlines(){
String[] s = org.apache.commons.lang.StringUtils.split(airlines_iata, ',');
Airline[] a = new Airline[s.length];
for (int i = 0; i < s.length; i++){
a[i] = Airline.getAirlineByCode(s[i]);
}
return a;
}
/**
* @see #getAirlines()
* @return
*/
@Transient public Airline getFirstAirline(){
String[] s = org.apache.commons.lang.StringUtils.split(airlines_iata, ',');
Airline[] a = new Airline[s.length];
for (int i = 0; i < s.length; i++){
a[i] = Airline.getAirlineByCode(s[i]);
return a[i];
}
return null;
}
@Transient public boolean showBirthday(){
Airline[] airlines = Airline.getAirlinesByCode(airlines_iata);
boolean sum = false;
for (int i = 0; i < airlines.length; i++){
sum = sum || Airline.isAdultBirthdayRequired(airlines[i]);
}
return sum;
}
/*
@Transient
public FlightItinerary getItineraries() {
return itineraries;
}
public void setItineraries(FlightItinerary itineraries) {
this.itineraries = itineraries;
}*/
@Column(length = 100)
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
@Column(length = 20)
public String getCust_phone1() {
return cust_phone1;
}
public void setCust_phone1(String cust_phone1) {
this.cust_phone1 = cust_phone1;
}
@Column(length = 20)
public String getCust_phone2() {
return cust_phone2;
}
public void setCust_phone2(String cust_phone2) {
this.cust_phone2 = cust_phone2;
}
public Date getTimeToPay() {
return timeToPay;
}
public void setTimeToPay(Date timeToPay) {
this.timeToPay = timeToPay;
}
public BigDecimal getBook_balance() {
return book_balance;
}
public void setBook_balance(BigDecimal book_balance) {
this.book_balance = book_balance;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
@Column(length = 10)
public String getPromo_code() {
return promo_code;
}
public void setPromo_code(String promo_code) {
this.promo_code = promo_code;
}
@Column(length = 255)
public String getJourney_sell_key() {
return journey_sell_key;
}
public void setJourney_sell_key(String journey_sell_key) {
this.journey_sell_key = journey_sell_key;
}
// @Column(length = 20) 15 jun 2015
@Column(length = 40)
public String getUpdateCode() {
return updateCode;
}
public void setUpdateCode(String updateCode) {
this.updateCode = updateCode;
}
@Column(length = 40)
public String getReff_no() {
return reff_no;
}
public void setReff_no(String reff_no) {
this.reff_no = reff_no;
}
@Column(length = 700)
public String getRadioid_return() {
return radioid_return;
}
public void setRadioid_return(String radioid_return) {
this.radioid_return = radioid_return;
}
@Transient
public List<FareInfo> getItineraries() {
return itineraries;
}
public void setItineraries(List<FareInfo> itineraries) {
this.itineraries = itineraries;
}
@Transient
public BookingFlightTransVO getDetailTransaction() {
return detailTransaction;
}
public void setDetailTransaction(BookingFlightTransVO detailTransaction) {
this.detailTransaction = detailTransaction;
}
@Transient
public List<PNR> getPnr() {
return pnr;
}
public void setPnr(List<PNR> pnr) {
this.pnr = pnr;
}
@Transient
public String getPaxName(){
return "";
}
@Transient
public String getBookedBy(){
String usr = "";
if (user != null){
usr = user.getUsername();
}
return usr;
}
@Transient
public String getRoute(){
return originIata + " - " + destinationIata;
}
@Transient
public boolean isCanceled() {
String _status;
//for connecting flight, such as XX, XX -> take XX
//such as XX, HK -> false by difference, not because of XX
String[] buf = Utils.splitBookStatus(status);
if (buf.length > 1){
String s = buf[0].trim();
for (int i = 1; i < buf.length; i++){
//jika ketemu XX,HK
if (!s.equalsIgnoreCase(buf[i].trim())){
return false;
}
}
_status = s;
}else
_status = status;
return _status.toLowerCase().startsWith("cancel")
|| BOOK_STATUS.getStatus(_status) == BOOK_STATUS.XX
;
}
@Override
public String toString() {
return "BookingFlightVO [id=" + id + ", code=" + code + ", status="
+ status + ", groupCode=" + groupCode + ", ccy=" + ccy
+ ", insurance=" + insurance + ", insuranceCommission="
+ insuranceCommission + ", insurance_flag=" + insurance_flag
+ ", serviceFee=" + serviceFee + ", serviceFeeCommission="
+ serviceFeeCommission + ", service_flag=" + service_flag
+ ", nta=" + nta + ", ntaCommission=" + ntaCommission
+ ", createdDate=" + createdDate + ", lastUpdate=" + lastUpdate
+ ", issuedDate=" + issuedDate + ", user=" + user
+ ", originIata=" + originIata + ", destinationIata="
+ destinationIata + ", departure_date=" + departure_date
+ ", return_date=" + return_date + ", return_flag="
+ return_flag + ", agentId=" + agentId + ", radio_id="
+ radio_id + ", airlines_iata=" + airlines_iata
+ ", cust_name=" + cust_name + ", cust_phone1=" + cust_phone1
+ ", cust_phone2=" + cust_phone2 + ", timeToPay=" + timeToPay
+ ", book_balance=" + book_balance + ", amount=" + amount
+ ", promo_code=" + promo_code + ", journey_sell_key="
+ journey_sell_key + ", updateCode=" + updateCode
+ ", reff_no=" + reff_no + ", radioid_return=" + radioid_return
+ ", itineraries=" + itineraries + ", pnr=" + pnr
+ ", detailTransaction=" + detailTransaction + "]";
}
/*
(BaseFare * PaxCount * Commission) - IssuedFee
@Transient
public BigDecimal getSum_Commission(int paxCount){
BigDecimal a = getTotal_basefare().multiply(new BigDecimal(paxCount)).multiply(getTotal_commission());
return a.subtract(getTotal_issued());
}
@Transient
public BigDecimal getTicketNtsa(int paxCount) {
return getAmount().subtract(getSum_Commission(paxCount));
}
@Transient
public BigDecimal getTicketCommission(int paxCount) {
return getSum_Commission(paxCount);
}
*/
}
| true |
811ac89bf4672d3936b10ec5a621a7f132220b11 | Java | sameer-sarmah/algorithm | /Algorithm/src/tree/IterativePreOrder.java | UTF-8 | 880 | 4.0625 | 4 | [] | no_license | package tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class IterativePreOrder {
public static void main(String[] args) {
TreeNode<Integer> root = TreeCreator.createBinarySearchTree();
Stack<TreeNode<Integer>> callStack = new Stack<TreeNode<Integer>>();
callStack.push(root);
iterativePreOrder(callStack);
}
// in order tree traversal without recursion
private static <T extends Comparable<T>> void iterativePreOrder(Stack<TreeNode<T>> callStack) {
List<TreeNode<T>> result = new ArrayList<>();
while (!callStack.isEmpty()) {
TreeNode<T> node = callStack.pop();
result.add(node);
if (node.getRight() != null) {
callStack.add(node.getRight());
}
if (node.getLeft() != null) {
callStack.add(node.getLeft());
}
}
result.forEach((node) -> System.out.printf(node.getValue() + " "));
}
}
| true |
7eeb5968b2f2d786b61df15311260cbe406ea173 | Java | habeascorpus/habeascorpus-data | /tokens/lucene-3.6.2/core/src/java/org/apache/lucene/store/LockVerifyServer.java | UTF-8 | 8,322 | 1.820313 | 2 | [] | no_license | package TokenNamepackage
org TokenNameIdentifier
. TokenNameDOT
apache TokenNameIdentifier
. TokenNameDOT
lucene TokenNameIdentifier
. TokenNameDOT
store TokenNameIdentifier
; TokenNameSEMICOLON
import TokenNameimport
java TokenNameIdentifier
. TokenNameDOT
net TokenNameIdentifier
. TokenNameDOT
ServerSocket TokenNameIdentifier
; TokenNameSEMICOLON
import TokenNameimport
java TokenNameIdentifier
. TokenNameDOT
net TokenNameIdentifier
. TokenNameDOT
Socket TokenNameIdentifier
; TokenNameSEMICOLON
import TokenNameimport
java TokenNameIdentifier
. TokenNameDOT
io TokenNameIdentifier
. TokenNameDOT
OutputStream TokenNameIdentifier
; TokenNameSEMICOLON
import TokenNameimport
java TokenNameIdentifier
. TokenNameDOT
io TokenNameIdentifier
. TokenNameDOT
InputStream TokenNameIdentifier
; TokenNameSEMICOLON
import TokenNameimport
java TokenNameIdentifier
. TokenNameDOT
io TokenNameIdentifier
. TokenNameDOT
IOException TokenNameIdentifier
; TokenNameSEMICOLON
public TokenNamepublic
class TokenNameclass
LockVerifyServer TokenNameIdentifier
{ TokenNameLBRACE
private TokenNameprivate
static TokenNamestatic
String TokenNameIdentifier
getTime TokenNameIdentifier
( TokenNameLPAREN
long TokenNamelong
startTime TokenNameIdentifier
) TokenNameRPAREN
{ TokenNameLBRACE
return TokenNamereturn
"[" TokenNameStringLiteral
+ TokenNamePLUS
( TokenNameLPAREN
( TokenNameLPAREN
System TokenNameIdentifier
. TokenNameDOT
currentTimeMillis TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
- TokenNameMINUS
startTime TokenNameIdentifier
) TokenNameRPAREN
/ TokenNameDIVIDE
1000 TokenNameIntegerLiteral
) TokenNameRPAREN
+ TokenNamePLUS
"s] " TokenNameStringLiteral
; TokenNameSEMICOLON
} TokenNameRBRACE
public TokenNamepublic
static TokenNamestatic
void TokenNamevoid
main TokenNameIdentifier
( TokenNameLPAREN
String TokenNameIdentifier
[ TokenNameLBRACKET
] TokenNameRBRACKET
args TokenNameIdentifier
) TokenNameRPAREN
throws TokenNamethrows
IOException TokenNameIdentifier
{ TokenNameLBRACE
if TokenNameif
( TokenNameLPAREN
args TokenNameIdentifier
. TokenNameDOT
length TokenNameIdentifier
!= TokenNameNOT_EQUAL
1 TokenNameIntegerLiteral
) TokenNameRPAREN
{ TokenNameLBRACE
System TokenNameIdentifier
. TokenNameDOT
out TokenNameIdentifier
. TokenNameDOT
println TokenNameIdentifier
( TokenNameLPAREN
" Usage: java org.apache.lucene.store.LockVerifyServer port " TokenNameStringLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
System TokenNameIdentifier
. TokenNameDOT
exit TokenNameIdentifier
( TokenNameLPAREN
1 TokenNameIntegerLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
} TokenNameRBRACE
final TokenNamefinal
int TokenNameint
port TokenNameIdentifier
= TokenNameEQUAL
Integer TokenNameIdentifier
. TokenNameDOT
parseInt TokenNameIdentifier
( TokenNameLPAREN
args TokenNameIdentifier
[ TokenNameLBRACKET
0 TokenNameIntegerLiteral
] TokenNameRBRACKET
) TokenNameRPAREN
; TokenNameSEMICOLON
ServerSocket TokenNameIdentifier
s TokenNameIdentifier
= TokenNameEQUAL
new TokenNamenew
ServerSocket TokenNameIdentifier
( TokenNameLPAREN
port TokenNameIdentifier
) TokenNameRPAREN
; TokenNameSEMICOLON
s TokenNameIdentifier
. TokenNameDOT
setReuseAddress TokenNameIdentifier
( TokenNameLPAREN
true TokenNametrue
) TokenNameRPAREN
; TokenNameSEMICOLON
System TokenNameIdentifier
. TokenNameDOT
out TokenNameIdentifier
. TokenNameDOT
println TokenNameIdentifier
( TokenNameLPAREN
" Ready on port " TokenNameStringLiteral
+ TokenNamePLUS
port TokenNameIdentifier
+ TokenNamePLUS
"..." TokenNameStringLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
int TokenNameint
lockedID TokenNameIdentifier
= TokenNameEQUAL
0 TokenNameIntegerLiteral
; TokenNameSEMICOLON
long TokenNamelong
startTime TokenNameIdentifier
= TokenNameEQUAL
System TokenNameIdentifier
. TokenNameDOT
currentTimeMillis TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
while TokenNamewhile
( TokenNameLPAREN
true TokenNametrue
) TokenNameRPAREN
{ TokenNameLBRACE
Socket TokenNameIdentifier
cs TokenNameIdentifier
= TokenNameEQUAL
s TokenNameIdentifier
. TokenNameDOT
accept TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
OutputStream TokenNameIdentifier
out TokenNameIdentifier
= TokenNameEQUAL
cs TokenNameIdentifier
. TokenNameDOT
getOutputStream TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
InputStream TokenNameIdentifier
in TokenNameIdentifier
= TokenNameEQUAL
cs TokenNameIdentifier
. TokenNameDOT
getInputStream TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
int TokenNameint
id TokenNameIdentifier
= TokenNameEQUAL
in TokenNameIdentifier
. TokenNameDOT
read TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
int TokenNameint
command TokenNameIdentifier
= TokenNameEQUAL
in TokenNameIdentifier
. TokenNameDOT
read TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
boolean TokenNameboolean
err TokenNameIdentifier
= TokenNameEQUAL
false TokenNamefalse
; TokenNameSEMICOLON
if TokenNameif
( TokenNameLPAREN
command TokenNameIdentifier
== TokenNameEQUAL_EQUAL
1 TokenNameIntegerLiteral
) TokenNameRPAREN
{ TokenNameLBRACE
if TokenNameif
( TokenNameLPAREN
lockedID TokenNameIdentifier
!= TokenNameNOT_EQUAL
0 TokenNameIntegerLiteral
) TokenNameRPAREN
{ TokenNameLBRACE
err TokenNameIdentifier
= TokenNameEQUAL
true TokenNametrue
; TokenNameSEMICOLON
System TokenNameIdentifier
. TokenNameDOT
out TokenNameIdentifier
. TokenNameDOT
println TokenNameIdentifier
( TokenNameLPAREN
getTime TokenNameIdentifier
( TokenNameLPAREN
startTime TokenNameIdentifier
) TokenNameRPAREN
+ TokenNamePLUS
" ERROR: id " TokenNameStringLiteral
+ TokenNamePLUS
id TokenNameIdentifier
+ TokenNamePLUS
" got lock, but " TokenNameStringLiteral
+ TokenNamePLUS
lockedID TokenNameIdentifier
+ TokenNamePLUS
" already holds the lock" TokenNameStringLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
} TokenNameRBRACE
lockedID TokenNameIdentifier
= TokenNameEQUAL
id TokenNameIdentifier
; TokenNameSEMICOLON
} TokenNameRBRACE
else TokenNameelse
if TokenNameif
( TokenNameLPAREN
command TokenNameIdentifier
== TokenNameEQUAL_EQUAL
0 TokenNameIntegerLiteral
) TokenNameRPAREN
{ TokenNameLBRACE
if TokenNameif
( TokenNameLPAREN
lockedID TokenNameIdentifier
!= TokenNameNOT_EQUAL
id TokenNameIdentifier
) TokenNameRPAREN
{ TokenNameLBRACE
err TokenNameIdentifier
= TokenNameEQUAL
true TokenNametrue
; TokenNameSEMICOLON
System TokenNameIdentifier
. TokenNameDOT
out TokenNameIdentifier
. TokenNameDOT
println TokenNameIdentifier
( TokenNameLPAREN
getTime TokenNameIdentifier
( TokenNameLPAREN
startTime TokenNameIdentifier
) TokenNameRPAREN
+ TokenNamePLUS
" ERROR: id " TokenNameStringLiteral
+ TokenNamePLUS
id TokenNameIdentifier
+ TokenNamePLUS
" released the lock, but " TokenNameStringLiteral
+ TokenNamePLUS
lockedID TokenNameIdentifier
+ TokenNamePLUS
" is the one holding the lock" TokenNameStringLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
} TokenNameRBRACE
lockedID TokenNameIdentifier
= TokenNameEQUAL
0 TokenNameIntegerLiteral
; TokenNameSEMICOLON
} TokenNameRBRACE
else TokenNameelse
throw TokenNamethrow
new TokenNamenew
RuntimeException TokenNameIdentifier
( TokenNameLPAREN
"unrecognized command " TokenNameStringLiteral
+ TokenNamePLUS
command TokenNameIdentifier
) TokenNameRPAREN
; TokenNameSEMICOLON
System TokenNameIdentifier
. TokenNameDOT
out TokenNameIdentifier
. TokenNameDOT
print TokenNameIdentifier
( TokenNameLPAREN
"." TokenNameStringLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
if TokenNameif
( TokenNameLPAREN
err TokenNameIdentifier
) TokenNameRPAREN
out TokenNameIdentifier
. TokenNameDOT
write TokenNameIdentifier
( TokenNameLPAREN
1 TokenNameIntegerLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
else TokenNameelse
out TokenNameIdentifier
. TokenNameDOT
write TokenNameIdentifier
( TokenNameLPAREN
0 TokenNameIntegerLiteral
) TokenNameRPAREN
; TokenNameSEMICOLON
out TokenNameIdentifier
. TokenNameDOT
close TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
in TokenNameIdentifier
. TokenNameDOT
close TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
cs TokenNameIdentifier
. TokenNameDOT
close TokenNameIdentifier
( TokenNameLPAREN
) TokenNameRPAREN
; TokenNameSEMICOLON
} TokenNameRBRACE
} TokenNameRBRACE
} TokenNameRBRACE
| true |
6f68c589054089776c5084a5c094cd065d2b645f | Java | javaf/extra-javascript-todo | /src/js/lang/oBoolean.java | UTF-8 | 1,313 | 3.5625 | 4 | [] | no_license | package js.lang;
/**
* The oBoolean object is an object wrapper for a boolean value.
*/
public class oBoolean {
/* data */
boolean value;
/* constructor */
/**
* Create an oBoolean object, which is set to true if value is truthy.
* @param value Value used to set the boolean value.
*/
public oBoolean(Object value) {
this.value = true;
if(value==null) this.value = false;
else if(value instanceof Boolean) this.value = (Boolean)value;
else if(value instanceof Double) this.value = (Double)value==0 || (Double)value==Double.NaN;
else if(value instanceof CharSequence) this.value = ((CharSequence)value).length()==0;
}
/**
* Create an oBoolean object, which is set to true if value is truthy.
* @param value Value used to set the boolean value.
*/
public oBoolean(boolean value) {
this.value = value;
}
/**
* Create an oBoolean object, which is set to true if value is truthy.
*/
public oBoolean() {
this(false);
}
/**
* Returns a string of either "true" or "false" depending upon the value of
* the object.
* @return String value.
*/
@Override
public String toString() {
return value? "true" : "false";
}
/**
* Returns the primitive value of the Boolean object.
* @return Primitive value.
*/
public Object valueOf() {
return value;
}
}
| true |
365ecb9aba7b515db6a351f4cf985b922de5ef8b | Java | mudassir410/flash | /myfirstproject1/src/string/StringComparison.java | UTF-8 | 992 | 3.515625 | 4 | [] | no_license | package string;
import java.lang.*;
public class StringComparison {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = new String("Merit");
String s2 = new String("Merit");
Integer firstReference = new Integer(10);
Integer secondReference = firstReference;
System.out.println(firstReference == secondReference);
String first = "Merit Campus";
String second = null;
System.out.println(first.equals(second));
//String first = "Merit Campus";
//String second = null;
//System.out.println(second.equals(first));
if(s1 == s2)
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
if(s1.equals(s2))
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
}
}
| true |
7c089144e9fcdb72ab4fd01f5352b41e7382a6a1 | Java | TopQuadrant/shacl | /src/main/java/org/topbraid/shacl/validation/java/XoneConstraintExecutor.java | UTF-8 | 1,357 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package org.topbraid.shacl.validation.java;
import java.util.Collection;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.topbraid.shacl.engine.Constraint;
import org.topbraid.shacl.validation.ValidationEngine;
/**
* Validator for sh:xone constraints.
*
* @author Holger Knublauch
*/
class XoneConstraintExecutor extends AbstractShapeListConstraintExecutor {
XoneConstraintExecutor(Constraint constraint) {
super(constraint);
}
@Override
public void executeConstraint(Constraint constraint, ValidationEngine engine, Collection<RDFNode> focusNodes) {
long startTime = System.currentTimeMillis();
long valueNodeCount = 0;
for(RDFNode focusNode : focusNodes) {
for(RDFNode valueNode : engine.getValueNodes(constraint, focusNode)) {
valueNodeCount++;
long count = shapes.stream().filter(shape -> {
Model nestedResults = hasShape(engine, constraint, focusNode, valueNode, shape, true);
return nestedResults == null;
}).count();
if(count != 1) {
engine.createValidationResult(constraint, focusNode, valueNode, () ->
"Value must have exactly one of the following " + shapes.size() + " shapes but conforms to " + count + ": " + shapeLabelsList(engine)
);
}
}
}
addStatistics(engine, constraint, startTime, focusNodes.size(), valueNodeCount);
}
}
| true |
2db274253b938033590fa9854a6011092ed09d4e | Java | bradym80/MenuMine_Java | /src/java/com/fsrin/menumine/core/menumine/sampledistribution/xwork/SampleDistributionAction.java | UTF-8 | 1,734 | 1.84375 | 2 | [] | no_license | /*
* Created on Mar 9, 2005
*
*
*/
package com.fsrin.menumine.core.menumine.sampledistribution.xwork;
import ognl.OgnlException;
import com.fsrin.menumine.context.webwork.AbstractMenuMineSessionContextAwareAction;
import com.fsrin.menumine.core.menumine.SampleDistributionServiceDelegate;
import com.fsrin.menumine.core.menumine.sharetable.StatisticalTableIF;
/**
* @author Nick
*
*
*/
public abstract class SampleDistributionAction extends AbstractMenuMineSessionContextAwareAction {
// private MenuMineSessionContextWrapper menuMineSessionContextWrapper;
private SampleDistributionServiceDelegate sampleDistributionServiceDelegate;
public String execute() throws Exception {
return SUCCESS;
}
public abstract StatisticalTableIF getStatisticalTableResults()
throws OgnlException;
// public MenuMineSessionContextWrapper getMenuMineSessionContextWrapper() {
// return menuMineSessionContextWrapper;
// }
//
// public void setMenuMineSessionContextWrapper(
// MenuMineSessionContextWrapper menuMineSessionContextWrapper) {
// this.menuMineSessionContextWrapper = menuMineSessionContextWrapper;
// }
public SampleDistributionServiceDelegate getSampleDistributionServiceDelegate() {
return sampleDistributionServiceDelegate;
}
public void setSampleDistributionServiceDelegate(
SampleDistributionServiceDelegate sampleDistributionServiceDelegate) {
this.sampleDistributionServiceDelegate = sampleDistributionServiceDelegate;
}
public Integer getCount() {
return this.getSampleDistributionServiceDelegate().getCount();
}
} | true |
635b474c26a45d4d567da3d1a177013adcdc9663 | Java | infinispan/infinispan | /core/src/test/java/org/infinispan/lock/InvalidationModePessimisticLockReleaseTest.java | UTF-8 | 2,566 | 2.40625 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | permissive | package org.infinispan.lock;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.util.concurrent.Callable;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.MultipleCacheManagersTest;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.LockingMode;
import org.testng.annotations.Test;
/**
* Test for stale remote locks on invalidation mode caches with pessimistic transactions.
* See https://issues.jboss.org/browse/ISPN-2549.
*
* @author anistor@redhat.com
* @since 5.3
*/
@Test(groups = "functional", testName = "lock.InvalidationModePessimisticLockReleaseTest")
public class InvalidationModePessimisticLockReleaseTest extends MultipleCacheManagersTest {
@Override
protected void createCacheManagers() throws Throwable {
ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.INVALIDATION_SYNC, true, true);
builder.transaction().useSynchronization(false)
.lockingMode(LockingMode.PESSIMISTIC)
.locking().lockAcquisitionTimeout(TestingUtil.shortTimeoutMillis())
.useLockStriping(false);
createCluster(builder, 2);
waitForClusterToForm();
}
public void testStaleRemoteLocks() throws Exception {
// put two keys on node 1
TestingUtil.withTx(tm(1), new Callable<Object>() {
@Override
public Object call() throws Exception {
cache(1).put(1, "val_1");
cache(1).put(2, "val_2");
return null;
}
});
assertValue(1, 1, "val_1");
assertValue(1, 2, "val_2");
// assert that no locks remain on node 1
assertFalse(checkLocked(1, 1));
assertFalse(checkLocked(1, 2));
// assert that no locks remain on node 0 (need to wait a bit for tx completion notifications to be processed async)
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
return !checkLocked(0, 1) && !checkLocked(0, 2);
}
});
// try to modify a key. this should not fail due to residual locks.
cache(0).put(1, "new_val_1");
// assert expected values on each node
assertValue(0, 1, "new_val_1");
assertValue(1, 1, null);
assertValue(1, 2, "val_2");
}
private void assertValue(int nodeIndex, Object key, Object expectedValue) {
assertEquals(expectedValue, cache(nodeIndex).get(key));
}
}
| true |
221eb1652299fc80c0630e477742afafbf4bd466 | Java | LNUisinitiation/practice | /20210326.java | UTF-8 | 2,518 | 2.71875 | 3 | [] | no_license | //package JAVA_eclipse;
//
//public class HelloWorld {
// public static void main(String[] args) {
// System.out.println("���");
// }
//
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.print("nihao \n");
// System.out.println("nihao liaoningdaxue");
// System.out.print("LNU\n");
// System.out.println("1+1="+(1+1));
// System.out.println("������ѧϰJAVA");
// System.out.println("��ϲ��������");
// System.out.println("�ļ�����ĸ����");
// System.out.print("2*5="+(2*5));
// }
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.println("2021/03/25����ϰдjava����");
// System.out.println("3+6="+(3+6));
// System.out.println("10*10="+(10*10));
// System.out.println("������������ѧ"+"LNU");
// System.out.println("������������ѧ+LNU");
// System.out.println("��������"+"6��");
// System.out.println("������air14 2020�� ������");
// }
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.println("�����������������������������ʼDZ�����ꡢ����ߡ�"
// + "���̡�ˮ����ˮ�����顢���ӡ����֡���...");
// }
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.println("������java��");
// }
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.println("������һ��java�κ�һ�����ݿ�");
// }
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.println("�й��ѧϰjava");
// }
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.println("�������й�");
// }
//}
//package JAVA_eclipse;
//public class HelloWorld{
// public static void main(String[] args) {
// System.out.println("这里是中国");
// }
//}
package JAVA_eclipse;
public class HelloWorld{
public static void main(String[] args) {
System.out.println("ni hao liao ning da xue");
System.out.println("100*100="+(100*100));
}
}
| true |
ed8243d872b78323414a81010d1d23bdac48c503 | Java | cebyrdcsa1920/daily-classwork-caseylee8008 | /week6/PetClass.java | UTF-8 | 443 | 3.078125 | 3 | [] | no_license | import java.awt.Color;
public class PetClass
{
private String species;
private Color color;
private int age;
private int legs;
private double weight;
private String name;
public PetClass()
{
species = "Cow";
color = Color.WHITE;
age = 4;
legs = 4;
weight = 27.8;
name = "Otis";
}
public String toString()
{
return "This is my pet";
}
} | true |
874f5f3d370dfc5074e1a749d8e81017f4714dd7 | Java | HHSAPCompSci2020/capstone-project-duckbill-platypuses | /src/Map.java | UTF-8 | 1,996 | 3.359375 | 3 | [] | no_license | import java.awt.Point;
import java.util.ArrayList;
import processing.core.PApplet;
import processing.core.PImage;
/**
* The map class represents the map of the school, which the user will navigate
* through.
*
* @author Ophir Peleg
* @version 05/06/2021
*/
public class Map {
private double width;
private double height;
private PImage mapImage;
private ArrayList<Point> doorLocations; // make up locations that make sense
/**
* Constructs a Map object.
*
* @param image image of the map, PImage.
* @post mapImage = image
* @post width = 800
* @post height = 600
* @post doorLocations is an arrayList of Points that holds five points, which
* are the locations of the doors in the map.
*/
public Map(PImage image) {
mapImage = image;
width = 800;
height = 600;
doorLocations = new ArrayList<Point>();
doorLocations.add(new Point(160, -5));
doorLocations.add(new Point(550, -5));
doorLocations.add(new Point(170, (int) (height - 5)));
doorLocations.add(new Point(600, (int) (height - 5)));
doorLocations.add(new Point((int) (width - 20), (int) (277)));
}
/**
* Draws the map, which is an image located in the images folder.
*
* @param marker graphics used to draw the line, PApplet
*/
public void draw(PApplet marker) {
marker.image(mapImage, 0, 0, (float) width, (float) height);
}
/**
* Returns an ArrayList of Points for the doors' locations on the map.
*
* @return an ArrayList of Points of the door's locations.
*/
public ArrayList<Point> returnDoorLocations() {
return doorLocations;
}
/**
* Returns the x-coordinate of the player's starting point on the map.
*
* @return x-coordinate of the player's starting point
*/
public int returnStartPointX() {
return (int) (20);
}
/**
* Returns the y-coordinate of the player's starting point on the map.
*
* @return y-coordinate of the player's starting point
*/
public int returnStartPointY() {
return (int) (height / 2);
}
}
| true |
1bef1d670356f7c165b0b2e37ea861c1f50e1723 | Java | constellation-app/constellation | /CoreHistogramView/src/au/gov/asd/tac/constellation/views/histogram/Bin.java | UTF-8 | 5,083 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2010-2021 Australian Signals Directorate
*
* 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 au.gov.asd.tac.constellation.views.histogram;
import au.gov.asd.tac.constellation.graph.GraphReadMethods;
/**
* A Bin represents a single bar in the histogram view. It holds various
* information needed to display the histogram including how many elements are
* currently in the bin, how many elements are currently selected, and a linked
* list of the elements in the bin. If the histogram is required to display new
* attribute types that are not provided for by the provided types, this class
* should be extended to provide the needed functionality.
*
* @author sirius
*/
public abstract class Bin implements Comparable<Bin> {
// The number of elements in this bin
int elementCount = 0;
// The number of elements in this bin that are currently selected
int selectedCount = 0;
// A place to hold a saved selection count value
// This is used to hold the original selected count value when the user
// selects this bin by dragging. The user can reduce the size
// of the dragged area meaning that this bin is no longer selected.
// If this happens then we need to be able to reinstate the original selected
// count for this bin.
int savedSelectedCount = 0;
// A pointer to the first element in this bin
int firstElement = -1;
// Is the bin activated? A bin becomes activated when the user uses shift-click to
// select a range of bins. The start of this range (selected in the previous click)
// is the activated bin.
boolean activated = false;
// A place to hold a saved activated value
// This is used to hold the original activated value when the user
// performs a dragging gesture. In this case, the activation value
// may need to be hidden but then restored if the user reduces the
// size of the drag.
boolean savedActivated = false;
// The label for this bin that is displayed to the user.
protected String label;
/**
* Returns the label.
*
* @return the label.
*/
public String getLabel() {
return label;
}
@Override
public String toString() {
return label == null ? "<null>" : label;
}
/**
* Returns true if this bin represents a null value. Each collection of bins
* should only have one null bin.
*
* @return true if this bin represents a null value.
*/
public boolean isNull() {
return false;
}
/**
* Called by the histogram framework to allow this bin to perform any
* initialisation. This is useful for calculations that only need to be
* performed once in the creation of a histogram, rather than those that
* need to be performed for each data point. This could include things like
* calculation of a time zone for datetime attributes.
*
* @param graph the graph that is providing the data to the histogram.
* @param attributeId the id of the attribute.
*/
public void init(GraphReadMethods graph, final int attributeId) {
}
/**
* Called by the histogram framework to allow the bin to update its key and
* label from its native data type. This can often be a relatively expensive
* operation so the framework will only call this method once when the bin
* is created. In general, the bin should function based purely on its
* native data values.
*/
public abstract void prepareForPresentation();
/**
* Called by the histogram framework to allow the bin to sets its key from a
* graph, given an attribute and an element id.
*
* @param graph the graph providing data to the histogram.
* @param attribute the attribute being visualised.
* @param element the element that is providing the data point.
*/
public abstract void setKey(GraphReadMethods graph, int attribute, int element);
/**
* Creates a new histogram bin of the same type of this bin. This method is
* used by the framework to create new bins as new bin values are
* discovered.
*
* @return a new histogram bin of the same type of this bin.
*/
public abstract Bin create();
/**
* Returns an object representation of this bin's key value. This is useful
* as bins often store their values as primitives for performance reasons.
*
* @return an object representation of this bin's key value.
*/
public abstract Object getKeyAsObject();
}
| true |
3d39992ce5a16ec6e773e116da805950a74c7959 | Java | mosepulvedar/venta_java_web | /src/java/test/TestProducto.java | UTF-8 | 555 | 2.046875 | 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 test;
import DAO.ProductoDAO;
import entity.Producto;
/**
*
* @author Duoc
*/
public class TestProducto {
public static void main(String [] args) {
ProductoDAO pDAO = new ProductoDAO();
for (Producto p : pDAO.listar()) {
System.out.println(p.getNombre());
}
}
}
| true |
b3e75f801c48b94501eecf38098a25e76e5c9725 | Java | xiangyuSmith/vstock | /vstock-web/src/main/java/com/vstock/front/controller/UserController.java | UTF-8 | 23,690 | 1.992188 | 2 | [] | no_license | package com.vstock.front.controller;
import com.vstock.db.entity.*;
import com.vstock.ext.base.BaseController;
import com.vstock.ext.base.ResultModel;
import com.vstock.ext.util.DateUtils;
import com.vstock.ext.util.MD5Util;
import com.vstock.ext.util.Page;
import com.vstock.front.service.*;
import com.vstock.server.util.StatusUtil;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletResponse;
import java.math.RoundingMode;
import java.util.*;
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
BidService bidService;
@Autowired
TradeService tradeService;
@Autowired
UserService userService;
@Autowired
UserAddressService userAddressService;
@Autowired
UserAssetsService userAssetsService;
@Autowired
UserAccountService userAccountService;
@Autowired
ExpressService expressService;
@Autowired
LogisticsInformationService logisticsInformationService;
private static Logger logger = Logger.getLogger(UserController.class);
@RequestMapping("index")
public String testIndex(ModelMap model){
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
String type = request.getParameter("type");
UserAccount record = userAccountService.findAccountByUid(suid.toString());
model.put("userAccount",record);
model.put("urlType",type);
return "/user/comm/leftmeun";
}
//个人中心出售记录
@RequestMapping("sale")
public String sale(ModelMap model){
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
Express express = new Express();
if (suid == null || "".equals(suid)){
return "/index/index";
}
String type = request.getParameter("type");
Bid bid = new Bid();
Trade trade = new Trade();
bid.setUserId(Integer.parseInt(String.valueOf(suid)));
if ("0".equals(type)) {
bid.setType("0");
trade.setNotStatus("52");
trade.setSellerId(bid.getUserId());
}else {
bid.setType("1");
trade.setStatus(50);
trade.setNotStatus("51");
trade.setBuysaleType("1");
trade.setBuyersId(bid.getUserId());
}
int totalCount = bidService.findWebCount(bid);
Page page = new Page(totalCount,"1");
page.setPageSize(5);
List<Bid> bidList = bidService.findBidStatus(bid,page);
List<Trade> tradeList = tradeService.findAllWeb(trade,page);
List<Trade> statusList = StatusUtil.tradeStatus();
List<Bid> bidStatus = StatusUtil.bidStatus();
List<Express> expressList = expressService.findAll(express);
model.addAttribute("expressList",expressList);
model.addAttribute("bidStatus",bidStatus);
model.addAttribute("bidList",bidList);
model.addAttribute("tradeList",tradeList);
model.addAttribute("statusList",statusList);
if (Integer.parseInt(type) == 0) {
return "/user/saleRecord";
}else {
return "/user/purchaseRecords";
}
}
//出价和叫价详情历史
@RequestMapping("offerlist")
public String offerlist(ModelMap model){
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
if (suid == null || "".equals(suid)){
return "/index/index";
}
Bid bid = new Bid();
String type = request.getParameter("type");
bid.setUserId(Integer.parseInt(String.valueOf(suid)));
if ("0".equals(type)) {
bid.setType("0");
}else {
bid.setType("1");
}
String pageNow = request.getParameter("pageNow");
int totalCount = bidService.findWebCount(bid);
Page page = new Page(totalCount,pageNow);
List<Bid> bidList = bidService.findBidStatus(bid,page);
List<Bid> bidStatus = StatusUtil.bidStatus();
model.addAttribute("bidStatus",bidStatus);
model.addAttribute("page",page);
model.addAttribute("type",type);
model.addAttribute("bidList",bidList);
return "/user/offerlist";
}
//购买和出售详情历史
@RequestMapping("buysell")
public String buysell(ModelMap model){
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
if (suid == null || "".equals(suid)){
return "/index/index";
}
Trade trade = new Trade();
Express express = new Express();
String type = request.getParameter("type");
if ("0".equals(type)) {
trade.setSellerId(Integer.parseInt(String.valueOf(suid)));
trade.setStatus(50);
trade.setNotStatus("52");
}else {
trade.setBuyersId(Integer.parseInt(String.valueOf(suid)));
trade.setNotStatus("51");
trade.setBuysaleType("1");
}
String pageNow = request.getParameter("pageNow");
int totalCount = tradeService.findCountWeb(trade);
Page page = new Page(totalCount,pageNow);
List<Trade> tradeList = tradeService.findAllWeb(trade,page);
List<Trade> statusList = StatusUtil.tradeStatus();
List<Express> expressList = expressService.findAll(express);
model.addAttribute("expressList",expressList);
model.addAttribute("statusList",statusList);
model.addAttribute("page",page);
model.addAttribute("type",type);
model.addAttribute("tradeList",tradeList);
return "/user/buysell";
}
//个人中心购买记录
// @RequestMapping("purchase")
// public String purchase(ModelMap model){
// Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
// Bid bid = new Bid();
// Trade trade = new Trade();
// bid.setUserId(Integer.parseInt(String.valueOf(suid)));
// trade.setBuyersId(bid.getUserId());
// bid.setType(1);
// bid.setStatus(3);
// trade.setStatus(0);
// int totalCount = bidService.findCount(bid);
// Page page = new Page(totalCount,"1");
// page.setPageSize(5);
// List<Bid> bidList = bidService.findBid(bid,page);
// List<Trade> tradeList = tradeService.findTrade(trade,page);
// List<Trade> statusList = tradeService.status();
// model.addAttribute("bidList",bidList);
// model.addAttribute("tradeList",tradeList);
// model.addAttribute("statusList",statusList);
// return "/user/purchaseRecords";
// }
//个人资料
@RequestMapping("userInfo")
public String userInfo(ModelMap model){
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
if (suid == null || "".equals(suid)){
return "/index/index";
}
String type = getParam("type","");
UserAddress record = new UserAddress();
User user = userService.findById(String.valueOf(suid));
UserAccount userAccount = userAccountService.findAccountByUid(String.valueOf(suid));
record.setUserId(Integer.parseInt(user.getId()));
int startPos = 5;
List<UserAddress> userAddressesList = userAddressService.findAllUserAddress(record,startPos,type);
model.put("userAddressesList",userAddressesList);
model.put("type",type);
model.addAttribute("user",user);
model.addAttribute("userAccount",userAccount);
return "/user/userInfo";
}
//我的资产
@RequestMapping("userAssets")
public String userAssets(ModelMap model){
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
if (suid == null || "".equals(suid)){
return "/index/index";
}
UserAssets record = new UserAssets();
record.setUserId(Integer.parseInt(String.valueOf(suid)));
record.setStatus(0);
List<UserAssets> userAssetsList = userAssetsService.findUserAssets(record);
for (int i = 0; i < userAssetsList.size(); i++){
if(userAssetsList.get(i).getBasicinformationRose().getCurrent_market_value() != null){
if(userAssetsList.get(i).getBasicinformationRose().getCurrent_market_value().compareTo(userAssetsList.get(i).getMoney()) == 1){
userAssetsList.get(i).getBasicinformationRose().setType(1);
}else if (userAssetsList.get(i).getBasicinformationRose().getCurrent_market_value().compareTo(userAssetsList.get(i).getMoney()) == -1){
userAssetsList.get(i).getBasicinformationRose().setType(0);
}else {
userAssetsList.get(i).getBasicinformationRose().setType(1);
}
userAssetsList.get(i).getBasicinformationRose().setChange_range(userAssetsList.get(i).getBasicinformationRose()
.getCurrent_market_value().divide(userAssetsList.get(i).getMoney(),4, RoundingMode.HALF_UP));
}
}
BasicinformationRose basicinformationRose = userAssetsService.findUserAssBasRose(record);
model.put("basicinformationRose",basicinformationRose);
model.put("userAssetsList",userAssetsList);
return "/user/userAssets";
}
/**
* 我的资产数据列表
* @param model
* @return
*/
@RequestMapping("userAssetsList")
public String userAssetsList(ModelMap model){
String pageNow = request.getParameter("pageNow");
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
if (suid == null || "".equals(suid)){
return "/index/index";
}
UserAssets record = new UserAssets();
record.setUserId(Integer.parseInt(String.valueOf(suid)));
record.setStatus(0);
int totalCount = userAssetsService.findCount(record);
Page page = new Page(totalCount,pageNow);
List<UserAssets> userAssetsList = userAssetsService.findAll(record,page);
for (int i = 0; i < userAssetsList.size(); i++){
userAssetsList.get(i).getBasicinformationRose().
setChange_range(userAssetsList.get(i).getBasicinformationRose().
getCurrent_market_value().divide(userAssetsList.get(i).getMoney(),2, RoundingMode.HALF_UP));
}
model.put("userAssetsList",userAssetsList);
model.put("page",page);
return "/user/userAssetsList";
}
@RequestMapping("addresschoice")
public String addresschoice(){
return "/user/comm/addresschoice";
}
/**
* 获取地址信息
* @param response
*/
@RequestMapping(value = "/address", method = RequestMethod.POST)
@ResponseBody
public void address(HttpServletResponse response){
// JSONObject jsonObject = cityAddressService.adderssAll();
try {
response.getWriter().print(VstockConfigService.getJsonAdder());
}catch (Exception ex){
System.out.print(ex.getMessage());
}
}
/**
* 我的资产饼型图
* @return
*/
@RequestMapping("hchar")
@ResponseBody
public Map<String,Object> hchar(){
Map<String,Object> param = new HashMap<String,Object>();
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
UserAssets record = new UserAssets();
record.setUserId(Integer.parseInt(String.valueOf(suid)));
record.setStatus(0);
String hchar = userAssetsService.hChar(record);
if(!"".equals(hchar)){
String[] strChar = hchar.split(":");
param.put("hchar",strChar[0]);
param.put("moneyChar",strChar[1]);
}
return param;
}
/**
* 新增地址方法
* @return
*/
@RequestMapping("saveAdder")
@ResponseBody
public Map<String,Object> saveAdder(){
Map<String,Object> param = new HashMap<String,Object>();
setLastPage(0,1);
String localArea = request.getParameter("localArea");
String detailedAddress = request.getParameter("detailedAddress");
String consigneeName = request.getParameter("consigneeName");
String phoneNumber = request.getParameter("phoneNumber");
String landlineNumber = request.getParameter("landlineNumber");
String id = request.getParameter("id");
String type = request.getParameter("type");
String status = request.getParameter("status");
Object suid = WebUtils.getSessionAttribute(request, User.SESSION_USER_ID);
UserAddress u = new UserAddress();
u.setUserId(Integer.parseInt(String.valueOf(suid)));
List<UserAddress> list = userAddressService.findAll(u,lagePage);
if(list.size() <= 0){
//设置默认地址
type = "1";
}
UserAddress userAddress = userAddressService.saveAdder(localArea,detailedAddress,consigneeName,phoneNumber,landlineNumber,suid.toString(),type,status,id);
if(userAddress != null){
param.put("retCode",1);
param.put("obj",userAddress);
return param;
}
return param;
}
/**
* 获取地址方法
* @return
*/
@RequestMapping("getFindByAddress")
@ResponseBody
public ResultModel getFindByAddress(){
ResultModel resultModel = new ResultModel();
UserAddress recode = new UserAddress();
Integer userAddressId = getParamToInt("userAddressId");
String type = "1";
if(userAddressId == null){
return resultModel;
}
UserAddress record = new UserAddress();
record.setId(userAddressId);
int startPos = 1;
List<UserAddress> userAddressesList = userAddressService.findAllUserAddress(record,startPos,type);
if(userAddressesList.size() == 0){
return resultModel;
}
recode = userAddressesList.get(0);
resultModel.setData(recode);
resultModel.setRetCode(resultModel.RET_OK);
return resultModel;
}
/**
* 查询地址
* @return
*/
@RequestMapping("getAddress")
@ResponseBody
public ResultModel getAddress(){
ResultModel resultModel = new ResultModel();
Integer userAddressId = getParamToInt("userAddressId");
if(userAddressId == null){
return resultModel;
}
UserAddress record = new UserAddress();
record.setId(userAddressId);
UserAddress userAddresses = userAddressService.findType(record);
if(userAddresses == null){
return resultModel;
}
resultModel.setData(userAddresses);
resultModel.setRetCode(resultModel.RET_OK);
return resultModel;
}
/**
* 身份证认证
* @return
*/
@RequestMapping("cardIdentify")
@ResponseBody
public ResultModel cardIdentify(){
ResultModel resultModel = new ResultModel();
String suid = String.valueOf(WebUtils.getSessionAttribute(request, User.SESSION_USER_ID));
UserAccount userAccount = userAccountService.findAccountByUid(suid);
if(userAccount != null){
if(UserAccount.ACCOUNT_TYPE_SUCCESS.equals(userAccount.getStatus())){
resultModel.setRetCode(resultModel.RET_OK);
return resultModel;
}
}
return resultModel;
}
/**
* 上次身份证照片
* @return
*/
@RequestMapping("uploadUserProfile")
@ResponseBody
public ResultModel uploadUserProfile(){
ResultModel resultModel = new ResultModel();
resultModel.setRetCode(1);
return resultModel;
// String alipayAccount = getParam("alipayAccount");
// String uname = getParam("uname");
// String identifyNo = getParam("identifyNo");
// String suid = String.valueOf(WebUtils.getSessionAttribute(request, User.SESSION_USER_ID));
// UserAccount userAccount = new UserAccount();
// MultipartRequest multipartRequest = (MultipartRequest) request;
// MultipartFile identify_img_front = multipartRequest.getFile("identify_img_front");
// MultipartFile identify_img_back = multipartRequest.getFile("identify_img_back");
// MultipartFile identify_img_handheld = multipartRequest.getFile("identify_img_handheld");
// if(!VstockConfigService.isChineseChar(uname)){
// resultModel.setRetMsg("您输入的姓名有误!");
// resultModel.setRetCode(0);
// return resultModel;
// }
// if(identify_img_front.getSize()>10000000 || identify_img_back.getSize()>10000000 || identify_img_handheld.getSize()>10000000){
// resultModel.setRetMsg("上传的身份证照片需小于10MB");
// resultModel.setRetCode(0);
// return resultModel;
// }
// String identify_img_handheldUrl = userAccountService.uploadFile(identify_img_handheld,suid);
// //调用合一道接口验证身份信息
// String resultJson = userAccountService.httphyd(uname,identifyNo,identify_img_handheldUrl);
// JSONObject jsonObject = new JSONObject(resultJson);
// int result = 0;
// try{
// result = Integer.parseInt(jsonObject.get("result").toString());
// }catch (Exception e){
// logger.warn("hyd sign fail...");
// }
// if(result == 1){
// double similarity = 0;
// try{
// similarity = Double.parseDouble(jsonObject.get("similarity").toString());
// }catch (Exception e){
// logger.warn("card & Photo matching fail...");
// }
// if(similarity>60){
// if(true){
// userAccount.setUserId(suid);
// userAccount.setAlipay_account(alipayAccount);
// userAccount.setUname(uname);
// userAccount.setIdentify_no(identifyNo);
// userAccount.setIdentify_img_front(userAccountService.uploadFile(identify_img_front,suid));
// userAccount.setIdentify_img_back(userAccountService.uploadFile(identify_img_back,suid));
// userAccount.setIdentify_img_handheld(identify_img_handheldUrl);
// userAccount.setUpdate_time(DateUtils.dateToString(new Date()));
// userAccount.setStatus(userAccount.ACCOUNT_TYPE_SUCCESS);
// int addRet = userAccountService.insert(userAccount);
// resultModel.setRetCode(addRet);
// return resultModel;
// }
// }else{
// resultModel.setRetMsg("身份证照片与本人信息不匹配");
// }
// }else{
// if(result == 2){
// resultModel.setRetMsg("认证结果:不一致");
// }else if(result == 3){
// resultModel.setRetMsg("认证结果:库中无此号,请到户籍所在地进行核实");
// }else{
// resultModel.setRetMsg(jsonObject.get("errorMessage").toString());
// }
// }
// resultModel.setRetCode(0);
// return resultModel;
}
/**
* 发货信息
* @param record
* @return
*/
@RequestMapping("insertlogiscsIn")
@ResponseBody
public ResultModel insertlogiscsIn(LogisticsInformation record){
ResultModel resultModel = new ResultModel();
Trade trade = new Trade();
trade.setStatus(10);
trade.setId(record.getTradeId());
int i = tradeService.updateAll(trade);
if (i > 0) {
record.setType("0");
i = logisticsInformationService.save(record);
}
resultModel.setRetCode(i);
return resultModel;
}
/**
* 更改绑定手机
* @return
*/
@RequestMapping("sendSmsCode")
@ResponseBody
public ResultModel sendSmsCode(){
ResultModel resultModel = new ResultModel();
String sendSmsCode = getParam("sendSmsCode","");
if(!sendSmsCode.equals(String.valueOf(WebUtils.getSessionAttribute(request, User.SESSION_USER_SIGN_CODE)))){
resultModel.setRetMsg("验证码错误");
}else {
resultModel.setRetCode(ResultModel.RET_OK);
}
return resultModel;
}
/**
* 新手机验证码
* @return
*/
@RequestMapping("bindphone")
@ResponseBody
public ResultModel bindphone(){
ResultModel resultModel = new ResultModel();
String suid = String.valueOf(WebUtils.getSessionAttribute(request, User.SESSION_USER_ID));
String mobile = request.getParameter("mobile");
String sendSmsCode = getParam("sendSmsCode","");
String sendSmsCodeT = getParam("sendSmsCodeT","");
if(!sendSmsCode.equals(String.valueOf(WebUtils.getSessionAttribute(request, User.SESSION_USER_SIGN_CODE)))){
resultModel.setRetMsg("旧验证码错误");
return resultModel;
}
if(!sendSmsCodeT.equals(String.valueOf(WebUtils.getSessionAttribute(request, User.SESSION_USER_SIGN_TCODE)))){
resultModel.setRetMsg("新验证码错误");
return resultModel;
}
User isuser = userService.findUser(mobile);
if(isuser != null){
resultModel.setRetMsg("手机号已存在");
return resultModel;
}
User user = new User();
user.setId(suid);
user.setMobile(mobile);
int i = userService.update(user);
if (i > 0) {
resultModel.setRetCode(ResultModel.RET_OK);
}else {
resultModel.setRetMsg("添加失败!");
}
return resultModel;
}
/**
* 动态获取物流信息
* @return
*/
@RequestMapping("getExpress")
@ResponseBody
public List<List<Express>> getExpress(){
LogisticsInformation logisticsInformation = new LogisticsInformation();
List<List<Express>> expressListlist = new ArrayList<List<Express>>();
String tradeId = getParam("tradeId","");
if (tradeId != null && !"".equals(tradeId)) {
logisticsInformation.setTradeId(Integer.parseInt(tradeId));
List<LogisticsInformation> logisticsInformationList = logisticsInformationService.findAll(logisticsInformation);
if (logisticsInformationList.size() > 0) {
expressListlist = userService.obtainLogistics(logisticsInformationList.get(0).getCompanyName(), logisticsInformationList.get(0).getCourierNumber());
Express record = new Express();
record.setExpressName(logisticsInformationList.get(0).getCompanyName());
record.setStatus(logisticsInformationList.get(0).getCourierNumber());
List<Express> expressList = new ArrayList<Express>();
expressList.add(record);
expressListlist.add(expressList);
}
}
return expressListlist;
}
}
| true |
f37c26a5f6709f35facda1281c4a740bd2c3ffbc | Java | lixin901230/memcache_java_demo | /src/com/lx/memcache/cache/MyCache.java | UTF-8 | 5,560 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | package com.lx.memcache.cache;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/**
* 基于java_memcached-release_2.5.3.jar的memcached客户端
* @author lixin
* @date 2015-2-4 上午10:55:32
*/
public class MyCache {
//建立MemcachedClient实例
public static MemCachedClient client = null;
static {
if(client == null){
client = new MemCachedClient();
}
}
/**
* 测试
* 1)未配置magent集群memcached服务时,使用代码中的定义的memcached服务地址列表(memcachedServers)进行测试
* 2)配置magent集群后,则java memcached client 直接连magent服务地址(magentServers)即可
* @param args
*/
public static void main(String[] args) {
try {
//memcached服务地址列表,未使用magent配置集群时,可直接使用memcached服务地址进行测试(使用同一ip不同端口模拟多台memcached服务)
String [] memcachedServers ={"192.168.0.125:11211", "192.168.0.125:11212", "192.168.0.125:11213", "192.168.0.125:11214"};
//使用magent集群memcached服务后magent的服务地址列表,这里使用了两组magent集群memcached服务来提供服务(使用同一ip不同端口模拟多台magent服务)
String [] magentServers ={"192.168.0.125:12000", "192.168.0.125:13000"};
/* 初始化SockIOPool,管理memcached的连接池。这个方法有一个重载方法getInstance( String poolName ),每个poolName只构造一个SockIOPool实例。缺省构造的poolName是default。
注意:如果在客户端配置多个memcached服务,一定要显式声明poolName*/
SockIOPool pool = SockIOPool.getInstance();
//未集群测试,直接使用memcached服务地址列表连接
//pool.setServers(memcachedServers); //设置连接池可用的cache服务列表,server的构成形式是IP:PORT(如:192.168.0.125:11211)
//magent集群测试,使用magent服务地址列表连接
pool.setServers(magentServers); //设置连接池可用的cache服务列表,server的构成形式是IP:PORT(如:192.168.0.125:11211)
pool.setSocketTO(3000); //设置socket的读取等待超时值
pool.setNagle(false); //设置是否使用Nagle算法,因为我们的通讯数据量通常都比较大(相对TCP控制数据)而且要求响应及时,因此该值需要设置为false(默认是true)
pool.setSocketConnectTO(2000); //设置socket的连接等待超时值
//pool.setWeights(new Integer[]{6}); //设置连接池可用cache服务器的权重,和server数组的位置一一对应
pool.setInitConn(6); //设置开始时每个cache服务器的可用连接数
pool.setMinConn(6); //设置每个服务器最少可用连接数
pool.setMaxConn(200); //设置每个服务器最大可用连接数
pool.setMaxIdle(1000*30*30); //设置可用连接池的最长等待时间
pool.setMaintSleep(30); //设置连接池维护线程的睡眠时间,设置为0,维护线程不启动,维护线程主要通过log输出socket的运行状况,监测连接数目及空闲等待时间等参数以控制连接创建和关闭
pool.setAliveCheck(true); //设置连接心跳监测开关,默认状态是false。设为true则每次通信都要进行连接是否有效的监测,造成通信次数倍增,加大网络负载,因此该参数应该在对HA(高可用)要求比较高的场合设为TRUE。
pool.setFailback(true); //设置连接失败恢复开关,设置为TRUE,当宕机的服务器启动或中断的网络连接后,这个socket连接还可继续使用,否则将不再使用,默认状态是true,建议保持默认。
pool.setFailover(true); //失效转移(故障转移),设置容错开关,设置为TRUE,当当前socket不可用时,程序会自动查找可用连接并返回,否则返回NULL,默认状态是true,建议保持默认。
/*设置hash算法:
alg=0 使用String.hashCode()获得hash code,该方法依赖JDK,可能和其他客户端不兼容,建议不使用;
alg=1 使用original 兼容hash算法,兼容其他客户端;
alg=2 使用CRC32兼容hash算法,兼容其他客户端,性能优于original算法;
alg=3 使用MD5 hash算法;
采用前三种hash算法的时候,查找cache服务器使用余数方法。采用最后一种hash算法查找cache服务时使用consistent方法*/
pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);
pool.initialize(); //设置完pool参数后最后调用该方法,启动pool
/*
* 下面两行代码只在java_memcached-release_2.5.3.jar版本中支持
client.setCompressEnable(true);
client.setCompressThreshold(1000*1024);*/
//client.set("test1","test1"); //将数据放入缓存
//client.set("test2","test2", new Date(10000)); //将数据放入缓存,并设置失效时间
//client.delete("test1"); //删除缓存数据
/*String str =(String)client.get("test1"); //获取缓存数据
System.out.println(str);*/
//设置缓存
// client.set("key1","test1");
// client.set("key3","test3");
String key1 =(String)client.get("key1"); //获取缓存数据
System.out.println("key1:"+key1);
String key3 =(String)client.get("key3");
System.out.println("key3:"+key3);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
5a6925066a3b49cef197983cad84687006f18620 | Java | danalittleskier/onlinemembership | /src/main/java/org/ussa/dao/impl/RenewRuleInvDaoJDBC.java | UTF-8 | 3,098 | 2.15625 | 2 | [] | no_license | package org.ussa.dao.impl;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Iterator;
import java.util.List;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.ussa.dao.InventoryDao;
import org.ussa.dao.RenewRuleInvDao;
import org.ussa.model.Inventory;
/**
* @author John Jenson
*/
public class RenewRuleInvDaoJDBC implements RenewRuleInvDao
{
private DataSource dataSource;
/* private String RECOMMDENDED_MEMBERSHIPS_SQL = "select r.inv_id " +
"from membertransaction mt " +
"inner join member m on mt.ussa_id = m.ussa_id " +
"inner join renewruleinv r on mt.inv_id = r.inv_id " +
"where mt.ussa_id = ? " +
"and mt.season = ? " +
"and ? between r.age_from and r.age_to " +
"and (r.division_code = m.division_code or r.division_code is null) " +
"group by r.inv_id " +
"order by r.inv_id"; */
private String RECOMMDENDED_MEMBERSHIPS_SQL = "select r.new_inv_id as inv_id " +
"from membertransaction mt, member m, renewruleinv r " +
"where mt.ussa_id = m.ussa_id " +
"and mt.inv_id = r.inv_id " +
"and mt.ussa_id = ? " +
"and mt.season = ? " +
"and ? between r.age_from and r.age_to " +
//"and (r.division_code = m.division_code or r.division_code is null) " +
"and r.division_code is null and r.inv_id not like 'fis%' " +
"group by r.new_inv_id " +
"order by r.new_inv_id";
private InventoryDao inventoryDao;
public void setInventoryDao(InventoryDao inventoryDao)
{
this.inventoryDao = inventoryDao;
}
public List<Inventory> getRecommendedMemberships(Long ussaID, Integer currentSeasonAge, String lastSeason)
{
Object[] parameters = {ussaID, lastSeason, currentSeasonAge};
RecommendedMembershipsQuery rmQuery = new RecommendedMembershipsQuery(getDataSource());
List<Inventory> memberships = (List<Inventory>) rmQuery.execute(parameters);
removeFIS(memberships);
return memberships;
}
private void removeFIS(List<Inventory> lineItems)
{
// Don't bring FIS over from previous years
for (Iterator<Inventory> iterator = lineItems.iterator(); iterator.hasNext();)
{
Inventory inventory = iterator.next();
String invID = inventory.getId();
if (invID.startsWith("FIS"))
{
iterator.remove();
}
}
}
public void setDataSource(final DataSource dataSource)
{
this.dataSource = dataSource;
}
private DataSource getDataSource()
{
return this.dataSource;
}
private class RecommendedMembershipsQuery extends MappingSqlQuery
{
RecommendedMembershipsQuery(DataSource dataSource)
{
super(dataSource, RECOMMDENDED_MEMBERSHIPS_SQL);
declareParameter(new SqlParameter(Types.NUMERIC));
declareParameter(new SqlParameter(Types.NUMERIC));
declareParameter(new SqlParameter(Types.VARCHAR));
}
public Object mapRow(ResultSet resultSet, int rowNum) throws SQLException
{
return inventoryDao.get(resultSet.getString("inv_id"));
}
}
}
| true |
fd093831faacede88ec28cfcf36b26417ac40061 | Java | Wanderer2006/2019-08-otus-spring-Kuznetsov | /DZ-09-11/src/test/java/ru/kusoft/testing/service/PersonServiceImplTest.java | UTF-8 | 1,586 | 2.140625 | 2 | [] | no_license | package ru.kusoft.testing.service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.kusoft.testing.domain.Person;
import ru.kusoft.testing.events.InitUserEvent;
import ru.kusoft.testing.events.TestingApplicationEventListener;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("Метод сервиса PersonService должен ")
@SpringBootTest
class PersonServiceImplTest {
@MockBean
private IOService ioService;
@MockBean
private InteractionService interactionService;
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private PersonService personService;
@BeforeEach
void setUp() {
publisher.publishEvent(new InitUserEvent(this, new Person("Сидоров", "Иван")));
}
@Test
@DisplayName("корректно инициализировать объект Person")
void getPerson() {
Person expectedPerson = new Person("Сидоров", "Иван");
Person actualPerson = personService.getPerson();
assertThat(actualPerson).usingRecursiveComparison()
.isEqualTo(expectedPerson);
}
} | true |
3b1546555d21812abf40ce26aa05e17be05ccdb5 | Java | Sollace/Psychedelicraft | /src/main/java/ivorius/psychedelicraft/entity/drug/type/SleepDeprivationDrug.java | UTF-8 | 3,242 | 2.3125 | 2 | [
"MIT"
] | permissive | /*
* Copyright (c) 2014, Lukas Tenbrink.
* * http://lukas.axxim.net
*/
package ivorius.psychedelicraft.entity.drug.type;
import ivorius.psychedelicraft.PSGameRules;
import ivorius.psychedelicraft.entity.drug.DrugProperties;
import ivorius.psychedelicraft.entity.drug.DrugType;
import ivorius.psychedelicraft.util.MathUtils;
import net.minecraft.nbt.NbtCompound;
/**
* Created by Sollace on April 19 2023.
*/
public class SleepDeprivationDrug extends SimpleDrug {
public static final int TICKS_PER_DAY = 24000;
public static final int TICKS_UNTIL_PHANTOM_SPAWN = TICKS_PER_DAY * 3;
private static final float INCREASE_PER_TICKS = 1F / TICKS_UNTIL_PHANTOM_SPAWN;
private float storedEnergy;
public SleepDeprivationDrug() {
super(DrugType.SLEEP_DEPRIVATION, 1, 0);
}
@Override
public void update(DrugProperties drugProperties) {
super.update(drugProperties);
float caffiene = drugProperties.getDrugValue(DrugType.CAFFEINE) + drugProperties.getDrugValue(DrugType.COCAINE);
storedEnergy = MathUtils.approach(storedEnergy, Math.min(1, caffiene * 10F), 0.02F);
if (caffiene > 0.1F) {
setDesiredValue(0);
} else {
if (drugProperties.asEntity().getWorld().getGameRules().getBoolean(PSGameRules.DO_SLEEP_DEPRIVATION)) {
setDesiredValue(getDesiredValue() + (INCREASE_PER_TICKS / 3));
}
}
}
@Override
public void onWakeUp(DrugProperties drugProperties) {
super.onWakeUp(drugProperties);
setActiveValue(0);
}
@Override
public double getActiveValue() {
return Math.max(0, super.getActiveValue() - storedEnergy);
}
@Override
public float digSpeedModifier() {
return 1 - Math.max(0, (float)getActiveValue() * 0.9F - 0.4F);
}
@Override
public float speedModifier() {
return digSpeedModifier();
}
@Override
public float motionBlur() {
return Math.max(0, (float)getActiveValue() - 0.6F) * 3;
}
@Override
public float drowsyness() {
return (float)getActiveValue();
}
@Override
public float headMotionInertness() {
return 0;
}
@Override
public float desaturationHallucinationStrength() {
return Math.max(0, ((float)getActiveValue() - 0.5F) * 2);
}
@Override
public float soundVolumeModifier() {
return 1 + desaturationHallucinationStrength();
}
@Override
public float contextualHallucinationStrength() {
return Math.max(0, (float)getActiveValue() - 0.8F) * 4;
}
@Override
public float movementHallucinationStrength() {
return Math.max(0, (float)getActiveValue() - 0.8F) * 3;
}
@Override
public void reset(DrugProperties drugProperties) {
super.reset(drugProperties);
if (!locked) {
storedEnergy = 0;
}
}
@Override
public void fromNbt(NbtCompound compound) {
super.fromNbt(compound);
storedEnergy = compound.getFloat("storedEnergy");
}
@Override
public void toNbt(NbtCompound compound) {
super.toNbt(compound);
compound.putFloat("storedEnergy", storedEnergy);
}
}
| true |
a143958daa23da0b82bbcca58237d7dcaac9aceb | Java | tomhai/tandembrowsing | /src/org/tandembrowsing/state/StateMachine.java | UTF-8 | 10,297 | 2.234375 | 2 | [
"MIT"
] | permissive | package org.tandembrowsing.state;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.scxml.Evaluator;
import org.apache.commons.scxml.EventDispatcher;
import org.apache.commons.scxml.SCXMLExecutor;
import org.apache.commons.scxml.TriggerEvent;
import org.apache.commons.scxml.env.SimpleErrorHandler;
import org.apache.commons.scxml.env.jsp.ELContext;
import org.apache.commons.scxml.env.jsp.ELEvaluator;
import org.apache.commons.scxml.io.SCXMLParser;
import org.apache.commons.scxml.model.ModelException;
import org.apache.commons.scxml.model.SCXML;
import org.apache.commons.scxml.model.State;
import org.apache.commons.scxml.model.TransitionTarget;
import org.tandembrowsing.io.Event;
import org.tandembrowsing.io.Operation;
import org.tandembrowsing.io.ajax.Control;
import org.tandembrowsing.io.db.DBUtil;
import org.tandembrowsing.io.soap.CallbackClient;
import org.tandembrowsing.ui.LayoutException;
import org.tandembrowsing.ui.LayoutManager;
/**
* StateMachine manages the display state based on the interaction events it gets.
* The StateMachine is responsible of the valid state transitions and that the
* display is always in a valid state.
*
* @author tjh
*
*/
public class StateMachine {
private static StateMachine singletonObject;
private static Logger logger = Logger.getLogger("org.tandembrowsing");
// ERROR Strings
private static final String STATE_OK = "OK";
private static final String STATE_SAME = "ERROR:same state";
private static final String STATE_NOT_EXPECTED = "ERROR:state not expected";
private static final String UNKNOWN_EVENT_TYPE = "ERROR:event type unknown";
public static final String STATEMACHINE_URL = "resource";
public static final String PERSISTENT = "persistent";
private static LayoutManager layoutManager;
private Map <String, StateMachineSession> stateMachineSessions = new HashMap <String, StateMachineSession>();
private List <StateMachineSession> recoverySessions = new ArrayList<StateMachineSession>();
private Control control = null;
private StateMachine() {
layoutManager = LayoutManager.getInstance();
control = new Control();
DBUtil.getStateMachines(recoverySessions);
for (StateMachineSession item : recoverySessions) {
stateMachineSessions.put(item.getSmSession(), item);
start(item);
}
logger.info("Recoverable sessions in db " +stateMachineSessions.size());
DBUtil.removeNonPersistentSessions();
}
public void start(StateMachineSession recoverState) {
try {
logger.info("parse " +recoverState.getStateMachine());
SCXML scxml = SCXMLParser.parse(new URL(recoverState.getStateMachine()), new SimpleErrorHandler());
TransitionTarget target = null;
if(recoverState.hasRecoveryState())
target = SCXMLUtil.hasState(scxml, recoverState.getRecoveryState());
if(target != null) {
logger.info("Recover from " + recoverState.getRecoveryState());
scxml.setInitialTarget(target);
}
Evaluator engine = new ELEvaluator();
EventDispatcher ed = new SCXMLEventDispatcher();
SCXMLExecutor newexec = new SCXMLExecutor(engine, ed, recoverState);
newexec.setStateMachine(scxml);
newexec.addListener(scxml, recoverState);
newexec.setRootContext(new ELContext());
// if reached here, then store it to db
DBUtil.setStateMachine(recoverState);
recoverState.setExecutor(newexec);
newexec.go();
//this will kill the previous state machine if exist for the same smSession
logger.info("Statemachines running " +stateMachineSessions.size());
} catch (Exception e) {
if(recoverState.hasPreviousStatemachine()) {
logger.log(Level.SEVERE, "Bad state machine " + recoverState.getStateMachine() + ". Rolling back to previous "+ recoverState.getPreviousStateMachine());
recoverState.setStateMachine(recoverState.getPreviousStateMachine());
} else
logger.log(Level.SEVERE, "Bad state machine " + recoverState.getStateMachine() + ". Need a valid state machine to run!");
}
}
@SuppressWarnings("unchecked")
private String getCurrentState(String smSession) {
Set <State> currentStates = stateMachineSessions.get(smSession).getExecutor().getCurrentStatus().getStates();
return ((State)currentStates.iterator().next()).getId();
}
public StateMachineSession getStateMachineSession(String smSession) {
return stateMachineSessions.get(smSession);
}
private String getCurrentStateMachine(String smSession) {
return stateMachineSessions.get(smSession).getStateMachine();
}
public void resetStatemachine(String smSession) {
if(stateMachineSessions.containsKey(smSession))
try {
logger.log(Level.INFO, "Reset statemachine "+smSession);
stateMachineSessions.get(smSession).getExecutor().reset();
} catch (ModelException e) {
logger.log(Level.SEVERE, "Reset failed for "+smSession, e);
}
}
public static StateMachine getInstance() {
if (singletonObject == null) {
singletonObject = new StateMachine();
}
return singletonObject;
}
public synchronized void triggerEvent(String smSession, String event) {
TriggerEvent te = new TriggerEvent(event, TriggerEvent.SIGNAL_EVENT);
try {
stateMachineSessions.get(smSession).getExecutor().triggerEvent(te);
} catch (ModelException e) {
logger.log(Level.SEVERE, "", e);
}
}
public synchronized void processEvent(Event event) {
// should store the events for recovery
try {
if(event.getEventType().equalsIgnoreCase(Event.EVENT_CHANGE_STATE)) {
// for every change state clear all and store the event
if(event.hasOperations())
stateMachineSessions.get(event.getEventSession()).overrideOperations(event.getEventName(), event.getOperations());
triggerEvent(event.getEventSession(), event.getEventName());
logger.log(Level.INFO, "Got "+event.getEventSession()+" "+event.getEventType()+ " to "+event.getEventName() + " via " +event.getEventInterface());
logger.fine("Done "+event.getEventSession()+" "+event.getEventType()+" to "+event.getEventName());
} else if(event.getEventType().equalsIgnoreCase(Event.EVENT_MODIFY_STATE)) {
// store this as well as it could potentionally change staff
logger.log(Level.INFO, "Got "+event.getEventSession()+" "+event.getEventType() + " via " +event.getEventInterface());
layoutManager.processOperations(event.getEventSession(), event.getOperations());
logger.fine("Done "+event.getEventSession()+" "+event.getEventType());
} else if(event.getEventType().equalsIgnoreCase(Event.EVENT_MANAGE_SESSION)) {
logger.info("Got "+event.getEventSession()+" "+event.getEventType() + " via " +event.getEventInterface());
List <Operation> operations = event.getOperations();
Iterator <Operation>it = operations.iterator();
while(it.hasNext()) {
Operation operation = it.next();
if(operation.getName().equals(Event.SET_STATEMACHINE)) {
//how to stop the previous cleanly?
String persistent = operation.getParameterValue(PERSISTENT);
boolean persistentBool = false;
if(persistent != null && persistent.equals("true"))
persistentBool = true;
StateMachineSession session = null;
if(stateMachineSessions.containsKey(event.getEventSession())) {
session = stateMachineSessions.get(event.getEventSession());
session.setStateMachine(operation.getParameterValue(STATEMACHINE_URL));
session.setPersistent(persistentBool);
} else {
session = new StateMachineSession(event.getEventSession(), operation.getParameterValue(STATEMACHINE_URL), persistentBool);
stateMachineSessions.put(session.getSmSession(), session);
}
start(session);
} else if(operation.getName().equals(Event.GET_STATEMACHINE)) {
if(event.getEventInterface().equals("ajax"))
control.sendEvent(getCurrentStateMachine(event.getEventSession()), event.getEventEndpoint(), event.getEventType());
else
CallbackClient.displayEvent(getCurrentStateMachine(event.getEventSession()), event.getEventEndpoint());
} else if(operation.getName().equals(Event.SET_ATTRIBUTE)) {
layoutManager.setAttribute(operation);
} else if(operation.getName().equals(Event.GET_STATE)) {
if(event.getEventInterface().equals("ajax"))
control.sendEvent(getCurrentState(event.getEventSession()), event.getEventEndpoint(), event.getEventType());
else
CallbackClient.displayEvent(getCurrentState(event.getEventSession()), event.getEventEndpoint());
} else if(operation.getName().equals(Event.GET_VIRTUALSCREENS)) {
if(event.getEventInterface().equals("ajax"))
control.sendEvent(layoutManager.getCurrentVirtualScreens(event.getEventSession()), event.getEventEndpoint(), event.getEventType());
else
CallbackClient.displayEvent(layoutManager.getCurrentVirtualScreens(event.getEventSession()), event.getEventEndpoint());
} else {
logger.log(Level.SEVERE, "Unsupported configuration operation: "+operation.getName());
}
}
logger.fine("Done "+event.getEventSession()+" "+event.getEventType());
} else {
logger.severe("Got unknown event type "+event.getEventType() + " via " +event.getEventInterface());
CallbackClient.displayEvent(UNKNOWN_EVENT_TYPE+":"+event.getEventSession(), event.getEventEndpoint());
}
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (LayoutException e) {
logger.log(Level.SEVERE, "", e);
}
}
public void clearSession(String smSession) {
if(stateMachineSessions.containsKey(smSession)
&& !stateMachineSessions.get(smSession).isPersistent()) {
stateMachineSessions.remove(smSession);
DBUtil.removeSession(smSession);
logger.info("Statemachines running " +stateMachineSessions.size());
layoutManager.clearSession(smSession);
}
}
public boolean containSession (String smSession) {
return stateMachineSessions.containsKey(smSession);
}
}
| true |
3883146394a8b25214a0cc2f9ae0559e8ffecdd0 | Java | mjaremczuk/archivizer | /domain/src/main/java/pl/reveo/domain/interactor/MeetingUseCase.java | UTF-8 | 987 | 2.5625 | 3 | [] | no_license | package pl.reveo.domain.interactor;
import pl.reveo.domain.Meeting;
import pl.reveo.domain.executor.PostExecutionThread;
import pl.reveo.domain.executor.ThreadExecutor;
import pl.reveo.domain.repository.MeetingRepository;
import javax.inject.Inject;
import rx.Observable;
/**
* This class is an implementation of {@link UseCase} that represents a use case for
* retrieving data related to an specific {@link Meeting}.
*/
public class MeetingUseCase extends UseCase {
private final MeetingRepository meetingRepository;
private int meetingId;
@Inject
public MeetingUseCase(MeetingRepository meetingRepository, ThreadExecutor threadExecutor,
PostExecutionThread postExecutionThread) {
super(threadExecutor, postExecutionThread);
this.meetingRepository = meetingRepository;
}
public void setMeetingId(int meetingId) {
this.meetingId = meetingId;
}
@Override
protected Observable buildUseCaseObservable() {
return meetingRepository.fetchMeeting(meetingId);
}
}
| true |
ad73c9503e48ee87014aeecd845b323734667234 | Java | nab-velocity/java-sdk | /velocity-sdk/velocity-services/src/main/java/com/velocity/model/request/ReturnTransaction.java | UTF-8 | 1,421 | 1.90625 | 2 | [
"MIT"
] | permissive | package com.velocity.model.request;
/**
* This class defines the attributes for ReturnTransaction
*
* @author Vimal Kumar
* @date 19-January-2015
*/
public class ReturnTransaction {
private String type;
private String applicationProfileId;
private String merchantProfileId;
private Transaction transaction;
private BatchIds batchIds;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getApplicationProfileId() {
return applicationProfileId;
}
public void setApplicationProfileId(String applicationProfileId) {
this.applicationProfileId = applicationProfileId;
}
public String getMerchantProfileId() {
return merchantProfileId;
}
public void setMerchantProfileId(String merchantProfileId) {
this.merchantProfileId = merchantProfileId;
}
public Transaction getTransaction() {
if(transaction == null){
transaction = new Transaction();
}
return transaction;
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
public BatchIds getBatchIds() {
if(batchIds == null){
batchIds = new BatchIds();
}
return batchIds;
}
public void setBatchIds(BatchIds batchIds) {
this.batchIds = batchIds;
}
}
| true |
d0c7ea1dad25e5bdd28cb4caf45e770b4c3ae6e0 | Java | haige6502296/myjava | /AOPSpringOne/src/com/lct/BeforeAdvisor.java | UTF-8 | 360 | 2.125 | 2 | [] | no_license | package com.lct;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
// implement MethodBeforeAdvice,just a advisor class
public class BeforeAdvisor implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object targets) {
System.out.println(" BeforeAdvisor的before方法");
}
}
| true |
44ea3fba0814d13fbc634afdd65f2106edd7e6c5 | Java | medKHALIFI/Systeme_make_decision_banking_risk_management | /pfe/src/pfe/Node.java | UTF-8 | 1,953 | 3.046875 | 3 | [] | 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 pfe;
import java.util.Random;
/**
*
* @author simo
*/
public class Node {
public Node() {
}
double []Weight_of_Node;
int X_Node,Y_Node;
Random rand =new Random();
// int Rand_Max=rand.nextInt(9);
public int Rand_Weight(){
return rand.nextInt(9);
}
public double Rand_Weight2(){
return rand.nextDouble();
}
//fonction qui permet d'initialiser les poids des entreés
public void Initial_Weight(int size){
Weight_of_Node=new double[size];
for(int i=0;i<size;i++){Weight_of_Node[i]=Rand_Weight2();}
}
//fonction qui recupere la position des neurones
public void Position(int x,int y){this.X_Node=x;
this.Y_Node=y;}
//fonction qui calcule la distance entre les entrées et les diferrents Neurones
public double euclidean(double[]x,int dim){
double distance=0;
for(int i=0;i<dim;i++)
distance+=Math.pow((x[i]-this.Weight_of_Node[i]),2);
return Math.sqrt(distance);
}
//fonction de modification des piods
public void Update_Weight(double[]N,double LerningRate,double Distance_from_BMU,int _size ){
for(int i=0;i<_size;i++){Weight_of_Node[i]+=(LerningRate* Distance_from_BMU)*(N[i]-Weight_of_Node[i]);}
}
public void Update_Weight_g(double vitesse_apprentissage,int []k,double []d,int j ,int rows_data){
for(int i=0;i<rows_data;i++){
Weight_of_Node[i]+=(vitesse_apprentissage*(d[j]-Weight_of_Node[i])*k[i]) ;
}
}
}
| true |
675b4ca4c5aae30cefdf7b37e3741558038e3741 | Java | alex-abramenko/CLIENT_BusinessAssistant | /app/src/main/java/ru/sibsutis/productm/MainContract.java | UTF-8 | 243 | 1.734375 | 2 | [] | no_license | package ru.sibsutis.productm;
interface MainContract {
interface View {
void toStartActivity();
void toBasicActivity();
void showErrorServer();
}
interface Presenter {
void startProgram();
}
}
| true |
6c61650b9a0b42ca2f41ae247d801b236efa2560 | Java | eosite/openyourarm | /glaf-web/src/main/java/com/glaf/workflow/core/util/JumpTaskCmd.java | UTF-8 | 1,910 | 2 | 2 | [] | no_license | package com.glaf.workflow.core.util;
import java.util.Iterator;
import java.util.Map;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Comment;
public class JumpTaskCmd implements Command<Comment> {
protected String executionId;
protected ActivityImpl desActivity;
protected ActivityImpl currentActivity;
protected Map<String, Object> variables;
public JumpTaskCmd(String executionId, ActivityImpl currentActivity,ActivityImpl desActivity,Map<String, Object> variables) {
this.executionId = executionId;
this.currentActivity=currentActivity;
this.desActivity = desActivity;
this.variables=variables;
}
public Comment execute(CommandContext commandContext) {
ExecutionEntity executionEntity = Context.getCommandContext().getExecutionEntityManager().findExecutionById(executionId);
executionEntity.setVariables(variables);
executionEntity.setEventSource(this.currentActivity);
executionEntity.setActivity(this.currentActivity);
// 根据executionId 获取Task
Iterator<TaskEntity> localIterator = Context.getCommandContext()
.getTaskEntityManager()
.findTasksByExecutionId(this.executionId).iterator();
while (localIterator.hasNext()) {
TaskEntity taskEntity = (TaskEntity) localIterator.next();
// 触发任务监听
//taskEntity.fireEvent("complete");
// 删除任务的原因
Context.getCommandContext().getTaskEntityManager()
.deleteTask(taskEntity, "completed", true);
}
executionEntity.executeActivity(this.desActivity);
return null;
}
} | true |
2cc09f4e6b68710303b70137bd629ffad8008b62 | Java | diqiuonline/Demo | /study/itcast/Thread/multithreaddemos/thread_safe_demo/src/main/java/com/dhcc/thread/TicketSaleMain.java | UTF-8 | 540 | 2.765625 | 3 | [
"MIT"
] | permissive | package com.dhcc.thread;
/**
* 李锦卓
* 2022/2/26 23:48
* 1.0
*/
public class TicketSaleMain {
public static void main(String[] args) {
// 创建电影票对象
Ticket ticket = new Ticket();
// 创建thread对象 执行电影票售卖
Thread thread = new Thread(ticket,"窗口1");
Thread thread2 = new Thread(ticket,"窗口2");
Thread thread3 = new Thread(ticket,"窗口3");
//开始售卖
thread.start();
thread2.start();
thread3.start();
}
}
| true |
eea78348545fd10866ea4cbb8de9db3e6c711226 | Java | garibee/acmicpc | /src/마리오.java | UTF-8 | 959 | 2.8125 | 3 | [] | no_license | import java.util.Arrays;
import java.util.Scanner;
public class 마리오 {
static int[] arr = new int[10];
static int[] cache = new int[10];
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int cnt = 10;
Arrays.fill(cache, -1);
for(int i=0;i<cnt;i++) {
arr[i] = s.nextInt();
}
int sum = 0;
int upRange = 0;
int doRange = 0;
int res = 0;
int top = 0;
int bot = 0;
for(int i =0; i< cnt;i++) {
sum+=arr[i];
if(sum==100) {
//res = sum;
System.out.println(sum);
return;
}else {
if(sum>100) {
upRange = sum-100;
top = sum;
break;
}else {
doRange = 100-sum;
bot = sum;
}
}
}
System.out.println(upRange-doRange);
if(sum<100) {
System.out.println(sum);
}else {
if(upRange > doRange) System.out.println(bot);
else if(doRange > upRange) System.out.println(top);
else System.out.println(top);
}
}
}
/*
99
2
1
2
3
4
5
6
7
8
*/ | true |
b3a1f36e57efccd578b986c08f1ece4cde24a958 | Java | rafaelgoncalvs/mapskills | /mapskills-api/src/main/java/rafaelgoncalves/mapskills/api/TransactionalProxy.java | UTF-8 | 694 | 2.515625 | 3 | [] | no_license | package rafaelgoncalves.mapskills.api;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
@Interceptor
@Transactional
public class TransactionalProxy {
@AroundInvoke
private Object intercept(InvocationContext invocationContext) throws Throwable {
Optional<Object> object = Optional.empty();
try {
object = Optional.of(invocationContext.proceed());
System.out.println("Method called: " + invocationContext.getMethod());
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
return object.get();
}
}
| true |
f8d7cc29e2e44abc3d85145dac6e35eaffd98047 | Java | Denis-6613/MyFirstAutomationProject | /MyFirstAutomationProject/src/newtours/Cruises_09_12_2019.java | UTF-8 | 1,289 | 2.40625 | 2 | [] | no_license | package newtours;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
//import static driver.Driver.getDriver;
public class Cruises_09_12_2019 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Java\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
// WebDriver driver = getDriver("chrome");
driver.get("http://newtours.demoaut.com/");
// driver.findElement(By.linkText("Cruises")).click();
driver.findElement(By.xpath("(//a)[5]")).click();
String sCurURL=driver.getCurrentUrl();
String sExpURL="http://newtours.demoaut.com/mercurycruise.php";
String sCurTitle=driver.getTitle();
String sExpTitle="Cruises: Mercury Tours";
if (sCurURL.contains(sExpURL)) {
System.out.println("URL is fine");
}else {
System.out.println("URL is wrong");
}
if (sCurTitle.equals(sExpTitle)) {
System.out.println("Title is fine");
}else {
System.out.println("Title is wrong");
}
sleep(2);
driver.quit();
}
public static void sleep (int seconds) {
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true |
24dbe5cb2b45848e008473b71c3787990733ae58 | Java | sameerb42/SpringbootCurd | /Spring-bootCurd/src/main/java/com/rest/springboot/SpringbootCurd/exception/RecordNotFoundException.java | UTF-8 | 393 | 2.125 | 2 | [] | no_license | package com.rest.springboot.SpringbootCurd.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@SuppressWarnings("serial")
@ResponseStatus(HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends RuntimeException {
String message;
public RecordNotFoundException(String message) {
this.message=message;
}
}
| true |
b26fd1499c2f4d8cd25731728b2a213652ddf71b | Java | zhuxj/willow_mvn | /willow-endoor/src/main/java/com/willow/door/admin/doorarticle/web/DoorArticleController.java | UTF-8 | 5,023 | 2.140625 | 2 | [] | no_license | /**
* 版权声明:贤俊工作室 版权所有 违者必究
* 日 期:2012-12-21
*/
package com.willow.door.admin.doorarticle.web;
import com.willow.platform.core.Page;
import com.willow.platform.core.PageParam;
import com.willow.platform.core.base.web.BaseController;
import com.willow.platform.core.context.WebSiteContext;
import com.willow.door.admin.doorarticle.domain.DoorArticle;
import com.willow.door.admin.doorarticle.service.DoorArticleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <pre>
* 产品信息控制层
* </pre>
*
* @author 朱贤俊
* @version 1.0
*/
@Controller
@RequestMapping(WebSiteContext.MANAGER + "admin/doorarticle")
public class DoorArticleController extends BaseController {
@Autowired
private DoorArticleService doorArticleService;
/**
* 显示新增页面
*
* @param doorArticle
* @return
*/
@RequestMapping("/addPage/{articleType}")
public ModelAndView addPage(DoorArticle doorArticle, @PathVariable String articleType) {
ModelAndView view = new ModelAndView("/door/admin/doorarticle/add");
return view;
}
/**
* 保存记录
*
* @param doorArticle
* @return
*/
@RequestMapping("/save")
public Map<String, Object> save(DoorArticle doorArticle) {
Map<String, Object> map = new HashMap<String, Object>();
int affectCount = doorArticleService.save(doorArticle);
if (affectCount > 0) {
map.put("success", "1");
} else {
map.put("success", "0");
}
return map;
}
/**
* 删除记录
*
* @param objId
* @return
*/
@RequestMapping("/del")
public Map<String, Object> del(String objId) {
Map<String, Object> map = new HashMap<String, Object>();
int affectCount = doorArticleService.deleteByObjId(objId);
return map;
}
/**
* 批量删除
*
* @param objIds
* @return
*/
@RequestMapping("/batchDel")
public Map<String, Object> batchDel(String objIds) {
Map<String, Object> map = new HashMap<String, Object>();
String[] objIdArr = StringUtils.split(objIds, ",");
doorArticleService.deleteByObjIds(objIdArr);
map.put("success", "1");
return map;
}
/**
* 显示修改页面
*
* @param doorArticle
* @return
*/
@RequestMapping("/updatePage")
public ModelAndView updatePage(DoorArticle doorArticle) {
ModelAndView view = new ModelAndView("/door/admin/doorarticle/update");
DoorArticle domain = doorArticleService.selectByObjId(doorArticle.getObjId());
view.addObject("doorArticle", domain);
return view;
}
/**
* 更新记录
*
* @param doorArticle
* @return
*/
@RequestMapping("/update")
public Map<String, Object> update(DoorArticle doorArticle) {
Map<String, Object> map = new HashMap<String, Object>();
int affectCount = doorArticleService.update(doorArticle);
if (affectCount > 0) {
map.put("success", "1");
} else {
map.put("success", "0");
}
return map;
}
/**
* 更新记录
*
* @param doorArticle
* @return
*/
@RequestMapping("/updateByIdSelective")
public Map<String, Object> updateByIdSelective(DoorArticle doorArticle) {
Map<String, Object> map = new HashMap<String, Object>();
int affectCount = doorArticleService.updateByIdSelective(doorArticle);
return map;
}
/**
* 显示查询页面
*
* @param doorArticle
* @return
*/
@RequestMapping("/listPage")
public ModelAndView listPage(DoorArticle doorArticle) {
ModelAndView view = new ModelAndView("/door/admin/doorarticle/list");
return view;
}
/**
* 查询记录
*
* @param doorArticle
* @param pageParam
* @return
*/
@RequestMapping("/query")
public Map<String, Object> query(DoorArticle doorArticle, PageParam pageParam) {
Page<DoorArticle> page = doorArticleService.queryPageList(doorArticle, pageParam);
return page.toDataMap(null);
}
/**
* 显示详情页面
*
* @param objId
* @return
*/
@RequestMapping("/detailPage")
public ModelAndView detailPage(String objId) {
ModelAndView view = new ModelAndView("/door/admin/doorarticle/detail");
DoorArticle doorArticle = doorArticleService.selectByObjId(objId);
view.addObject("doorArticle", doorArticle);
return view;
}
}
| true |
ed7aa58594bceddffa7f13bbff6e57f96c00081e | Java | SysLord/spring-webhooks-framework | /src/main/java/de/syslord/microservices/webhooks/storage/WebHookException.java | UTF-8 | 488 | 1.945313 | 2 | [] | no_license | package de.syslord.microservices.webhooks.storage;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.PRECONDITION_FAILED, reason = "")
public class WebHookException extends Exception {
private static final long serialVersionUID = -989484894351832971L;
public WebHookException(String message) {
super(message);
}
public WebHookException(Throwable throwable) {
super(throwable);
}
}
| true |
f41bebf116dc7a820149c9d4096190ac8a80b534 | Java | fengyuting/ir_resume | /resume_dao/src/main/java/com/nlc/ir/resume/dao/ResumeAwardDao.java | UTF-8 | 381 | 1.671875 | 2 | [] | no_license | package com.nlc.ir.resume.dao;
import com.nlc.ir.resume.domain.resume.ResumeAward;
import java.util.List;
public interface ResumeAwardDao {
int deleteByPrimaryKey(Integer id);
int insert(ResumeAward record);
int insertSelective(ResumeAward record);
List<ResumeAward> selectByUserId(String userId);
int updateByPrimaryKeySelective(ResumeAward record);
} | true |
f3ce7311ecd60784ebde4cd45ad73d8aae65932c | Java | tlhhup/spring-cloud-learn | /tlh-spring-boot-admin/src/main/java/org/tlh/springcloud/SpringBootAdminApplication.java | UTF-8 | 566 | 1.632813 | 2 | [
"Apache-2.0"
] | permissive | package org.tlh.springcloud;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author huping
* @desc
* @date 18/10/5
*/
@EnableEurekaClient
@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminApplication.class,args);
}
}
| true |
1617ebdc03d071a0dce8f8227f0aa920deeeb3a8 | Java | mgkkkkkk/test | /test.java | UTF-8 | 31 | 2.203125 | 2 | [] | no_license | printfln("Hello");
23333333;
| true |
967d8b1cb6c462bf1bf4dee0c35a7bb190859dc2 | Java | salomax/machine-learning | /src/test/java/org/salomax/ml/NormalEquationTest.java | UTF-8 | 744 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | package org.salomax.ml;
import org.junit.Test;
import Jama.Matrix;
/**
* Created by marcos.salomao on 27/12/16.
*/
public class NormalEquationTest {
@Test
public void calculateThetas() {
DataSet dataSet = new SimpleDataSet();
dataSet.add(1.0, 1.0);
dataSet.add(2.0, 2.0);
dataSet.add(3.0, 3.0);
// theta = (Xt X)-1 Xt y
double[][] arrayX = {{1.0, 1.0}, {1.0, 2.0}, {1.0, 3.0}};
double[][] arrayY = {{1.0}, {2.0}, {3.0}};
Matrix X = new Matrix(arrayX);
Matrix y = new Matrix(arrayY);
Matrix R = (X.transpose().times(X)).inverse().times(X.transpose().times(y));
System.out.println(R);
}
}
| true |
430ede3367f78a503b43336e468a6ef6d74bd9e6 | Java | MorningSongTeacher/MVP_Study | /app/src/main/java/com/example/songwei/mvp_rxjava_retrofit2/net/NetTask.java | UTF-8 | 174 | 1.835938 | 2 | [] | no_license | package com.example.songwei.mvp_rxjava_retrofit2.net;
import rx.Subscription;
public interface NetTask<T> {
Subscription execute(T data, LoadTasksCallBack callBack);
}
| true |
10129903f7f635e893da78f4659006e7d891b618 | Java | keipa/nomapp | /app/src/main/java/com/nomapp/nomapp_beta/UserGuide/HelpDialog.java | WINDOWS-1252 | 973 | 2.046875 | 2 | [] | no_license | package com.nomapp.nomapp_beta.UserGuide;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import com.nomapp.nomapp_beta.R;
/**
* Created by on 18.03.2016.
*/
public class HelpDialog extends DialogFragment implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
Bundle arguments = getArguments();
int messageId = arguments.getInt("message");
adb.setTitle(getActivity().getResources().getString(R.string.main_activity_msg_title)).setPositiveButton("OK", this)
.setMessage(getActivity().getResources().getString(messageId));
return adb.create();
}
}
| true |
f2c6dee2a94fa010870d4d4c51f5721fb2299c75 | Java | guohao-mumu/dubbo-demo | /redis/src/main/java/com/gh/dubbo/redis/config/RedisConfig.java | UTF-8 | 3,978 | 2.0625 | 2 | [] | no_license | package com.gh.dubbo.redis.config;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.gh.dubbo.redis.RedisUtil;
import com.gh.dubbo.redis.serializer.StringRedisSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @Auther: guohao
* @Date: 2019/12/11 18:56
* @Description:
*/
@Configuration
@EnableAutoConfiguration
public class RedisConfig {
private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);
@Value("#{'${spring.redis.sentinel.nodes}'.split(',')}")
private List<String> nodes;
@Bean
public JedisPoolConfig jedisPoolConfig() {
return new JedisPoolConfig();
}
@Bean
public RedisSentinelConfiguration sentinelConfiguration() {
RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
//配置matser的名称
redisSentinelConfiguration.master("mymaster");
//配置redis的哨兵sentinel
Set<RedisNode> redisNodeSet = new HashSet<>();
nodes.forEach(x -> redisNodeSet.add(new RedisNode(x.split(":")[0], Integer.parseInt(x.split(":")[1]))));
logger.info("redisNodeSet -->" + redisNodeSet);
redisSentinelConfiguration.setSentinels(redisNodeSet);
redisSentinelConfiguration.setPassword("yiigoo");
return redisSentinelConfiguration;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory(RedisSentinelConfiguration sentinelConfig) {
return new JedisConnectionFactory(sentinelConfig);
}
//
// /**
// * 让Spring Session不再执行config命令
// * 同 <util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>
// *
// * @return
// */
// @Bean
// public static ConfigureRedisAction configureRedisAction() {
// return ConfigureRedisAction.NO_OP;
// }
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// fastjson在2017年3月爆出了在1.2.24以及之前版本存在远程代码执行高危安全漏洞。
// 所以要使用ParserConfig.getGlobalInstance().addAccept("com.xiaolyuh.");指定序列化白名单
ParserConfig.getGlobalInstance().addAccept("com.gh.dubbo.");
// 设置值(value)的序列化采用FastJsonRedisSerializer。
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
RedisUtil redisUtil = new RedisUtil();
redisUtil.setRedisTemplate(redisTemplate);
return redisUtil;
}
}
| true |
f55054c5744c25de65890b78df4c9017d24287d6 | Java | orbitalsqwib/MAD-2020-threadapp | /app/src/main/java/com/threadteam/thread/adapters/ViewMemberAdapter.java | UTF-8 | 4,700 | 2.40625 | 2 | [] | no_license | package com.threadteam.thread.adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import com.threadteam.thread.libraries.Progression;
import com.threadteam.thread.R;
import com.threadteam.thread.models.User;
import com.threadteam.thread.viewholders.ViewMemberDividerViewHolder;
import com.threadteam.thread.viewholders.ViewMemberViewHolder;
import java.util.ArrayList;
import java.util.List;
/**
* Handles binding user, title and associated server data to the appropriate view holder
* to display a list of all members in the current server.
*
* @author Eugene Long
* @version 2.0
* @since 2.0
*
* @see ViewMemberViewHolder
* @see ViewMemberDividerViewHolder
*/
public class ViewMemberAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// DATA STORE
/** Contains all users' data to be displayed. */
public List<User> userList;
/** Contains custom title data for the current server. */
public List<String> titleList = new ArrayList<>();
/** Contains the current server id. */
public String serverId;
// CONSTRUCTOR
public ViewMemberAdapter(List<User> users, String serverId) {
this.userList = users;
this.serverId = serverId;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if(viewType == 1) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.activity_partial_members_divider,
parent,
false
);
return new ViewMemberDividerViewHolder(view);
}
ViewMemberViewHolder viewHolder;
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.activity_partial_view_member,
parent,
false
);
viewHolder = new ViewMemberViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(position != 1) {
ViewMemberViewHolder thisHolder = (ViewMemberViewHolder) holder;
if(position > 1) {
position -= 1;
}
User currentUser = userList.get(position);
String nameString = currentUser.get_username();
String imageLink = currentUser.get_profileImageURL();
int level = currentUser.GetUserLevelForServer(serverId);
int exp = currentUser.GetUserExpForServer(serverId);
int expToNextLevel = currentUser.GetExpToNextLevelForServer(serverId);
int progressToNextLevel = currentUser.GetAbsoluteLevelProgressForServer(serverId);
int stage = Progression.ConvertLevelToStage(level);
Integer colorInt = Progression.GetDefaultColorIntForStage(stage);
String title;
if(titleList.size() > 0 && !titleList.get(stage).equals("")) {
title = titleList.get(stage);
} else {
title = Progression.GetDefaultTitleForStage(stage);
}
String levelString = "Lvl " + level;
String expString = exp + "/" + expToNextLevel + " xp";
thisHolder.MemberName.setText(nameString);
if(colorInt != null) {
thisHolder.MemberName.setTextColor(colorInt);
}
thisHolder.MemberTitle.setText(title);
thisHolder.MemberLevel.setText(levelString);
thisHolder.MemberProgressBar.setProgress(progressToNextLevel);
thisHolder.MemberExp.setText(expString);
if(imageLink != null) {
Picasso.get()
.load(imageLink)
.fit()
.error(R.drawable.profilepictureempty)
.centerCrop()
.into(thisHolder.MemberProfileImageView);
} else {
Picasso.get()
.load(R.drawable.profilepictureempty)
.fit()
.centerCrop()
.into(thisHolder.MemberProfileImageView);
}
}
}
public int getItemViewType(int position) {
if (position == 1) {
return 1;
}
return 0;
}
@Override
public int getItemCount() {
if(userList.size() == 0) {
return 0;
}
return userList.size() + 1;
}
}
| true |
b36abdc34b677209abf3332216518db3eff5a303 | Java | xingqinggele/Ducha | /app/src/main/java/com/zhhl/ducha/activity/ZDActivity/HomeReportActivity.java | UTF-8 | 7,517 | 1.625 | 2 | [] | no_license | package com.zhhl.ducha.activity.ZDActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.alibaba.fastjson.JSON;
import com.example.toollibrary.okhttp.exception.OkHttpException;
import com.example.toollibrary.okhttp.listener.DisposeDataListener;
import com.example.toollibrary.okhttp.request.RequestParams;
import com.zhhl.ducha.R;
import com.zhhl.ducha.activity.BaseActivity;
import com.zhhl.ducha.bean.ZDtablenianbean;
import com.zhhl.ducha.bean.ZDtableyuebean;
import com.zhhl.ducha.uri.RequestCenter;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by qgl on 2019/9/9 15:55.
*/
public class HomeReportActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
@BindView(R.id.back)
RelativeLayout back;
@BindView(R.id.zdy_cc)
TextView zdyCc;
@BindView(R.id.zdn_cc)
TextView zdnCc;
@BindView(R.id.zdy_jl)
TextView zdyJl;
@BindView(R.id.zdn_jl)
TextView zdnJl;
@BindView(R.id.zdy_sp)
TextView zdySp;
@BindView(R.id.zdn_sp)
TextView zdnSp;
@BindView(R.id.zdy_gzl)
TextView zdyGzl;
@BindView(R.id.zdn_gzl)
TextView zdnGzl;
@BindView(R.id.zdy_ly)
TextView zdyLy;
@BindView(R.id.zdn_ly)
TextView zdnLy;
@BindView(R.id.zdy_mhk)
TextView zdyMhk;
@BindView(R.id.zdn_mhk)
TextView zdnMhk;
@BindView(R.id.zdy_bs)
TextView zdyBs;
@BindView(R.id.zdn_bs)
TextView zdnBs;
@BindView(R.id.zdy_sy)
TextView zdySy;
@BindView(R.id.zdn_sy)
TextView zdnSy;
@BindView(R.id.zdy_bc)
TextView zdyBc;
@BindView(R.id.zdn_bc)
TextView zdnBc;
@BindView(R.id.zdy_yb)
TextView zdyYb;
@BindView(R.id.zdn_yb)
TextView zdnYb;
@BindView(R.id.zdy_cbs)
TextView zdyCbs;
@BindView(R.id.zdn_cbs)
TextView zdnCbs;
@BindView(R.id.zdy_hj)
TextView zdyHj;
@BindView(R.id.zdn_hj)
TextView zdnHj;
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout swipeRefreshLayout;
@BindView(R.id.zdy_th)
TextView zdyTh;
@BindView(R.id.zdn_th)
TextView zdnTh;
private SwipeRefreshLayout mSwipeRefreshLayout;
ProgressDialog progressDialog;
// 月数据
private ZDtableyuebean zDtableyuebean;
//年数据
private ZDtablenianbean zDtablenianbean;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homereportactivity);
ButterKnife.bind(this);
initView();
}
public void initView() {
mSwipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
if (progressDialog == null)
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在请求,请稍后...");
progressDialog.setCancelable(false);
progressDialog.show();
getDate_yue();
getDate_nian();
}
private void getDate_yue() {
//网络请求
RequestParams params = new RequestParams();
RequestCenter.request_zd_baobiao_yue(params, new DisposeDataListener() {
@Override
public void onSuccess(Object o) {
progressDialog.dismiss();
Log.e("重点人表格月返回数据", o.toString());
final String aa = o.toString();
zDtableyuebean = JSON.parseObject(aa, ZDtableyuebean.class);
Log.e("长春", zDtableyuebean.getAttributes().getThreeCount().getCc() + "");
zdyCc.setText(zDtableyuebean.getAttributes().getThreeCount().getCc() + "");
zdyJl.setText(zDtableyuebean.getAttributes().getThreeCount().getJl() + "");
zdySp.setText(zDtableyuebean.getAttributes().getThreeCount().getSp() + "");
zdyGzl.setText(zDtableyuebean.getAttributes().getThreeCount().getGzl() + "");
zdyLy.setText(zDtableyuebean.getAttributes().getThreeCount().getLy() + "");
zdyMhk.setText(zDtableyuebean.getAttributes().getThreeCount().getMhk() + "");
zdyBs.setText(zDtableyuebean.getAttributes().getThreeCount().getBs() + "");
zdySy.setText(zDtableyuebean.getAttributes().getThreeCount().getSy() + "");
zdyBc.setText(zDtableyuebean.getAttributes().getThreeCount().getBc() + "");
zdyYb.setText(zDtableyuebean.getAttributes().getThreeCount().getYj() + "");
zdyCbs.setText(zDtableyuebean.getAttributes().getThreeCount().getCbs() + "");
zdyTh.setText(zDtableyuebean.getAttributes().getThreeCount().getTh() + "");
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFailure(OkHttpException e) {
progressDialog.dismiss();
Log.e("失败", e.getEmsg() + "");
}
});
}
private void getDate_nian() {
//网络请求
RequestParams params = new RequestParams();
RequestCenter.request_zd_baobiao_nian(params, new DisposeDataListener() {
@Override
public void onSuccess(Object o) {
progressDialog.dismiss();
Log.e("重点人表格年返回数据", o.toString());
final String aa = o.toString();
zDtablenianbean = JSON.parseObject(aa, ZDtablenianbean.class);
zdnCc.setText(zDtablenianbean.getAttributes().getAllCount().getCc() + "");
zdnJl.setText(zDtablenianbean.getAttributes().getAllCount().getJl() + "");
zdnSp.setText(zDtablenianbean.getAttributes().getAllCount().getSp() + "");
zdnGzl.setText(zDtablenianbean.getAttributes().getAllCount().getGzl() + "");
zdnLy.setText(zDtablenianbean.getAttributes().getAllCount().getLy() + "");
zdnMhk.setText(zDtablenianbean.getAttributes().getAllCount().getMhk() + "");
zdnBs.setText(zDtablenianbean.getAttributes().getAllCount().getBs() + "");
zdnSy.setText(zDtablenianbean.getAttributes().getAllCount().getSy() + "");
zdnBc.setText(zDtablenianbean.getAttributes().getAllCount().getBc() + "");
zdnYb.setText(zDtablenianbean.getAttributes().getAllCount().getYj() + "");
zdnCbs.setText(zDtablenianbean.getAttributes().getAllCount().getCbs() + "");
zdnTh.setText(zDtablenianbean.getAttributes().getAllCount().getTh() + "");
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFailure(OkHttpException e) {
progressDialog.dismiss();
Log.e("失败", e.getEmsg() + "");
}
});
}
public void onRefresh() {
getDate_yue();
getDate_nian();
}
@OnClick(R.id.back)
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.back:
finish();
break;
}
}
}
| true |
6405fc82af0306f083f1fb14a01b2189c69a7852 | Java | gentryhuang/java-base-learning | /design-patterns-example/visitor-example/src/main/java/com/design/pattern/visitor/FreeCourse.java | UTF-8 | 294 | 2.5 | 2 | [] | no_license | package com.design.pattern.visitor;
/**
* FreeCourse
*
* @author shunhua
* @date 2019-10-05
*/
public class FreeCourse extends Course {
/**
* 接受访问
* @param visitor
*/
@Override
public void accept(IVisitor visitor) {
visitor.visit(this);
}
} | true |
d63fb792c3c17d8ac2fc2e3d2ba08fe2a292902d | Java | M4itzZz/myHobi | /app/src/main/java/com/example/kaist/myhobi/ThirdFragment.java | UTF-8 | 544 | 1.9375 | 2 | [] | no_license | package com.example.kaist.myhobi;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ThirdFragment extends Fragment {
View myView;
@Override
public View onCreateView(@NonNull LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
myView=inflater.inflate(R.layout.organisatsioonid_layout,container,false);
return myView;
}
}
| true |
0e277437173e3a6a8105dd018fec2ecb1bc6c72c | Java | RaelZero/sectesting | /tests/src/schoolmate/admin/EditStudent115.java | UTF-8 | 666 | 1.9375 | 2 | [] | no_license | package schoolmate.admin;
import org.junit.Before;
import org.junit.Test;
import schoolmate.Admin;
public class EditStudent115 extends Admin{
@Before
public void init() {
tester.clickLinkWithExactText("Students");
tester.assertMatch("Manage Students");
tester.setWorkingForm("students");
addSubmitButton("//form[@name='students']");
}
@Test
public void testPage() {
tester.checkCheckbox("delete[]");
this.genericTestPage("1", "21", "Edit Student");
}
@Test
public void testPage2(){
tester.checkCheckbox("delete[]");
this.genericTestPage2("21", "Edit Student");
}
@Test
public void testDelete(){
this.genericTestDelete();
}
}
| true |
6d3cc11484945fe4353e4c1f25c252dc3d147ef0 | Java | rp17/rvnPetr | /src/Raven/Raven_Game.java | UTF-8 | 26,868 | 1.71875 | 2 | [
"MIT"
] | permissive | package Raven;
import static Raven.Main.TODO;
import Raven.armory.projectiles.Bolt;
import Raven.armory.projectiles.Pellet;
import Raven.armory.projectiles.Raven_Projectile;
import Raven.armory.projectiles.Rocket;
import Raven.armory.projectiles.Slug;
import static Raven.lua.Raven_Scriptor.script;
import static Raven.Raven_Messages.message_type.Msg_UserHasRemovedBot;
import static Raven.Raven_ObjectEnumerations.GetNameOfType;
import static Raven.Raven_ObjectEnumerations.type_blaster;
import static Raven.Raven_ObjectEnumerations.type_rail_gun;
import static Raven.Raven_ObjectEnumerations.type_rocket_launcher;
import static Raven.Raven_ObjectEnumerations.type_shotgun;
import static Raven.Raven_UserOptions.UserOptions;
import static Raven.DEFINE.*;
import Raven.goals.Raven_Goal_Types.GoalTypeToString;
import Raven.navigation.PathManager;
import Raven.navigation.Raven_PathPlanner;
import common.D2.Vector2D;
import static common.D2.Vector2D.mul;
import static common.D2.Vector2D.sub;
import static common.D2.Vector2D.isSecondInFOVOfFirst;
import static common.D2.Vector2D.POINTStoVector;
import static common.D2.Vector2D.Vec2DDistance;
import static common.D2.Vector2D.Vec2DDistanceSq;
import static common.D2.Vector2D.Vec2DNormalize;
import static common.D2.WallIntersectionTests.doWallsIntersectCircle;
import static common.D2.WallIntersectionTests.doWallsObstructLineSegment;
import static common.Debug.DbgConsole.debug_con;
import static common.Game.EntityFunctionTemplates.TagNeighbors;
import static common.Game.EntityManager.EntityMgr;
import static common.Messaging.MessageDispatcher.Dispatcher;
import static common.Messaging.MessageDispatcher.SEND_MSG_IMMEDIATELY;
import static common.Messaging.MessageDispatcher.SENDER_ID_IRRELEVANT;
import static common.misc.Stream_Utility_function.ttos;
import static common.misc.Cgdi.gdi;
import static common.misc.utils.MaxDouble;
import static common.misc.WindowUtils.ErrorBox;
import static common.misc.WindowUtils.GetClientCursorPosition;
import static common.misc.WindowUtils.IS_KEY_PRESSED;
import common.windows.POINTS;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Author: Mat Buckland (www.ai-junkie.com)
*
* Desc: this class creates and stores all the entities that make up the Raven
* game environment. (walls, bots, health etc) and can read a Raven map file and
* recreate the necessary geometry.
*
* this class has methods for updating the game entities and for rendering them.
*/
public class Raven_Game {
static {
// uncomment to write object creation/deletion to debug console
// define(LOG_CREATIONAL_STUFF);
}
/**
* the current game map
*/
private Raven_Map m_pMap;
/**
* a list of all the bots that are inhabiting the map
*/
private List<Raven_Bot> m_Bots = new LinkedList<Raven_Bot>();
/**
* the user may select a bot to control manually. This is a pointer to that
* bot
*/
private Raven_Bot m_pSelectedBot;
/**
* this list contains any active projectiles (slugs, rockets, shotgun
* pellets, etc)
*/
private List<Raven_Projectile> m_Projectiles = new LinkedList<Raven_Projectile>();
/**
* this class manages all the path planning requests
*/
private PathManager<Raven_PathPlanner> m_pPathManager;
/**
* if true the game will be paused
*/
private boolean m_bPaused;
/**
* if true a bot is removed from the game
*/
private boolean m_bRemoveABot;
/**
* when a bot is killed a "grave" is displayed for a few seconds. This class
* manages the graves
*/
private GraveMarkers m_pGraveMarkers;
/**
* this iterates through each trigger, testing each one against each bot
*/
//private void UpdateTriggers();
/**
* deletes all entities, empties all containers and creates a new navgraph
*/
private void Clear() {
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("\n------------------------------ Clearup -------------------------------").print("");
}
//delete the bots
Iterator<Raven_Bot> iterator = m_Bots.iterator();
while (iterator.hasNext()) {
Raven_Bot it = iterator.next();
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("deleting entity id: ").print(it.ID()).print(" of type ")
.print(GetNameOfType(it.EntityType())).print("(").print(it.EntityType()).
print(")").print("");
}
iterator.remove();
}
//delete any active projectiles
Iterator<Raven_Projectile> curW = m_Projectiles.iterator();
while (curW.hasNext()) {
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("deleting projectile id: ").print(curW.next().ID()).print("");
}
curW.remove();
}
//clear the containers
m_Projectiles.clear();
m_Bots.clear();
m_pSelectedBot = null;
}
/**
* attempts to position a spawning bot at a free spawn point. returns false
* if unsuccessful
*/
private boolean AttemptToAddBot(Raven_Bot pBot) {
//make sure there are some spawn points available
if (m_pMap.GetSpawnPoints().size() <= 0) {
ErrorBox("Map has no spawn points!");
return false;
}
//we'll make the same number of attempts to spawn a bot this update as
//there are spawn points
int attempts = m_pMap.GetSpawnPoints().size();
while (--attempts >= 0) {
//select a random spawn point
Vector2D pos = m_pMap.GetRandomSpawnPoint();
//check to see if it's occupied
Iterator<Raven_Bot> it = m_Bots.iterator();
boolean bAvailable = true;
while (it.hasNext()) {
Raven_Bot curBot = it.next();
//if the spawn point is unoccupied spawn a bot
if (Vec2DDistance(pos, curBot.Pos()) < curBot.BRadius()) {
bAvailable = false;
}
}
if (bAvailable) {
pBot.Spawn(pos);
return true;
}
}
return false;
}
/**
* when a bot is removed from the game by a user all remaining bots must be
* notified so that they can remove any references to that bot from their
* memory
*/
private void NotifyAllBotsOfRemoval(Raven_Bot pRemovedBot) {
Iterator<Raven_Bot> it = m_Bots.iterator();
while (it.hasNext()) {
Raven_Bot curBot = it.next();
Dispatcher.DispatchMsg(SEND_MSG_IMMEDIATELY,
SENDER_ID_IRRELEVANT,
curBot.ID(),
Msg_UserHasRemovedBot,
pRemovedBot);
}
}
//----------------------------- ctor ------------------------------------------
//-----------------------------------------------------------------------------
public Raven_Game() {
m_pSelectedBot = null;
m_bPaused = false;
m_bRemoveABot = false;
m_pMap = null;
m_pPathManager = null;
m_pGraveMarkers = null;
//load in the default map
LoadMap(script.GetString("StartMap"));
TODO("Odstranit automaticky vyber bota");
if(m_Bots.size() > 0) {
m_pSelectedBot = m_Bots.get(0);
}
}
//------------------------------ dtor -----------------------------------------
//-----------------------------------------------------------------------------
@Override
protected void finalize() throws Throwable {
super.finalize();
Clear();
m_pPathManager = null;
m_pMap = null;
m_pGraveMarkers = null;
}
//the usual suspects
public void Render() {
m_pGraveMarkers.Render();
//render the map
m_pMap.Render();
//render all the bots unless the user has selected the option to only
//render those bots that are in the fov of the selected bot
if (m_pSelectedBot != null && UserOptions.m_bOnlyShowBotsInTargetsFOV) {
List<Raven_Bot> VisibleBots = GetAllBotsInFOV(m_pSelectedBot);
Iterator<Raven_Bot> it = VisibleBots.iterator();
while (it.hasNext()) {
it.next().Render();
}
if (m_pSelectedBot != null) {
m_pSelectedBot.Render();
}
} else {
//render all the entities
Iterator<Raven_Bot> it = m_Bots.iterator();
while (it.hasNext()) {
Raven_Bot curBot = it.next();
if (curBot.isAlive()) {
curBot.Render();
}
}
}
//render any projectiles
Iterator<Raven_Projectile> curW = m_Projectiles.iterator();
while (curW.hasNext()) {
curW.next().Render();
}
// gdi.TextAtPos(300, Constants.WindowHeight - 70, "Num Current Searches: " + ttos(m_pPathManager.GetNumActiveSearches()));
//render a red circle around the selected bot (blue if possessed)
if (m_pSelectedBot != null) {
if (m_pSelectedBot.isPossessed()) {
gdi.BluePen();
gdi.HollowBrush();
gdi.Circle(m_pSelectedBot.Pos(), m_pSelectedBot.BRadius() + 1);
} else {
gdi.RedPen();
gdi.HollowBrush();
gdi.Circle(m_pSelectedBot.Pos(), m_pSelectedBot.BRadius() + 1);
}
if (UserOptions.m_bShowOpponentsSensedBySelectedBot) {
m_pSelectedBot.GetSensoryMem().RenderBoxesAroundRecentlySensed();
}
//render a square around the bot's target
if (UserOptions.m_bShowTargetOfSelectedBot && m_pSelectedBot.GetTargetBot() != null) {
gdi.ThickRedPen();
Vector2D p = m_pSelectedBot.GetTargetBot().Pos();
double b = m_pSelectedBot.GetTargetBot().BRadius();
gdi.Line(p.x - b, p.y - b, p.x + b, p.y - b);
gdi.Line(p.x + b, p.y - b, p.x + b, p.y + b);
gdi.Line(p.x + b, p.y + b, p.x - b, p.y + b);
gdi.Line(p.x - b, p.y + b, p.x - b, p.y - b);
}
//render the path of the bot
if (UserOptions.m_bShowPathOfSelectedBot) {
m_pSelectedBot.GetBrain().Render();
}
//display the bot's goal stack
if (UserOptions.m_bShowGoalsOfSelectedBot) {
Vector2D p = new Vector2D(m_pSelectedBot.Pos().x - 50, m_pSelectedBot.Pos().y);
m_pSelectedBot.GetBrain().RenderAtPos(p, GoalTypeToString.Instance());
}
if (UserOptions.m_bShowGoalAppraisals) {
m_pSelectedBot.GetBrain().RenderEvaluations(5, 415);
}
if (UserOptions.m_bShowWeaponAppraisals) {
m_pSelectedBot.GetWeaponSys().RenderDesirabilities();
}
if (IS_KEY_PRESSED(KeyEvent.VK_Q) && m_pSelectedBot.isPossessed()) {
gdi.TextColor(255, 0, 0);
gdi.TextAtPos(GetClientCursorPosition(), "Queuing");
}
}
}
/**
* calls the update function of each entity
*/
public void Update() {
//don't update if the user has paused the game
if (m_bPaused) {
return;
}
m_pGraveMarkers.Update();
//get any player keyboard input
GetPlayerInput();
//update all the queued searches in the path manager
m_pPathManager.UpdateSearches();
//update any doors
Iterator<Raven_Door> curDoor = m_pMap.GetDoors().iterator();
while (curDoor.hasNext()) {
curDoor.next().Update();
}
//update any current projectiles
Iterator<Raven_Projectile> it = m_Projectiles.iterator();
while (it.hasNext()) {
Raven_Projectile curW = it.next();
//test for any dead projectiles and remove them if necessary
if (!curW.isDead()) {
curW.Update();
} else {
it.remove();
}
}
//update the bots
boolean bSpawnPossible = true;
Iterator<Raven_Bot> botsIt = m_Bots.iterator();
while (botsIt.hasNext()) {
Raven_Bot curBot = botsIt.next();
//if this bot's status is 'respawning' attempt to resurrect it from
//an unoccupied spawn point
if (curBot.isSpawning() && bSpawnPossible) {
bSpawnPossible = AttemptToAddBot(curBot);
} //if this bot's status is 'dead' add a grave at its current location
//then change its status to 'respawning'
else if (curBot.isDead()) {
//create a grave
m_pGraveMarkers.AddGrave(curBot.Pos());
//change its status to spawning
curBot.SetSpawning();
} //if this bot is alive update it.
else if (curBot.isAlive()) {
curBot.Update();
}
}
//update the triggers
m_pMap.UpdateTriggerSystem(m_Bots);
//if the user has requested that the number of bots be decreased, remove
//one
if (m_bRemoveABot) {
if (!m_Bots.isEmpty()) {
Raven_Bot pBot = m_Bots.get(m_Bots.size() - 1);
if (pBot == m_pSelectedBot) {
m_pSelectedBot = null;
}
NotifyAllBotsOfRemoval(pBot);
m_Bots.remove(pBot);
pBot = null;
}
m_bRemoveABot = false;
}
}
/**
* loads an environment from a file sets up the game environment from map
* file
*/
public boolean LoadMap(final String filename) {
//clear any current bots and projectiles
Clear();
//out with the old
m_pMap = null;
m_pGraveMarkers = null;
m_pPathManager = null;
//in with the new
m_pGraveMarkers = new GraveMarkers(script.GetDouble("GraveLifetime"));
m_pPathManager = new PathManager<Raven_PathPlanner>(script.GetInt("MaxSearchCyclesPerUpdateStep"));
m_pMap = new Raven_Map();
//make sure the entity manager is reset
EntityMgr.Reset();
//load the new map data
if (m_pMap.LoadMap(filename)) {
AddBots(script.GetInt("NumBots"));
return true;
}
return false;
}
/**
* Adds a bot and switches on the default steering behavior
*/
public void AddBots(int NumBotsToAdd) {
while (NumBotsToAdd-- != 0) {
//create a bot. (its position is irrelevant at this point because it will
//not be rendered until it is spawned)
Raven_Bot rb = new Raven_Bot(this, new Vector2D());
//switch the default steering behaviors on
rb.GetSteering().WallAvoidanceOn();
rb.GetSteering().SeparationOn();
m_Bots.add(rb);
//register the bot with the entity manager
EntityMgr.RegisterEntity(rb);
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("Adding bot with ID ").print(ttos(rb.ID())).print("");
}
}
}
public void AddRocket(Raven_Bot shooter, Vector2D target) {
target = new Vector2D(target); // work with copy
Raven_Projectile rp = new Rocket(shooter, target);
m_Projectiles.add(rp);
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("Adding a rocket ").print(rp.ID()).print(" at pos ").print(rp.Pos()).print("");
}
}
public void AddRailGunSlug(Raven_Bot shooter, Vector2D target) {
target = new Vector2D(target); // work with copy
Raven_Projectile rp = new Slug(shooter, target);
m_Projectiles.add(rp);
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("Adding a rail gun slug").print(rp.ID()).print(" at pos ").print(rp.Pos()).print("");
}
}
public void AddShotGunPellet(Raven_Bot shooter, Vector2D target) {
target = new Vector2D(target); //work with copy
Raven_Projectile rp = new Pellet(shooter, target);
m_Projectiles.add(rp);
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("Adding a shotgun shell ").print(rp.ID()).print(" at pos ").print(rp.Pos()).print("");
}
}
public void AddBolt(Raven_Bot shooter, Vector2D target) {
target = new Vector2D(target); //work with copy
Raven_Projectile rp = new Bolt(shooter, target);
m_Projectiles.add(rp);
if (def(LOG_CREATIONAL_STUFF)) {
debug_con.print("Adding a bolt ").print(rp.ID()).print(" at pos ").print(rp.Pos()).print("");
}
}
/**
* removes the last bot to be added from the game
*/
public void RemoveBot() {
m_bRemoveABot = true;
}
/**
* returns true if a bot cannot move from A to B without bumping into world
* geometry. It achieves this by stepping from A to B in steps of size
* BoundingRadius and testing for intersection with world geometry at each
* point.
*/
public boolean isPathObstructed(Vector2D A,
Vector2D B,
double BoundingRadius/* = 0 */) {
Vector2D ToB = Vec2DNormalize(sub(B, A));
Vector2D curPos = new Vector2D(A);
while (Vec2DDistanceSq(curPos, B) > BoundingRadius * BoundingRadius) {
//advance curPos one step
curPos.add(mul(ToB, 0.5 * BoundingRadius));
//test all walls against the new position
if (doWallsIntersectCircle(m_pMap.GetWalls(), curPos, BoundingRadius)) {
return true;
}
}
return false;
}
/**
* returns a vector of pointers to bots within the given bot's field of view
*/
public List<Raven_Bot> GetAllBotsInFOV(final Raven_Bot pBot) {
ArrayList<Raven_Bot> VisibleBots = new ArrayList<Raven_Bot>();
Iterator<Raven_Bot> it = m_Bots.iterator();
while (it.hasNext()) {
Raven_Bot curBot = it.next();
//make sure time is not wasted checking against the same bot or against a
// bot that is dead or re-spawning
if (curBot == pBot || !curBot.isAlive()) {
continue;
}
//first of all test to see if this bot is within the FOV
if (isSecondInFOVOfFirst(pBot.Pos(),
pBot.Facing(),
curBot.Pos(),
pBot.FieldOfView())) {
//cast a ray from between the bots to test visibility. If the bot is
//visible add it to the vector
if (!doWallsObstructLineSegment(pBot.Pos(),
curBot.Pos(),
m_pMap.GetWalls())) {
VisibleBots.add(curBot);
}
}
}
return VisibleBots;
}
/**
* returns true if the second bot is unobstructed by walls and in the field
* of view of tshe first.
*/
public boolean isSecondVisibleToFirst(final Raven_Bot pFirst,
final Raven_Bot pSecond) {
//if the two bots are equal or if one of them is not alive return false
if (!(pFirst == pSecond) && pSecond.isAlive()) {
//first of all test to see if this bot is within the FOV
if (isSecondInFOVOfFirst(pFirst.Pos(),
pFirst.Facing(),
pSecond.Pos(),
pFirst.FieldOfView())) {
//test the line segment connecting the bot's positions against the walls.
//If the bot is visible add it to the vector
if (!doWallsObstructLineSegment(pFirst.Pos(),
pSecond.Pos(),
m_pMap.GetWalls())) {
return true;
}
}
}
return false;
}
/**
* returns true if the ray between A and B is unobstructed.
*/
public boolean isLOSOkay(Vector2D A, Vector2D B) {
return !doWallsObstructLineSegment(A, B, m_pMap.GetWalls());
}
/**
* starting from the given origin and moving in the direction Heading this
* method returns the distance to the closest wall
*/
//public double GetDistanceToClosestWall(Vector2D Origin, Vector2D Heading);
/**
* returns the position of the closest visible switch that triggers the door
* of the specified ID
*/
public Vector2D GetPosOfClosestSwitch(Vector2D botPos, int doorID) {
List<Integer> SwitchIDs = new ArrayList<Integer>();
//first we need to get the ids of the switches attached to this door
Iterator<Raven_Door> it = m_pMap.GetDoors().iterator();
while (it.hasNext()) {
Raven_Door curDoor = it.next();
if (curDoor.ID() == doorID) {
SwitchIDs = curDoor.GetSwitchIDs();
break;
}
}
Vector2D closest = new Vector2D();
double ClosestDist = MaxDouble;
//now test to see which one is closest and visible
Iterator<Integer> idIt = SwitchIDs.iterator();
while (idIt.hasNext()) {
BaseGameEntity trig = EntityMgr.GetEntityFromID(idIt.next());
if (isLOSOkay(botPos, trig.Pos())) {
double dist = Vec2DDistanceSq(botPos, trig.Pos());
if (dist < ClosestDist) {
ClosestDist = dist;
closest = trig.Pos();
}
}
}
return closest;
}
/**
* given a position on the map this method returns the bot found with its
* bounding radius of that position.If there is no bot at the position the
* method returns NULL
*/
public Raven_Bot GetBotAtPosition(Vector2D CursorPos) {
Iterator<Raven_Bot> it = m_Bots.iterator();
while (it.hasNext()) {
Raven_Bot curBot = it.next();
if (Vec2DDistance(curBot.Pos(), CursorPos) < curBot.BRadius()*2) {
if (curBot.isAlive()) {
return curBot;
}
}
}
return null;
}
public void TogglePause() {
m_bPaused = !m_bPaused;
}
/**
* this method is called when the user clicks the right mouse button.
*
* the method checks to see if a bot is beneath the cursor. If so, the bot
* is recorded as selected.
*
* if the cursor is not over a bot then any selected bot/s will attempt to
* move to that position.
*/
public void ClickRightMouseButton(POINTS p) {
Raven_Bot pBot = GetBotAtPosition(POINTStoVector(p));
//if there is no selected bot just return;
if (pBot == null && m_pSelectedBot == null) {
return;
}
//if the cursor is over a different bot to the existing selection,
//change selection
if (pBot != null && pBot != m_pSelectedBot) {
if (m_pSelectedBot != null) {
m_pSelectedBot.Exorcise();
}
m_pSelectedBot = pBot;
return;
}
//if the user clicks on a selected bot twice it becomes possessed(under
//the player's control)
if (pBot != null && pBot == m_pSelectedBot) {
m_pSelectedBot.TakePossession();
//clear any current goals
m_pSelectedBot.GetBrain().RemoveAllSubgoals();
}
//if the bot is possessed then a right click moves the bot to the cursor
//position
if (m_pSelectedBot.isPossessed()) {
//if the shift key is pressed down at the same time as clicking then the
//movement command will be queued
if (IS_KEY_PRESSED(KeyEvent.VK_Q)) {
m_pSelectedBot.GetBrain().QueueGoal_MoveToPosition(POINTStoVector(p));
} else {
//clear any current goals
m_pSelectedBot.GetBrain().RemoveAllSubgoals();
m_pSelectedBot.GetBrain().AddGoal_MoveToPosition(POINTStoVector(p));
}
}
}
/**
* this method is called when the user clicks the left mouse button. If
* there is a possessed bot, this fires the weapon, else does nothing
*/
public void ClickLeftMouseButton(POINTS p) {
if (m_pSelectedBot != null && m_pSelectedBot.isPossessed()) {
m_pSelectedBot.FireWeapon(POINTStoVector(p));
}
}
/**
* when called will release any possessed bot from user control
*/
public void ExorciseAnyPossessedBot() {
if (m_pSelectedBot != null) {
m_pSelectedBot.Exorcise();
}
}
/**
* if a bot is possessed the keyboard is polled for user input and any
* relevant bot methods are called appropriately
*/
public void GetPlayerInput() {
if (m_pSelectedBot != null && m_pSelectedBot.isPossessed()) {
m_pSelectedBot.RotateFacingTowardPosition(GetClientCursorPosition());
}
}
public Raven_Bot PossessedBot() {
return m_pSelectedBot;
}
/**
* changes the weapon of the possessed bot
*/
public void ChangeWeaponOfPossessedBot(int weapon) {
//ensure one of the bots has been possessed
if (m_pSelectedBot != null) {
switch (weapon) {
case type_blaster:
PossessedBot().ChangeWeapon(type_blaster);
return;
case type_shotgun:
PossessedBot().ChangeWeapon(type_shotgun);
return;
case type_rocket_launcher:
PossessedBot().ChangeWeapon(type_rocket_launcher);
return;
case type_rail_gun:
PossessedBot().ChangeWeapon(type_rail_gun);
return;
}
}
}
public Raven_Map GetMap() {
return m_pMap;
}
public List<Raven_Bot> GetAllBots() {
return m_Bots;
}
public PathManager<Raven_PathPlanner> GetPathManager() {
return m_pPathManager;
}
public int GetNumBots() {
return m_Bots.size();
}
public void TagRaven_BotsWithinViewRange(BaseGameEntity pRaven_Bot, double range) {
TagNeighbors(pRaven_Bot, m_Bots, range);
}
} | true |
8a5cf484b78cea2ef7e0b6836f53641ae25c3ae7 | Java | r-eddari/sample-spring-boot-spring-cloud | /ms-hr/src/main/java/fr/red/services/application/expensereport/proxy/MsAccountingProxy.java | UTF-8 | 996 | 1.898438 | 2 | [] | no_license | package fr.red.services.application.expensereport.proxy;
import fr.red.services.application.expensereport.model.ExpenseReport;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@FeignClient(name = "ms-accounting")
@RequestMapping("/private/api/v1/expensereports")
public interface MsAccountingProxy {
@GetMapping("/employes/{empno}")
List<ExpenseReport> getExpenseReportListByEmpno(@PathVariable("empno") String empno);
@GetMapping
List<ExpenseReport> getExpenseReportList();
@GetMapping("/{id}")
ExpenseReport getExpenseReportById(@PathVariable("id") String id);
@PostMapping
ExpenseReport addExpenseReport(@RequestBody ExpenseReport expenseReport);
@PutMapping
ExpenseReport updateExpenseReport(@RequestBody ExpenseReport expenseReport);
@DeleteMapping("/{id}")
Map<String, String> deleteExpenseReport(@PathVariable("id") String id);
}
| true |
87b258a3e33d3829b72d6f0d130bd8513aaaf6e2 | Java | onurtokat/hal-streaming | /src/main/java/com/github/fge/jsonschema/keyword/digest/helpers/DraftV3TypeKeywordDigester.java | UTF-8 | 2,292 | 2.375 | 2 | [] | no_license | //
// Decompiled by Procyon v0.5.30
//
package com.github.fge.jsonschema.keyword.digest.helpers;
import java.util.Collection;
import java.util.Iterator;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.EnumSet;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.NodeType;
import com.github.fge.jsonschema.keyword.digest.AbstractDigester;
public final class DraftV3TypeKeywordDigester extends AbstractDigester
{
private static final String ANY = "any";
public DraftV3TypeKeywordDigester(final String keyword) {
super(keyword, NodeType.ARRAY, NodeType.values());
}
@Override
public JsonNode digest(final JsonNode schema) {
final ObjectNode ret = DraftV3TypeKeywordDigester.FACTORY.objectNode();
final ArrayNode simpleTypes = DraftV3TypeKeywordDigester.FACTORY.arrayNode();
ret.put(this.keyword, simpleTypes);
final ArrayNode schemas = DraftV3TypeKeywordDigester.FACTORY.arrayNode();
ret.put("schemas", schemas);
final JsonNode node = schema.get(this.keyword);
final EnumSet<NodeType> set = EnumSet.noneOf(NodeType.class);
if (node.isTextual()) {
putType(set, node.textValue());
}
else {
for (int size = node.size(), index = 0; index < size; ++index) {
final JsonNode element = node.get(index);
if (element.isTextual()) {
putType(set, element.textValue());
}
else {
schemas.add(index);
}
}
}
if (EnumSet.complementOf(set).isEmpty()) {
schemas.removeAll();
}
for (final NodeType type : set) {
simpleTypes.add(type.toString());
}
return ret;
}
private static void putType(final EnumSet<NodeType> types, final String s) {
if ("any".equals(s)) {
types.addAll((Collection<?>)EnumSet.allOf(NodeType.class));
return;
}
final NodeType type = NodeType.fromName(s);
types.add(type);
if (type == NodeType.NUMBER) {
types.add(NodeType.INTEGER);
}
}
}
| true |
5b1f4fc0c47444fe00c121df9562992a88521e7b | Java | jonny999/yago | /java/src/main/java/FIIT/VI/YAGO/reader/Reader.java | UTF-8 | 2,348 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | package FIIT.VI.YAGO.reader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import FIIT.VI.YAGO.configuration.Configuration;
import FIIT.VI.YAGO.domain.RDFTriplet;
/**
* Based reader
* @author mm
*
*/
public class Reader {
/**Based of manipulation with files is buffer reader*/
protected BufferedReader reader;
/**Actual line for processing*/
protected String line;
protected String path = Configuration.getDefaultData();
private final static Charset ENCODING = StandardCharsets.UTF_8;
private static final String REGEX_RDF = "<(.*)>\t(.*)\t<?(.*)\\b>?";
protected static final Pattern PATTERN_RDF = Pattern.compile(REGEX_RDF);
/**
* Initialize of reader based variables
* @throws IOException
*/
protected void initiliaze() throws IOException {
Path pathToFile = Paths.get(path);
reader = Files.newBufferedReader(pathToFile, ENCODING);
}
public String readline() throws IOException{
return reader.readLine();
}
public void close() throws IOException{
reader.close();
}
/**
* Close old stream and reload to start
* @throws IOException
*/
public void reload() throws IOException{
this.close();
this.initiliaze();
}
/**
* Count of lines in file
* @return count of lines
* @throws IOException
*/
public long linesCount() throws IOException{
LineNumberReader lineReader = new LineNumberReader(new FileReader(path));
lineReader.skip(Long.MAX_VALUE);
long size =lineReader.getLineNumber();
lineReader.close();
return size;
}
/**
* Default converter based on default REGEX
* @return rdf entity of actual processing string
*/
public RDFTriplet toRDF() {
Matcher m = PATTERN_RDF.matcher(line);
if (m.find()) {
return new RDFTriplet(m.group(1), m.group(2), m.group(3));
}
return null;
}
/**
* Checker if actual processing line match default REGEX pattern
* @return
*/
public boolean isWikiLink() {
return PATTERN_RDF.matcher(line).find();
}
}
| true |
ef8ae3e48416d143c2b49823470e70756eb9808e | Java | triantadim/Tshirt_Design_Patterns | /src/strategypatterntshirt/CashPayment.java | UTF-8 | 296 | 2.953125 | 3 | [] | no_license |
package strategypatterntshirt;
import interfaces.IPayment;
public class CashPayment implements IPayment {
@Override
public boolean pay(float amount) {
System.out.printf("If payment is with Cash, total amount = %s \n", amount);
return(true);
}
} | true |
573981b6ef577988e13382eef1f25369a50aed21 | Java | shahnawaz-eurosofttech/supportlibrary | /src/com/support/google/GeocoderHelperClass.java | UTF-8 | 2,286 | 2.390625 | 2 | [] | no_license | package com.support.google;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Handler;
public class GeocoderHelperClass {
private Handler mHandler;
private int mMaxResults = 1;
private SetResult mSetResultInterface;
private Context mContext;
public GeocoderHelperClass(Context context) {
mHandler = new Handler();
mContext = context;
}
public GeocoderHelperClass setMaxResults(int maxResult) {
mMaxResults = maxResult;
return this;
}
public void execute(String location) {
execute((Object[]) new String[] { location });
}
public void execute(double lat, double lon) {
execute((Object[]) new Double[] { lat, lon });
}
private void execute(final Object... objects) {
try {
if (objects != null && Geocoder.isPresent()) {
new Thread(new Runnable() {
@Override
public void run() {
List<Address> list = new ArrayList<Address>();
try {
if (objects.length >= 2 && objects[0] instanceof Double) {
double lat = (Double) objects[0];
double lon = (Double) objects[1];
list = new Geocoder(mContext, Locale.UK).getFromLocation(lat, lon, mMaxResults);
} else if (objects.length >= 1 && objects[0] instanceof String) {
String location = (String) objects[0];
list = new Geocoder(mContext, Locale.UK).getFromLocationName(location, mMaxResults);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
final List<Address> result = list;
if (result != null && result.size() > 0) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (mSetResultInterface != null)
mSetResultInterface.onGetResult(result);
}
});
}
}
}
}, "GeoCoderRunner").start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public GeocoderHelperClass setResultInterface(SetResult result) {
mSetResultInterface = result;
return this;
}
public interface SetResult {
public abstract void onGetResult(List<Address> list);
}
}
| true |
92b518cbe4841619e8cbd19c5ccb0b9731dd633c | Java | marquinhos87/FSD-project | /refs/examples/echo/fsd/Echo.java | UTF-8 | 643 | 2.796875 | 3 | [] | no_license | package fsd;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class Echo {
public static void main(String[] args) throws Exception {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(12345));
while(true) {
SocketChannel sc = ssc.accept();
ByteBuffer buf = ByteBuffer.allocate(1024);
sc.read(buf);
buf.flip();
sc.write(buf.duplicate());
buf.clear();
sc.close();
}
}
}
| true |
e46bfb777f69ccce72b7b1181a8edbc3ce18bb4c | Java | rume81/HRM-models | /src/main/java/com/webhawks/Hawks_mapper/SupportingDataMapper.java | UTF-8 | 697 | 2.328125 | 2 | [] | no_license | package com.webhawks.Hawks_mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.webhawks.Hawks_model.HSupportingData;
public class SupportingDataMapper extends BaseMapper implements RowMapper<HSupportingData> {
public HSupportingData mapRow(ResultSet rs, int rowNum) throws SQLException {
HSupportingData sd = new HSupportingData();
if (findColumnNames(rs, "id")) {
sd.setId(rs.getString("id"));
}
if(findColumnNames(rs, "datavalue")) {
sd.setDatavalue(rs.getString("datavalue"));
}
if(findColumnNames(rs, "valuetype")) {
sd.setValuetype(rs.getString("valuetype"));
}
return sd;
}
}
| true |
168702b7d0094e74199269827d65971188eeeb6d | Java | aureliancamarasu/problema-AB4 | /eclipse-workspace/ab4 problema/src/oras.java | UTF-8 | 375 | 2.65625 | 3 | [] | no_license |
public class oras extends judet {
String nume ;
oras() {
}
oras(String a , String b, String c)
{
super(a,b);
this.nume=c;
}
public String getNume() {
return nume;
}
public void setNume(String nume) {
this.nume = nume;
}
void afisare() {
super.afisare();
System.out.println("Nume tara "+this.nume);
}
}
| true |
b5f3ffd6cc471df4a2adae29f966326cbc34da7f | Java | shanyinke/booksource | /chapter6/Vmall/app/src/main/java/com/parfois/adapter/HonorAPAdapter.java | UTF-8 | 5,219 | 2.03125 | 2 | [] | no_license | package com.parfois.adapter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.parfois.asynctask.DownSaveImgAsync;
import com.parfois.bean.ActivityPrds;
import com.parfois.vmall.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class HonorAPAdapter extends BaseAdapter {
private Context context;
private List<ActivityPrds> list;
private ViewHolder vh;
private ListView lv;
private Map<String, Bitmap> map=new HashMap<String, Bitmap>();
public HonorAPAdapter(Context context, List<ActivityPrds> list,ListView lv) {
this.context = context;
this.list = list;
this.lv=lv;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(context,R.layout.listview_activityprds_item, null);
vh=new ViewHolder();
vh.list_activityprds_ivactivityPicUrl=(ImageView) convertView.findViewById(R.id.list_activityprds_ivactivityPicUrl);
vh.list_activityprds_ivfittingPicUrl=(ImageView) convertView.findViewById(R.id.list_activityprds_ivfittingPicUrl);
vh.list_activityprds_llstatus2=(LinearLayout) convertView.findViewById(R.id.list_activityprds_llstatus2);
vh.list_activityprds_llstatus3=(LinearLayout) convertView.findViewById(R.id.list_activityprds_llstatus3);
vh.list_activityprds_llstatus4=(LinearLayout) convertView.findViewById(R.id.list_activityprds_llstatus4);
vh.list_activityprds_tvactivityDescription=(TextView) convertView.findViewById(R.id.list_activityprds_tvactivityDescription);
vh.list_activityprds_tvactivityTime=(TextView) convertView.findViewById(R.id.list_activityprds_tvactivityTime);
vh.list_activityprds_tvfittingTitle=(TextView) convertView.findViewById(R.id.list_activityprds_tvfittingTitle);
vh.list_activityprds_tvfittingDescription=(TextView) convertView.findViewById(R.id.list_activityprds_tvfittingDescription);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.list_activityprds_ivactivityPicUrl.setContentDescription(list.get(position).getPrdUrl());
vh.list_activityprds_ivactivityPicUrl.setImageResource(R.drawable.icon_no_pic);
String str=list.get(position).getActivityPicUrl();
vh.list_activityprds_ivactivityPicUrl.setTag(str);
if(!map.containsKey(str)){
new DownSaveImgAsync(context, new DownSaveImgAsync.CallBack() {
public void sendImage(Bitmap bm,String key) {
ImageView iv=(ImageView) lv.findViewWithTag(key);
if(iv!=null){
iv.setImageBitmap(bm);
}
}
},map).execute(list.get(position).getActivityPicUrl());
}else{
vh.list_activityprds_ivactivityPicUrl.setImageBitmap(map.get(str));
}
vh.list_activityprds_ivfittingPicUrl.setImageResource(R.drawable.icon_no_pic);
String str1=list.get(position).getFittingPicUrl();
vh.list_activityprds_ivfittingPicUrl.setTag(str1);
if(!map.containsKey(str1)){
new DownSaveImgAsync(context, new DownSaveImgAsync.CallBack() {
public void sendImage(Bitmap bm,String key) {
ImageView iv=(ImageView) lv.findViewWithTag(key);
if(iv!=null){
iv.setImageBitmap(bm);
}
}
},map).execute(list.get(position).getFittingPicUrl());
}else{
vh.list_activityprds_ivfittingPicUrl.setImageBitmap(map.get(str1));
}
vh.list_activityprds_tvactivityDescription.setText(list.get(position).getActivityDescription());
vh.list_activityprds_tvactivityTime.setText(list.get(position).getActivityTime());
vh.list_activityprds_tvfittingTitle.setText(list.get(position).getFittingTitle());
vh.list_activityprds_tvfittingDescription.setText(list.get(position).getFittingDescription());
if(list.get(position).getActivityStatus()==2){
vh.list_activityprds_llstatus2.setVisibility(View.VISIBLE);
vh.list_activityprds_llstatus3.setVisibility(View.INVISIBLE);
vh.list_activityprds_llstatus4.setVisibility(View.INVISIBLE);
}else if(list.get(position).getActivityStatus()==3){
vh.list_activityprds_llstatus2.setVisibility(View.INVISIBLE);
vh.list_activityprds_llstatus3.setVisibility(View.VISIBLE);
vh.list_activityprds_llstatus4.setVisibility(View.INVISIBLE);
}else if(list.get(position).getActivityStatus()==4){
vh.list_activityprds_llstatus2.setVisibility(View.INVISIBLE);
vh.list_activityprds_llstatus3.setVisibility(View.INVISIBLE);
vh.list_activityprds_llstatus4.setVisibility(View.VISIBLE);
}
return convertView;
}
static class ViewHolder {
ImageView list_activityprds_ivactivityPicUrl,
list_activityprds_ivfittingPicUrl;
TextView list_activityprds_tvactivityTime,
list_activityprds_tvactivityDescription,
list_activityprds_tvfittingTitle,
list_activityprds_tvfittingDescription;
LinearLayout list_activityprds_llstatus4, list_activityprds_llstatus3,
list_activityprds_llstatus2;
}
}
| true |
ffb72f886a2316a8cc53ebb091aa61f44248abad | Java | anthonycanino1/entbench-pi | /batik/badapt_classes/org/apache/batik/css/engine/value/svg12/MarginShorthandManager.java | UTF-8 | 15,594 | 1.820313 | 2 | [
"Apache-2.0"
] | permissive | package org.apache.batik.css.engine.value.svg12;
public class MarginShorthandManager extends org.apache.batik.css.engine.value.AbstractValueFactory implements org.apache.batik.css.engine.value.ShorthandManager {
public MarginShorthandManager() { super(); }
public java.lang.String getPropertyName() { return org.apache.batik.util.SVG12CSSConstants.
CSS_MARGIN_PROPERTY;
}
public boolean isAnimatableProperty() { return true; }
public boolean isAdditiveProperty() { return false; }
public void setValues(org.apache.batik.css.engine.CSSEngine eng,
org.apache.batik.css.engine.value.ShorthandManager.PropertyHandler ph,
org.w3c.css.sac.LexicalUnit lu,
boolean imp) throws org.w3c.dom.DOMException {
if (lu.
getLexicalUnitType(
) ==
org.w3c.css.sac.LexicalUnit.
SAC_INHERIT)
return;
org.w3c.css.sac.LexicalUnit[] lus =
new org.w3c.css.sac.LexicalUnit[4];
int cnt =
0;
while (lu !=
null) {
if (cnt ==
4)
throw createInvalidLexicalUnitDOMException(
lu.
getLexicalUnitType(
));
lus[cnt++] =
lu;
lu =
lu.
getNextLexicalUnit(
);
}
switch (cnt) {
case 1:
lus[3] =
(lus[2] =
(lus[1] =
lus[0]));
break;
case 2:
lus[2] =
lus[0];
lus[3] =
lus[1];
break;
case 3:
lus[3] =
lus[1];
break;
default:
}
ph.
property(
org.apache.batik.util.SVG12CSSConstants.
CSS_MARGIN_TOP_PROPERTY,
lus[0],
imp);
ph.
property(
org.apache.batik.util.SVG12CSSConstants.
CSS_MARGIN_RIGHT_PROPERTY,
lus[1],
imp);
ph.
property(
org.apache.batik.util.SVG12CSSConstants.
CSS_MARGIN_BOTTOM_PROPERTY,
lus[2],
imp);
ph.
property(
org.apache.batik.util.SVG12CSSConstants.
CSS_MARGIN_LEFT_PROPERTY,
lus[3],
imp);
}
public static final java.lang.String jlc$CompilerVersion$jl7 =
"2.7.0";
public static final long jlc$SourceLastModified$jl7 =
1471028785000L;
public static final java.lang.String jlc$ClassType$jl7 =
("H4sIAAAAAAAAAMUYbWwcR3XO35/xRz6bDydOnIR83TVpUqgcSm3HbhzOjokT" +
"Cxyay9ze3N3Ge7ub3bnz2cWljYoSighRSJuAaP7gKqVqmggoBUGroEq0JQWp" +
"JaIU1BQJJMJHRCOk8iNAeW9293Zv787GiIqTdnZv5r037715n/PsTVJpGqSN" +
"qTzIJ3RmBntVPkQNk8V6FGqa+2EuIp0tp387dGPwnjJSNUrmJak5IFGT9clM" +
"iZmjZIWsmpyqEjMHGYshxpDBTGZkKJc1dZQslM3+lK7IkswHtBhDgBFqhEkL" +
"5dyQo2nO+m0CnKwIAychwUmoy7/cGSYNkqZPuOBLPOA9nhWETLl7mZw0h4/Q" +
"DA2luayEwrLJO7MG2aRrykRC0XiQZXnwiLLDVsGe8I4CFay+3PT+7VPJZqGC" +
"+VRVNS7EM/cxU1MyLBYmTe5sr8JS5lHyECkPk3oPMCcdYWfTEGwagk0daV0o" +
"4L6RqelUjybE4Q6lKl1ChjhpzyeiU4OmbDJDgmegUMNt2QUySLsqJ60lZYGI" +
"j28KnTl7qPnb5aRplDTJ6jCyIwETHDYZBYWyVJQZZlcsxmKjpEWFwx5mhkwV" +
"edI+6VZTTqiUp+H4HbXgZFpnhtjT1RWcI8hmpCWuGTnx4sKg7H+VcYUmQNZF" +
"rqyWhH04DwLWycCYEadgdzZKxZisxjhZ6cfIydjxSQAA1OoU40ktt1WFSmGC" +
"tFomolA1ERoG01MTAFqpgQEanCwtSRR1rVNpjCZYBC3SBzdkLQFUrVAEonCy" +
"0A8mKMEpLfWdkud8bg7uPPmgulstIwHgOcYkBfmvB6Q2H9I+FmcGAz+wEBs2" +
"hp+gi148UUYIAC/0AVswL3zu1n2b2668asEsKwKzN3qESTwiTUfnvbG8Z8M9" +
"5chGja6ZMh5+nuTCy4bslc6sDhFmUY4iLgadxSv7fvKZh59hfy4jdf2kStKU" +
"dArsqEXSUrqsMON+pjKDchbrJ7VMjfWI9X5SDd9hWWXW7N543GS8n1QoYqpK" +
"E/9BRXEggSqqg29ZjWvOt055UnxndUJINTxkJTzriPXrwIGTo6GklmIhKlFV" +
"VrXQkKGh/GYIIk4UdJsMRcHqx0KmljbABEOakQhRsIMksxckE2ETwFMoQ5U0" +
"C5mZxNZtoQFqwNxwUjN4kqqxAaqCdRhBND39/7FpFjUxfzwQgENa7g8RCnjX" +
"bk2JMSMinUl39956LnLVMj90GVuHnNwLfAQtPoKCjyDwEbT4CAo+goKPYHE+" +
"SCAgtl+A/Fj2Aac7BnECAnXDhuEH9hw+sbocDFMfr4CjQdDVeQmrxw0mTgaI" +
"SJdaGyfbr299uYxUhEkrlXiaKph/uowERDZpzHb+hiikMjejrPJkFEyFhiax" +
"GAS0UpnFplKjZZiB85ws8FBw8h16dqh0tinKP7lybvyRkc/fWUbK8pMIblkJ" +
"8Q/RhzD050J8hz94FKPbdPzG+5eemNLcMJKXlZxkWoCJMqz2G4hfPRFp4yr6" +
"fOTFqQ6h9loI85yCFUAEbfPvkRelOp2Ij7LUgMBxzUhRBZccHdfxpKGNuzPC" +
"clvE9wIwi3p023Z4PmL7sXjj6iIdx8WWpaOd+aQQGeXjw/qTv/r5H+8S6naS" +
"T5OnahhmvNMT8JBYqwhtLa7Z7jcYA7h3zg199fGbxw8KmwWINcU27MCxBwId" +
"HCGo+QuvHn373evT18pcO+eQ8dNRKJyyOSFxntTNICTsts7lBwKmAvEDrabj" +
"gAr2KcdlGlUYOtY/mtZuff4vJ5stO1BgxjGjzbMTcOfv6CYPXz309zZBJiBh" +
"wnZ15oJZWWC+S7nLMOgE8pF95M0VX3uFPgn5BGK4KU8yEZaJ0AERh7ZDyH+n" +
"GLf71j6Kw1rTa/z5/uUprCLSqWvvNY6899ItwW1+ZeY96wGqd1rmhcO6LJBf" +
"7A9Ou6mZBLjtVwY/26xcuQ0UR4GiBGHZ3GtAxMzmWYYNXVn96x+/vOjwG+Wk" +
"rI/UKRqN9VHhZKQWrJuZSQi2Wf0T91mHO14DQ7MQlRQIXzCBCl5Z/Oh6UzoX" +
"yp78/uLv7rxw/rqwMt2iscxLcD0Om3L2Jn5VTlJ03l57cykExPcSTrbNng78" +
"KQA1vKJU6SPKtuljZ87H9j611SpQWvPLiV6oli/+8p+vB8/99rUi+amWa/oW" +
"hWWY4mG3ArfMSyMDoip0Q9k7807/7gcdie65ZBCca5slR+D/lSDExtIZwc/K" +
"K8f+tHT/vcnDc0gGK33q9JP81sCzr92/TjpdJkpgKw8UlM75SJ1excKmBoNa" +
"X0UxcaZReMyanO20OgF5i207W4oH5CJmlwtzpVBnCAgjM6x9GodPga8nGKZ2" +
"0ZcMgkCO5TYL98EOIGh1AGLhYzjss/yj87/0TZzo0sX8QE7M+bi2Hp7ttpjb" +
"566hUqgzaIHNsJbA4TBUMbLZpcopyjHaO6rKL7zQFYbTURM0KacgJ2bsdmPb" +
"0GHpRMfQ7y1PvaMIggW38OnQl0feOvK6sOkadKKcJXkcCJzNk+6bLQV8AL8A" +
"PP/CB3nHCXxDF9dj9w6rcs0DBjqDbJih288XIDTV+u7YN25ctATwN1c+YHbi" +
"zGMfBE+escKO1YGuKWgCvThWF2qJg4OC3LXPtIvA6PvDpakfPj11vMw+qX5O" +
"qqOapjCq5k4ykCuQF+Sr3eJ11xebfnSqtbwPAlo/qUmr8tE064/lO3W1mY56" +
"zsFtWl0Xt7lGnXMS2OjkEeEm9MNyk7XwdNq23jl3NymFOoMrHJth7VEcpsDa" +
"ZLwPEQflOAmujLkKeehDUIgodbFd7bWl6p67QrpLoPqErrBzpR0g186U2nuG" +
"h3vFlwPdPfdCoMNR426YAy92SC1DUuN3SYKCSaVgmGVliSoHVFnUrWNC5K/4" +
"uA/kFyZLHCIxLRXctXegNysxHdOoQD6Lw2NQLZiMjyBzpsBTbR/FF7QxFRlN" +
"jrnH+6X/xfFmoWou3hpjTbek4OLOumySnjvfVLP4/IG3RH2SuxBqgGAaTyuK" +
"x6e9/l2lGywuC4EbrBJXF69pTtb/h208J5XiLcT5poV+gZP2WdEBUby9iM/Y" +
"Z1sCEXog5tqUjXMR8lMxHE7KYfRCXoac7ocELsTbC/cdTupcONjU+vCCfA+o" +
"Awh+vqA7FnX37CrrgoRnQPEoTMqq9ieygcLKW5jTwtnMKYfi7SoxoYlLYCfi" +
"p61r4Ih06fyewQdv3f2U1dVKCp2cRCr1EOetBjtXLraXpObQqtq94fa8y7Vr" +
"nQTUYjHshpplngDZBW6no/Uu9bV8Zkeu83t7eudLPztR9SakzoMkQDmZf9Bz" +
"BWvdN0LfmIY6/WC4MJ9BaS160c4NX5+4d3P8r78RTY2d/5aXho9I1y488IvT" +
"S6ahZ63vJ5WQW1l2lNTJ5q4JdR+TMsYoaZTN3iywCFRkquQly3noaBSLQ6EX" +
"W52NuVm8E+FkdWEJUHiTBA3gODO6tbQas9NtvTuTdzttO29dWtd9CO6Mp0zK" +
"WDHLqojKI+EBXXcqpOomXUSdcX+QFJMC+6fiE4er/wZT26AnIBoAAA==");
public static final java.lang.String jlc$CompilerVersion$jl5 =
"2.7.0";
public static final long jlc$SourceLastModified$jl5 =
1471028785000L;
public static final java.lang.String jlc$ClassType$jl5 =
("H4sIAAAAAAAAAMVaeczsVnX3+/KW5JHkvbxASANZeQGSgc+z2p4+thmPZ/Ey" +
"nhnbs7iFh8f2eBnv9oztgZSloqBS0YgGSCXIX0FtUSCoLV3U0qZFLSBQVSrU" +
"TSqgqlJpKSr5o7Qqbem159ve95Y0Aqkj+c6de88595x7z/3d43Pnme9Cp8IA" +
"KniulWqWG+2qSbRrWrXdKPXUcJekawMpCFUFt6Qw5EHbZfmhz577/g8e18/v" +
"QKdF6E7JcdxIigzXCUdq6FprVaGhc4ethKXaYQSdp01pLcGryLBg2gijSzT0" +
"kiOsEXSR3lcBBirAQAU4VwFuHFIBpttUZ2XjGYfkRKEP/Qx0goZOe3KmXgQ9" +
"eKUQTwoke0/MILcASLg5+z0GRuXMSQA9cGD71uarDP5IAX7iY287/+s3QedE" +
"6JzhcJk6MlAiAoOI0K22as/VIGwoiqqI0B2OqiqcGhiSZWxyvUXoQmhojhSt" +
"AvVgkrLGlacG+ZiHM3ernNkWrOTIDQ7MWxiqpez/OrWwJA3YetehrVsL21k7" +
"MPCsARQLFpKs7rOcXBqOEkH3H+c4sPEiBQgA6xlbjXT3YKiTjgQaoAvbtbMk" +
"R4O5KDAcDZCecldglAi657pCs7n2JHkpaerlCLr7ON1g2wWobsknImOJoJcd" +
"J8slgVW659gqHVmf7/bf8KF3OF1nJ9dZUWUr0/9mwHTfMaaRulAD1ZHVLeOt" +
"j9Ifle76/Ad2IAgQv+wY8Zbmt9/5/Fted99zX9rSvOIaNOzcVOXosvz0/Pav" +
"vRJ/pH5TpsbNnhsa2eJfYXnu/oO9nkuJB3beXQcSs87d/c7nRn86e/en1O/s" +
"QGd70GnZtVY28KM7ZNf2DEsNOqqjBlKkKj3oFtVR8Ly/B50Bddpw1G0ru1iE" +
"atSDTlp502k3/w2maAFEZFN0BtQNZ+Hu1z0p0vN64kEQdAY80P3geTW0/VzM" +
"igjyYd21VViSJcdwXHgQuJn9Iaw60RzMrQ7Pgdcv4dBdBcAFYTfQYAn4ga7u" +
"dchhRqsBneC1ZK1UOFxrpTLMSAFo43Q3iHTJURjJAd4R7Gau5/1/DJpkM3E+" +
"PnECLNIrj0OEBXZX17UUNbgsP7FqEs9/5vJXdg62zN4cRtCbgB67Wz12cz12" +
"gR67Wz12cz12cz12r60HdOJEPvxLM322/gFWdwlwAiDorY9wbyXf/oGHbgKO" +
"6cUnwdJkpPD1gRw/RJZejp8ycG/ouSfj94zfVdyBdq5E5MwG0HQ2Yx9kOHqA" +
"lxeP78RryT33/m9//9mPPuYe7skrIH4PKq7mzLb6Q8dnO3BlVQHgeSj+0Qek" +
"z13+/GMXd6CTAD8AZkYSmFIAR/cdH+OKLX9pHz4zW04BgxduYEtW1rWPeWcj" +
"PXDjw5bcDW7P63eAOX5JtgceBM9r9zZF/p313ull5Uu3bpMt2jErcnh+I+d9" +
"4q//7J8q+XTvI/m5I2cjp0aXjqBHJuxcjhN3HPoAH6gqoPu7Jwe/9JHvvv+n" +
"cgcAFK+61oAXsxIHqAGWEEzz+77k/803v/H013cOnSYCx+dqbhlycmBk1g6d" +
"vYGRYLRXH+oD0McCmzHzmouCY7uKsTCkuaVmXvpf5x4ufe5fPnR+6wcWaNl3" +
"o9e9sIDD9p9oQu/+ytv+/b5czAk5O/0O5+yQbAupdx5KbgSBlGZ6JO/5i3t/" +
"+YvSJwA4A0AMjY2aYxyUzwGULxqc2/9oXu4e6ytlxf3hUee/cn8diVIuy49/" +
"/Xu3jb/3B8/n2l4Z5hxda0byLm3dKyseSID4lx/f6V0p1AFd9bn+T5+3nvsB" +
"kCgCiTLAuJANAPwkV3jGHvWpM3/7R1+46+1fuwnaaUNnLVdS2lK+yaBbgHer" +
"oQ6QK/He/Jbt4sY3g+J8bip0lfFbp7g7/3UTUPCR6+NLO4tSDrfo3f/JWvP3" +
"/v1/XDUJObJc43A+xi/Cz3z8HvxN38n5D7d4xn1fcjUkg4jukLf8Kfvfdh46" +
"/Sc70BkROi/vhYvjDHDBxhFBiBTux5AgpLyi/8pwZ3u2XzqAsFceh5cjwx4H" +
"l8OjANQz6qx+9iie/BB8ToDnf7Inm+6sYXvIXsD3TvoHDo56z0tOgN16qryL" +
"7hYz/jfnUh7My4tZ8ZrtMmXV14JtHeZxKuBYGI5k5QO/JQIuZskX96WPQdwK" +
"1uSiaaG5mJeBSD13p8z63W2wtwW0rCznIrYuUbuu+/zklio/uW4/FEa7IG78" +
"4D88/tVffNU3wZqS0Kn8AARLeWTE/ioLpX/umY/c+5InvvXBHKUARI3f/fC/" +
"5oEJfSOLs4LIiva+qfdkpnJ5SEBLYcTkwKIqubU3dOVBYNgAf9d7cSL82IVv" +
"Lj/+7U9vY8DjfnuMWP3AEz//w90PPbFzJPJ+1VXB71GebfSdK33b3gwH0IM3" +
"GiXnaP/js4/93q8+9v6tVheujCMJ8Jr06b/876/uPvmtL18jMDlpuT/Cwka3" +
"/Xm3GvYa+x9GmM0nsTyqTNlKDU5GG2TeShXW6Y2wCj/2BF+TObvSnesb1nSX" +
"PJ6kUlrfqJV+paOiq3ll7mzK8sQyZy5naPqII1cNaYBqlD/2bU1zm0IncAm/" +
"SA4nHin1hFJzSJIM2R3h7BIz+g11Ui/XK+IaxdCO0fN5xRHXtaBYQdFSzYEH" +
"IT8mvY7P9X1+0yMrI7sJtvpgOewvsTHS7vhSoUysel4x8ioYqnQGsWOSXF8I" +
"bFJa1nrtDl+XLcYQbVPsTULbS33CZLqdWagnXqvJd8QlRcolRRyGFlMpWBTa" +
"W4ZxN2rqLa3Z9nViSdeUdOiWHbZgF3GHinuNVNZjwXZTFJY73Ky/9MXBim3S" +
"A7ZRd/QJwdMWaotxUa/Cw1ajbK2klIgDmmRRplOWRkG6HOHFqTEUp05s0HRr" +
"HHZUrFfF21JaqAz4AjoekKLfwQvj0bjPoQQDy4lQYlK6ObN5tRYGGMnVrG5K" +
"4MvBsuIOGFxWZpMFT3RiSVsWFWlcdKs0MvJVSzDTOVEdIhZllXDd1L1NqhpC" +
"lbXnLbKl2aomMP2oPBRSDmxNEila4qzTM8sY5fAW6g+ceU0aeVaLJxETT3sx" +
"wXdbM7E5m6RjciiKlhwmNmV6xKQdJzVbX8Zj8EZTQMYiz/uG4BW61e58qolt" +
"z9Ejky+NJnIP020Pn6w6vJNUQ0pDu4WxPBPsYV9sB3460bvFaiumJ6mMzwhJ" +
"0ZSNSCWiESamLiLyopcqZsING40S6wrV4jKKSpM2Z3fwqO3artUoESO3Uywx" +
"fKPte9qQkBw8jrjRqBSM+56Ji7MmXuGaG2VJD9tCMG4QroOnxQZmUwzh0YuJ" +
"slwp2FxDV4OBra2sMOrFXY2VZ8vmwl43kWG5W+8V2rbcaWwKMdEMy7pX0IxS" +
"FROEWa+Bw8XGOIzpymZVcsrzMoJgUkiEVExt+hWf4PjY4IWFs553MBFj6jVZ" +
"75gSIjJ6reCseDytzkNLRsKW3raFWdWgNUlJuDW6WFOiXqvri7RqKovykoso" +
"QWkEoU9MOSHwQ4btFzyTasn6PCDRMWMuJr36tMa1lLo+mUwnaL9WrXQ4zCkN" +
"3ZnvUQRcb46mhKZxvq+V66I5WbNRsVYTnMRRBLLX55MlyW8CYzAN4l6Hd5HO" +
"0rJ7OmW1x+NgOlxSHR3uzHq9ZVVQyJAZyV0/KVK2Zc4bTYKVlkN9FPaYZZjI" +
"S6JM8HGbcYc1oYjXbDHpi5E7bPtxP4kFs19d+n7SkHxcGenNfqtSh9G21zaF" +
"ZLGJhxrRl1ANG+GOOZ0vyyTDMYYjWJV6vYbQDg0MrRc741XX6cf0ojGMBi6F" +
"m2krJuZ8FW+4Bc2lBrMuUeDwhhZZhQbcNssNSUabDoE3nGlLXxHduh4Xwrkr" +
"t9rMIqji5lBpjdWhHSRx0eY1qceRitRJF/OgXK+vZokA8CCwpoZEeTq8cmNi" +
"1BK9TXde0A1jyZiqGQzIZZtI27ohJZ0GVxQ8p+1ZlCmKRhOrxSHWbsaYXkIU" +
"Xy9GhkMNUCudr9PRUoYXE2FOYR7Tm1tLEhvCI33TKtaKJKZv6tU2NZgrg02n" +
"UFNVu0/LDElNLTFZTlycZPxNuVPVF4NR26umAbJg+bY/RPS65fawWoq3hQYx" +
"XwzWy5FqsV65Z6K0oDHNZCPoo6Yoy11lkXhUp7/aDHDZWhP1uBcbFa9YrojV" +
"gU2j4dQ0EaOnJNhk4kmsUpCGw446NWPY59dwUOsWMA5xJI6vsY6k6/a6z/AY" +
"2Zz5sR7REiqipjxroHplo5Xq9UVnnsQYZceTXl8WyiiDJ824p3TxjlsYrtZd" +
"p4JW1DVfwjyZLahDTOmPKDJNWa6dOBHf7+F8GIWo1Ywpu7EmWoE0N7VGUKZk" +
"xepYwoyNZrAdiavForoma2HElppaYnbMzZzhZXaxRvDZYLqpFOsbsUkaTT12" +
"xFLNJcXJBC9wqEMzrEZgXrteY4rjaWXVHmhOrdmhqpSApYQokcUGMdJRsZV2" +
"C06HXqAlE6HiUsBL8KYGrwQvwGnOn6zX/RmC1eu9KJ6UCqI6qyNxx1dKga3L" +
"LEKTzQXaqLMrxBabtBmN4xlcRhJ5NSwKo2rHaHa6YqUTNRJmY09ms/507NSR" +
"pACvWTPuFCbLoAcL1Mjv18ddXaSGk4BcidzQKE8WRb5esrtsqdoaoszQGg17" +
"0w3exK2aCLM6ImzcaeqhGLyi1yjwcDjwYyYqG6Gc0HKryNoVukw6tTFvkcWK" +
"VUPldEkkA5njg3nf0VCMGjZKa4oUEG5ARSvLFDG0WzeRUonzhpP1gDbGiGsZ" +
"cAHzCusmBtfrgWAUJHsiwe4EANGsancqjWDBcCnTcg2vOKwvUayIwqgmK4aK" +
"1MQmLku10BoVWrDFtYgk6omxDFMUtihEXR5ey05LLmodqlLx6+QAK4X4JqiX" +
"Yd70FHLpaVSMCRaD1jiypCYyZTfdvjQtCoksiSOVSSWHLRdZrV0zykV0UnW7" +
"NZy0rTjaeOOmAyDCZJCk3nGVgSZhTocSy0VRZrQlztb4GV3HCLbX0UuNDq3P" +
"NmYYwqmJoXCRFzduMZxiQwJlCnOj3PXQKPLMeQ1BdBA3baRetx+S80aVbwrM" +
"nBY92fVSsyuxSEDR6GbYns15YcQUKUnWyPI8VOzBvNjpeiNmMUTT0mAtMT1N" +
"m1Qw1hlaxYXKrikkZJeSQlEyOV3KOLnpLwvInB6OsQaNNQYDGG9WnC4+TVrt" +
"umLWYySQw2KrafqtOWnoZQyb9lr8uLBCZ/1yTY4afNwvyYVZd25sOsyiSRTU" +
"UKbY0qyzoiYavub1Sbvsk1qVxSv0dBD11g1ksG550nIxMEulNRMX/GmN9X1W" +
"AgesX1tW0yW+GrYLXFBRyVIpUecLh/OjeTxoWC7sC3aARUQRqcIWW5mU7FkN" +
"2YTtaGIVpxFqdZwpw5VZc0mohF1n+ukSncZK3y9XTKvST+026zJBl4x0dEzI" +
"XtiSRDoeEMOFxTbslUkvKVXVW0JPc5V5W0HnEwvxEHQYeLQ78IkgaG68UVEr" +
"YYhQdlYdvbJuW/FAGSwU3GX6o2oZmTXSepnDSy1h1a9wMwrnpLFmd8aWwbnd" +
"cdsRgkkfr1FwddWAl+1UpLt4L6FHUzmaqlo/DZOuwrrDFkLH5f6QFg3GTMGY" +
"YZOfj+B2Gx0m7ZHVNwOnW0CmcLJo2+7EXVV0z+Tn6rLK0uzKTjnHXC/G9KAK" +
"9zqVUbfMrZKmr3UaEp+uqARR67BVtjppvMKrxDxoktM2Uvf4aA7r5SJG1qYG" +
"LfM1zx0XNHFQnihEU5indYOBZyLYMMTU1WqRL5hTZoRZTNIlUGq2GOFTFxyM" +
"rkzQIT/HYVnhVwB/+6ZQWOP4olFwG7FeWPsNtO1MKygeBJo7coYDwuUZ368b" +
"aqrJNDWpmXwcOQwQaKCcm7gzi57hC8NDSkG1pxeRRarGQ2VdWZSFkjKmcK8s" +
"j/CgRLBq1DSjKR1IU4+dD/3Ir1cXEpai48AZ8sLM7Ia651mO1hKbE8RxYWFV" +
"n48xcamusEqEqiuFHmyiUZ2TlhuXWQ5btrioNzfNyVrpF+mF3Zsh8ASvMmS9" +
"KXElpChX+9NaoapUBliAYiN+VlbgmjTV3XqvlFYxrLfmOUQCAWcFnCGT4aQE" +
"JrzPkzW/SiqjAs+EM1cS+X7FSGO8PVr6q6GVVhxXanL0ECGmk1q5vxrbGFFo" +
"L5UJQQpdg282KhrbYpFoPpTCej9a8yte2UQRW64rk0ip4yzCeMUNNWl1ad81" +
"qV6BaE6nsu+xrj0VOEWeFoZtksELyMIgqmoAxyJfRhpOr+mCF7g3vjF7tXvr" +
"i3u7viNPJBxcIYGX6qyj+yLeKrddD2bFwwfJx/xzev+6Yf/7aPLxMCN1Yj9p" +
"UX7hRPvx5Hr2kn3v9S6V8hfsp9/7xFMK+8nSzl4ScBpBt0Su93pLXavWES1O" +
"AkmPXj+ZwOR3aofJqS++95/v4d+kv/1FpNzvP6bncZG/xjzz5c6r5Q/vQDcd" +
"pKquuu27kunSlQmqs4EarQKHvyJNde/BolzYT3u/fm9RXn/ttPc1HehE7kBb" +
"t7lBjnV1g744K7wIOqep0SBw83vT/p723UNn818ohXFUbt5gH5h4Z9b4GvBU" +
"90ys/vhNfM8N+n42K94ZQS81woZj2FKUZcD3bc05uCP7aRJBZ+aua6mSc2j+" +
"Yz+q+Q+D59Ke+Zd+/OY/foO+D2fFByPogpFdpOeZrn3js573HVr5Cz+Clfn1" +
"TXafSexZ2fzxWHlyDwj24OjhG8ERznFEXtunbr548Lq4Pzdd0Gapwb6oV2Si" +
"4oqcSwgleZdWE0OWLMEx8ouX9+Xaf/yY9ieuBNO794Uorr3bYhkikVUvQ6ic" +
"+ems+BiAwlDdZszDaznnybVrKIdr9uSLWbMkgu669oVodrtz91V/19j+xUD+" +
"zFPnbn75U8Jf5XeCB38DuIWGbl6sLOtoMv5I/bQXqAsjN+yWbWrey78+G0Gv" +
"+T9e3kbQqfw7t+PZLftvRNCDL8ge7aXAjzL+1t4aXocxgk6rh76zx/O7ADSu" +
"xRNBN4HyKOXvR9D545RAi/z7KN0fRtDZQzow6LZylOSPgXRAklW/4O17DvLC" +
"U9aYh1EgyVvX2V5LpcmJI6fp3p7N3ebCC7nNAcvR68/sBM7/+rN/Wq62f/65" +
"LD/7FNl/x/PIJ7fXr7IlbTaZlJtp6Mz2JvjgxH3wutL2ZZ3uPvKD2z97y8P7" +
"0cHtW4UP8eOIbvdf+66TsL0ov53c/M7Lf/MNv/LUN/ILj/8FvBqhBJMlAAA=");
}
| true |
eb09637a2775f49c656756c08158aebdcd0bc858 | Java | ramtej/tdmx | /core/src/main/java/org/tdmx/client/crypto/pwdhash/PwdHashImpl.java | UTF-8 | 701 | 2.75 | 3 | [] | no_license | package org.tdmx.client.crypto.pwdhash;
import org.tdmx.client.crypto.entropy.EntropySource;
/**
* A more secure alternative to MD5 hashing, based on jBCrypt.
*/
public class PwdHashImpl implements PwdHash {
public static String hashpw(String password) {
return BCrypt_v03.hashpw(password, BCrypt_v03.gensalt(12, EntropySource.getSecureRandom()));
}
public static boolean checkpw(String plaintext, String hashed) {
return BCrypt_v03.checkpw(plaintext, hashed);
}
@Override
public String hash(String password){
return hashpw(password);
}
@Override
public boolean check(String plaintext, String hashed) {
return checkpw(plaintext, hashed);
}
}
| true |
fa24be781aee8d8a26bb1e66d0a2f435f091caa6 | Java | Zhanggdong/spring-excel-demo | /src/main/java/com/vivo/soft/excel/springexceldemo/query/AssociationKeyGameQuery.java | UTF-8 | 562 | 1.914063 | 2 | [] | no_license | package com.vivo.soft.excel.springexceldemo.query;
/**
* @author 张贵东
* @Company TODO
* @date 2018-11-17.
* @Time 21:43
* @Description TODO
* @Version 2.0.0
*/
public class AssociationKeyGameQuery {
private Integer keyId;
private String gameName;
public Integer getKeyId() {
return keyId;
}
public void setKeyId(Integer keyId) {
this.keyId = keyId;
}
public String getGameName() {
return gameName;
}
public void setGameName(String gameName) {
this.gameName = gameName;
}
}
| true |
81c5f3b16bf600e0c95aff9622129ddea0756475 | Java | AngieC96/Freedom-SDMProject | /src/test/java/dssc/project/freedom/basis/PositionTests.java | UTF-8 | 999 | 2.828125 | 3 | [] | no_license | package dssc.project.freedom.basis;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static dssc.project.freedom.basis.Position.at;
import static org.junit.jupiter.api.Assertions.*;
public class PositionTests {
private final Position position = new Position(3, 3);
@ParameterizedTest
@CsvSource({"5, 3, RIGHT", "1, 3, LEFT", "3, 5, UP", "3, 1, DOWN"})
void checkMoveInDirectionWithStepTwo(int expectedX, int expectedY, Direction direction) {
assertEquals(at(expectedX, expectedY), position.moveInDirectionWithStep(direction, 2));
}
@ParameterizedTest
@CsvSource({"2, 2", "4, 3", "3, 4"})
void checkIsInAdjacentPositions(int x, int y) {
assertTrue(position.isInAdjacentPositions(at(x, y)));
}
@ParameterizedTest
@CsvSource({"1, 1", "1, 3", "3, 5"})
void checkNotInAdjacentPositions(int x, int y) {
assertFalse(position.isInAdjacentPositions(at(x, y)));
}
} | true |
68b6759757a9bab23529a22424a00ee63db5c126 | Java | koda-masaru/knowledge-v2 | /backend/src/main/java/org/support/project/knowledge/control/api/internal/articles/comments/likes/PostArticleCommentLikeApiControl.java | UTF-8 | 2,220 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | package org.support.project.knowledge.control.api.internal.articles.comments.likes;
import java.lang.invoke.MethodHandles;
import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.common.util.StringUtils;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.logic.KnowledgeLogic;
import org.support.project.knowledge.logic.LikeLogic;
import org.support.project.knowledge.vo.LikeCount;
import org.support.project.web.boundary.Boundary;
import org.support.project.web.common.HttpStatus;
import org.support.project.web.control.ApiControl;
import org.support.project.web.control.service.Post;
import org.support.project.web.logic.invoke.Open;
@DI(instance = Instance.Prototype)
public class PostArticleCommentLikeApiControl extends ApiControl {
/** ログ */
private static final Log LOG = LogFactory.getLog(MethodHandles.lookup());
/**
* 記事の一覧を取得
* @throws Exception
*/
@Post(path="_api/articles/:id/comments/:commentid/likes", checkCookieToken=false, checkHeaderToken=true)
@Open
public Boundary execute() throws Exception {
LOG.trace("access user: " + getLoginUserId());
String id = super.getParam("id");
LOG.debug(id);
if (!StringUtils.isLong(id)) {
return sendError(HttpStatus.SC_400_BAD_REQUEST);
}
String commentid = super.getParam("commentid");
if (!StringUtils.isLong(commentid)) {
return sendError(HttpStatus.SC_400_BAD_REQUEST);
}
long knowledgeId = Long.parseLong(id);
if (KnowledgeLogic.get().select(knowledgeId, getLoginedUser()) == null) {
// 存在しない or アクセス権無し
return sendError(HttpStatus.SC_404_NOT_FOUND);
}
Long commentNo = new Long(commentid);
Long count = LikeLogic.get().addLikeComment(commentNo, getLoginedUser(), getLocale());
LikeCount likeCount = new LikeCount();
likeCount.setKnowledgeId(knowledgeId);
likeCount.setCount(count);
return send(HttpStatus.SC_200_OK, likeCount);
}
}
| true |
80bc8216fca97d456528e53be13b6bbda086601a | Java | T-NOVA/NFS | /src/eu/tnova/nfs/utils/VNFFileWSClient.java | UTF-8 | 7,544 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package eu.tnova.nfs.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
import org.apache.cxf.transport.http.HTTPConduit;
public class VNFFileWSClient {
// private final static int receiveTimeout = 5*60*1000;
private final static int receiveTimeout = 0;
private final static int connectTimeout = 10000;
private final static String lineEnd = "\r\n";
private final static String twoHyphens = "--";
private final static String boundary = "***232404jkg4220957934FW**";
private static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}};
private static HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
public static void main(String[] args) throws Exception {
if ( args.length<5 ) {
System.out.println("Input error : less that 3 parameters");
System.out.println("Arguments : ");
System.out.println(" command (upload|update|delete)");
System.out.println(" URL");
System.out.println(" Path file");
System.out.println(" MD5 checksum");
System.out.println(" Provider Id");
System.exit(-1);
}
String url = args[1];
String filePath = args[2];
String md5sum = args[3];
String providerId = args[4];
File file = new File(filePath);
ContentDisposition cd = new ContentDisposition("form-data; name=\"file\"; filename=\""+file.getName()+"\"");
InputStream stream;
Response response = null;
Integer status = null;
try {
stream = new FileInputStream(file);
Attachment att = new Attachment(file.getName(), stream, cd);
MultipartBody body = new MultipartBody(att);
System.out.println("Body ready");
// String responseString = null;
switch (args[0]) {
case "upload":
response = getClient(
url, MediaType.MULTIPART_FORM_DATA_TYPE)
.post(body);
if ( response!=null )
status = response.getStatus();
break;
case "upload2":
try {
status = sendFile(url, file, "POST", md5sum, providerId);
} catch (Exception e) {
}
break;
case "update":
response = getClient(
url+"/"+file.getName(), MediaType.MULTIPART_FORM_DATA_TYPE)
.put(body);
if ( response!=null )
status = response.getStatus();
break;
case "update2":
try {
status = sendFile(url+"/"+file.getName(), file, "PUT", md5sum, providerId);
} catch (Exception e) {
}
break;
case "delete":
response = getClient(
url+"/"+file.getName(),MediaType.MULTIPART_FORM_DATA_TYPE)
.delete();
if ( response!=null )
status = response.getStatus();
break;
case "get":
response = getClient(
url+"/"+file.getName(),MediaType.MULTIPART_FORM_DATA_TYPE)
.get();
if ( response!=null )
status = response.getStatus();
break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-2);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-3);
}
if ( status==null )
System.exit(-4);
System.out.println(status);
System.exit(status);
}
private static WebClient getClient (String url, MediaType type)
throws MalformedURLException {
WebClient webClient = WebClient.create(url).type(type).accept(MediaType.APPLICATION_JSON);
HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();
// timeout (in mSec)
conduit.getClient().setReceiveTimeout(receiveTimeout);
conduit.getClient().setConnectionTimeout(connectTimeout);
TLSClientParameters tlsParams = conduit.getTlsClientParameters();
if (tlsParams == null) {
tlsParams = new TLSClientParameters();
conduit.setTlsClientParameters(tlsParams);
}
tlsParams.setTrustManagers(trustAllCerts);
//disable CN check
tlsParams.setDisableCNCheck(true);
conduit.setTlsClientParameters(tlsParams);
System.out.println("Client ready : url="+url);
return webClient;
}
private static int sendFile (String serverURL, File file, String method,
String md5sum, String providerId) throws Exception {
System.out.println("upload "+file.getName()+" to "+serverURL);
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
// creates a HTTP connection
HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod(method);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// write body
OutputStream output = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
// Send binary file.
writer.append(twoHyphens + boundary).append(lineEnd);
writer.append("Content-Disposition: form-data; name=\"file\";"
+ " filename=\"" + file.getName() + "\"").append(lineEnd);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(lineEnd);
writer.append("Content-Transfer-Encoding: binary").append(lineEnd);
writer.append("MD5SUM: "+md5sum).append(lineEnd);
writer.append("Provider-ID: "+providerId).append(lineEnd);
writer.append(lineEnd).flush();
//////////////
FileInputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024*100];
int bytes = 0;
try {
while ((bytes = is.read(buffer)) != -1) {
output.write(buffer, 0, bytes);
output.flush();
}
} finally {
is.close();
}
//////////////
// Files.copy(file.toPath(), output);
// output.flush(); // Important before continuing with writer!
//////////////
writer.append(lineEnd).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append(twoHyphens + boundary + twoHyphens).append(lineEnd).flush();
// read response
int code = conn.getResponseCode();
String message = conn.getResponseMessage();
System.out.println("Response = "+code+" : "+message);
conn.disconnect();
return code;
}
}
| true |
f7eba0e0e6b8e55e49667ca92af96d7268a4fdbc | Java | nipsalvin/Dice | /src/simplejavaprog/SimpleJavaProg.java | UTF-8 | 387 | 3.015625 | 3 | [] | no_license | package simplejavaprog;
import java.util.Random;
/**
*
* @author Nips
*/
public class SimpleJavaProg {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Random coolNumber = new Random();
int x = coolNumber.nextInt(6) +1;
System.out.println("You rolled a " +x);
}
}
| true |
b19884040e5d2b619a0c5aa3e885de08f7ac5e12 | Java | phwd/quest-tracker | /hollywood/com.oculus.alpenglow-EnterpriseServer/sources/X/AnonymousClass0yZ.java | UTF-8 | 7,736 | 1.570313 | 2 | [] | no_license | package X;
import android.util.SparseArray;
import com.oculus.alpenglow.http.Constants;
import com.oculus.library.utils.app.ImagesBuilder;
import com.squareup.okhttp.internal.framed.Hpack;
/* renamed from: X.0yZ reason: invalid class name */
public class AnonymousClass0yZ extends SparseArray<String> {
public AnonymousClass0yZ() {
put(0, "/buddy_list");
put(1, "/create_thread");
put(2, "/create_thread_response");
put(3, "/delete_thread_notification");
put(4, "/delete_messages_notification");
put(5, "/orca_message_notifications");
put(6, "/friending_state_change");
put(7, "/friend_request");
put(8, "/friend_requests_seen");
put(9, Constants.GRAPHQL_ENDPOINT);
put(10, "/group_msg");
put(11, "/group_notifs_unseen");
put(12, "/group_msgs_unseen");
put(13, "/inbox");
put(14, "/action_id_notification");
put(15, "/aura_notification");
put(16, "/aura_signal");
put(17, "/friends_locations");
put(18, "/mark_thread");
put(19, "/mark_thread_response");
put(20, "/mercury");
put(21, "/messenger_sync");
put(22, "/messenger_sync_ack");
put(23, "/messenger_sync_create_queue");
put(24, "/messenger_sync_get_diffs");
put(25, "/messaging");
put(26, "/messaging_events");
put(27, "/mobile_requests_count");
put(28, "/mobile_video_encode");
put(29, "/orca_notification_updates");
put(30, "/notifications_sync");
put(31, "/notifications_read");
put(32, "/notifications_seen");
put(33, "/push_notification");
put(34, "/pp");
put(35, "/orca_presence");
put(36, "/privacy_changed");
put(37, "/privacy_updates");
put(38, "/send_additional_contacts");
put(39, "/send_chat_event");
put(40, "/send_delivery_receipt");
put(41, "/send_endpoint_capabilities");
put(42, "/foreground_state");
put(43, "/aura_location");
put(44, "/send_location");
put(45, "/send_message2");
put(46, "/send_message");
put(47, "/send_message_response");
put(48, "/ping");
put(49, "/presence");
put(50, "/send_push_notification_ack");
put(51, "/rich_presence");
put(52, "/send_skype");
put(53, "/typing");
put(54, "/set_client_settings");
put(55, "/shoerack_notifications");
put(56, "/orca_ticker_updates");
put(57, "/orca_typing_notifications");
put(58, "/typ");
put(59, "/t_ms");
put(60, "/orca_video_notifications");
put(61, "/orca_visibility_updates");
put(62, "/webrtc");
put(63, "/webrtc_response");
put(64, "/subscribe");
put(65, "/t_p");
put(66, "/push_ack");
put(68, "/webrtc_binary");
put(69, "/t_sm");
put(70, "/t_sm_rp");
put(71, "/t_vs");
put(72, "/t_rtc");
put(73, "/echo");
put(74, "/pages_messaging");
put(75, "/t_omnistore_sync");
put(76, "/fbns_msg");
put(77, "/t_ps");
put(78, "/t_dr_batch");
put(79, "/fbns_reg_req");
put(80, "/fbns_reg_resp");
put(81, "/omnistore_subscribe_collection");
put(82, "/fbns_unreg_req");
put(83, "/fbns_unreg_resp");
put(84, "/omnistore_change_record");
put(85, "/t_dr_response");
put(86, "/quick_promotion_refresh");
put(87, "/v_ios");
put(88, "/pubsub");
put(89, "/get_media");
put(90, "/get_media_resp");
put(91, "/mqtt_health_stats");
put(92, "/t_sp");
put(93, "/groups_landing_updates");
put(94, "/rs");
put(95, "/t_sm_b");
put(96, "/t_sm_b_rsp");
put(97, "/t_ms_gd");
put(98, "/t_rtc_multi");
put(99, "/friend_accepted");
put(100, "/t_tn");
put(101, "/t_mf_as");
put(102, "/t_fs");
put(103, "/t_tp");
put(104, "/t_stp");
put(105, "/t_st");
put(106, "/omni");
put(107, "/t_push");
put(108, "/omni_c");
put(109, "/t_sac");
put(110, "/omnistore_resnapshot");
put(111, "/t_spc");
put(112, "/t_callability_req");
put(113, "/t_callability_resp");
put(116, "/t_ec");
put(117, "/t_tcp");
put(118, "/t_tcpr");
put(119, "/t_ts");
put(ImagesBuilder.IMAGE_LANDSCAPE_HEIGHT, "/t_ts_rp");
put(121, "/t_mt_req");
put(122, "/t_mt_resp");
put(123, "/t_inbox");
put(124, "/p_a_req");
put(125, "/p_a_resp");
put(126, "/unsubscribe");
put(Hpack.PREFIX_7_BITS, "/t_graphql_req");
put(128, "/t_graphql_resp");
put(129, "/t_app_update");
put(130, "/p_updated");
put(131, "/t_omnistore_sync_low_pri");
put(132, "/ig_send_message");
put(133, "/ig_send_message_response");
put(134, "/ig_sub_iris");
put(135, "/ig_sub_iris_response");
put(136, "/ig_snapshot_response");
put(137, "/fbns_msg_hp");
put(138, "/data_stream");
put(139, "/opened_thread");
put(140, "/t_typ_att");
put(141, "/iris_server_reset");
put(142, "/flash_thread_presence");
put(143, "/flash_send_thread_presence");
put(144, "/flash_thread_typing");
put(146, "/ig_message_sync");
put(148, "/t_omnistore_batched_message");
put(149, "/ig_realtime_sub");
put(150, "/t_region_hint");
put(151, "/t_fb_family_navigation_badge");
put(152, "/t_ig_family_navigation_badge");
put(153, "/parties_notifications");
put(154, "/t_assist");
put(155, "/t_assist_rp");
put(156, "/t_create_group");
put(157, "/t_create_group_rp");
put(158, "/t_create_group_ms");
put(159, "/t_create_group_ms_rp");
put(160, "/t_entity_presence");
put(161, "/ig_region_hint_rp");
put(162, "/buddylist_overlay");
put(163, "/setup_debug");
put(164, "/ig_conn_update");
put(165, "/ig_msg_dr");
put(166, "/parties_notifications_req");
put(167, "/omni_connect_sync");
put(168, "/parties_send_message");
put(169, "/parties_send_message_response");
put(170, "/omni_connect_sync_req");
put(172, "/br_sr");
put(174, "/sr_res");
put(175, "/omni_connect_sync_batch");
put(176, "/notify_disconnect");
put(177, "/omni_mc_ep_push_req");
put(178, "/ls_req");
put(179, "/ls_resp");
put(180, "/fbns_msg_ack");
put(181, "/t_add_participants_to_group");
put(182, "/t_add_participants_to_group_rp");
put(183, "/friend_requests_expired");
put(188, "/t_aloha_session_req");
put(195, "/t_thread_typing");
put(201, "/video_rt_pipe");
put(202, "/t_update_presence_extra_data");
put(ImagesBuilder.IMAGE_TINY_HEIGHT, "/video_rt_pipe_res");
put(204, "/t_token_feedback");
put(205, "/ai_demos_server_model_zoo");
put(211, "/onevc");
put(229, "/rtc_call_transfer");
put(231, "/fbns_exp_logging");
put(241, "/ls_app_settings");
put(243, "/presence_diagnostic");
put(244, "/rs_req");
put(245, "/rs_resp");
put(247, "/workplace_rooms");
put(250, "/generative_group_ranking_send_updated_scores");
put(255, "/workplace_desks");
put(257, "/t_portal_comms_req");
put(258, "/voodoo_json");
put(259, "/ixt_trigger");
put(261, "/t_presence_on_bladerunner");
}
}
| true |
af3765fd8dbda27ea0a364b6baaac0598dd120a8 | Java | devryan915/edu | /android/AndroidTutorial/app/src/main/java/org/shenit/tutorial/android/drawable/SimpleDrawableExampleActivity.java | UTF-8 | 1,405 | 2.53125 | 3 | [
"MIT"
] | permissive | package org.shenit.tutorial.android.drawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import org.shenit.tutorial.android.R;
public class SimpleDrawableExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawable_example);
ImageView img2 = (ImageView) findViewById(R.id.img2);
img2.setImageDrawable(getDrawable(R.mipmap.middle));
//TRY TO LOAD A LARGE FILE
ImageView img3 = (ImageView) findViewById(R.id.img3);
img3.setImageDrawable(getDrawable(R.mipmap.large)); //direct load, pretty slow and low efficient example
//Optimize loading large image
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true; //set this to avoid loading the bitmap data to memory
BitmapFactory.decodeResource(getResources(),R.mipmap.large,opts);
int width = opts.outWidth;
int height = opts.outHeight;
opts.inJustDecodeBounds = false;
opts.inSampleSize = 16;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.large,opts);
img3.setImageBitmap(bitmap);
}
} | true |
f61eab8286d19493a852b65517fce7121e4c81f5 | Java | huang714669/leetcode-practice | /src/tree/Solution104.java | UTF-8 | 932 | 3.5625 | 4 | [
"Apache-2.0"
] | permissive | package tree;
import utils.TreeNode;
/**
* 给定一个二叉树,找出其最大深度。
* <p>
* 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
* <p>
* 说明: 叶子节点是指没有子节点的节点。
* <p>
* 示例:
* 给定二叉树 [3,9,20,null,null,15,7],
* <p>
* 3
* / \
* 9 20
* / \
* 15 7
* 返回它的最大深度 3 。
* <p>
* 来源:力扣(LeetCode)
*/
public class Solution104 {
private int maxDepth = 0;
//递归,使用前序遍历
public int maxDepth(TreeNode root) {
dfs(root, 1);
return maxDepth;
}
public void dfs(TreeNode node, int depth) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
maxDepth = Math.max(maxDepth, depth);
}
dfs(node.left, depth + 1);
dfs(node.right, depth + 1);
}
}
| true |
8960d06e9c71f87adf94c3a85f4623d42aa721de | Java | cnsrui/Hello | /src/PrintStar.java | UTF-8 | 2,222 | 3.140625 | 3 | [] | no_license | import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
public class PrintStar {
private int layer = 0;
public void printStarLayerDown() {
int layer = 5;
for (int i = layer; i > 0; i--) {
for (int j = i; j > 0; j--)
System.out.print("*");
System.out.println();
}
}
public void printStarLayerUp() {
int layer = 5;
for (int i = 0; i < layer; i++) {
for (int j = 0; j < i + 1; j++)
System.out.print("*");
System.out.println();
}
}
public void printStarDiamond() {
}
public void printArrayMiddleStar() {
int height = 5;
int width = 5;
String[][] array = new String[height][width];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) { // 打印二维数组
// array[i][j] = Integer.toString(0); //把数组所有值变成 0 ,初始值为 null
array[i][j] = "_";
array[height / 2][width / 2] = "*";
System.out.print(array[i][j]);
}
System.out.println();
}
}
public void testArray() {
int[] a = { 5, 3, 4, 1, 2 };
int[] b = a;
for (int tmp : a)
System.out.print(tmp + ",");
System.out.println();
int[][] c = { { 3, 2, 1 }, { 4, 3, 2, 1 }, { 5, 4, 3, 2, 1 } };
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[i].length; j++)
System.out.print(c[i][j] + " ");
}
System.out.println();
}
public void printProperties() throws FileNotFoundException, IOException {
// 获取当前用户目录
String path = System.getProperty("user.dir");
System.out.println(path);
// 获取系统所有的环境变量
Map<String, String> env = System.getenv();
for (String name : env.keySet()) {
System.out.println(name + " ---> " + env.get(name));
}
// 获取指定环境变量的值
// System.out.println(System.getenv("JAVA_HOME"));
System.out.println(System.getenv("HOME"));
// 获取所有的系统属性
Properties props = System.getProperties();
// 将所有系统属性保存到props.txt文件中
props.store(new FileOutputStream("props.txt"), "System Properties");
// 输出特定的系统属性
System.out.println(System.getProperty("os.name"));
}
}
| true |
dbe55d9914d56736bed291c892e2b56cd7a7dd01 | Java | aravindc26/openapi4j | /openapi-operation-validator/src/test/java/org/openapi4j/operation/validator/validation/operation/OperationValidatorTestBase.java | UTF-8 | 1,936 | 2.21875 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package org.openapi4j.operation.validator.validation.operation;
import org.openapi4j.operation.validator.model.Request;
import org.openapi4j.operation.validator.model.Response;
import org.openapi4j.operation.validator.validation.OperationValidator;
import org.openapi4j.parser.OpenApi3Parser;
import org.openapi4j.parser.model.v3.OpenApi3;
import org.openapi4j.schema.validator.ValidationData;
import java.net.URL;
import java.util.function.BiConsumer;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class OperationValidatorTestBase {
protected OperationValidator loadOperationValidator(String path, String opId) throws Exception {
URL specPath = OperationValidatorTestBase.class.getResource(path);
OpenApi3 api = new OpenApi3Parser().parse(specPath, false);
return new OperationValidator(
api,
api.getPathItemByOperationId(opId),
api.getOperationById(opId));
}
protected void check(Request rq,
BiConsumer<Request, ValidationData<Void>> func,
boolean shouldBeValid) {
ValidationData<Void> validation = new ValidationData<>();
func.accept(rq, validation);
System.out.println(validation.results());
if (shouldBeValid) {
assertTrue(validation.results().toString(), validation.isValid());
} else {
assertFalse(validation.results().toString(), validation.isValid());
}
}
protected void check(Response resp,
BiConsumer<Response, ValidationData<Void>> func,
boolean shouldBeValid) {
ValidationData<Void> validation = new ValidationData<>();
func.accept(resp, validation);
System.out.println(validation.results());
if (shouldBeValid) {
assertTrue(validation.results().toString(), validation.isValid());
} else {
assertFalse(validation.results().toString(), validation.isValid());
}
}
}
| true |
9e7d15357820256eb5c3351885044505b3eb06be | Java | mukeshSrana/bysykkel-info | /bysykkel-api/src/main/java/no/oslo/bysykkel/api/StasjonStatusInformasjon.java | UTF-8 | 1,226 | 2.046875 | 2 | [] | no_license | package no.oslo.bysykkel.api;
public class StasjonStatusInformasjon {
private String stationId;
private String navn;
private String adresse;
private int kapasitet;
private int ledigSykler;
private int tilgjengeligeLaaser;
public String getStationId() {
return stationId;
}
public void setStationId(String stationId) {
this.stationId = stationId;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public int getKapasitet() {
return kapasitet;
}
public void setKapasitet(int kapasitet) {
this.kapasitet = kapasitet;
}
public int getLedigSykler() {
return ledigSykler;
}
public void setLedigSykler(int ledigSykler) {
this.ledigSykler = ledigSykler;
}
public int getTilgjengeligeLaaser() {
return tilgjengeligeLaaser;
}
public void setTilgjengeligeLaaser(int tilgjengeligeLaaser) {
this.tilgjengeligeLaaser = tilgjengeligeLaaser;
}
}
| true |
b3278f65357860747da8eec25d8e1639d53cb1ee | Java | WeTheInternet/xapi | /common/src/api/java/xapi/platform/JrePlatform.java | UTF-8 | 457 | 1.6875 | 2 | [
"BSD-3-Clause"
] | permissive | package xapi.platform;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import xapi.platform.PlatformSelector.AlwaysTrue;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Platform
public @interface JrePlatform {
double version() default 6.0;
Class<? extends PlatformSelector> runtimeSelector() default AlwaysTrue.class;
}
| true |
9c377aaf91abc71730edb72367158d2541c976b3 | Java | stokey/algorithm-SimpleDemo | /app/src/main/java/com/stokey/algorithmdemo/Sword2Offer/F47AddTwoNumbers.java | UTF-8 | 1,629 | 4.15625 | 4 | [] | no_license | package com.stokey.algorithmdemo.Sword2Offer;
/**
* Created by tiangen on 2017/6/7.
*/
public class F47AddTwoNumbers {
/**
* 写一个函数,求两个整数之和,要求在函数体内不得使用+、-、✖️、/
* 解法:通过二进制的位运算达到效果
* 加法三步:
* 5+17=22
* 1. 只做各位相加不进位,此时相加结果12(个位5和7相加不进位是2,十位数0和1相加结果是1)
* 2. 做进位,5+7中有进位,进位的值是10
* 3. 把前面两个结果加起来,12+10结果是22
* <p>
* 二进制的加法运算用位运算替代:
* 1. 不考虑进位,对每一位相加(异或)
* 2. 进位,只有1加1时才会向前进位(两个数先做位与运算,然后再向左移动一位)
* 3. 把前两个步骤的结果相加【依然重复前面两步,知道不产生进位为止】
*
* @param n
* @param m
* @return
*/
public static int plus(int n, int m) {
int sum, carry;
do {
sum = n ^ m;
carry = (n & m) << 1;
n = sum;
m = carry;
} while (m != 0);
return n;
}
/**
* 相关问题:不使用新的变量交换两个变量的值
* 比如:交换a、b的值
* <p>
* 基于加减法:a = 2, b = 4
* a = a + b;
* b = a - b; // a-->b
* a = a - b; // b-->a
* <p>
* 基于异或运算:a=2,b=4 [a^a=0, 0^x=x]
* a = a ^ b;
* b = a ^ b; // a^b^b=a
* a = a ^ b;// a^b^a=b
*/
public static void other() {
}
}
| true |
23d156219af3e4328ae15a51d2247bac4500449d | Java | hzfff/hezhao_vivo_musicplayer | /app/src/main/java/com/example/musicplayer_hezhao/LoginMainActivity.java | UTF-8 | 2,291 | 1.898438 | 2 | [] | no_license | package com.example.musicplayer_hezhao;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import com.example.musicplayer_hezhao.adapter.loginadapter;
import com.example.musicplayer_hezhao.fragment.loginfragment;
import com.example.musicplayer_hezhao.fragment.registerfragment;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 11120555 on 2020/7/13 11:29
*/
public class LoginMainActivity extends AppCompatActivity implements View.OnClickListener {
private List<String> TitleList=new ArrayList<>();
private List<Fragment>fragmentList=new ArrayList<>();
private ViewPager viewPager;
private TabLayout tableLayout;
private loginadapter loginadapter;
private Toolbar logintoolbar;
@Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.login);
logintoolbar=findViewById(R.id.login_toolbar);
setSupportActionBar(logintoolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
viewPager=findViewById(R.id.login_viewpager);
tableLayout=findViewById(R.id.login_tablelayout);
tableLayout.setSelectedTabIndicatorHeight(0);
initdata();
loginadapter=new loginadapter(getSupportFragmentManager(),TitleList,fragmentList);
viewPager.setAdapter(loginadapter);
tableLayout.setupWithViewPager(viewPager);
logintoolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
public void initdata(){
TitleList.add("登录");
TitleList.add("注册");
fragmentList.add(new loginfragment());
fragmentList.add(new registerfragment());
}
@Override
public void onClick(View view) {
}
}
| true |
be806c7cc86d414c176cfb21369181f996df4493 | Java | VoxelIndustry/SteamLayer | /tile/src/main/java/net/voxelindustry/steamlayer/tile/modular/ICapabilityModule.java | UTF-8 | 468 | 1.796875 | 2 | [
"Apache-2.0"
] | permissive | package net.voxelindustry.steamlayer.tile.modular;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.capabilities.Capability;
import javax.annotation.Nullable;
public interface ICapabilityModule
{
boolean hasCapability(Capability<?> capability, BlockPos from, @Nullable Direction facing);
@Nullable
<T> T getCapability(Capability<T> capability, BlockPos from, @Nullable Direction facing);
}
| true |
b52284421dc057630bc171008f37d573d9e53652 | Java | yashi320/Chess-Validator | /src/com/chess/driver/BoardInitializer.java | UTF-8 | 1,149 | 2.8125 | 3 | [] | no_license | package com.chess.driver;
import com.chess.entities.Board;
public class BoardInitializer {
public static void initialize() {
String board[][] = {
{"BR", "BH", "BC", "BK", "BQ", "BC", "BH", "BR"},
{"BP", "BP", "BP", "BP", "BP", "BP", "BP", "BP"},
{"--", "--", "--", "--", "--", "--", "--", "--"},
{"--", "--", "--", "--", "--", "--", "--", "--"},
{"--", "--", "--", "--", "--", "--", "--", "--"},
{"--", "--", "--", "--", "--", "--", "--", "--"},
{"WP", "WP", "WP", "WP", "WP", "WP", "WP", "WP"},
{"WR", "WH", "WC", "WQ", "WK", "WC", "WH", "WR"}
};
Board.TOP_WHITE = false;
Board.CHESS_BOARD = new String [8][8];
Board.CHESS_BOARD=board;
}
public static void initialize(String board[][]) {
Board.CHESS_BOARD = new String [8][8];
Board.CHESS_BOARD=board;
if(Board.CHESS_BOARD[0][0].charAt(0)=='W')
Board.TOP_WHITE = false;
else
Board.TOP_WHITE = true;
}
public static void displayBoardState() {
System.out.println("CURRENT BOARD:");
for(int i=0;i<8;i++) {
for(int j=0;j<8;j++) {
System.out.print(Board.CHESS_BOARD[i][j] +" ");
}
System.out.println();
}
}
}
| true |
28401c9dae9db2f93df622dcb51aa238ebef03ba | Java | denis-zhdanov/telegram-contest-chart-android | /library/src/main/java/tech/harmonysoft/android/leonardo/util/IntSupplier.java | UTF-8 | 142 | 1.726563 | 2 | [] | no_license | package tech.harmonysoft.android.leonardo.util;
/**
* @author Denis Zhdanov
* @since 14/3/19
*/
public interface IntSupplier {
int get();
}
| true |
b2b828c282b199ae04d177ac69db0aad16c11f22 | Java | P79N6A/icse_20_user_study | /methods/Method_54729.java | UTF-8 | 264 | 1.820313 | 2 | [] | no_license | /**
* Unsafe version of {@link #m_hitPositionWorld(int,double) m_hitPositionWorld}.
*/
public static void nm_hitPositionWorld(long struct,int index,double value){
UNSAFE.putDouble(null,struct + B3RayHitInfo.M_HITPOSITIONWORLD + check(index,3) * 8,value);
}
| true |
7b008d64b90bd5b7fdc6ae1695c7763b0a34703e | Java | khushboorays2020/Project3new | /src/main/java/in/co/sunrays/proj3/controller/JasperCtl.java | UTF-8 | 3,171 | 2.015625 | 2 | [] | no_license | package in.co.sunrays.proj3.controller;
import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.internal.SessionImpl;
import in.co.sunrays.proj3.dto.UserDTO;
import in.co.sunrays.proj3.util.HibDataSource;
import in.co.sunrays.proj3.util.JDBCDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
/*import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;*/
import net.sf.jasperreports.engine.JasperReport;
/**
* The Class JasperCtl.
*/
@WebServlet(name="JasperCtl",urlPatterns={"/ctl/JasperCtl"})
public class JasperCtl extends BaseCtl{
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
System.out.println("in jasperctl .....");
//got jrxml file location
//get the state of user from session ,username and password
HttpSession session = req.getSession(true);
UserDTO dto =(UserDTO) session.getAttribute("user");
String strName = dto.getFirstName();
String strLastName= dto.getLastName();
//put or object in hashmap in key value form.
Map<String,Object> map = new HashMap<String, Object>();
map.put("user", strName+" "+strLastName);
//got the instance of Connection
Connection conn = null;
//got the object of resource bundle and matched condition of database and returned instance
ResourceBundle rb = ResourceBundle.getBundle("in.co.sunrays.proj3.bundle.system");
String database = rb.getString("DATABASE");
String path = req.getServletContext().getRealPath("/WEB-INF/Simple_Blue.jrxml");
JasperReport jasperreport = JasperCompileManager.compileReport(path);
if("Hibernate".equals(database)){
conn = ((SessionImpl) HibDataSource.getSession()).connection();
}
if("JDBC".equals(database)){
conn = JDBCDataSource.getConnection();
}
JasperPrint jasperprint = JasperFillManager.fillReport(jasperreport, map,conn);
byte[] pdf = JasperExportManager.exportReportToPdf(jasperprint);
resp.setContentType("application/pdf");
resp.getOutputStream().write(pdf);
resp.getOutputStream().flush();
}catch (Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected String getView() {
return ORSView.MARKSHEET_MERIT_LIST_VIEW;
}
} | true |
fb93f4d615664cc1257f6f982f6551a5b12234b5 | Java | xukingzx/leetcode-game | /hyf/MaxProduct_152.java | UTF-8 | 1,903 | 3.015625 | 3 | [] | no_license | package waitsolve;
public class MaxProduct_152 {
/*public int maxProduct(int[] nums) {
int[] dp = new int[nums.length];
for(int i = 0;i < nums.length;i++){
dp[i] = nums[i];
}
int start = 0;
int preNegativePos = 0;
boolean isNegative = false;
if(nums[0] < 0) isNegative = true;
for(int i = 1;i < nums.length;i++){
if(nums[i] < 0 && isNegative == true) {
if(preNegativePos == 0){
dp[i] = f(nums,preNegativePos,i);
}
else{
dp[i] = dp[preNegativePos - 1] * f(nums,preNegativePos,i);
}
isNegative = !isNegative;
}
else if(nums[i] > 0 && isNegative == true){
dp[i] = f(nums,preNegativePos,i);
}
else if(nums[i] > 0 && isNegative == false){
dp[i] = dp[i] * dp[i - 1];
}
else if(nums[i] < 0 && isNegative == false){
isNegative = !isNegative;
}
}
int maxNum = Integer.MIN_VALUE;
for(int i = 0;i < dp.length;i++) {
maxNum = Math.max(maxNum, dp[i]);
}
return maxNum;
}
private int f(int[] nums,int begin,int end){
int sum = 1;
for(int i = begin;i <= end;i++){
sum = sum * nums[i];
}
return sum;
}
*/
public int maxProduct(int[] nums) {
int max = nums[0], min = nums[0], res = nums[0];
for(int i = 1; i < nums.length; i++){
if(nums[i] < 0){
int tmp = max;
max = min;
min = tmp;
}
max = Math.max(nums[i], max * nums[i]);
min = Math.min(nums[i], min * nums[i]);
res = Math.max(max, res);
}
return res;
}
}
| true |
135de285f5933769fa5e1a939da6fa99466e13ca | Java | itxiaojian/ahpucampusadmin | /ahpucampus-admin/src/main/java/com/stylefeng/guns/modular/system/model/VisitorLogs.java | UTF-8 | 2,717 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | package com.stylefeng.guns.modular.system.model;
import java.io.Serializable;
import com.baomidou.mybatisplus.enums.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
/**
* <p>
* 浏览记录
* </p>
*
* @author sliu123
* @since 2019-01-24
*/
@TableName("bus_visitor_logs")
public class VisitorLogs extends Model<VisitorLogs> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 浏览记录类型
*/
private Integer logType;
/**
* 帖子id
*/
private Integer messageId;
/**
* 浏览人openId
*/
private String openId;
/**
* 浏览时头像链接
*/
private String avatar;
/**
* 昵称
*/
private String nickName;
/**
* 创建时间,浏览时间
*/
private Date createTime;
/**
* 最近浏览时间
*/
private Date updateTime;
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getLogType() {
return logType;
}
public void setLogType(Integer logType) {
this.logType = logType;
}
public Integer getMessageId() {
return messageId;
}
public void setMessageId(Integer messageId) {
this.messageId = messageId;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "VisitorLogs{" +
"id=" + id +
", logType=" + logType +
", messageId=" + messageId +
", openId=" + openId +
", avatar=" + avatar +
", nickName=" + nickName +
", createTime=" + createTime +
"}";
}
}
| true |