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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
43d60b3a71f67553db6c39bb778ee80f1dfebd57 | Java | jurenqianyi/zll-project | /zll-cmn/src/main/java/com/zll/entity/ask/AskRecord.java | UTF-8 | 2,109 | 2.046875 | 2 | [] | no_license | package com.zll.entity.ask;
import java.util.List;
import java.util.Date;
import javacommon.base.BaseEntity;
import javacommon.util.DateUtil;
public class AskRecord extends BaseEntity {
private static final long serialVersionUID = 1L;
// 提问表id
private int askId;
// 回复人
private String name;
// 回复人头像
private String headUrl;
// 电话
private String phone;
// 回复人详情页
private String url;
// adress
private String adress;
// 内容
private String content;
// 回复时间
private Date time;
// 状态
private int status;
// 操作人id(来自system_user表的主键id)
private int adminId;
public void setAskId(int value) {
this.askId = value;
}
public int getAskId() {
return this.askId;
}
public void setName(String value) {
this.name = value;
}
public String getName() {
return this.name;
}
public void setHeadUrl(String value) {
this.headUrl = value;
}
public String getHeadUrl() {
return this.headUrl;
}
public void setPhone(String value) {
this.phone = value;
}
public String getPhone() {
return this.phone;
}
public void setUrl(String value) {
this.url = value;
}
public String getUrl() {
return this.url;
}
public void setAdress(String value) {
this.adress = value;
}
public String getAdress() {
return this.adress;
}
public void setContent(String value) {
this.content = value;
}
public String getContent() {
return this.content;
}
public String getTimeString() {
return DateUtil.formatDatetime(getTime());
}
public void setTimeString(String value) {
setTime(DateUtil.parseDatetime(value));
}
public void setTime(Date value) {
this.time = value;
}
public Date getTime() {
return this.time;
}
public void setStatus(int value) {
this.status = value;
}
public int getStatus() {
return this.status;
}
public void setAdminId(int value) {
this.adminId = value;
}
public int getAdminId() {
return this.adminId;
}
}
| true |
74255170230a0f5f041b66e9e207be2b4b1fd3af | Java | hchim/DataReceiver | /src/main/java/im/hch/datareceiver/utils/JsonParser.java | UTF-8 | 671 | 2.546875 | 3 | [
"MIT"
] | permissive | package im.hch.datareceiver.utils;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
public class JsonParser {
public static JSONObject jsonFromFile(String filePath) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject object = new JSONObject(buffer.toString());
return object;
} catch (Exception e) {
return null;
}
}
}
| true |
036a74c75ad66c67b69e44e8dc9ff6789134b9bf | Java | sameerror/Saffersmall | /SaffersMall/src/com/nurakanbpo/saffersmall/adapters/GridViewRowAdapter.java | UTF-8 | 1,728 | 2.3125 | 2 | [] | no_license | package com.nurakanbpo.saffersmall.adapters;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nurakanbpo.saffersmall.R;
public class GridViewRowAdapter extends ArrayAdapter<HashMap<String, String>> {
private Context context;
private List<HashMap<String, String>> dataList;
public GridViewRowAdapter(Context context,
List<HashMap<String, String>> dataList) {
super(context, R.layout.grid_view_row_layout, R.id.itemNameTextView,
dataList);
this.context = context;
this.dataList = dataList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.grid_view_row_layout, null,
false);
viewHolder.imageView = (ImageView) convertView
.findViewById(R.id.itemImage);
viewHolder.name = (TextView) convertView
.findViewById(R.id.itemNameTextView);
viewHolder.user = (TextView) convertView
.findViewById(R.id.itemUserTextView);
viewHolder.date = (TextView) convertView
.findViewById(R.id.itemDateTextView);
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
return convertView;
}
private class ViewHolder {
ImageView imageView;
TextView name;
TextView user;
TextView date;
}
}
| true |
2490e69ab65dcc92be0934d63a2e22b1f7e26fb5 | Java | AndersonAnson/SpringCoding | /src/pencilTest/XiaoCangShooting.java | UTF-8 | 503 | 2.578125 | 3 | [] | no_license | package pencilTest;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class XiaoCangShooting {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int round = s.nextInt();
double p = s.nextDouble();
double q = s.nextDouble();
double ratio = p / q;
List<Integer> mark = new LinkedList<Integer>();
for (int i = 0; i < round; i++) {
mark.add(s.nextInt());
}
}
}
| true |
bac8fd2c36aa5c2c9f98826ae6cbbaa1c89d9598 | Java | hpsworldwide/pwc-utils | /src/main/java/com/hpsworldwide/powercard/utils/socket/SslSocketServer.java | UTF-8 | 4,478 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | package com.hpsworldwide.powercard.utils.socket;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SslSocketServer implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(SslSocketServer.class);
private final ServerSocket serverSocket;
private final Map<Long, Socket> sockets;
private final Random random;
private final ISocketListener socketListener;
/**
* @param backlog how many connections are queued
*/
public SslSocketServer(int localPort, String localHost, int backlog, boolean ssl, ISocketListener socketListener) throws IOException {
this.socketListener = socketListener;
serverSocket = generateServerSocket(localPort, localHost, backlog, ssl);
if (serverSocket instanceof SSLServerSocket) {
String[] cipherSuites = ((SSLServerSocket) serverSocket).getSupportedCipherSuites();
LOG.debug(cipherSuites.length + " cipher suites supported");
for (String cipherSuite : cipherSuites) {
LOG.debug("supported cipher suite : " + cipherSuite);
}
}
LOG.info("socket ready on " + localHost + ":" + localPort + " backlog[" + backlog + "] ssl?" + ssl);
sockets = new HashMap<>();
random = new Random();
}
/**
* @param loop if true, will listen perpetually for a connexion ; if false,
* will listen only to the first connexion
*/
public void start(boolean loop) throws IOException {
do {
LOG.info("waiting for socket connexion...");
final Socket socket = serverSocket.accept();
final SslSocketServer sslSocketServer = this;
new Thread() {
@Override
public void run() {
boolean isSSL = socket instanceof SSLSocket;
LOG.info("socket connected; ssl=" + isSSL);
long socketId = random.nextLong();
sockets.put(socketId, socket);
if (isSSL) {
String[] enabledProtocols = ((SSLSocket) socket).getEnabledProtocols();
LOG.debug(enabledProtocols.length + " enabled protocols");
for (String enabledProtocol : enabledProtocols) {
LOG.debug("enabled protocol : " + enabledProtocol);
}
}
try {
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
LOG.info("action delegated to socket listener");
socketListener.onConnected(sslSocketServer, socketId, socket, inputStream, outputStream);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}.start();
} while (loop);
}
/**
* @param backlog how many connections are queued
*/
private static ServerSocket generateServerSocket(int localPort, String localHost, int backlog, boolean ssl) throws IOException {
ServerSocketFactory serverSocketFactory = generateServerSocketFactory(ssl);
InetAddress localHostAddress = InetAddress.getByName(localHost);
return serverSocketFactory.createServerSocket(localPort, backlog, localHostAddress);
}
private static ServerSocketFactory generateServerSocketFactory(boolean ssl) {
if (!ssl) {
return ServerSocketFactory.getDefault();
} else {
return SSLServerSocketFactory.getDefault();
}
}
public void closeSocket(long socketId) throws IOException {
Socket socket = sockets.get(socketId);
socket.close();
sockets.remove(socketId);
}
@Override
public void close() throws IOException {
for (Socket socket : sockets.values()) {
socket.close();
}
sockets.clear();
}
}
| true |
1f9f34996060af96f11d80cc562f32faae185171 | Java | JGeetha/SelFramework | /FrameWork/src/main/java/pageFactory/CRMSFAHomePage.java | UTF-8 | 604 | 1.851563 | 2 | [] | no_license | package pageFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.testng.internal.EclipseInterface;
public class CRMSFAHomePage extends AbstractPage{
public CRMSFAHomePage(){
PageFactory.initElements(eventdriver, this);
}
@FindBy(how=How.LINK_TEXT,using="CRM/SFA")
WebElement CRMSFALink;
public CRMSFAMyHomePage clickCRMSFA(){
eleclick(CRMSFALink);
return new CRMSFAMyHomePage();
}
}
| true |
8f2e134c496137b47c208c0cc7f1e44759c6c327 | Java | Taekyung2/Algo_collection | /BOJ/4000번대/4900/4963/Q4963.java | UTF-8 | 1,204 | 2.921875 | 3 | [] | no_license | package boj;
import java.util.Scanner;
public class Q4963 {
static int w, h;
static int[] dy = {-1, -1, 0, 1, 1, 1, 0, -1}, dx = {0, 1, 1, 1, 0, -1, -1, -1};
static int[][] map;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(true) {
w = sc.nextInt();
h = sc.nextInt();
int cnt = 0;
if(w == 0 && h == 0)
break;
map = new int[h][w];
for(int i = 0; i < h; i++)
for(int j = 0; j < w; j++)
map[i][j] = sc.nextInt();
for(int i = 0; i < h; i++) {
for(int j = 0; j < w; j++) {
if(map[i][j] != 0) {
dfs(i, j);
cnt++;
}
}
}
System.out.println(cnt);
}
}
public static void dfs(int y, int x) {
map[y][x] = 0;
for(int d = 0; d < 8; d++) {
int ny = y + dy[d], nx = x + dx[d];
if(ny < 0 || nx < 0 || ny >= h || nx >= w || map[ny][nx] == 0)
continue;
dfs(ny, nx);
}
}
}
| true |
ce59a14f709167ae1722abe957d79b67a0ac3c45 | Java | Nurbek03/Homewa5 | /app/src/main/java/com/example/myapplicationrecycler/ModelSender.java | UTF-8 | 126 | 1.625 | 2 | [] | no_license | package com.example.myapplicationrecycler;
public interface ModelSender {
void modelSender(ContactModel contactModel);
}
| true |
f6af8edfdc899650f02c382ce8f970b596eb9389 | Java | kaden-kykim/CICCC-Java | /JavaLec/src/ca/ciccc/wmad/kaden/oct_24th/material/src/Lessons/ASimpleComputer/HandHeldCalculator.java | UTF-8 | 506 | 2.515625 | 3 | [
"MIT"
] | permissive | package ca.ciccc.wmad.kaden.oct_24th.material.src.Lessons.ASimpleComputer;
public class HandHeldCalculator<T> extends AbstractComputer<T> {
public HandHeldCalculator() {
}
@Override
public boolean powerOn() {
return false;
}
@Override
public boolean powerOff() {
return false;
}
@Override
public void UpdateModel() {
}
@Override
public void UpdateView() {
}
@Override
public void UpdateController() {
}
}
| true |
6ba9df5850ab6f38afd4c4a48f451ec9bc9bf3d2 | Java | zllAndroid/DoubleQ | /app/src/main/java/com/mding/chatfeng/about_chat/group_manage/ExitOrTransferGroupActivity.java | UTF-8 | 1,702 | 2 | 2 | [] | no_license | package com.mding.chatfeng.about_chat.group_manage;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.mding.chatfeng.R;
import com.mding.chatfeng.about_base.BaseActivity;
import com.mding.chatfeng.about_utils.IntentUtils;
import com.projects.zll.utilslibrarybyzll.about_dialog.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ExitOrTransferGroupActivity extends BaseActivity {
@BindView(R.id.include_top_tv_tital)
TextView includeTopTvTital;
@Override
protected int getLayoutView() {
return R.layout.activity_exit_or_transfer_group;
}
@Override
protected void initBaseView() {
super.initBaseView();
includeTopTvTital.setText(getResources().getString(R.string.exit_group_title));
}
@OnClick({R.id.exit_group_tv_transfer, R.id.exit_group_tv_dismiss})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.exit_group_tv_transfer:
//跳转到群成员列表界面
// IntentUtils.JumpTo();
DialogUtils.showDialog("跳转到群成员列表");
break;
case R.id.exit_group_tv_dismiss:
DialogUtils.showDialog(getResources().getString(R.string.exit_group_dialog_is_sure_dismiss), new DialogUtils.OnClickSureListener() {
@Override
public void onClickSure() {
DialogUtils.showDialog(getResources().getString(R.string.exit_group_dialog_dismiss_succeed));
}
});
break;
}
}
}
| true |
2c52847533b94f3b10131473ce21cbd31effa692 | Java | nickman/heliosJMX | /src/main/java/com/heliosapm/script/fixtures/FixtureAccessor.java | UTF-8 | 5,630 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | /**
* Helios, OpenSource Monitoring
* Brought to you by the Helios Development Group
*
* Copyright 2007, Helios Development Group and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.heliosapm.script.fixtures;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.heliosapm.jmx.util.helpers.JMXHelper;
import com.heliosapm.jmx.util.helpers.JMXHelper.MBeanEventHandler;
import com.heliosapm.script.DeployedScript;
/**
* <p>Title: FixtureAccessor</p>
* <p>Description: Provides a direct invoker to deployed fixtures which are otherwise limited by
* the MXBean interface which is the only other acces point to fixtures.</p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.script.fixtures.FixtureAccessor</code></p>
* @param <T> The type returned by the wrapped fixture
*/
public class FixtureAccessor<T> implements FixtureAccessorMBean<T> {
/** The fixture this accessor invokes against */
protected final DeployedFixture<T> fixture;
/** The accessor JMX ObjectName */
protected final ObjectName objectName;
/** Instance logger */
protected final Logger log;
/**
* Creates a new FixtureAccessor for the passed fixture
* @param fixture the fixture to create the accessor for
* @return The created FixtureAccessor
*/
public static <T> FixtureAccessor<T> newFixtureAccessor(final DeployedFixture<T> fixture) {
return new FixtureAccessor<T>(fixture);
}
/**
* Creates a new FixtureAccessor
* @param fixture The fixture this accessor invokes against
*/
public FixtureAccessor(final DeployedFixture<T> fixture) {
this.fixture = fixture;
// @Fixture(name="JMXConnector", type=javax.management.remote.JMXConnector.class, params=[
// @FixtureArg(name="jmxUrl", type=java.lang.String.class)
log = LoggerFactory.getLogger(getClass().getName() + "." + fixture.getFixtureName());
objectName = JMXHelper.objectName(DeployedScript.FIXTURE_DOMAIN + ".invokers:name=" + fixture.getFixtureName() + ",type=" + fixture.getFixtureTypeName());
JMXHelper.registerMBean(this, objectName);
log.info("Registered Fixture Invoker [{}]", objectName);
JMXHelper.onMBeanUnregistered(objectName, new MBeanEventHandler() {
public void onEvent(final MBeanServerConnection connection, final ObjectName on, final boolean reg) {
JMXHelper.unregisterMBean(objectName);
log.info("Unregistered Fixture Invoker [{}]", objectName);
}
});
FixtureCache.getInstance().put(this);
}
/**
* Returns a set of the parameters keys
* @return a set of the parameters keys
*/
public Set<String> getParamKeys() {
return fixture.getParamKeys();
}
/**
* Returns a map of the parameter types keyed by the parameter name
* @return a map of the parameter types keyed by the parameter name
*/
public Map<String, Class<?>> getParamTypes() {
return fixture.getParamTypes();
}
/**
* {@inheritDoc}
* @see com.heliosapm.script.fixtures.Fixture#get(java.util.Map)
*/
@Override
public T get(final Map<String, Object> config) {
return fixture.get(config);
}
/**
* {@inheritDoc}
* @see com.heliosapm.script.fixtures.Fixture#get()
*/
@Override
public T get() {
return fixture.get();
}
/**
* {@inheritDoc}
* @see com.heliosapm.script.fixtures.FixtureAccessorMBean#getObjectName()
*/
@Override
public ObjectName getObjectName() {
return objectName;
}
/**
* {@inheritDoc}
* @see com.heliosapm.script.fixtures.FixtureAccessorMBean#getFixtureName()
*/
@Override
public String getFixtureName() {
return fixture.getFixtureName();
}
/**
* {@inheritDoc}
* @see com.heliosapm.script.fixtures.FixtureAccessorMBean#getFixtureType()
*/
@Override
public Class<T> getFixtureType() {
return (Class<T>) fixture.getFixtureType();
}
/**
* {@inheritDoc}
* @see com.heliosapm.script.fixtures.FixtureAccessorMBean#getFixtureTypeName()
*/
@Override
public String getFixtureTypeName() {
return fixture.getFixtureTypeName();
}
/**
* {@inheritDoc}
* @see com.heliosapm.script.fixtures.FixtureAccessorMBean#getFixtureObjectName()
*/
@Override
public ObjectName getFixtureObjectName() {
return fixture.getObjectName();
}
/**
* {@inheritDoc}
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("FixtureAccessor [");
builder.append("name:").append(getFixtureName()).append(", type:").append(getFixtureTypeName());
builder.append("]");
return builder.toString();
}
}
| true |
238a15964e489835e843bf5cd87ba6fa11e1f79a | Java | saintbeller96/Algorithm-Practice | /Boj/src/P20366같이눈사람/Main.java | UTF-8 | 1,365 | 3.0625 | 3 | [] | no_license | package P20366같이눈사람;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;
public class Main {
static int N;
static int answer;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
StringTokenizer stk = new StringTokenizer(br.readLine());
int[] arr = new int[N];
for(int i = 0; i<N; i++) {
arr[i] = Integer.parseInt(stk.nextToken());
}
Arrays.sort(arr);
TreeMap<Integer, List<int[]>> map = new TreeMap<>();
for(int i = 0; i<N-1; i++) {
for(int j = i+1; j<N; j++) {
int n = arr[i] + arr[j];
map.putIfAbsent(n, new ArrayList<>());
map.get(n).add(new int[] {i, j});
}
}
List<Integer> sumList = new ArrayList<>(map.keySet());
answer = Integer.MAX_VALUE;
for(int i = 0; i < sumList.size()-1; i++) {
int n = sumList.get(i);
int m = sumList.get(i+1);
boolean flag = false;
for(int[] arr1 : map.get(n)) {
for(int[] arr2 : map.get(m)) {
Set<Integer> temp = new TreeSet<>(Arrays.asList(arr1[0], arr1[1], arr2[0], arr2[1]));
if(temp.size() == 4) {
flag = true;
break;
}
}
if(flag) break;
}
if(flag) answer = Math.min(answer, m-n);
}
System.out.println(answer);
}
}
| true |
870b75415124e56ba4cf5662ec61f2d0d194db76 | Java | lishaodan995/jian | /app/src/main/java/com/example/xiangmuu/presenter/RegisterMSMPresenter.java | UTF-8 | 1,483 | 1.984375 | 2 | [] | no_license | package com.example.xiangmuu.presenter;
import com.example.xiangmuu.base.BasePresenter;
import com.example.xiangmuu.bean.VerfiedBean;
import com.example.xiangmuu.contract.RegisterMSMContract;
import com.example.xiangmuu.model.RegisterMSMModel;
import com.example.xiangmuu.net.api.INetCallBack;
public class RegisterMSMPresenter extends BasePresenter<RegisterMSMContract.IRegisterMSMView> implements RegisterMSMContract.IRegisterMSMPresenter {
private RegisterMSMContract.IRegisterMSMMode iRegisterMSMMode;
public RegisterMSMPresenter() {
iRegisterMSMMode = new RegisterMSMModel();
}
@Override
public void getVerified(String string, String type) {
iRegisterMSMMode.getVerified(string, type, new INetCallBack<VerfiedBean>() {
@Override
public void onSuccess(VerfiedBean verfiedBean) {
mview.getVerified(verfiedBean);
}
@Override
public void onError(Throwable throwable) {
}
});
}
@Override
public void checkSmsCode(String phoneNum, String smsCode, String type) {
iRegisterMSMMode.checkSmsCode(phoneNum, smsCode, type, new INetCallBack<VerfiedBean>() {
@Override
public void onSuccess(VerfiedBean verfiedBean) {
mview.checkSmsCodeResult(verfiedBean);
}
@Override
public void onError(Throwable throwable) {
}
});
}
}
| true |
c67f5af5e90d84beed372bbcd1c9e24e2eec18c3 | Java | RakaChoudhury/Retail-Warehouse-Management | /RetailWarehouseManagement/java/ReportSupply.java | UTF-8 | 2,802 | 2.234375 | 2 | [] | no_license |
import java.io.IOException;
import java.lang.reflect.Type;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mysql.jdbc.Connection;
import com.sore.model.Stock;
/**
* Servlet implementation class ReportSupply
*/
@WebServlet("/ReportSupply")
public class ReportSupply extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ReportSupply() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
Stock obj=null;
Gson gson=new Gson();
ArrayList<Stock>stocks=new ArrayList<Stock>();
String stock1=request.getParameter("WarehouseStocks");
String option=request.getParameter("report");
System.out.println(option);
Type listType = new TypeToken<ArrayList<Stock>>() {}.getType();
stocks=new Gson().fromJson(stock1, listType);
System.out.println(stock1);
obj=stocks.get(Integer.parseInt(option.substring(7))-1);
System.out.println(obj.item_id+" "+obj.supplier_quantity);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/retail1", "root", "root");
if(obj.supplier_quantity>obj.po_quantity){
PreparedStatement pst = conn.prepareStatement("call report_insert_surplus(?,?,?)");
pst.setInt(1,obj.carton_id );
pst.setInt(2, obj.item_id);
pst.setInt(3, obj.supplier_quantity-obj.po_quantity);
}
if(obj.supplier_quantity<obj.po_quantity){
PreparedStatement pst = conn.prepareStatement("call report_insert_deficit(?,?,?)");
pst.setInt(1,obj.carton_id );
pst.setInt(2, obj.item_id);
pst.setInt(3, obj.po_quantity-obj.supplier_quantity);
}
}
catch(Exception e){}
}
}
| true |
ad4a9b8cd9050d73589e3578fd31c6729bad8d80 | Java | Stainlesswang/cloud-demo | /user/src/main/java/com/allen/user/service/UserService.java | UTF-8 | 633 | 2.171875 | 2 | [] | no_license | package com.allen.user.service;
import com.allen.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author AllenWong
* @date 2020/5/1 8:19 PM
*/
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public boolean isEnough(Integer id,Long useMoney){
Long now=userMapper.getMoney(id);
return now != null && now > useMoney;
}
public boolean useMoney(Integer id,Long useMoney){
Integer now=userMapper.updateMoney(id,useMoney);
return now != null && now > 0;
}
}
| true |
a70c17699c23158c489b2d18e4cff36dbc692a6c | Java | shanthshivam/equifax-creditreport | /spring-swagger-codegen-equifax-cs/src/main/java/com/b4nkd/creditscore/equifax/model/ConsumerCreditReportEmployments.java | UTF-8 | 5,038 | 2.171875 | 2 | [] | no_license | package com.b4nkd.creditscore.equifax.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* ConsumerCreditReportEmployments
*/
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-11-08T10:55:31.099545300Z[Europe/London]")
public class ConsumerCreditReportEmployments {
@JsonProperty("identifier")
private String identifier = null;
@JsonProperty("occupation")
private String occupation = null;
@JsonProperty("employer")
private String employer = null;
@JsonProperty("dateLastReported")
private String dateLastReported = null;
@JsonProperty("dateFirstReported")
private String dateFirstReported = null;
public ConsumerCreditReportEmployments identifier(String identifier) {
this.identifier = identifier;
return this;
}
/**
* It describes the type of employment
* @return identifier
**/
@ApiModelProperty(example = "[\"current\",\"former\",\"secondFormer\"]", value = "It describes the type of employment")
@Size(max=12) public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public ConsumerCreditReportEmployments occupation(String occupation) {
this.occupation = occupation;
return this;
}
/**
* Subject's occupation
* @return occupation
**/
@ApiModelProperty(value = "Subject's occupation")
@Size(max=35) public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public ConsumerCreditReportEmployments employer(String employer) {
this.employer = employer;
return this;
}
/**
* Employer's name
* @return employer
**/
@ApiModelProperty(value = "Employer's name")
@Size(max=35) public String getEmployer() {
return employer;
}
public void setEmployer(String employer) {
this.employer = employer;
}
public ConsumerCreditReportEmployments dateLastReported(String dateLastReported) {
this.dateLastReported = dateLastReported;
return this;
}
/**
* Get dateLastReported
* @return dateLastReported
**/
@ApiModelProperty(value = "")
@Size(max=6) public String getDateLastReported() {
return dateLastReported;
}
public void setDateLastReported(String dateLastReported) {
this.dateLastReported = dateLastReported;
}
public ConsumerCreditReportEmployments dateFirstReported(String dateFirstReported) {
this.dateFirstReported = dateFirstReported;
return this;
}
/**
* Get dateFirstReported
* @return dateFirstReported
**/
@ApiModelProperty(value = "")
@Size(max=6) public String getDateFirstReported() {
return dateFirstReported;
}
public void setDateFirstReported(String dateFirstReported) {
this.dateFirstReported = dateFirstReported;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConsumerCreditReportEmployments consumerCreditReportEmployments = (ConsumerCreditReportEmployments) o;
return Objects.equals(this.identifier, consumerCreditReportEmployments.identifier) &&
Objects.equals(this.occupation, consumerCreditReportEmployments.occupation) &&
Objects.equals(this.employer, consumerCreditReportEmployments.employer) &&
Objects.equals(this.dateLastReported, consumerCreditReportEmployments.dateLastReported) &&
Objects.equals(this.dateFirstReported, consumerCreditReportEmployments.dateFirstReported);
}
@Override
public int hashCode() {
return Objects.hash(identifier, occupation, employer, dateLastReported, dateFirstReported);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ConsumerCreditReportEmployments {\n");
sb.append(" identifier: ").append(toIndentedString(identifier)).append("\n");
sb.append(" occupation: ").append(toIndentedString(occupation)).append("\n");
sb.append(" employer: ").append(toIndentedString(employer)).append("\n");
sb.append(" dateLastReported: ").append(toIndentedString(dateLastReported)).append("\n");
sb.append(" dateFirstReported: ").append(toIndentedString(dateFirstReported)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| true |
8f0c217384cc2e2c382814456120ab81b1af0a5c | Java | cga2351/code | /DecompiledViberSrc/app/src/main/java/com/google/android/gms/tasks/OnSuccessListener.java | UTF-8 | 359 | 1.90625 | 2 | [] | no_license | package com.google.android.gms.tasks;
public abstract interface OnSuccessListener<TResult>
{
public abstract void onSuccess(TResult paramTResult);
}
/* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar
* Qualified Name: com.google.android.gms.tasks.OnSuccessListener
* JD-Core Version: 0.6.2
*/ | true |
a875a19fb6c005479d283d318639cc243147f9c8 | Java | songzhaoheng/Java_Swing_Network_Chat_Room-2019-4-10 | /src/com/userInfo/UserPassName.java | UTF-8 | 595 | 2.484375 | 2 | [] | no_license | package com.userInfo;
import lombok.Getter;
import lombok.Setter;
/*
* 用户名和密码
* */
@Setter
@Getter
public class UserPassName {
private String username;
private String userpass;
public UserPassName() {
super();
}
public UserPassName(String username, String userpass) {
this.username = username;
this.userpass = userpass;
}
@Override
public String toString() {
return "UserPassName{" +
"username='" + username + '\'' +
", userpass='" + userpass + '\'' +
'}';
}
}
| true |
ad9b9e2c58da5a347b6c0bae30626c1613a0a502 | Java | vashenko49/java-basic-homework | /homework13/src/family/CollectionFamilyDao.java | UTF-8 | 3,020 | 2.90625 | 3 | [] | no_license | package family;
import logger.Logger;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class CollectionFamilyDao implements FamilyDAO {
private static final CollectionFamilyDao collectionFamilyDao = new CollectionFamilyDao();
private List<Family> families = new ArrayList<>();
private CollectionFamilyDao() {
}
public static CollectionFamilyDao instanceOf() {
return collectionFamilyDao;
}
@Override
public List<Family> getAllFamilies() {
Logger.info("getAllFamilies");
return families;
}
@Override
public Family getFamilyByIndex(int index) {
Logger.info("getFamilyByIndex " + index);
return families.get(index);
}
@Override
public boolean deleteFamilyByIndex(int index) {
Logger.info("deleteFamilyByIndex " + index);
return families.remove(index) != null;
}
@Override
public boolean deleteFamily(Family family) {
Logger.info("deleteFamily");
return families.remove(family);
}
@Override
public void saveFamily(Family family) {
Logger.info("saveFamily");
families.add(family);
}
@Override
public boolean saveDataToFile() {
if (families.size() > 0) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
objectOutputStream.writeObject(families);
} catch (IOException e) {
e.printStackTrace();
return false;
}
byte[] bytes = byteArrayOutputStream.toByteArray();
try (OutputStream outputStream = new FileOutputStream("families")) {
Logger.info("loadData");
outputStream.write(bytes);
} catch (IOException e) {
Logger.error("Ошибка сохранения");
return false;
}
return true;
} else {
return false;
}
}
@Override
public boolean loadData() {
File file = new File("families");
if (file.isFile()) {
try (InputStream inputStream = new FileInputStream(file)) {
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
List<Family> familyList = (ArrayList<Family>) objectInputStream.readObject();
for (Family family : familyList) {
if (!families.contains(family)) {
families.add(family);
}
}
Logger.info("recoverData");
} catch (IOException | ClassNotFoundException e) {
Logger.error("Ошибка восстановления");
return false;
}
return true;
} else {
return false;
}
}
}
| true |
4ff781a988d135590a6df752a143065f1c955e0e | Java | chaijewon/2020-12-22-JavaStudy | /20210128-라이브러리활용(제네릭스,어노테이션)/src/com/sist/anno/RequestMapping.java | UTF-8 | 576 | 2.65625 | 3 | [] | no_license | package com.sist.anno;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/*
* class A
* {
* @RequestMapping("")
* public void aaa(){}
* @RequestMapping
* public void bbb(){}
* @RequestMapping
* public void ccc(){}
* }
*/
// @RequestMapping("구분문자")
@Retention(RUNTIME)
@Target(METHOD)
public @interface RequestMapping {
public String value();
}
| true |
8ee85ba794de5182ef6b92d42f492f5e34de3375 | Java | moutainhigh/sunnyday | /com.f2b2c.eco/src/main/java/com/f2b2c/eco/service/platform/BCommissionService.java | UTF-8 | 386 | 1.882813 | 2 | [] | no_license | package com.f2b2c.eco.service.platform;
import com.f2b2c.eco.model.common.ApiResultModel;
/**
* 佣金Service
* @author jane.hui
*
*/
public interface BCommissionService {
/**
* 转出功能
* @param userId:佣金功能
* @param money:转出金额
* @return 返回转账结果
*/
ApiResultModel<String> transfer(Integer userId,Integer money);
}
| true |
585fe3eaa67a0812c0d5a70b140ebd644c9dad48 | Java | tobyli/Sugilite_development | /app/src/main/java/edu/cmu/hcii/sugilite/sovite/communication/SoviteAppResolutionResultPacket.java | UTF-8 | 940 | 2.0625 | 2 | [] | no_license | package edu.cmu.hcii.sugilite.sovite.communication;
import java.util.List;
import java.util.Map;
/**
* @author toby
* @date 2/26/20
* @time 10:52 AM
*/
public class SoviteAppResolutionResultPacket {
private String dataset;
private String type;
private List<String> available_apps;
private Map<String, List<ResultScorePair>> result_map;
private String query_type;
private String activity_name;
private String package_name;
public String getDataset() {
return dataset;
}
public String getType() {
return type;
}
public List<String> getAvailable_apps() {
return available_apps;
}
public Map<String, List<ResultScorePair>> getResult_map() {
return result_map;
}
public String getQuery_type() {
return query_type;
}
public class ResultScorePair {
public String result_string;
public Double score;
}
}
| true |
8132fdfaa8e0402c3933635819c96c8bb1c83cc3 | Java | SongLinYang12138/MyApps | /app/src/main/java/com/bondex/ysl/pdaapp/main/MainActivity.java | UTF-8 | 6,408 | 1.585938 | 2 | [] | no_license | package com.bondex.ysl.pdaapp.main;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SlidingPaneLayout;
import android.support.v7.widget.SwitchCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bondex.ysl.installlibrary.InstallApk;
import com.bondex.ysl.pdaapp.R;
import com.bondex.ysl.pdaapp.bean.UpdateBean;
import com.bondex.ysl.pdaapp.login.LoginActivity;
import com.bondex.ysl.pdaapp.util.CommonUtil;
import com.bondex.ysl.pdaapp.util.PdaUtils;
import com.bondex.ysl.pdaapp.application.PdaApplication;
import com.bondex.ysl.pdaapp.base.BaseActivtiy;
import com.bondex.ysl.pdaapp.util.Constant;
import com.bondex.ysl.pdaapp.util.PermissionUtil;
import com.bondex.ysl.pdaapp.util.SharedPreferecneUtils;
import com.bondex.ysl.pdaapp.util.ToastUtils;
import com.gc.materialdesign.views.ButtonRectangle;
import com.orhanobut.logger.Logger;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends BaseActivtiy<MainPresenter> implements MainView {
@BindView(R.id.user_name)
TextView userName;
@BindView(R.id.tv_stowrage)
TextView tvSorage;
@BindView(R.id.user_id)
TextView tvUserId;
@BindView(R.id.menu_bt_loginout)
ButtonRectangle btLoginout;
@BindView(R.id.version)
TextView version;
@BindView(R.id.check_update)
TextView checkUpdate;
@BindView(R.id.menu_bt_porwer)
SwitchCompat swPower;
@BindView(R.id.main_panel)
SlidingPaneLayout mainPanel;
@BindView(R.id.main_banner)
ConvenientBanner banner;
@BindView(R.id.main_listvew)
ListView listView;
private ColorStateList normal, select;
private String subSystemName;
private long lastback = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
showLeft(true, R.mipmap.menu, v -> {
boolean isOpen = mainPanel.isOpen() ? mainPanel.closePane() : mainPanel.openPane();
});
showRight(false, 0, null);
showTitle(true, "仓库PDA");
}
@Override
public MainPresenter getPresenter() {
if (presenter == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PermissionUtil.checkPermission(this);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PermissionUtil.checkIsAndroidO(this);
}
subSystemName = SharedPreferecneUtils.getValue(this, Constant.STORWAGEPAGE, Constant.SUBSYSTEM_NAME);
presenter = new MainPresenter(this, this);
}
return presenter;
}
@Override
protected void onResume() {
super.onResume();
banner.startTurning();
}
@Override
protected void onPause() {
super.onPause();
banner.stopTurning();
}
@Override
public void noDoubleClick(View v) {
switch (v.getId()) {
case R.id.menu_bt_loginout:
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra(Constant.LOGIN_OUT, true);
startBaseActivity(intent);
finish();
break;
}
}
@Override
public void initView() {
normal = getResources().getColorStateList(R.color.bottom_normal);
select = getResources().getColorStateList(R.color.colorPrimary);
btLoginout.setOnClickListener(clickListener);
tvUserId.setText("用户ID: " + PdaApplication.LOGINBEAN.getUserid());
userName.setText("用户名: " + PdaApplication.LOGINBEAN.getUsername());
tvSorage.setText("" + subSystemName);
version.setText("当前版本: " + CommonUtil.getVersionName(this));
swPower.setChecked(true);
// swPower.setChecked(SharedPreferecneUtils.getBoolean(this, Constant.STORWAGEPAGE, Constant.POWER_STATE));
swPower.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
PdaUtils.turnOnOffPda(isChecked, PdaApplication.context);
SharedPreferecneUtils.saveBoolean(MainActivity.this, Constant.STORWAGEPAGE, Constant.POWER_STATE, isChecked);
}
});
PdaUtils.turnOnOffPda(true, this);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (System.currentTimeMillis() - lastback > 2000) {
ToastUtils.showToast(this,"请再按一次退出");
lastback = System.currentTimeMillis();
} else {
SharedPreferecneUtils.saveValue(this, Constant.STORWAGEPAGE, Constant.SUBSYSTEM_NAME, "");
finish();
}
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void showLoading() {
}
@Override
public void stopLoading() {
}
@Override
public void onSuccess(String data) {
}
@Override
public void faile(String msg) {
}
@Override
public void setBnnerrs(CBViewHolderCreator holderCreator, ArrayList<String> localImages) {
banner.setPages(holderCreator, localImages).setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
Logger.i("click banner: " + position);
}
});
}
@Override
public void listAdapter(MainAdapter adapter) {
listView.setAdapter(adapter);
}
@Override
public void showUpdate(UpdateBean bean) {
}
@Override
public void installApk(String path) {
InstallApk.install(path, this);
}
}
| true |
c34f955d928dde736fba6b05d15dbbbb66078b73 | Java | glibovet/papers | /src/main/java/ua/com/papers/services/mailing/EmailBuilder.java | UTF-8 | 3,030 | 2.40625 | 2 | [] | no_license | package ua.com.papers.services.mailing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Component;
import ua.com.papers.pojo.entities.UserEntity;
import ua.com.papers.pojo.enums.EmailTypes;
import ua.com.papers.services.users.IUserService;
import java.io.*;
import java.util.Locale;
import java.util.Map;
/**
* Created by KutsykV on 24.01.2016.
*/
@Component
public class EmailBuilder {
@Value("${mail.host}")
private String host;
public String getEmailContent(EmailTypes typeOfEmail, Map<String, String> data, Locale locale) {
try {
String content = readResourceText("email/" + locale.getLanguage() + "/email." + typeOfEmail.toString() + ".html");
if (typeOfEmail == EmailTypes.approve_publication_order) {
return formApprovePublicationOrder(data, content);
} else if (typeOfEmail == EmailTypes.reject_publication_order) {
return formRejectPublicationOrder(data, content);
} else if (typeOfEmail == EmailTypes.crawling_start || typeOfEmail == EmailTypes.crawling_finish) {
return content;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private String formRejectPublicationOrder(Map<String, String> data, String content) {
content = content.replaceAll("REJECT_REASON",data.get("REJECT_REASON"));
return content;
}
private String formApprovePublicationOrder(Map<String, String> data, String content) {
content = content.replaceAll("PUBLICATION_LINK",data.get("PUBLICATION_LINK"));
return content;
}
private String readResourceText(String resourceName) throws IOException {
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
try {
StringBuilder content = new StringBuilder();
Resource resource = new ClassPathResource(resourceName);
fileInputStream = new FileInputStream(resource.getFile().getAbsolutePath());
inputStreamReader = new InputStreamReader(fileInputStream, "UTF8");
reader = new BufferedReader(inputStreamReader);
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
return content.toString();
} finally {
close(reader);
close(inputStreamReader);
close(fileInputStream);
}
}
private void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) { }
}
}
}
| true |
aaa905cd2e9d6c7b17f902f312cd5a2c2ffbfa0a | Java | chenqixu/ojdbc7 | /src/main/java/oracle/jdbc/pool/OracleRuntimeLoadBalancingEventHandlerThread.java | UTF-8 | 2,618 | 1.9375 | 2 | [] | no_license | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package oracle.jdbc.pool;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.sql.SQLException;
import oracle.ons.Notification;
import oracle.ons.ONSException;
import oracle.ons.Subscriber;
import oracle.ons.SubscriptionException;
/** @deprecated */
class OracleRuntimeLoadBalancingEventHandlerThread extends Thread {
private Notification event = null;
private OracleConnectionCacheManager cacheManager = null;
String m_service;
private static final String _Copyright_2007_Oracle_All_Rights_Reserved_ = null;
public static final String BUILD_DATE = "Thu_Apr_04_15:09:24_PDT_2013";
public static final boolean TRACE = false;
OracleRuntimeLoadBalancingEventHandlerThread(String var1) throws SQLException {
this.m_service = var1;
this.cacheManager = OracleConnectionCacheManager.getConnectionCacheManagerInstance();
}
public void run() {
Subscriber var1 = null;
final String var2 = "%\"eventType=database/event/servicemetrics/" + this.m_service + "\"";
while(this.cacheManager.failoverEnabledCacheExists()) {
try {
var1 = (Subscriber)AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() {
try {
return new Subscriber(var2, "", 30000L);
} catch (SubscriptionException var2x) {
return null;
}
}
});
} catch (PrivilegedActionException var5) {
}
if (var1 != null) {
try {
while(this.cacheManager.failoverEnabledCacheExists()) {
if ((this.event = var1.receive(300000L)) != null) {
this.handleEvent(this.event);
}
}
} catch (ONSException var6) {
var1.close();
}
}
try {
Thread.currentThread();
Thread.sleep(10000L);
} catch (InterruptedException var4) {
}
}
}
void handleEvent(Notification var1) {
try {
this.cacheManager.parseRuntimeLoadBalancingEvent(this.m_service, var1 == null ? null : var1.body());
} catch (SQLException var3) {
}
}
}
| true |
2860462a2ac3c12996a0989b0513e5ee26f5f2ac | Java | agalberti/carfactory | /src/main/java/com/alberti/sysone/carfactory/jpa/model/Car.java | UTF-8 | 1,469 | 2.75 | 3 | [] | no_license | package com.alberti.sysone.carfactory.jpa.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
@Entity
public class Car {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private long id;
private String name;
@ManyToOne
private Variant variant;
@ManyToMany
private Set<Equipment> equipments = new HashSet<>();
private Double price;
public Car() {
}
public Car(String name, Variant variant) {
this.name = name;
this.variant = variant;
}
public Variant getVariant() {
return variant;
}
public void setVariant(Variant variant) {
this.variant = variant;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set<Equipment> getEquipments() {
return equipments;
}
public void setEquipments(Set<Equipment> equipments) {
this.equipments = equipments;
}
public void addEquipment(Equipment e) {
this.equipments.add(e);
e.getCars().add(this);
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
| true |
3d45a1700baaf0b1a673ec330dd52915941a13d0 | Java | SuryasnatGit/JavaAlgorithmsAndDSPractise | /src/main/java/com/ctci/bigo/IntegerPairWithDifferenceK.java | UTF-8 | 3,641 | 4.03125 | 4 | [] | no_license | package com.ctci.bigo;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.algo.ds.array.FindElementsOccurringMoreThanNByKTimes.Pair;
/**
* Given an array of distinct integer values, count the number of distinct pairs of integers that have difference k. For
* example, given the array {1, 7, 5, 9, 2, 12, 3} and the difference k = 2, there are four pairs with difference 2: (1,
* 3), (3, 5), (5, 7), (7, 9) .
*
* LeetCode 532 - K-diff Pairs in an Array
*
*
*/
public class IntegerPairWithDifferenceK {
public void getPairs_hashing_duplicates(int[] nums, int k) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (set.contains(num - k)) {
System.out.println(num + "," + (num - k));
}
if (set.contains(num + k)) {
System.out.println(num + "," + (num + k));
}
set.add(num);
}
}
public void getPairs_hashing_distinct(int[] nums, int k) {
Arrays.sort(nums);
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
// to avoid duplicates
while (i + 1 < nums.length && nums[i] == nums[i + 1]) {
i++;
}
if (set.contains(nums[i] - k)) {
System.out.println(nums[i] + "," + (nums[i] - k));
}
if (set.contains(nums[i] + k)) {
System.out.println(nums[i] + "," + (nums[i] + k));
}
set.add(nums[i]);
}
}
/**
* Another approach using java sliding window
*
* @param nums
* @param k
* @return
*/
public int getPairs_slidingWindow(int[] nums, int k) {
if (k < 0 || nums.length <= 1) {
return 0;
}
Arrays.sort(nums);
int count = 0;
int left = 0;
int right = 1;
while (right < nums.length) {
int firNum = nums[left];
int secNum = nums[right];
// If less than k, increase the right index
if (secNum - firNum < k) {
right++;
}
// If larger than k, increase the left index
else if (secNum - firNum > k) {
left++;
}
// If equal, move left and right to next different number
else {
count++;
while (left < nums.length && nums[left] == firNum) {
left++;
}
while (right < nums.length && nums[right] == secNum) {
right++;
}
}
// left and right should not be the same number
if (right == left) {
right++;
}
}
return count;
}
/**
* self balancing BST like AVL tree or Red black tree. complexity - O(N log N)
*
* @param arr
* @param k
* @return
*/
public List<Pair> getPairs_balancedBST(int[] arr, int k) {
return null;
}
public static void main(String[] args) {
IntegerPairWithDifferenceK intk = new IntegerPairWithDifferenceK();
intk.getPairs_hashing_duplicates(new int[] { 1, 7, 5, 9, 2, 12, 3 }, 2);
System.out.println();
intk.getPairs_hashing_distinct(new int[] { 1, 7, 5, 9, 2, 12, 3 }, 2);
System.out.println();
System.out.println(intk.getPairs_slidingWindow(new int[] { 1, 7, 5, 9, 2, 12, 3 }, 2));
System.out.println();
intk.getPairs_hashing_duplicates(new int[] { 3, 1, 4, 1, 5 }, 2);
System.out.println();
intk.getPairs_hashing_distinct(new int[] { 3, 1, 4, 1, 5 }, 2);
System.out.println();
System.out.println(intk.getPairs_slidingWindow(new int[] { 3, 1, 4, 1, 5 }, 2));
System.out.println();
intk.getPairs_hashing_duplicates(new int[] { 1, 3, 1, 5, 4 }, 0);
System.out.println();
intk.getPairs_hashing_distinct(new int[] { 1, 3, 1, 5, 4 }, 0);
System.out.println();
System.out.println(intk.getPairs_slidingWindow(new int[] { 1, 3, 1, 5, 4 }, 0));
}
}
| true |
e7c276bfce696253cbfb2efe629aea5c27f75fac | Java | grahambenevelli/stats | /server/src/main/java/com/grahamsfault/stats/server/factory/StatsApplicationFactory.java | UTF-8 | 8,139 | 1.953125 | 2 | [] | no_license | package com.grahamsfault.stats.server.factory;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.grahamsfault.stats.server.StatsConfiguration;
import com.grahamsfault.nfl.api.NflService;
import com.grahamsfault.stats.server.dao.GameDAO;
import com.grahamsfault.stats.server.dao.ImportDAO;
import com.grahamsfault.stats.server.dao.PlayerDAO;
import com.grahamsfault.stats.server.dao.PredictionDAO;
import com.grahamsfault.stats.server.dao.StatsDAO;
import com.grahamsfault.stats.server.dao.mysql.MySQLGameDAO;
import com.grahamsfault.stats.server.dao.mysql.MySQLImportDAO;
import com.grahamsfault.stats.server.dao.mysql.MySQLPlayerDAO;
import com.grahamsfault.stats.server.dao.mysql.MySQLPredictionDAO;
import com.grahamsfault.stats.server.dao.mysql.MySQLStatsDAO;
import com.grahamsfault.stats.server.file.GameFileReader;
import com.grahamsfault.stats.server.manager.GameManager;
import com.grahamsfault.stats.server.manager.ImportManager;
import com.grahamsfault.stats.server.manager.PlayerManager;
import com.grahamsfault.stats.server.manager.PredictionManager;
import com.grahamsfault.stats.server.manager.StatsManager;
import com.grahamsfault.stats.server.manager.helper.QualifyingNumbersHelper;
import com.grahamsfault.stats.server.manager.helper.average.NaiveAverageHelper;
import com.grahamsfault.stats.server.manager.helper.average.QualifyingAverageHelper;
import javax.sql.DataSource;
import javax.ws.rs.client.ClientBuilder;
/**
* The factory object to build application logic
*/
public class StatsApplicationFactory {
private static StatsApplicationFactory factory = new StatsApplicationFactory();
private PlayerManager playerManager;
private GameManager gameManager;
private StatsManager statsManager;
private ImportManager importManager;
private MySQLPlayerDAO playerDAO;
private GameDAO gameDAO;
private StatsDAO statsDAO;
private ImportDAO importDAO;
private ObjectMapper objectMapper;
private DataSource statsDataSource;
private GameFileReader gameFileReader;
private NflService nflService;
private PredictionManager predictionManager;
private PredictionDAO predictionDAO;
private NaiveAverageHelper naiveAverageHelper;
private QualifyingAverageHelper qualifyingAverageHelper;
private StatsApplicationFactory() {}
public static StatsApplicationFactory instance() {
return factory;
}
/*
* The getter method for managers
*/
/**
* Get the manager for reading and writing players
*
* @param configuration The stats server configuration
* @return The player manager
*/
public PlayerManager getPlayerManager(StatsConfiguration configuration) {
if (playerManager == null) {
PlayerDAO playerDAO = getPlayerDAO(configuration);
playerManager = new PlayerManager(playerDAO);
}
return playerManager;
}
/**
* Get the manager for business logic around games
*
* @param configuration The stats server configuration
* @return The game manager
*/
public GameManager getGameManager(StatsConfiguration configuration) {
if (gameManager == null) {
GameDAO gameDAO = getGameDAO(configuration);
gameManager = new GameManager(gameDAO);
}
return gameManager;
}
/**
* Get the manager fro business logic around stats
*
* @param configuration The stats server configuration
* @return The stats manager
*/
public StatsManager getStatsManager(StatsConfiguration configuration) {
if (statsManager == null) {
StatsDAO statsDAO = getStatsDAO(configuration);
statsManager = new StatsManager(statsDAO);
}
return statsManager;
}
/**
* Get the manager for handling imports
*
* @param configuration The stats server configuration
* @return The impor manager
*/
public ImportManager getImportManager(StatsConfiguration configuration) {
if (importManager == null) {
ImportDAO importDAO = getImportDAO(configuration);
importManager = new ImportManager(importDAO);
}
return importManager;
}
public PredictionManager getPredictionManager(StatsConfiguration configuration) {
if (predictionManager == null) {
PredictionDAO predictionDAO = getPredictionDAO(configuration);
StatsManager statsManager = getStatsManager(configuration);
ImportManager importManager = getImportManager(configuration);
predictionManager = new PredictionManager(predictionDAO, statsManager, importManager);
}
return predictionManager;
}
/*
* The getter method for DAOs
*/
/**
* Get the player DAO
*
* @param configuration The stats server configuration
* @return The player DAO
*/
public MySQLPlayerDAO getPlayerDAO(StatsConfiguration configuration) {
if (playerDAO == null) {
DataSource stats = getStatsDataSource(configuration);
playerDAO = new MySQLPlayerDAO(stats);
}
return playerDAO;
}
/**
* Get the game DAO
*
* @param configuration The stats server configuration
* @return The game DAO
*/
public GameDAO getGameDAO(StatsConfiguration configuration) {
if (gameDAO == null) {
gameDAO = new MySQLGameDAO(getStatsDataSource(configuration));
}
return gameDAO;
}
/**
* Get the stats DAO
*
* @param configuration The stats server configuration
* @return The stats DAO
*/
public StatsDAO getStatsDAO(StatsConfiguration configuration) {
if (statsDAO == null) {
statsDAO = new MySQLStatsDAO(getStatsDataSource(configuration));
}
return statsDAO;
}
/**
* Get the import DAO
*
* @param configuration The stats server configuration
* @return The import DAO
*/
public ImportDAO getImportDAO(StatsConfiguration configuration) {
if (importDAO == null) {
importDAO = new MySQLImportDAO(getStatsDataSource(configuration));
}
return importDAO;
}
/**
* Get the prediction DAO
*
* @param configuration The stats server configuration
* @return The prediction DAO
*/
public PredictionDAO getPredictionDAO(StatsConfiguration configuration) {
if (predictionDAO == null) {
predictionDAO = new MySQLPredictionDAO(getStatsDataSource(configuration));
}
return predictionDAO;
}
/*
* The getter methods for helper classes
*/
/**
* Get the game file reader
* @return The game file reader
*/
public GameFileReader getGameFileReader() {
if (gameFileReader == null) {
gameFileReader = new GameFileReader(getObjectMapper());
}
return gameFileReader;
}
/**
* Get the stats database data source
*
* @param configuration The stats server configuration
* @return The stats database data source
*/
public DataSource getStatsDataSource(StatsConfiguration configuration) {
if (statsDataSource == null) {
statsDataSource = configuration.getDataSourceFactory().build(new MetricRegistry(), "stats");
}
return statsDataSource;
}
/**
* Get the obejct mapper
*
* @return The object mapper
*/
public ObjectMapper getObjectMapper() {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
return objectMapper;
}
/**
* The NFL service object
*
* @return THe NFL service object
*/
public NflService getNflService() {
if (nflService == null) {
nflService = new NflService(ClientBuilder.newClient());
}
return nflService;
}
/**
* Get the naive average helper
*
* @param configuration The stats server configuration
* @return The naive average helper
*/
public NaiveAverageHelper getNaiveAverageHelper(StatsConfiguration configuration) {
if (naiveAverageHelper == null) {
naiveAverageHelper = new NaiveAverageHelper(
getPlayerManager(configuration),
getStatsManager(configuration)
);
}
return naiveAverageHelper;
}
/**
* Get the qualifying average helper
*
* @param configuration The stats server configuration
* @return The qualifying average helper
*/
public QualifyingAverageHelper getQualifyingAverageHelper(QualifyingNumbersHelper qualifyingNumbersHelper, StatsConfiguration configuration) {
if (qualifyingAverageHelper == null) {
qualifyingAverageHelper = new QualifyingAverageHelper(
getPlayerManager(configuration),
getStatsManager(configuration),
qualifyingNumbersHelper
);
}
return qualifyingAverageHelper;
}
}
| true |
827bf0ff8575bc72092eb2fe5b329b3bfecf9e18 | Java | Mcpwko/Smartphone | /ProjetSmartphone/src/Gallery.java | UTF-8 | 14,928 | 2.796875 | 3 | [] | no_license | import net.miginfocom.swing.MigLayout;
import org.apache.commons.io.FileUtils;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* <p> Classe qui gère les dispositions et les paramètres de l'application Gallery</p>
* @author Mickaël Puglisi
* @version 2.0
*/
public class Gallery extends JPanel implements ActionListener {
/**
* <p> Objet ButtonWithIcon qui ajoute le bouton permettant d'ajouter une image</p>
*/
private ButtonWithIcon addphoto = new ButtonWithIcon(".//images//addphoto.png");
/**
* <p> Pannel qui crée un panneau au sud</p>
*/
private JPanel southpanel1 = new JPanel();
/**
* <p> Panel principal où sont affichés les images</p>
*/
private JPanel panelPictures = new JPanel();
/**
* <p> Le Cardlayout qui permet de changer de panel</p>
*/
private CardLayout cardLayout = new CardLayout();
/**
* <p> Pannel qui s'affiche lorsqu'une image est sélectionnée</p>
*/
private JPanel panel1 = new JPanel();
/**
* <p> Objet JScrollPane qui ajoute une barre de défilement</p>
*/
private JScrollPane scrollPane = new JScrollPane(panelPictures);
/**
* <p> Objet JFileChooser qui demande à l'utilisateur de rajouter une image</p>
*/
private JFileChooser fileChooser = new JFileChooser();
/**
* <p> Panel qui gère le mouvement entre les panels principaux</p>
*/
private JPanel panelcont = new JPanel();
/**
* <p> Panel se trouvant au sud pour ajouter une photo </p>
*/
private JPanel south = new JPanel();
/**
* <p> Crée le bouton previous </p>
*/
private ButtonWithIcon previous = new ButtonWithIcon(".//images//previousApp.png");
/**
* <p> Panneau qui s'ajoute lorsqu'une image est sélectionnée</p>
*/
private JPanel northSelectedPicture = new JPanel();
/**
* <p> Crée ke bouton de suppression d'image</p>
*/
private JButton deletePicture = new JButton("Delete");
/**
* <p> Objet JOptionPane qui demande à l'utilisateur de valider la suppression</p>
*/
private JOptionPane deletePermanent = new JOptionPane();
/**
* <p> Titre de l'application</p>
*/
private JLabel titre = new JLabel("Photos");
/**
* <p> Objet de type File qui donne la localisation des images enregistrées</p>
*/
private File monRepertoire=new File("Gallery");
/**
* <p> Panel qui s'affiche lorsqu'une image est sélectionnée</p>
*/
private JPanel selectedPicture = new JPanel();
/**
* <p> Appel l'image et la redimensionne</p>
* @see JLabelPictureSelected
*/
private JLabelPictureSelected image;
/**
* <p> Constructeur qui gère le positionnement des éléments déclarés</p>
* @throws IOException
*/
public Gallery() throws IOException {
setBackground(Color.BLACK);
setLayout(new BorderLayout());
add(panelcont,BorderLayout.CENTER);
panelcont.setBackground(Color.BLACK);
add(south,BorderLayout.SOUTH);
south.setLayout(new FlowLayout(FlowLayout.CENTER));
south.setBackground(Color.BLACK);
panelcont.setLayout(cardLayout);
panelcont.add(panel1,"1");
panel1.setBackground(Color.BLACK);
panel1.setLayout(new BorderLayout());
panel1.add(titre,BorderLayout.NORTH);
titre.setForeground(Color.WHITE);
titre.setFont(new Font("Arial", Font.BOLD,40));
panel1.add(southpanel1,BorderLayout.SOUTH);
southpanel1.add(addphoto);
southpanel1.setBackground(Color.black);
scrollPane.setBorder((BorderFactory.createLineBorder(Color.BLACK, 1)) );
scrollPane.setBackground(Color.BLACK);
addphoto.addActionListener(this);
scrollPane.setViewportView(panelPictures);
panel1.add(scrollPane);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panelPictures.setLayout(new MigLayout());
panelPictures.setBackground(Color.BLACK);
scrollPane.getVerticalScrollBar().setUnitIncrement(100);
northSelectedPicture.setLayout(new BorderLayout());
northSelectedPicture.setBackground(Color.BLACK);
selectedPicture.setLayout(new BorderLayout());
northSelectedPicture.add(previous,BorderLayout.WEST);
previous.addActionListener(this);
northSelectedPicture.add(deletePicture,BorderLayout.EAST);
deletePicture.setContentAreaFilled(false);
deletePicture.setBorderPainted(false);
deletePicture.addActionListener(this);
deletePicture.setForeground(Color.WHITE);
deletePicture.setFont((new Font("Arial",Font.BOLD,20)));
initComponentPictures();
}
/**
* @return panelPictures
*/
public JPanel getPanelPictures() {
return panelPictures;
}
/**
* @return panelcont
*/
public JPanel getPanelcont(){
return panelcont;
}
/**
* @return cardLayout
*/
public CardLayout getCardLayout() {
return cardLayout;
}
/**
* @throws IOException
* <p> Méthode qui lit les images stockées</p>
*/
//initialiser les composants
private void initComponentPictures() throws IOException {
File [] f = monRepertoire.listFiles();
for(int i =0; i< f.length; i++){
System.out.println("Chargement de l'image : " + i);
//ButtonWithIcon button = new ButtonWithIcon ( "Gallery\\" + i +".jpg" );
JButton button = new JButton ( );
Image img = null;
try {
img = ImageIO.read(new File ("./Gallery/" + i +".jpg"));
} catch (IOException e) {
e.printStackTrace ();
}
ImageIcon ii = new ImageIcon(img);
ImageIcon iiNew = getScaledImage ( ii,110,110 );
button.setIcon ( iiNew );
button.setMaximumSize(new Dimension(112,112));
button.setMinimumSize(new Dimension(112,112));
if((panelPictures.getComponentCount()+1)%4==0 && panelPictures.getComponentCount()!=0){
button.setActionCommand ( panelPictures.getComponentCount ()+ "" );
panelPictures.add(button,"wrap");
button.addActionListener ( new newImage() );
}
else{
button.setActionCommand ( panelPictures.getComponentCount ()+ "" );
panelPictures.add(button);
button.addActionListener ( new newImage() );
}
}
}
/**
* <p> Méthode qui sauvegarde les nouvelles images</p>
* @param fileNewName
*/
public void addNewScreenshot(String fileNewName){
JButton button = new JButton ( );
Image img = null;
try {
img = ImageIO.read(new File ("./Gallery/" + fileNewName));
} catch (IOException e) {
e.printStackTrace ();
}
ImageIcon ii = new ImageIcon(img);
ImageIcon iiNew = getScaledImage ( ii,110,110 );
button.setIcon ( iiNew );
button.setMaximumSize ( new Dimension ( 112, 112 ) );
button.setMinimumSize ( new Dimension ( 112, 112 ) );
button.setContentAreaFilled(false);
button.setBorderPainted(false);
if ((panelPictures.getComponentCount () + 1) % 4 == 0 && panelPictures.getComponentCount () != 0) {
button.setActionCommand ( "" + panelPictures.getComponentCount () );
panelPictures.add ( button, "wrap" );
} else {
button.setActionCommand ( "" + panelPictures.getComponentCount () );
panelPictures.add ( button );
}
button.addActionListener ( new Gallery.newImage () );
panelPictures.revalidate ();
panelPictures.repaint ( );
}
/**
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
System.out.println ( "J'ai appuyé sur l'image : " + e.getActionCommand () );
if (e.getSource () == addphoto) {
int returnVal = fileChooser.showOpenDialog ( this );
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile ();
File destination = new File ( ".\\Gallery\\" + panelPictures.getComponentCount () + ".jpg" );
try {
FileUtils.copyFile ( file, destination );
} catch (IOException e1) {
e1.printStackTrace ();
}
String path = file.getAbsolutePath ();
//ImageIcon img = new ImageIcon ( path );
/*ButtonWithIcon button = null;
try {
button = new ButtonWithIcon ( path );
} catch (IOException e1) {
e1.printStackTrace ();
}*/
JButton button = new JButton ( );
Image img = null;
try {
img = ImageIO.read(new File (path));
} catch (IOException e2) {
e2.printStackTrace ();
}
ImageIcon ii = new ImageIcon(img);
ImageIcon iiNew = getScaledImage ( ii,110,110 );
button.setIcon ( iiNew );
button.setMaximumSize ( new Dimension ( 112, 112 ) );
button.setMinimumSize ( new Dimension ( 112, 112 ) );
if ((panelPictures.getComponentCount () + 1) % 4 == 0 && panelPictures.getComponentCount () != 0) {
button.setActionCommand ( "" + panelPictures.getComponentCount () );
panelPictures.add ( button, "wrap" );
} else {
button.setActionCommand ( "" + panelPictures.getComponentCount () );
panelPictures.add ( button );
}
button.addActionListener ( new newImage () );
panelPictures.revalidate ();
System.out.println ( panelPictures.getComponentCount () );
}
} else {
if ( e.getSource () == previous) {
cardLayout.show ( panelcont, "1" );
} else {
if (e.getSource () == deletePicture) {
int newName = Integer.valueOf ( image.getName () );
int rep = deletePermanent.showConfirmDialog ( this, "Do you really want to delete the picture ?",
"Delete", JOptionPane.OK_CANCEL_OPTION );
if (rep == JOptionPane.OK_OPTION) {
//panelcont.remove(panel);
System.out.println ( "J'ai appuyé sur OK" );
System.out.println("J'ai supprimé l'image : " + image.getName ());
File file = new File ( ".//Gallery//" + image.getName () + ".jpg" );
file.delete ();
boolean exists = file.exists();
System.out.println(exists);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for (int i = Integer.valueOf ( newName ) + 1; i < panelPictures.getComponentCount (); i++) {
File fileName = new File ( ".//Gallery//" + i + ".jpg" );
File fileNewName = new File ( ".//Gallery//" + (i - 1) + ".jpg" );
System.out.println("Le nouveau nom des images : " + fileNewName.getName ());
fileName.renameTo ( fileNewName );
}
cardLayout.show ( panelcont, "1" );
panelPictures.removeAll ();
System.out.println("Nombre de composants : " +panelPictures.getComponentCount ());
try {
initComponentPictures();
} catch (IOException e1) {
e1.printStackTrace ();
}
}
}
}
}
}
/**
* <p> Gère le placement d'une nouvelle image dans l'application</p>
*/
class newImage implements ActionListener{
/**
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
selectedPicture.removeAll();
System.out.println(".//Gallery//"+(e.getActionCommand())+".jpg");
try {
image = new JLabelPictureSelected(".//Gallery//"+(e.getActionCommand())+".jpg");
} catch (IOException e1) {
e1.printStackTrace();
}
image.setName(e.getActionCommand());
System.out.println(image.getName());
selectedPicture.add(image,BorderLayout.CENTER);
selectedPicture.add(northSelectedPicture,BorderLayout.NORTH);
selectedPicture.revalidate();
selectedPicture.repaint();
panelcont.add(selectedPicture, "2" );
cardLayout.show(panelcont, "2");
}
}
/**
* <p> Méthode permettant de redimensionner une image</p>
* @param srcImg
* @param w
* @param h
* @return ImageIcon
*/
private ImageIcon getScaledImage(ImageIcon srcImg, int w, int h){
Image img = srcImg.getImage();
int width = img.getWidth(null);
int height = img.getHeight(null);
System.out.println(height + " ET " + width);
if(width >=480 || height>=700) {
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return new ImageIcon(resizedImg);
}else
return new ImageIcon(img);
}
/**
* <p> Classe qui gère la dimension d'une image sélectionnée</p>
*/
class JLabelPictureSelected extends JLabel{
/**
* @param icon
* @throws IOException
*/
public JLabelPictureSelected(String icon) throws IOException {
Image img = ImageIO.read(new File (icon));
ImageIcon ii = new ImageIcon(img);
ImageIcon ii2 = getScaledImage(ii,480,700);
setIcon(ii2);
}
}
}
| true |
ceda4b42434ec8d7a2a05e21351d38dcd5f9b892 | Java | sittingonunicorn/Purchasing | /src/main/java/com/test/purchasing/model/entity/Discount.java | UTF-8 | 568 | 2.140625 | 2 | [] | no_license | package com.test.purchasing.model.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "discount",
uniqueConstraints = {@UniqueConstraint(columnNames = {"percent", "discount_id"})})
public class Discount {
@Id
@GeneratedValue
@Column(name = "discount_id", nullable = false)
private Long id;
@Column(name = "percent", nullable = false)
private Integer percent;
}
| true |
94a52b093ef7d740764a5eed7a6f9c42856d017f | Java | mikeb01/scratch | /java/risk/src/main/java/org/sample/enums/TestEnum.java | UTF-8 | 158 | 1.992188 | 2 | [
"CC0-1.0"
] | permissive | package org.sample.enums;
public enum TestEnum
{
A, B, C, D, E;
public static final Enum<TestEnum>[] enums = TestEnum.class.getEnumConstants();
}
| true |
17826575def957915b019d4d6eeb4b7bd984cfa7 | Java | imazjav0017/RentTest | /app/src/main/java/com/rent/rentmanagement/renttest/Adapters/TotalTenantsAdapter.java | UTF-8 | 3,412 | 2.109375 | 2 | [] | no_license | package com.rent.rentmanagement.renttest.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.rent.rentmanagement.renttest.DataModels.RoomModel;
import com.rent.rentmanagement.renttest.R;
import com.rent.rentmanagement.renttest.DataModels.StudentModel;
import com.rent.rentmanagement.renttest.studentProfile;
import java.util.ArrayList;
import java.util.List;
/**
* Created by imazjav0017 on 17-03-2018.
*/
public class TotalTenantsAdapter extends RecyclerView.Adapter<TotalTenantsAdapter.TotalTenantsHolder> {
List<StudentModel> studentModels;
public TotalTenantsAdapter(List<StudentModel> studentModels) {
this.studentModels = studentModels;
}
@Override
public TotalTenantsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.total_students,parent,false);
return new TotalTenantsHolder(v);
}
@Override
public void onBindViewHolder(final TotalTenantsHolder holder, int position) {
final StudentModel model=studentModels.get(position);
holder.studentName.setText(model.getName());
holder.phNo.setText("Room No "+model.getRoomNo());
holder.call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:"+model.getPhNo()));
holder.context.startActivity(i);
}
});
holder.rl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(holder.context,studentProfile.class);
i.putExtra("name",model.getName());
i.putExtra("id",model.get_id());
i.putExtra("roomNo",model.getRoomNo());
i.putExtra("aadharNo",model.getAadharNo());
i.putExtra("phNo",model.getPhNo());
i.putExtra("total",true);
holder.context.startActivity(i);
}
});
}
@Override
public int getItemCount() {
return studentModels.size();
}
public void setFilter(List<StudentModel> filteredList)
{
studentModels=new ArrayList<>();
studentModels.addAll(filteredList);
notifyDataSetChanged();
}
/**
* Created by imazjav0017 on 17-03-2018.
*/
public static class TotalTenantsHolder extends RecyclerView.ViewHolder {
TextView studentName,phNo;
Button call;
Context context;
RelativeLayout rl;
public TotalTenantsHolder(View itemView) {
super(itemView);
studentName=(TextView)itemView.findViewById(R.id.studentNameTextView2);
phNo=(TextView)itemView.findViewById(R.id.studentPhoneNumber2);
call=(Button)itemView.findViewById(R.id.callButton1);
rl=(RelativeLayout)itemView.findViewById(R.id.viewDetailsRl);
context=itemView.getContext();
}
}
}
| true |
370313221466971a03cf52ea9ebb86148d085fdd | Java | zy136946818/user-center | /user-center-api/src/main/java/com/study/util/FormatUtil.java | UTF-8 | 888 | 2.75 | 3 | [] | no_license | package com.study.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author zhangYu
* @Date 2021/4/7 9:33
*/
public class FormatUtil {
//判断是否为邮箱
public static boolean isMailFormat(String mail){
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern mailRegex = Pattern.compile(check);
Matcher matcher = mailRegex.matcher(mail);
return matcher.matches();
}
//判断是否为手机
public static boolean isPhoneFormat(String phone){
boolean flag2 = false;
Pattern phoneRegex = Pattern.compile("^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
"|(18[0-9])|(19[8,9]))\\d{8}$"); // 验证手机号
Matcher m = phoneRegex.matcher(phone);
return m.matches()||flag2;
}
}
| true |
3612060d5113c9d740ff577eb6f31ca75d817836 | Java | pxbachs/shpman | /shopman/meruocshop/android/version100/src/com/machine/shop/adapter/AlbumAdapter.java | UTF-8 | 4,754 | 2.09375 | 2 | [] | no_license | //package com.machine.shop.adapter;
//
//import java.io.File;
//
//import android.app.Activity;
//import android.content.Context;
//import android.content.Intent;
//import android.net.Uri;
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.View.OnClickListener;
//import android.view.ViewGroup;
//import android.widget.BaseAdapter;
//import android.widget.RelativeLayout;
//
//import com.androidquery.AQuery;
//import com.machine.shop.R;
//
//public class AlbumAdapter extends BaseAdapter implements OnClickListener {
// private Context context;
// private LayoutInflater inflater;
//
// private News mCurrentNews;
// private NewsImage[] mNewsImages;
//
// private View[] mView;
// private View mCover;
//
// public AlbumAdapter(Context context, News currentNews) {
// this.context = context;
// this.inflater = LayoutInflater.from(context);
// this.mCurrentNews = currentNews;
// this.mNewsImages = mCurrentNews.getImages();
// mView = new View[mNewsImages.length];
// }
//
// @Override
// public int getCount() {
// return this.mNewsImages.length + 2;
// }
//
// @Override
// public Object getItem(int position) {
// return this.mNewsImages[position-1];
// }
//
// @Override
// public long getItemId(int position) {
// return this.mNewsImages[position - 1].getId();
// }
//
// @Override
// public int getViewTypeCount() {
// return 2;
// }
// @Override
// public int getItemViewType(int position) {
// if (position == 0 || position == this.mNewsImages.length + 1) return 0;
// return 1;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// if (position == 0 || position == this.mNewsImages.length + 1) {
// if (mCover == null) {
// mCover = inflater.inflate(R.layout.cover_page, null);
// }
// return mCover;
// }
//
// int aCurrentPosition = position - 1;
//
// View view = null;
// if (mView[aCurrentPosition] == null) {
// mView[aCurrentPosition] = inflater.inflate(R.layout.layout_album, parent, false);
// }
//
// view = mView[aCurrentPosition];
//
// // if(view == null) view = inflater.inflate(R.layout.layout_album,
// // parent, false);
//
// AQuery aq = new AQuery(view);
//
// // aq.id(R.id.album_image_item).image(mNewsImages[position].getUrl());
// if (mNewsImages[aCurrentPosition].isFullScreen()) {
// aq.id(R.id.album_image_item).getImageView().setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
// aq.id(R.id.album_image_item).getImageView().setScaleType(android.widget.ImageView.ScaleType.CENTER_CROP);
// }
//
// aq.id(R.id.album_image_item).image(mNewsImages[aCurrentPosition].getUrl(), false, true, 0, 0, null, 0);
// aq.id(R.id.album_header_name).text("Ảnh " + (aCurrentPosition + 1) + "/" + mNewsImages.length);
//
// aq.id(R.id.album_header_name).clicked(this);
// aq.id(R.id.button_back).clicked(this);
// aq.id(R.id.button_share).clicked(this);
// aq.id(R.id.album_image_item).clicked(this);
// return view;
// }
//
// AQuery aq = new AQuery(this.context);
// private int mCurrentPosition;
//
// public void setCurrentPosition(int position) {
// mCurrentPosition = position - 1;
// // Preload next image
// if (mCurrentPosition + 1 < mNewsImages.length) {
// if (aq.getCachedFile(mNewsImages[mCurrentPosition + 1].getUrl()) == null) {
// aq.cache(mNewsImages[mCurrentPosition + 1].getUrl(), 0);
// }
// }
// }
//
// @Override
// public void onClick(View v) {
// if (v.getId() == R.id.button_back) {
// ((Activity) this.context).onBackPressed();
// } else if (v.getId() == R.id.button_share) {
// File file = aq.makeSharedFile(mNewsImages[mCurrentPosition].getUrl(), "tin59s_shared_image.jpg");
//
// if (file != null) {
// Intent intent = new Intent(Intent.ACTION_SEND);
// intent.setType("image/jpeg");
// intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
// ((Activity) this.context).startActivityForResult(Intent.createChooser(intent, this.context.getResources().getString(R.string.share_image)), Activity.RESULT_CANCELED);
// }
// } else if (v.getId() == R.id.album_header_name) {
// } else if (v.getId() == R.id.album_image_item) {
// // show zoom activity
// Intent intent = new Intent(context, ImageZoomActivity.class);
// intent.putExtra("current_url", "file://" + mNewsImages[mCurrentPosition].getCachedUrl());
// context.startActivity(intent);
// }
// }
//
// public void onDestroy() {
// mView = null;
// mCurrentNews = null;
// mNewsImages = null;
// inflater = null;
// System.gc();
// }
//
//}
| true |
48e2c3cd3710a114896f0ab03fdeda5bbcf52601 | Java | cytcool/TodayInformation | /task/src/main/java/com/cyt/task/TaskThreadFactory.java | UTF-8 | 253 | 2.234375 | 2 | [] | no_license | package com.cyt.task;
import java.util.concurrent.ThreadFactory;
public class TaskThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable runnable) {
return new Thread(runnable,"task_thread_pool");
}
}
| true |
5a1b2a279df5ae144162c5643e05efc3aa52a925 | Java | JavaPathFinderExtensions/jpf-cool-search-strategies | /src/main/gov/nasa/jpf/search/DynamicPriorityVMState.java | UTF-8 | 1,918 | 2.96875 | 3 | [] | no_license | package gov.nasa.jpf.search;
import gov.nasa.jpf.vm.RestorableVMState;
import gov.nasa.jpf.vm.ThreadInfo;
import gov.nasa.jpf.vm.VM;
import java.util.Random;
public class DynamicPriorityVMState implements Comparable<DynamicPriorityVMState>{
protected RestorableVMState vmState;
protected int stateId;
protected int priority;
protected ThreadInfo threadInfo;
public DynamicPriorityVMState (VM vm, int priority) {
stateId = vm.getStateId();
vmState = vm.getRestorableState();
threadInfo = vm.getCurrentThread();
this.priority = priority;
}
public RestorableVMState getVMState () {
return vmState;
}
public int getStateId() {
return stateId;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
@Override
public int compareTo(DynamicPriorityVMState o)
{
if (this.getPriority() < o.getPriority()) {
return -1;
}
if (this.getPriority() > o.getPriority()) {
return 1;
}
int rand = new Random().nextInt(2);
if (rand == 0) {
return 1;
}
else {
return -1;
}
}
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
/* Check if o is an instance of Complex or not
"null instanceof [type]" also returns false */
if (!(o instanceof DynamicPriorityVMState)) {
return false;
}
// typecast o to Complex so that we can compare data members
DynamicPriorityVMState c = (DynamicPriorityVMState) o;
// Compare the data members and return accordingly
return this.threadInfo.equals(c.threadInfo);
}
}
| true |
441a8e3a49bae71d95a418baee0a75949f4b1e44 | Java | LeeKamentsky/imglib | /imglib2/core/src/main/java/net/imglib2/roi/BinaryMaskRegionOfInterest.java | UTF-8 | 9,215 | 1.984375 | 2 | [
"BSD-2-Clause"
] | permissive | /*
* #%L
* ImgLib2: a general-purpose, multidimensional image processing library.
* %%
* Copyright (C) 2009 - 2012 Stephan Preibisch, Stephan Saalfeld, Tobias
* Pietzsch, Albert Cardona, Barry DeZonia, Curtis Rueden, Lee Kamentsky, Larry
* Lindsey, Johannes Schindelin, Christian Dietz, Grant Harris, Jean-Yves
* Tinevez, Steffen Jaensch, Mark Longair, Nick Perry, and Jan Funke.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package net.imglib2.roi;
import java.util.Iterator;
import net.imglib2.AbstractCursor;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import net.imglib2.IterableRealInterval;
import net.imglib2.Positionable;
import net.imglib2.RandomAccess;
import net.imglib2.RandomAccessible;
import net.imglib2.RealPositionable;
import net.imglib2.img.Img;
import net.imglib2.type.Type;
import net.imglib2.type.logic.BitType;
/**
* TODO
*
* @author Stephan Saalfeld
* @author Lee Kamentsky
* @author leek
*/
public class BinaryMaskRegionOfInterest<T extends BitType, I extends Img<T>> extends
AbstractRegionOfInterest implements IterableRegionOfInterest {
final I img;
/*
* One RandomAccess per thread so that the thread can call setPosition.
*/
final ThreadLocal<RandomAccess<T>> randomAccess;
long cached_size = -1;
long [] firstPosition;
long [] minima;
long [] maxima;
protected class BMROIIterationOrder
{
protected I getImg() {
return img;
}
@Override
public boolean equals( final Object obj )
{
if ( ! ( obj instanceof BinaryMaskRegionOfInterest.BMROIIterationOrder ) )
return false;
@SuppressWarnings( "unchecked" )
final BMROIIterationOrder o = ( BMROIIterationOrder )obj;
return o.getImg() == getImg();
}
}
protected class BMROIIterableInterval<TT extends Type<TT>> implements IterableInterval<TT> {
final RandomAccess<TT> src;
/**
* The cursor works by managing a cursor from the original image. It
* advances the underlying cursor to the next true position
* with each fwd() step.
*/
protected class BMROICursor extends AbstractCursor<TT> {
boolean nextIsValid;
boolean cursorHasNext;
Cursor<T> cursor;
final long [] position;
protected BMROICursor() {
super(BMROIIterableInterval.this.numDimensions());
cursor = img.localizingCursor();
position = new long[BMROIIterableInterval.this.numDimensions()];
}
@Override
public TT get() {
src.setPosition(this);
return src.get();
}
@Override
public void fwd() {
validateNext();
cursor.localize(position);
nextIsValid = false;
}
@Override
public void reset() {
cursor.reset();
nextIsValid = false;
}
@Override
public boolean hasNext() {
validateNext();
return cursorHasNext;
}
@Override
public void localize(long[] position) {
System.arraycopy(this.position, 0, position, 0, numDimensions());
}
@Override
public long getLongPosition(int d) {
return this.position[d];
}
@Override
public AbstractCursor<TT> copy() {
return copyCursor();
}
@Override
public AbstractCursor<TT> copyCursor() {
BMROICursor c = new BMROICursor();
c.cursor = cursor.copyCursor();
System.arraycopy(position, 0, c.position, 0, numDimensions());
c.nextIsValid = nextIsValid;
return c;
}
private void validateNext() {
if (! nextIsValid) {
while(cursor.hasNext()) {
if (cursor.next().get()) {
nextIsValid = true;
cursorHasNext = true;
return;
}
}
nextIsValid = true;
cursorHasNext = false;
}
}
}
protected BMROIIterableInterval(final RandomAccess<TT> src) {
this.src = src;
}
@Override
public long size() {
return getCachedSize();
}
@Override
public TT firstElement() {
src.setPosition(getFirstPosition());
return src.get();
}
@Override
public Object iterationOrder()
{
return new BMROIIterationOrder();
}
@Override
public boolean equalIterationOrder(final IterableRealInterval<?> f) {
return iterationOrder().equals( f.iterationOrder() );
}
@Override
public double realMin(int d) {
return img.realMin(d);
}
@Override
public void realMin(double[] min) {
img.realMin(min);
}
@Override
public void realMin(RealPositionable min) {
img.realMin(min);
}
@Override
public double realMax(int d) {
return img.realMax(d);
}
@Override
public void realMax(double[] max) {
img.realMax(max);
}
@Override
public void realMax(RealPositionable max) {
img.realMax(max);
}
@Override
public int numDimensions() {
return BinaryMaskRegionOfInterest.this.numDimensions();
}
@Override
public Iterator<TT> iterator() {
return new BMROICursor();
}
@Override
public long min(int d) {
validate();
return minima[d];
}
@Override
public void min(long[] min) {
validate();
System.arraycopy(minima, 0, min, 0, numDimensions());
}
@Override
public void min(Positionable min) {
validate();
min.setPosition( minima );
}
@Override
public long max(int d) {
validate();
return maxima[d];
}
@Override
public void max(long[] max) {
validate();
System.arraycopy(maxima, 0, max, 0, numDimensions());
}
@Override
public void max(Positionable max) {
validate();
max.setPosition( maxima );
}
@Override
public void dimensions(long[] dimensions) {
img.dimensions(dimensions);
}
@Override
public long dimension(int d) {
return img.dimension(d);
}
@Override
public Cursor<TT> cursor() {
return new BMROICursor();
}
@Override
public Cursor<TT> localizingCursor() {
return new BMROICursor();
}
}
public BinaryMaskRegionOfInterest(final I img) {
super(img.numDimensions());
this.img = img;
randomAccess = new ThreadLocal<RandomAccess<T>>() {
/* (non-Javadoc)
* @see java.lang.ThreadLocal#initialValue()
*/
@Override
protected RandomAccess<T> initialValue() {
return img.randomAccess();
}
};
}
@Override
public <TT extends Type<TT>> IterableInterval<TT> getIterableIntervalOverROI(
RandomAccessible<TT> src) {
return new BMROIIterableInterval<TT>(src.randomAccess());
}
/* (non-Javadoc)
* @see net.imglib2.roi.AbstractRegionOfInterest#isMember(double[])
*/
@Override
protected boolean isMember(double[] position) {
/*
* Quantize by nearest-neighbor (-0.5 < x < 0.5)
*/
validate();
for (int i=0; i<numDimensions(); i++) {
long lPosition = Math.round(position[i]);
if ((lPosition < minima[i]) || (lPosition > maxima[i]))
return false;
randomAccess.get().setPosition(lPosition, i);
}
return randomAccess.get().get().get();
}
@Override
protected void getRealExtrema(double[] minima, double[] maxima) {
validate();
for (int i=0; i<numDimensions(); i++) {
minima[i] = this.minima[i];
maxima[i] = this.maxima[i];
}
}
/**
* Scan the image, counting bits once, then return the cached value.
* @return
*/
protected long getCachedSize() {
validate();
return cached_size;
}
protected long [] getFirstPosition() {
validate();
return firstPosition;
}
protected void validate() {
if (cached_size == -1) {
cached_size = 0;
minima = new long [numDimensions()];
maxima = new long [numDimensions()];
Cursor<T> c = img.localizingCursor();
while(c.hasNext()) {
if (c.next().get()) {
cached_size = 1;
firstPosition = new long[numDimensions()];
c.localize(firstPosition);
c.localize(minima);
c.localize(maxima);
break;
}
}
while(c.hasNext()) {
if (c.next().get()) {
cached_size++;
for (int i=0; i<numDimensions(); i++) {
long pos = c.getLongPosition(i);
minima[i] = Math.min(minima[i], pos);
maxima[i] = Math.max(maxima[i], pos);
}
}
}
}
}
}
| true |
ead57bb5419aaf5f2ea1931b2522bdc879271361 | Java | Tuco98/PG3 | /NSP/src/main/java/com/lti/dto/InsLoginStatus.java | UTF-8 | 394 | 1.953125 | 2 | [] | no_license | package com.lti.dto;
public class InsLoginStatus extends Status {
private long instituteId;
private String insName;
public long getInstituteId() {
return instituteId;
}
public void setInstituteId(long instituteId) {
this.instituteId = instituteId;
}
public String getInsName() {
return insName;
}
public void setInsName(String insName) {
this.insName = insName;
}
}
| true |
593c3ee11da64e0b1aeda50a53dc381947786274 | Java | tandvu/jbpm-msco-client | /src/main/java/com/msco/mil/client/GreetingServiceAsync.java | UTF-8 | 1,535 | 1.984375 | 2 | [] | no_license | package com.msco.mil.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.msco.mil.shared.MyDeployment;
public interface GreetingServiceAsync {
/**
* GWT-RPC service asynchronous (client-side) interface
*
* @see com.msco.mil.client.GreetingService
*/
void getDeployments(AsyncCallback<java.util.List<MyDeployment>> callback);
void getProcessInstances(Integer status, AsyncCallback<java.util.List<com.msco.mil.shared.MyProcessInstance>> callback);
void getTasks(AsyncCallback<java.util.List<com.msco.mil.shared.Task>> callback);
void getActors(AsyncCallback<java.util.List<com.msco.mil.shared.Actor>> callback);
/**
* GWT-RPC service asynchronous (client-side) interface
*
* @see com.msco.mil.client.GreetingService
*/
void undeploy(java.lang.String deploymentIdentifier, AsyncCallback<java.lang.String> callback);
/**
* Utility class to get the RPC Async interface from client-side code
*/
public static final class Util {
private static GreetingServiceAsync instance;
public static final GreetingServiceAsync getInstance() {
if (instance == null) {
instance = (GreetingServiceAsync) GWT.create(GreetingService.class);
}
return instance;
}
private Util() {
// Utility class should not be instanciated
}
}
}
| true |
62cbee5d9d0d026b7125b5bb3aafb37d01d393fc | Java | ozdemiryuksel/Spring2020_B20 | /src/day35_ArrayList/ArrayListMethods.java | UTF-8 | 1,376 | 3.546875 | 4 | [] | no_license | package day35_ArrayList;
import java.util.ArrayList;
public class ArrayListMethods {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("yuksel");
list.add("ali");
list.add("veli");
list.add("deli");
list.add("ahmet");
list.set(2,"mahmut");
list.set(0,"hasan");
System.out.println(list);
list.clear();
System.out.println(list);
System.out.println(list.size());
System.out.println("\n----------------\n");
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(1);
list2.add(2);
list2.add(3);
list2.add(4);
list2.add(5);
System.out.println(list2);
list2.remove(2);
System.out.println(list2);
list2.remove(2);
System.out.println(list2);
Integer a = 1;
list2.remove(a);
System.out.println(list2);
System.out.println("\n----------------\n");
ArrayList<String> list3 = new ArrayList<>();
list3.add("ali");
list3.add("veli");
list3.add("deli");
list3.add("hasan");
list3.add("ahmet");
System.out.println(list3);
list3.remove(2);
System.out.println(list3);
list3.remove("ali");
System.out.println(list3);
}
}
| true |
4f3e7225ca309cd3c9d0f8c1b883a69ad99d4f7e | Java | Bubba74/LWJGL-Testing | /Boundaries.java | UTF-8 | 5,744 | 2.71875 | 3 | [] | no_license | import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_MODELVIEW;
import static org.lwjgl.opengl.GL11.GL_PROJECTION;
import static org.lwjgl.opengl.GL11.GL_QUADS;
import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glClear;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glMatrixMode;
import static org.lwjgl.opengl.GL11.glOrtho;
import static org.lwjgl.opengl.GL11.glVertex2i;
import java.util.Random;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
public class Boundaries {
public static final int WIDTH = 800;
public static final int HEIGHT = 500;
public static int x = 100;
public static int width = 60;
public static int y = 200;
public static int height = 100;
public static int x2 = 0;
public static int y2 = 0;
public static Obstacle objects[];
public static final int X_INC = 5;
public static final int GROUND = 430;
public static boolean up = true;
public static boolean down = true;
public static boolean right = true;
public static boolean left = true;
public static void main (String Args[]){
try {
//initiate display
Display.setDisplayMode(new DisplayMode(WIDTH,HEIGHT));
Display.setTitle("Hello");
Display.setLocation(500, 300);
Display.setInitialBackground(00, 255, 200);
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,800,500,0,1,-1);
glMatrixMode(GL_MODELVIEW);
objects = new Obstacle[1];
objects[0] = new Obstacle();
objects[0].setX(500);
objects[0].setY(200);
objects[0].setWidth(200);
objects[0].setHeight(70);
while (!Display.isCloseRequested()){
//render
//https://www.opengl.org/sdk/docs/man2/
//^^^^good information^^^^//
glClear(GL_COLOR_BUFFER_BIT);
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)){
Display.destroy();
System.exit(0);
}
if (Keyboard.isKeyDown(Keyboard.KEY_UP) && up){
y-=8;
} if (Keyboard.isKeyDown(Keyboard.KEY_DOWN) && down){
y+=10;
} if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT) && right){
x+=X_INC;
} if (Keyboard.isKeyDown(Keyboard.KEY_LEFT) && left){
x-=X_INC;
}
/*
if (Keyboard.isKeyDown(Keyboard.KEY_W)){
if (checkPush("up",200,100)){
if (up){
y-=5;
y2-=5;
} else{
y2+=5;
}
}
y2-=5;
} if (Keyboard.isKeyDown(Keyboard.KEY_S)){
y2+=5;
} if (Keyboard.isKeyDown(Keyboard.KEY_D)){
if (checkPush("right",200,100)) x += X_INC;
x2+=X_INC;
} if (Keyboard.isKeyDown(Keyboard.KEY_A)){
if (checkPush("left",200,100)) x -= X_INC;
x2-=X_INC;
}
*/
if (y<GROUND-height && down) y+=5;
clearDirs();
regularBounds();
// Draw.gingerBreadMan(x, y, 100);
Draw.drawImage(x, y, 100, "GingerbreadMan");//Character
Draw.drawRect(0,WIDTH,HEIGHT-70,70,.5f,.8f,0);//Ground
// Draw.drawRect(x2, 200, y2, 100, .8f, 0, 0);// Obstacle
// checkBoundaries(x2,200,y2,100);
for (int i = 0; i<objects.length;i++){
Draw.drawObstacle(objects[i]);
}
Display.update();
Display.sync(60);
}
Display.destroy();
}//main method
public static boolean checkPush(String dir,int objWidth, int objHeight){
boolean objThere = false;
int halfWidth = objWidth/2;
int halfHeight = objHeight/2;
int lz = 5;
switch(dir){
case "up":
if (isBetween(x,x2+halfWidth,halfWidth+lz) || isBetween(x+width,x2+halfWidth,halfWidth+lz)){
if (isBetween(y+height,y2,lz)){
objThere = true;
}
}
break;
case "down":
break;
case "right":
break;
case "left":
break;
}//switch statement
return objThere;
}//checkPush method
public static void regularBounds(){
if (y <= 0) up = false;//Top of Display
if (y >= GROUND-height) down = false;//Ground of Display
if (x >= WIDTH-60) right = false;//Right side of Display
if (x<=0) left = false; //Left side of Display
}//regularBounds method
public static void checkBoundaries(int locX, int objWidth, int locY, int objHeight){
int lz = 5; //leeway-zone
int halfWidth = objWidth/2;
int halfHeight = objHeight/2;
int centerX = locX+(objWidth/2);
int centerY = locY+(objHeight/2);
if (up){
if (isBetween(x,centerX,halfWidth+lz) || isBetween(x+width,centerX,halfWidth+lz)){
if (isBetween(y,locY+objHeight,lz)) up = false;
}
}
if (down){
if (isBetween(x,centerX,halfWidth+lz) || isBetween(x+width,centerX,halfWidth+lz)){
if (isBetween(y+height,locY,2*lz)) down = false;
}
}
if (isBetween(y,centerY,halfHeight) || isBetween(y+height,centerY,halfHeight) || isBetween(locY,(y+height/2),height/2) || isBetween(locY+objHeight,(y+height/2),height/2)){
if (left){
if (isBetween(x,locX+objWidth,lz)){
left = false;
// print("Left="+left);
}
}
if (right){
if (isBetween(x+width,locX,lz)){
right = false;
// print("Right=" + right);
}
}
}
}//checkBoundaries method
public static void clearDirs(){
up=true;
down=true;
right=true;
left=true;
}//clearDirs method
public static boolean isBetween(int testLoc,int targetLoc,int variation){
boolean isCloseTo = false;
if (targetLoc-variation <= testLoc && testLoc <= targetLoc+variation){
isCloseTo = true;
}
return isCloseTo;
}//isCloseTo method
public static void print(String text){
System.out.println("[INFO]: "+text);
}//print method
}//WindowTest class
| true |
348abe5984c6be1bbd3388df0545f63c90912f93 | Java | YIHANZHOU/MAP_REDUCE_DICTIONARY | /ComputeHandler.java | UTF-8 | 6,461 | 2.609375 | 3 | [] | no_license | import org.apache.thrift.TException;
import java.io.*;
import java.util.*;
import java.lang.Math;
public class ComputeHandler implements Compute.Iface
{
private Double loadProbability;
private long delay;
private int num; // number of total map tasks accepted by this node
private static final Object lock = new Object(); // lock for num
// private int num1; // debug use (count number of injections)
// private static final Object lock1 = new Object(); // debug use (lock for num1)
// Constructor with parameters
ComputeHandler(Double loadProbability, long delay) {
this.loadProbability = loadProbability;
this.delay = delay;
num = 0;
// num1 = 0; // debug
}
@Override
public int handleMap(String inputFile, int policy) {
// based on the policy, determine if reject the task
double randomDouble;
int count; // local count of # of the map task
if(policy == 2) {
// random generate the number to see if is < probability
randomDouble = Math.random(); // [0.0,1.0)
if(randomDouble < loadProbability) { // reject it!
System.out.println(" Reject a map task!!");
return 2;
}
}
synchronized(lock) { // increment the count of map tasks
num++;
count = num;
}
System.out.println("#"+count+" map tasks accepted by this node; filename:"+inputFile);
// based on the probability, determine if inject the delay.
randomDouble = Math.random(); // [0.0,1.0)
if(randomDouble < loadProbability) {
// synchronized(lock1) {
// num1++;
// }
// System.out.println(" Load injection:"+delay+"milliseconds");
try {
Thread.sleep(delay);
} catch (Exception e) {
e.printStackTrace();
return 3;
}
}
// then do the word count and calculate the sentiment score
// define the delimiter
String delimiter = "[^-a-zA-Z]+";
// create the hashset
Set<String> setPositive = new HashSet<>();
Set<String> setNegative = new HashSet<>();
try {
// add the nagative and positive words into the hashset
Scanner scNeg = new Scanner(new File("negative.txt"));
while(scNeg.hasNext()) {
setNegative.add(scNeg.next());
}
Scanner scPos = new Scanner(new File("positive.txt"));
while(scPos.hasNext()) {
setPositive.add(scPos.next());
}
// count the negative and positive word of the input file
Scanner scInput = (new Scanner(new BufferedReader(new FileReader("input_dir/"+inputFile)))).useDelimiter(delimiter);
int countPos = 0;
int countNeg = 0;
while(scInput.hasNext()) {
String words = scInput.next();
String[] word=words.split("--");
for(int i=0;i<word.length;i++){
if(setPositive.contains(word[i].toLowerCase())) {
//System.out.println(word[i].toLowerCase());
countPos++;
}if(setNegative.contains(word[i].toLowerCase())) {
//System.out.println(word.toLowerCase());
countNeg++;
}}
}
// calculate the sentiment score
Double score = (countPos-countNeg+0.0)/(countPos+countNeg);
// generate the intermediate file and store the <filename, score> pair into it
String newFileName = "intermediate_dir/"+"inter_"+inputFile;
File interFile = new File(newFileName);
// create a new file. Overwrite if exist
PrintWriter writer = new PrintWriter(interFile);
// print the <filename:score> pair into the intermediate file
writer.println(inputFile+":"+score);
writer.close();
scNeg.close();
scPos.close();
System.out.println("#"+count+" Map task done!");
}
catch (Exception x) {
System.out.println("Error: executing word counting fail");
return 3; // return fail
}
// job finished return success
return 1;
}
@Override
public String handleSort(String interFileDir) { // return the name of the reuslt file
System.out.println("Sort task received!");
// read info from each intermdediate file into list
File folder = new File(interFileDir); // this is hardcode or pass by parameter?
File[] listOfFiles = folder.listFiles();
if (listOfFiles == null) {
System.out.println("Error message: sort phase - input file dir not exist");
return null;
}
int numOfFiles = 0;
List<Entry> list = new ArrayList<Entry>();
// traverse all the file entries
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
numOfFiles++;
// open this file and read the number
String delimiter = ":";
try {
Scanner sc = (new Scanner(new File("intermediate_dir/"+listOfFiles[i].getName()))).useDelimiter(delimiter);
Entry entry = new Entry(sc.next(), Double.parseDouble(sc.next()));
list.add(entry);
} catch (Exception e) {
System.out.println("Error message: Scan the intermediate files error");
return null;
}
}
}
// sort this list
Collections.sort(list);
// print the result into the result file
String newFileName = "output_dir/result";
File resultFile = new File(newFileName);
try {
// create a new file. Overwrite if exist
PrintWriter writer = new PrintWriter(resultFile);
// print the result into the result file
for(int i=0; i<list.size(); i++) {
// System.out.println(" "+list.get(i).getScore());
writer.println(list.get(i).getFileName()+":"+list.get(i).getScore());
}
writer.close();
} catch(Exception e) {
System.out.println("Error message: writing output file fail");
return null;
}
System.out.println("Sort task done!");
return "output_dir/result";
}
// define structures to prepare for sort()
private class Entry implements Comparable<Entry>{
private String fileName;
private Double score;
public Entry(String fileName, Double score) {
this.fileName = fileName;
this.score = score;
}
// getter and setter
public String getFileName() { return fileName; }
public void setFileName(String fileName) { this.fileName = fileName; }
public Double getScore() { return score; }
public void setScore(Double score) { this.score = score; }
@Override
public int compareTo(Entry en) {
return score < en.getScore() ? 1 : -1;
}
}
}
| true |
3c461bf52c036f631d86bb623e3166ed45a6dec1 | Java | verygreenboi/singletune | /app/src/main/java/com/pixel/singletune/app/fragments/TimelineFragment.java | UTF-8 | 8,861 | 1.820313 | 2 | [] | no_license | package com.pixel.singletune.app.fragments;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.pixel.singletune.app.ParseConstants;
import com.pixel.singletune.app.R;
import com.pixel.singletune.app.SingleTuneApplication;
import com.pixel.singletune.app.adapters.TuneAdapter;
import com.pixel.singletune.app.helpers.TuneDbHelper;
import com.pixel.singletune.app.interfaces.OnFragmentInteractionListener;
import com.pixel.singletune.app.models.Tune;
import com.pixel.singletune.app.subClasses.Tunes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TimelineFragment extends BaseListFragment implements LoaderManager.LoaderCallbacks<Object> {
protected SwipeRefreshLayout.OnRefreshListener OnRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getTunes();
Log.i(TAG, "Has refreshed");
}
};
private JSONArray tuneArray = new JSONArray();
private OnFragmentInteractionListener mListener;
private TuneAdapter adapter;
private List<Tune> mTuneList;
private ParseUser mCurrentUser;
private List<ParseUser> mFriends;
private ParseRelation mFriendRelation;
private String[] tuneQueryIdList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrentUser = ParseUser.getCurrentUser();
getTunes();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
if (!SingleTuneApplication.isTablet(getActivity().getApplicationContext())) {
rootView = inflater.inflate(R.layout.fragment_timeline, container, false);
} else {
rootView = inflater.inflate(R.layout.fragment_timeline_tablet, container, false);
}
getActivity().setProgressBarIndeterminateVisibility(true);
mSwipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(OnRefreshListener);
mSwipeRefreshLayout.setColorScheme(
R.color.swipeRefresh1,
R.color.swipeRefresh2,
R.color.swipeRefresh3,
R.color.swipeRefresh4
);
Log.i(TAG, "onCreateView");
return rootView;
}
@Override
public void onResume(){
super.onResume();
// Get tunes
tuneContentQuery();
ArrayList<Tune> t = Tune.fromJson(tuneArray);
adapter = new TuneAdapter(getActivity().getApplicationContext(), t);
setListAdapter(adapter);
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public Loader<Object> onCreateLoader(int i, Bundle bundle) {
return null;
}
@Override
public void onLoadFinished(Loader<Object> objectLoader, Object o) {
}
@Override
public void onLoaderReset(Loader<Object> objectLoader) {
}
private void getTunes() {
long mTuneCount = Tune.count(Tune.class, null, null);
String tuneCreatedAt = null;
if (mTuneCount > 0){
List<Tune> l = Tune.findWithQuery(Tune.class, "select * from Tune order by id desc limit ?", "1");
for (Tune lT : l){
tuneCreatedAt = lT.getCreatedAt();
}
selectFriends();
ParseQuery<Tunes> query = ParseQuery.getQuery(Tunes.class);
query.addDescendingOrder(ParseConstants.KEY_CREATED_AT);
query.whereGreaterThan("createdAt", tuneCreatedAt);
try {
query.whereContainedIn("artisteId", Arrays.asList(tuneQueryIdList));
} catch (Exception e) {
e.printStackTrace();
}
query.include("parent");
query.findInBackground(new FindCallback<Tunes>() {
@Override
public void done(List<Tunes> t, ParseException e) {
if(mSwipeRefreshLayout.isRefreshing()){
mSwipeRefreshLayout.setRefreshing(false);
}
if (e == null){
for (Tunes tune : t){
Tune mTunes = new Tune(
tune.getTitle(),
tune.getObjectId(),
tune.getSongFile().getUrl(),
tune.getCoverArt().getUrl(),
tune.getArtist().getUsername(),
tune.getArtist().getObjectId(),
tune.getCreatedAt().toString()
);
mTunes.save();
}
}
}
});
}else {
ParseQuery<Tunes> query = ParseQuery.getQuery(Tunes.class);
query.addDescendingOrder(ParseConstants.KEY_CREATED_AT);
try {
query.whereContainedIn("artisteId", Arrays.asList(tuneQueryIdList));
} catch (Exception e) {
e.printStackTrace();
}
query.include("parent");
query.findInBackground(new FindCallback<Tunes>() {
@Override
public void done(List<Tunes> t, ParseException e) {
if(mSwipeRefreshLayout.isRefreshing()){
mSwipeRefreshLayout.setRefreshing(false);
}
if (e == null){
for (Tunes tune : t){
Tune mTunes = new Tune(
tune.getTitle(),
tune.getObjectId(),
tune.getSongFile().getUrl(),
tune.getCoverArt().getUrl(),
tune.getArtist().getUsername(),
tune.getArtist().getObjectId(),
tune.getCreatedAt().toString()
);
mTunes.save();
}
}
}
});
}
}
private void selectFriends() {
mFriendRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
mFriendRelation.getQuery().findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> list, ParseException e) {
mFriends = list;
// Add current user to Friends list
mFriends.add(mCurrentUser);
int i = 0;
tuneQueryIdList = new String[mFriends.size()];
for (ParseUser user : mFriends){
tuneQueryIdList[i] = user.getObjectId();
i++;
}
}
});
}
private void tuneContentQuery() {
mTuneList = Tune.listAll(Tune.class);
tuneArray = new JSONArray();
for (Tune t : mTuneList){
JSONObject tune = new JSONObject();
String tID = t.getTuneObjectId();
String tuneTitle = t.getTitle();
String tuneAudioUrl = t.getTuneAudioUrl();
String tuneArtUrl = t.getTuneArtUrl();
String artisteObjId = t.getArtisteObjectId();
String artisteName = t.getArtisteName();
String createdAt = t.getCreatedAt();
try {
tune.put(TuneDbHelper.TUNE_OBJECT_ID, tID);
tune.put(TuneDbHelper.TUNE_TITLE, tuneTitle);
tune.put(TuneDbHelper.TUNE_AUDIO_URL, tuneAudioUrl);
tune.put(TuneDbHelper.TUNE_ART_URL, tuneArtUrl);
tune.put(TuneDbHelper.ARTISTE_OBJECT_ID, artisteObjId);
tune.put(TuneDbHelper.ARTISTE_NAME, artisteName);
tune.put(TuneDbHelper.CREATED_AT, createdAt);
} catch (JSONException e) {
e.printStackTrace();
}
tuneArray.put(tune);
}
}
}
| true |
56e69fff4fa39be5645c887d5fe7847562df9f74 | Java | MelissaMB/Jetset | /src/main/java/com/sisvuelo/aplication/repository/impl/ReservaRepositoryImpl.java | UTF-8 | 2,885 | 2.140625 | 2 | [] | no_license | package com.sisvuelo.aplication.repository.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import com.sisvuelo.aplication.repository.helper.ReservaHelper;
import com.sisvuelo.aplication.filter.ReservaFilter;
import com.sisvuelo.aplication.model.Reserva;
public class ReservaRepositoryImpl implements ReservaHelper {
@PersistenceContext
private EntityManager manager;
@SuppressWarnings("unchecked")
public Page<Reserva> filtrar(ReservaFilter reservaFilter, Pageable pageable) {
Criteria criteria = manager.unwrap(Session.class).createCriteria(Reserva.class);
int paginaAtual = pageable.getPageNumber();
int totalRegistrosPorPagina = pageable.getPageSize();
int primeiroRegistro = paginaAtual * totalRegistrosPorPagina;
criteria.setFirstResult(primeiroRegistro);
criteria.setMaxResults(totalRegistrosPorPagina);
addFilter(reservaFilter, criteria);
return new PageImpl<>(criteria.list(), pageable, total(reservaFilter));
}
private Long total(ReservaFilter reservaFilter) {
Criteria criteria = manager.unwrap(Session.class).createCriteria(Reserva.class);
addFilter(reservaFilter, criteria);
criteria.setProjection(Projections.rowCount());
return (Long) criteria.uniqueResult();
}
private void addFilter(ReservaFilter reservaFilter, Criteria criteria) {
if (reservaFilter != null) {
if (reservaFilter.getId() != null) {
criteria.add(Restrictions.eq("id", reservaFilter.getId()));
}
if (reservaFilter.getPasajero() != null) {
criteria.add(Restrictions.eq("pasajero", reservaFilter.getPasajero()));
}
if (reservaFilter.getEstatusReserva() != null) {
criteria.add(Restrictions.eq("estatusReserva", reservaFilter.getEstatusReserva()));
}
if (reservaFilter.getVuelo() != null) {
criteria.add(Restrictions.eq("vuelo", reservaFilter.getVuelo()));
}
if (reservaFilter.getClase() != null) {
criteria.add(Restrictions.eq("clase", reservaFilter.getClase()));
}
if (reservaFilter.getCantidad() != null) {
criteria.add(Restrictions.eq("cantidad", reservaFilter.getCantidad()));
}
if (reservaFilter.getNumeroEquipaje() != null) {
criteria.add(Restrictions.eq("numeroEquipaje", reservaFilter.getNumeroEquipaje()));
}
if (reservaFilter.getFechaReserva() != null) {
criteria.add(Restrictions.eq("fechaReserva", reservaFilter.getFechaReserva()));
}
}
}
}
| true |
a7ab190664ab2180509b9d00406851f974b53b0a | Java | modmuss50/MappingPoet | /src/main/java/net/fabricmc/mappingpoet/Environment.java | UTF-8 | 1,758 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2020 FabricMC
*
* 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 net.fabricmc.mappingpoet;
import com.squareup.javapoet.ClassName;
import net.fabricmc.mappingpoet.signature.ClassStaticContext;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* Represents an overall runtime environment, knows all inner class,
* super class, etc. information.
*/
public record Environment(
Map<String, Collection<String>> superTypes,
Set<String> sealedClasses,
// declaring classes keep track of namable inner classes
// and local/anon classes in whole codebase
Map<String, NestedClassInfo> declaringClasses
) implements ClassStaticContext {
public record NestedClassInfo(String declaringClass, boolean instanceInner, String simpleName) {
// two strings are nullable
}
public record ClassNamePointer(String simple, String outerClass) {
public ClassName toClassName(ClassName outerClassName) {
if (simple == null)
return null;
return outerClassName.nestedClass(simple);
}
}
@Override
public boolean isInstanceInner(String internalName) {
var info = declaringClasses.get(internalName);
return info != null && info.declaringClass != null && info.instanceInner;
}
}
| true |
93302844cad90fdd28895898d9f1f52359751fd3 | Java | grubed/tps | /src/main/java/com/test/tps/common/MultiTree.java | UTF-8 | 3,899 | 3.078125 | 3 | [] | no_license | package com.test.tps.common;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class MultiTree<E> {
public Node<E> root;
public List<Node<E>> nodeList;
public MultiTree(E e) {
this(new Node<>(e));
}
public MultiTree(Node<E> root) {
this.root = root;
nodeList = new ArrayList<>();
consumeForNode(nodeList::add, root);
}
public Optional<Node<E>> getNode(E e) {
return matchNode(e, root);
}
/**
* _______[是否匹配]
* | / \
* | y n
* | / \
* | [return] [是否有子节点]
* | / \
* | y n
* |_____________ / \
* | [父节点是否有兄弟节点]___
* | / \ |
* | y n |
* |__________________/ \_________|
*/
private Optional<Node<E>> matchNode(E e, Node<E> currentNode) {
if (e.equals(currentNode.element)) {
return Optional.of(currentNode);
} else {
if (currentNode.children != null) {
for (Node<E> child : currentNode.children) {
Optional<Node<E>> result = matchNode(e, child);
if (result.isPresent()) {
return result;
}
}
}
}
return Optional.empty();
}
/**
* 拆分多叉树
*/
public List<MultiTree<E>> departIf(Predicate<E> predicate) {
List<MultiTree<E>> list = new ArrayList<>();
list.add(this);
for (Node<E> eNode : nodeList) {
if (predicate.test(eNode.element)) {
Node<E> parent = eNode.parent;
// 断开父子节点之间的指向
if (parent != null) {
parent.children.remove(eNode);
}
eNode.parent = null;
list.add(new MultiTree<>(eNode));
}
}
return list;
}
/**
* 将点添加至指定点的子节点中
* @param node 指定点
* @param e 需要添加的点
*/
public boolean add(Node<E> node, E e) {
if (node.children == null) {
node.children = new ArrayList<>();
}
Node<E> newNode = new Node<>(e);
newNode.parent = node;
node.children.add(newNode);
return nodeList.add(newNode);
}
/**
* 前序遍历
*/
public void preTraversal(Consumer<E> action) {
Objects.requireNonNull(action);
consume(action, root);
}
private void consume(Consumer<E> action, Node<E> currentNode) {
action.accept(currentNode.element);
if (currentNode.children != null) {
currentNode.children.forEach(o -> consume(action, o));
}
}
private void consumeForNode(Consumer<Node<E>> action, Node<E> currentNode) {
action.accept(currentNode);
if (currentNode.children != null) {
currentNode.children.forEach(o -> consumeForNode(action, o));
}
}
public static class Node<E> {
/**
* 父节点
*/
Node<E> parent;
/**
* 当前点的值
*/
final E element;
/**
* 子节点
*/
List<Node<E>> children;
public Node(E element) {
this.element = element;
}
}
@Override
public String toString() {
List<E> list = new ArrayList<>();
this.preTraversal(list::add);
return list.stream().map(Object::toString).collect(Collectors.joining(",", "[", "]"));
}
} | true |
5ccd2bba61635075d4b293d4f276c615ce6f709a | Java | wg400/tetris | /trtris/app/src/main/java/com/wanggang/tetris/util/AlertDialogUtil.java | UTF-8 | 3,824 | 2.359375 | 2 | [] | no_license | package com.wanggang.tetris.util;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wanggang.tetris.R;
/**
* Created by Administrator on 2015/10/12 0012.
*/
public class AlertDialogUtil {
/**
* 显示系统对话框
*
* @param msg 提示信息
* @param msgColor 提示信息颜色
* @param hasCancel 是否包含取消按钮
* @param canCancle 是否能够点击外部关闭
* @param okText 确定按钮文本
* @param cancelText 取消按钮文本
* @param okListener 确定按钮回调
* @param cancelListener 取消按钮回调
*/
public static void show(Context context, String msg, int msgColor, boolean hasCancel, boolean canCancle, String okText,
String cancelText, final DialogInterface.OnClickListener okListener, final DialogInterface.OnClickListener cancelListener) {
LinearLayout dialogview = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.layout_dialog, null);
TextView tvMsg = (TextView) dialogview.findViewById(R.id.tvMsg);
TextView tvOk = (TextView) dialogview.findViewById(R.id.tvOk);
TextView tvCancel = (TextView) dialogview.findViewById(R.id.tvCancel);
dialogview.findFocus();
final AlertDialog dialog = new AlertDialog.Builder(context).create();
dialog.show();
Window window = dialog.getWindow();
window.setContentView(dialogview);
dialog.setCancelable(canCancle);
tvMsg.setText(msg);
tvMsg.setTextColor(context.getResources().getColor(msgColor));
if (!hasCancel) {
tvCancel.setVisibility(View.GONE);
} else {
tvCancel.setText(cancelText);
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (cancelListener != null) {
cancelListener.onClick(dialog, 1);
}
}
});
}
tvOk.setText(okText);
tvOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (okListener != null) {
okListener.onClick(dialog, 0);
}
}
});
}
public static void show(Context context, String msg, boolean hasCancel, String okText,
String cancelText, final DialogInterface.OnClickListener okListener, final DialogInterface.OnClickListener cancelListener) {
show(context, msg, R.color.black, hasCancel, true, okText, cancelText, okListener, cancelListener);
}
public static void show(Context context, String msg) {
show(context, msg, R.color.black, false, false, "确定", "", null, null);
}
public static void showGreen(Context context, String msg) {
show(context, msg, R.color.green, false, false, "确定", "", null, null);
}
public static void show(Context context, String msg, DialogInterface.OnClickListener okListener) {
show(context, msg, R.color.black, false, false, "确定", "", okListener, null);
}
public static void showGreen(Context context, String msg, DialogInterface.OnClickListener okListener) {
show(context, msg, R.color.green, false, false, "确定", "", okListener, null);
}
}
| true |
3719511f59ccdba2f0e3ae89d63b81a5f66331d2 | Java | zhangmushui/FoldingLayout | /foldlayout/src/main/java/com/jersay/foldlayout/FoldSlidingPanelLayout.java | UTF-8 | 1,417 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | package com.jersay.foldlayout;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.widget.SlidingPaneLayout;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by zhangjie on 2018/10/24.
*/
public class FoldSlidingPanelLayout extends SlidingPaneLayout {
public FoldSlidingPanelLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
View child = getChildAt(0);
if (child != null) {
removeView(child);
final FoldLayout foldLayout = new FoldLayout(getContext());
foldLayout.addView(child);
ViewGroup.LayoutParams layoutParams = child.getLayoutParams();
addView(foldLayout, 0, layoutParams);
setPanelSlideListener(new PanelSlideListener() {
@Override
public void onPanelSlide(@NonNull View panel, float slideOffset) {
foldLayout.setFactor(slideOffset);
}
@Override
public void onPanelOpened(@NonNull View panel) {
}
@Override
public void onPanelClosed(@NonNull View panel) {
}
});
}
}
}
| true |
8c1270f91cb74ea0c238655a4289e4168a651874 | Java | oldpride/java | /tpdist/src/main/java/com/tpsup/tpdist/Tar.java | UTF-8 | 11,381 | 2.375 | 2 | [] | no_license | package com.tpsup.tpdist;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarConstants;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
public class Tar {
public static TarArchiveOutputStream createTar(String outputString, String relativeString,
ArrayList<String> inputStringList, boolean inputIsRelative,
TarArchiveOutputStream tarArchiveOutputStream) throws IOException {
relativeString = relativeString.replace("\\", "/").replaceAll("[/]+$", "");
File outputFile = new File(outputString);
File relativePath = new File(relativeString);
if (tarArchiveOutputStream == null) {
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(outputFile);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
tarArchiveOutputStream = new TarArchiveOutputStream(bufferedOutputStream);
tarArchiveOutputStream.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
}
for (String inputString : inputStringList) {
MyLog.append(inputString);
String relativeFilePath;
String absoluteFilePath;
if (inputIsRelative) {
relativeFilePath = inputString;
absoluteFilePath = relativeString + "/" + inputString;
} else {
absoluteFilePath = inputString;
relativeFilePath = relativePath.toURI().relativize(new File(absoluteFilePath).toURI())
.getPath().replace("\\", "/");
}
File inputFile = new File(absoluteFilePath);
MyLog.append("absolute Path : " + absoluteFilePath);
MyLog.append("relative Path : " + relativeFilePath);
TarArchiveEntry tarEntry = null;
// if (Files.isSymbolicLink(inputFile.toPath())) {
if (Files.isSymbolicLink(Paths.get(absoluteFilePath))) {
// note: symlinks on windows have to be created by mklink command, not
// by "ln -s target link" in GitBash, neither in Cygwin
// note: I don't have privilege to run mklink on window
//
// C:\Users\hantian\testdir>mklink /D blink b
// You do not have sufficient privilege to perform this operation.
//
// C:\Users\hantian\testdir>mklink alink.txt a.txt
// You do not have sufficient privilege to perform this operation.
MyLog.append("this is a sym link");
// https://www.codota.com/code/java/methods/org.apache.commons.compress.archivers.tar.TarArchiveEntry/setLinkName
tarEntry = new TarArchiveEntry(inputFile.toString(), TarConstants.LF_SYMLINK);
tarEntry.setLinkName(relativeFilePath);
} else {
tarEntry = new TarArchiveEntry(inputFile, relativeFilePath);
tarEntry.setSize(inputFile.length());
tarEntry.setModTime(inputFile.lastModified());
}
tarArchiveOutputStream.putArchiveEntry(tarEntry);
tarArchiveOutputStream.write(IOUtils.toByteArray(new FileInputStream(inputFile)));
tarArchiveOutputStream.closeArchiveEntry();
}
// need manually close because we will tar multiple times
// tarArchiveOutputStream.close();
return tarArchiveOutputStream;
}
public static void createTar(String outputString, String inputDirString) throws IOException {
List<File> files = new ArrayList<File>(FileUtils.listFiles(new File(inputDirString),
new RegexFileFilter("^(.*?)"), DirectoryFileFilter.DIRECTORY));
ArrayList<String> inputList = new ArrayList<String>();
for (File inputFile : files) {
String absoluteFilePath = inputFile.toString().replace("\\", "/");
inputList.add(absoluteFilePath);
}
TarArchiveOutputStream tarArchiveOutputStream = createTar(outputString, inputDirString, inputList,
false, null);
tarArchiveOutputStream.close();
}
public static void main(String[] args) {
int willdo = 1;
try {
// use absolute paths
if (willdo == 0) {
List<File> files = new ArrayList<File>(FileUtils.listFiles(new File("C:/Users/william/github/tpsup/ps1"),
new RegexFileFilter("^(.*?)"), DirectoryFileFilter.DIRECTORY));
ArrayList<String> StringList = new ArrayList<String>();
for (File file : files) {
StringList.add(file.getPath().replace("\\", "/"));
}
TarArchiveOutputStream tarArchiveOutputStream = createTar("c:/users/william/junk.tar",
"C:/Users/william/testdir", StringList, false, null);
tarArchiveOutputStream.close();
}
// use relative path
if (willdo == 0) {
String[] relativePaths = { "a.txt", "b.txt", "c/d.txt" };
ArrayList<String> StringList = new ArrayList<String>();
for (String s : relativePaths) {
StringList.add(s);
}
TarArchiveOutputStream tarArchiveOutputStream = createTar("c:/users/william/junk2.tar",
"C:/Users/william/testdir", StringList, true, null);
tarArchiveOutputStream.close();
}
// test 2nd function
if (willdo == 1) {
createTar("c:/users/william/junk3.tar", "C:/Users/william/github/tpsup/ps1");
}
// test unTar
if (willdo == 1) {
String outputDir = "C:/Users/william/tmp3";
if ((new File(outputDir)).exists()) {
FileUtils.cleanDirectory(new File(outputDir));
}
List<File> outputFiles = unTar("C:/Users/william/junk3.tar", outputDir);
MyLog.append("outputFiles = " + MyGson.toJson(outputFiles));
}
} catch (IOException e) {
e.printStackTrace();
} catch (ArchiveException e) {
e.printStackTrace();
}
}
// https://stackoverflow.com/questions/315618/how-do-i-extract-a-tar-file-in-java/7556307#7556307
public static List<File> unTar(final String inputTarFileName, final String outputDirName)
throws FileNotFoundException, IOException, ArchiveException {
File inputFile = new File(inputTarFileName);
File outputDir = new File(outputDirName);
MyLog.append(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath().replace("\\", "/"),
outputDir.getAbsolutePath().replace("\\", "/")));
final List<File> untaredFiles = new LinkedList<File>();
final InputStream is = new FileInputStream(inputFile);
final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
.createArchiveInputStream("tar", is);
TarArchiveEntry entry = null;
while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
final File outputFile = new File(outputDir, entry.getName());
MyLog.append(entry.getName());
if (entry.isSymbolicLink()) {
// in windows, by default, one cannot create symbolic link
// https://stackoverflow.com/questions/8228030/getting-filesystemexception-a-required-privilege-is-not-held-by-the-client-usi
// https://commons.apache.org/proper/commons-compress/apidocs/org/apache/commons/compress/archivers/tar/TarArchiveEntry.html
String target = entry.getLinkName();
String newLink = outputFile.getAbsolutePath();
MyLog.append(String.format("Attempting to link %s to %s.", target, newLink));
// if it should be a link, we try to create the link first.
// if we cannot create link, we copy
boolean success = true;
try {
Files.createSymbolicLink(Paths.get(newLink), Paths.get(target));
} catch (Exception e) {
success = false;
e.printStackTrace();
MyLog.append("failed to create sym link " + newLink + ". will resort to copy");
}
if (success) {
continue;
}
} else if (entry.isDirectory()) {
MyLog.append(String.format("Attempting to write output directory %s.",
outputFile.getAbsolutePath()));
if (!outputFile.exists()) {
MyLog.append(String.format("Attempting to create output directory %s.",
outputFile.getAbsolutePath()));
if (!outputFile.mkdirs()) {
throw new IllegalStateException(
String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
}
}
} else {
File parent = outputFile.getParentFile();
if (!parent.exists())
if (!parent.mkdirs()) {
throw new IllegalStateException(
String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
}
final OutputStream outputFileStream = new FileOutputStream(outputFile);
IOUtils.copy(debInputStream, outputFileStream);
outputFileStream.close();
}
// set timestamp
BasicFileAttributeView attributes = Files.getFileAttributeView(outputFile.toPath(),
BasicFileAttributeView.class);
Date mtime = entry.getModTime();
FileTime fileTime = FileTime.fromMillis(mtime.getTime());
try {
attributes.setTimes(fileTime, fileTime, fileTime);
} catch (IOException e) {
MyLog.append(MyLog.ERROR, e.getStackTrace().toString());
}
untaredFiles.add(outputFile);
}
debInputStream.close();
return untaredFiles;
}
}
| true |
f1723f04c02ccfd96b378123e39d4fe771eeace0 | Java | Bobaphtt/Paint | /src/main/java/model/Reta.java | UTF-8 | 927 | 3.046875 | 3 | [] | no_license | package model;
public class Reta extends FiguraGeometrica{
private Ponto a;
private Ponto b;
private double tamanho;
private double coeficienteAngular;
public Reta(Ponto a, Ponto b){
this.a = a;
this.b = b;
double tamanho;
double deltaX = b.getX() - a.getX();
double deltaY = b.getY() - a.getY();
tamanho = Math.sqrt((deltaX*deltaX)+(deltaY*deltaY));
this.tamanho = tamanho;
}
public Reta(double tamanho){
this.a = new Ponto(0, 0);
this.b = new Ponto(tamanho,0);
this.tipo = 2;
this.tamanho = tamanho;
}
public double getTamanho() {
return tamanho;
}
public double mostrarArea(){return 0;}
public double mostrarPerimetro(){return tamanho;}
public int getTipo(){
return this.tipo;
}
@Override
public String toString() {
return "RETA";
}
}
| true |
0450912e70acb6810b16e2d3909e4a906e33c5e6 | Java | 529909385/SSM | /ssm_strongpower_pojo/src/main/java/com/kylin/electricassistsys/service/impl/tyx/TYxYxsjZyxlnServiceImap.java | UTF-8 | 649 | 1.515625 | 2 | [] | no_license | package com.kylin.electricassistsys.service.impl.tyx;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kylin.electricassistsys.dao.tyx.TYxYxsjZyxlnDao;
import com.kylin.electricassistsys.pojo.tyx.TYxYxsjZyxln;
import com.kylin.electricassistsys.service.tyx.TYxYxsjZyxlnService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* 服务实现类
* </p>
*
* @author 陈文旭
* @since 2018-04-24
*/
@Service
@Transactional
public class TYxYxsjZyxlnServiceImap extends ServiceImpl<TYxYxsjZyxlnDao, TYxYxsjZyxln> implements TYxYxsjZyxlnService {
}
| true |
17926cfde218a4e9157ccaec7b8a917bf7a25275 | Java | arun-tm/FleetIQ | /googleservices/src/main/java/in/teramatrix/googleservices/model/Place.java | UTF-8 | 1,868 | 2.578125 | 3 | [] | no_license | package in.teramatrix.googleservices.model;
import com.google.android.gms.maps.model.LatLng;
/**
* This model will hold the information about a place fetched from the server by calling Google's Places Api. This is
* used in {@link in.teramatrix.googleservices.service.PlacesExplorer} to parse and bind results in a better way.
* @author Mohsin Khan
* @date 3/18/2016
*/
@SuppressWarnings("unused")
public class Place {
private String id;
private String placeId;
private String name;
private String type;
private String icon;
private LatLng location;
private String vicinity;
public Place() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
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;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public LatLng getLocation() {
return location;
}
public void setLocation(LatLng location) {
this.location = location;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
@Override
public String toString() {
return "Place{" +
"name='" + name + '\'' +
", type=" + type +
", location=" + location +
", vicinity='" + vicinity + '\'' +
'}';
}
}
| true |
15e2098b6d227460ee0843ffd2d410ce4f394558 | Java | dampce32/ecms | /ecms/src/com/csit/filter/StuTeaLoginVerifyInterceptor.java | UTF-8 | 935 | 2.125 | 2 | [] | no_license | package com.csit.filter;
import com.csit.model.Student;
import com.csit.model.Teacher;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @Description:学生教师都可以登录
*
* @Copyright: 福州骏华信息有限公司 (c)2013
* @Created Date : 2013-3-29
* @Author lys
*/
public class StuTeaLoginVerifyInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = -86246303854807787L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Integer studentLogin = (Integer) invocation.getInvocationContext().getSession().get(Student.LOGIN_ID);
Integer userLogin = (Integer) invocation.getInvocationContext().getSession().get(Teacher.LOGIN_TEACHERID);
if (userLogin == null && studentLogin==null) {
return "loginStu";
}
return invocation.invoke();
}
} | true |
f962355d2b88ac4dc5c784454e0300ff577defc1 | Java | jianxiaopang2018/clouddisk | /src/main/java/top/jianxiaopang/clouddisk/interceptor/TokenInterceptor.java | UTF-8 | 1,761 | 2.296875 | 2 | [] | no_license | package top.jianxiaopang.clouddisk.interceptor;
import com.google.gson.Gson;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.jianxiaopang.clouddisk.pojo.Result;
import top.jianxiaopang.clouddisk.pojo.User;
import top.jianxiaopang.clouddisk.utils.JWT;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* 登录状态验证
*/
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String token = request.getParameter("token");
Boolean bl = false;
if(null != token) {
User user = JWT.unsign(token, User.class);
String email = request.getParameter("email");
if(null != user && null != email) {
if(user.getEmail().equals(email)) {
bl = true;
} else{
bl = false;
}
} else {
bl = false;
}
} else {
bl = false;
}
if(bl == false) {
Result result = Result.message(400,"登录超时,请重新登录!");
//用gson来格式化类成json
Gson gson = new Gson();
String json = gson.toJson(result);
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
}
return bl;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
| true |
597406e11a2e37cae024ac33e5732d7a8fb1e7b6 | Java | yijunhuan/netty | /src/com/huang/chatnetty/ChatSocketHandle.java | UTF-8 | 2,109 | 2.71875 | 3 | [] | no_license | package com.huang.chatnetty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
public class ChatSocketHandle extends SimpleChannelInboundHandler<String>
{
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg)
throws Exception
{
Channel channel = ctx.channel();
for (Channel ch : channelGroup)
{
if (ch != channel)
ch.writeAndFlush(ch.remoteAddress() + "发送的消息是:" + msg + "\n");
else
ch.writeAndFlush("[自己]" + msg + "\n");
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx)
throws Exception
{
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[服务器 -]" + channel.remoteAddress() + "加入\n");
channelGroup.add(channel);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx)
throws Exception
{
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[服务器 -]" + channel.remoteAddress() + "已下线\n");
}
@Override
public void channelActive(ChannelHandlerContext ctx)
throws Exception
{
System.out.println(ctx.channel().remoteAddress() + "已上线");
}
@Override
public void channelInactive(ChannelHandlerContext ctx)
throws Exception
{
System.out.println(ctx.channel().remoteAddress() + "已下线");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception
{
cause.printStackTrace();
ctx.close();
}
}
| true |
6e511850677b0925f18e3a82feb893d7390d1e72 | Java | IgnazMaula/TrainerAgency | /TrainerTableModel.java | UTF-8 | 2,721 | 3.34375 | 3 | [] | no_license | import java.util.*;
import javax.swing.table.*;
public class TrainerTableModel extends AbstractTableModel {
//create header for the table
private static final String[] tableHeader =
{"Trainer ID", "Trainer Category", "Trainer Name", "Course Taught",
"Base Salary" , "Commission" ,"Monthly Salary"};
private ArrayList<Trainer> trainerArray;
public TrainerTableModel() {
setTrainer(new ArrayList<Trainer>());
}
//set the trainer ArrayList that want to show on the table
public TrainerTableModel(ArrayList<Trainer> trainerArray) {
setTrainer(trainerArray);
}
//get the amount of the row
public int getRowCount() {
return getTrainer().size();
}
//get the amount of the column
public int getColumnCount() {
return tableHeader.length;
}
//get the information of the object in each
//row of the table
public Object getValueAt(int row, int column) {
Trainer trainer = (Trainer) getTrainer().get(row);
switch (column) {
case 0:
return trainer.getID();
case 1:
return trainer.getCategory();
case 2:
return trainer.getName();
case 3:
return trainer.getCourseTaught();
case 4:
return trainer.getBaseSalary();
case 5:
return trainer.commission();
case 6:
return trainer.monthlySalary();
default:
return "";
}
}
//get the name of the selected column
public String getColumnName(int column) {
return tableHeader[column];
}
//add trainer to the row
public void addRow(Trainer trainer) {
int row = getTrainer().size();
getTrainer().add(trainer);
fireTableRowsInserted(row, row);
}
//get element at the selected row
public Trainer getElementAt(int row) {
Trainer trainer = (Trainer) getTrainer().get(row);
return trainer;
}
//remove element at the selected row
public Trainer removeRow(int row) {
Trainer trainer = (Trainer) getTrainer().remove(row);
fireTableRowsDeleted(row, row);
return trainer;
}
//clear the data of the selected row
public void clear() {
int row = getTrainer().size() -1;
getTrainer().clear();
if(row >=0)
fireTableRowsDeleted(0, row);
}
//check if selected trainer is contains in the
//trainer ArrayList
public boolean contains(Trainer trainer) {
return getTrainer().contains(trainer);
}
//check if trainer ArrayList is empty
public boolean isEmpty() {
return getTrainer().size() == 0;
}
//set the ArrayList of trainer that want to be display
//in the table
public void setTrainer(ArrayList<Trainer> array) {
trainerArray = array;
this.fireTableDataChanged();
}
//get the ArrayList of trainer
public ArrayList<Trainer> getTrainer() {
return trainerArray;
}
} | true |
0797825f00a08dcf98fbdbb138e790d8fc105b6a | Java | chenyp1994/Weather | /weather/src/main/java/com/chenyp/weather/db/AreaDB.java | UTF-8 | 6,084 | 2.609375 | 3 | [] | no_license | package com.chenyp.weather.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import com.chenyp.weather.bean.Area;
import java.util.ArrayList;
import java.util.List;
/**
* Created by chenyp on 15-6-17.
*/
public class AreaDB {
/**
* DataBase Name
*/
public static final String DB_NAME = "DBArea";
/**
* DataBase Version
*/
public static final int VERSION = 1;
private static AreaDB areaDB;
private SQLiteDatabase db;
/**
* 将构造方法私有化
*
* @param context
*/
private AreaDB(Context context) {
AreaOpenHelper dbHelper = new AreaOpenHelper(context,
DB_NAME, null, VERSION);
db = dbHelper.getWritableDatabase();
}
/**
* 获取DataBaseDB的实例。
*
* @param context
* @return
*/
public synchronized static AreaDB getInstance(Context context) {
if (areaDB == null) {
areaDB = new AreaDB(context);
}
return areaDB;
}
/**
* 将Area实例存储到数据库。
*
* @param area
*/
public void saveArea(Area area) {
if (area != null) {
ContentValues values = new ContentValues();
values.put("areaid", area.getAreaid());
values.put("namecn", area.getNamecn());
values.put("nameen", area.getNameen());
values.put("districtcn", area.getDistrictcn());
values.put("districten", area.getDistricten());
values.put("provincecn", area.getProvincecn());
values.put("provinceen", area.getProvinceen());
values.put("nationcn", area.getNationcn());
values.put("nationen", area.getNameen());
db.insert("Area", null, values);
}
}
/**
* 根据areaid获取Area实例
*
* @param areaid
* @return
*/
public Area getAreaByAreaid(String areaid) {
if (TextUtils.isEmpty(areaid))
return null;
Cursor cursor = db.query("Area", null, "areaid = ?",
new String[]{areaid}, null, null, null);
if (cursor.moveToFirst()) {
return null;
}
Area area = new Area();
area.setId(cursor.getLong(cursor.getColumnIndex("id")));
area.setAreaid(cursor.getLong(cursor.getColumnIndex("areaid")));
area.setNamecn(cursor.getString(cursor
.getColumnIndex("namecn")));
area.setNameen(cursor.getString(cursor
.getColumnIndex("nameen")));
area.setDistrictcn(cursor.getString(cursor
.getColumnIndex("districtcn")));
area.setDistricten(cursor.getString(cursor
.getColumnIndex("districten")));
area.setProvincecn(cursor.getString(cursor
.getColumnIndex("provincecn")));
area.setProvinceen(cursor.getString(cursor.getColumnIndex("provinceen")));
area.setNationcn(cursor.getString(cursor.getColumnIndex("nationcn")));
area.setNationen(cursor.getString(cursor.getColumnIndex("nationen")));
cursor.close();
return area;
}
/**
* 通过区域的名字获取到Area实例
*
* @param namecn
* @return
*/
public Area getAreaByName(String namecn) {
if (TextUtils.isEmpty(namecn))
return null;
Cursor cursor = db.query("Area", null, "namecn = ?",
new String[]{namecn}, null, null, null);
if (cursor.moveToFirst()) {
return null;
}
Area area = new Area();
area.setId(cursor.getLong(cursor.getColumnIndex("id")));
area.setAreaid(cursor.getLong(cursor.getColumnIndex("areaid")));
area.setNamecn(cursor.getString(cursor
.getColumnIndex("namecn")));
area.setNameen(cursor.getString(cursor
.getColumnIndex("nameen")));
area.setDistrictcn(cursor.getString(cursor
.getColumnIndex("districtcn")));
area.setDistricten(cursor.getString(cursor
.getColumnIndex("districten")));
area.setProvincecn(cursor.getString(cursor
.getColumnIndex("provincecn")));
area.setProvinceen(cursor.getString(cursor.getColumnIndex("provinceen")));
area.setNationcn(cursor.getString(cursor.getColumnIndex("nationcn")));
area.setNationen(cursor.getString(cursor.getColumnIndex("nationen")));
cursor.close();
return area;
}
/**
* 获取所有城市List
* @return
*/
public List<Area> getAllArea() {
List<Area> list = new ArrayList<Area>();
Cursor cursor = db.query("Area", null, null,
null, null, null, null);
if (cursor.moveToFirst()) {
do {
Area area = new Area();
area.setId(cursor.getLong(cursor.getColumnIndex("id")));
area.setAreaid(cursor.getLong(cursor.getColumnIndex("areaid")));
area.setNamecn(cursor.getString(cursor
.getColumnIndex("namecn")));
area.setNameen(cursor.getString(cursor
.getColumnIndex("nameen")));
area.setDistrictcn(cursor.getString(cursor
.getColumnIndex("districtcn")));
area.setDistricten(cursor.getString(cursor
.getColumnIndex("districten")));
area.setProvincecn(cursor.getString(cursor
.getColumnIndex("provincecn")));
area.setProvinceen(cursor.getString(cursor.getColumnIndex("provinceen")));
area.setNationcn(cursor.getString(cursor.getColumnIndex("nationcn")));
area.setNationen(cursor.getString(cursor.getColumnIndex("nationen")));
list.add(area);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
}
| true |
34bff3117f86b5e9ea750607764001b0313338eb | Java | idau2012/EasySmartHouse-web | /ui/webui/src/main/java/net/easysmarthouse/ui/webui/server/ActuatorsServiceImpl.java | UTF-8 | 1,452 | 2.1875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.easysmarthouse.ui.webui.server;
import net.easysmarthouse.provider.device.actuator.Actuator;
import net.easysmarthouse.provider.device.actuator.ActuatorsModule;
import net.easysmarthouse.provider.device.exception.DeviceException;
import net.easysmarthouse.ui.webui.client.rpc.ActuatorsService;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author mirash
*/
public class ActuatorsServiceImpl extends ServerBaseServlet implements ActuatorsService {
private final Logger log = Logger.getLogger(ActuatorsServiceImpl.class.getName());
@Autowired
ActuatorsModule actuatorsModule;
@Override
public List<Actuator> getActuators() {
return actuatorsModule.getDevices();
}
@Override
public void changeState(String address, Double state) {
try {
actuatorsModule.changeState(address, state);
} catch (DeviceException ex) {
log.error("Cannot change the state of: [" + address + "]", ex);
}
}
@Override
public void changeState(String address, Boolean state) {
try {
actuatorsModule.changeState(address, state);
} catch (DeviceException ex) {
log.error("Cannot change the state of: [" + address + "]", ex);
}
}
}
| true |
c02b5652fe5beab7a61a66ef815f92f47c4cc0df | Java | GeXyu/tools | /mvc2/src/cn/xiuyu/annotation/Action.java | UTF-8 | 460 | 2.03125 | 2 | [] | no_license | package cn.xiuyu.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author gexyuzz
* @version date:2017年6月19日 下午2:01:10
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface Action {
String value() default "/";
}
| true |
41108e6e2b3ac5184908587709bc90ca6916bcad | Java | peteanMihai/ToyInterpretorFinal | /src/model/MyStack.java | UTF-8 | 1,442 | 3.375 | 3 | [] | no_license | package model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
import model.interfaces.IStak;
public class MyStack<T> implements IStak<T> {
protected Stack<T> myStack;
public MyStack(){
myStack = new Stack<T>();
}
@Override
public int size(){
return myStack.size();
}
@Override
public void push(T mySta) {
myStack.push(mySta);
}
@Override
public T pop() {
return myStack.pop();
}
@Override
public Iterator<T> getAll() {
return myStack.iterator();
}
@Override
public boolean isEmpty() {
return myStack.isEmpty();
}
@Override
public String toString(){
return "" + myStack;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public ArrayList<String> getList() {
ArrayList<String> result = new ArrayList<>();
for (Iterator<T> it = getAll(); it.hasNext(); ) {
T object = it.next();
result.add(object.toString());
}
for(int i = 0; i < result.size() /2 ; i++){
String aux = result.get(i);
result.set(i, result.get(result.size() - i - 1));
result.set(result.size() - i - 1, aux);
}
return result;
}
@Override
public T top() {
return myStack.peek();
}
}
| true |
c0d13c541713c4eaef8cceb30f552b5684849143 | Java | jademy-12/WebMediaStoreRox | /src/main/java/ro/jademy/domain/entities/EBOOK.java | UTF-8 | 1,172 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | package ro.jademy.domain.entities;
import ro.jademy.domain.entities.EBOOK.Builder;
public class EBOOK extends Media{
private String author;
public EBOOK(String title, double price, String code, MediaGenre genre, String author) {
super(title, price, code, genre);
this.author = author;
// TODO Auto-generated constructor stub
}
public EBOOK() {
// TODO Auto-generated constructor stub
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return author;
}
public static class Builder {
String title;
double price;
String code;
MediaGenre genre;
String author;
public Builder title(String title) {
this. title= title;
return this;
}
public Builder author(String author) {
this.author = author;
return this;
}
public Builder price(double price) {
this. price= price;
return this;
}
public Builder code(String code) {
this. code= code;
return this;
}
public Builder genre(MediaGenre genre) {
this. genre= genre;
return this;
}
public EBOOK build() {
return new EBOOK(title, price, code, genre, author);
}
}
}
| true |
a16af1ae9c2d6ee3f4f6b8c2220d3f57109b200e | Java | rogue7hack/kielce-java | /src/edu/kielce/lab4/Cuboid.java | UTF-8 | 935 | 3.359375 | 3 | [] | no_license | package edu.kielce.lab4;
public class Cuboid {
double width, depth, height;
public Cuboid(double width, double depth, double height) {
this.width = width;
this.depth = depth;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getDepth() {
return depth;
}
public void setDepth(double depth) {
this.depth = depth;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
double getDiagonal(){
return Math.sqrt(Math.pow(width, 2) + Math.pow(depth, 2) + Math.pow(height, 2));
}
double getCapacity(){
return width*depth*height;
}
double getArea(){
return(2*(width*height + width*depth + height*depth));
}
}
| true |
b9b2b708d1708a277232e7ca10041f42cba0525b | Java | zhongxingyu/Seer | /Diff-Raw-Data/27/27_817a7d9d8cb107b5e2422e891f5a38613b08ecc2/GameSettingFrame/27_817a7d9d8cb107b5e2422e891f5a38613b08ecc2_GameSettingFrame_s.java | UTF-8 | 47,921 | 1.554688 | 2 | [] | no_license | /*
* Copyright (C) 2007 TGMG <thegamemakerguru@gmail.com>
* Copyright (C) 2007, 2008, 2010, 2011 IsmAvatar <IsmAvatar@gmail.com>
* Copyright (C) 2007, 2008 Clam <clamisgood@gmail.com>
* Copyright (C) 2007, 2008 Quadduc <quadduc@gmail.com>
*
* This file is part of LateralGM.
* LateralGM is free software and comes with ABSOLUTELY NO WARRANTY.
* See LICENSE for details.
*/
package org.lateralgm.subframes;
import static java.lang.Integer.MAX_VALUE;
import static javax.swing.GroupLayout.DEFAULT_SIZE;
import static javax.swing.GroupLayout.PREFERRED_SIZE;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.beans.ExceptionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.table.AbstractTableModel;
import org.lateralgm.components.ColorSelect;
import org.lateralgm.components.CustomFileChooser;
import org.lateralgm.components.NumberField;
import org.lateralgm.components.impl.CustomFileFilter;
import org.lateralgm.components.impl.IndexButtonGroup;
import org.lateralgm.components.impl.ResNode;
import org.lateralgm.file.GmFile;
import org.lateralgm.file.GmStreamDecoder;
import org.lateralgm.file.GmStreamEncoder;
import org.lateralgm.file.iconio.ICOFile;
import org.lateralgm.main.LGM;
import org.lateralgm.main.Util;
import org.lateralgm.messages.Messages;
import org.lateralgm.resources.GameSettings;
import org.lateralgm.resources.Include;
import org.lateralgm.resources.GameSettings.ColorDepth;
import org.lateralgm.resources.GameSettings.Frequency;
import org.lateralgm.resources.GameSettings.IncludeFolder;
import org.lateralgm.resources.GameSettings.PGameSettings;
import org.lateralgm.resources.GameSettings.Priority;
import org.lateralgm.resources.GameSettings.ProgressBar;
import org.lateralgm.resources.GameSettings.Resolution;
import org.lateralgm.resources.sub.Constant;
public class GameSettingFrame extends ResourceFrame<GameSettings,PGameSettings> implements
ActionListener,ExceptionListener
{
private static final long serialVersionUID = 1L;
boolean imagesChanged = false;
public JTabbedPane tabbedPane = new JTabbedPane();
public JCheckBox startFullscreen;
public IndexButtonGroup scaling;
public NumberField scale;
public JCheckBox interpolatecolors;
public ColorSelect colorbutton;
public JCheckBox resizeWindow;
public JCheckBox stayOnTop;
public JCheckBox noWindowBorder;
public JCheckBox noWindowButtons;
public JCheckBox displayMouse;
public JCheckBox freezeGame;
private JPanel makeGraphicsPane()
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
startFullscreen = new JCheckBox(Messages.getString("GameSettingFrame.FULLSCREEN")); //$NON-NLS-1$
plf.make(startFullscreen,PGameSettings.START_FULLSCREEN);
JPanel scalegroup = new JPanel();
GroupLayout sLayout = new GroupLayout(scalegroup);
scalegroup.setLayout(sLayout);
String t = Messages.getString("GameSettingFrame.SCALING_TITLE"); //$NON-NLS-1$
scalegroup.setBorder(BorderFactory.createTitledBorder(t));
scaling = new IndexButtonGroup(3,true,false,this);
JRadioButton osFixed = new JRadioButton(Messages.getString("GameSettingFrame.SCALING_FIXED")); //$NON-NLS-1$
scaling.add(osFixed,1);
scale = new NumberField(1,999,100);
JRadioButton osRatio = new JRadioButton(Messages.getString("GameSettingFrame.SCALING_RATIO")); //$NON-NLS-1$
scaling.add(osRatio,-1);
JRadioButton osFull = new JRadioButton(Messages.getString("GameSettingFrame.SCALING_FULL")); //$NON-NLS-1$
scaling.add(osFull,0);
//due to the complexity of this setup resolving to 1 property, we handle this in commitChanges.
sLayout.setHorizontalGroup(sLayout.createParallelGroup()
/**/.addGroup(sLayout.createSequentialGroup()
/* */.addComponent(osFixed).addPreferredGap(ComponentPlacement.RELATED)
/* */.addComponent(scale,DEFAULT_SIZE,DEFAULT_SIZE,PREFERRED_SIZE).addContainerGap())
/**/.addComponent(osRatio)
/**/.addComponent(osFull));
sLayout.setVerticalGroup(sLayout.createSequentialGroup()
/**/.addGroup(sLayout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(osFixed)
/* */.addComponent(scale))
/**/.addComponent(osRatio)
/**/.addComponent(osFull));
int s = res.properties.get(PGameSettings.SCALING);
scaling.setValue(s > 1 ? 1 : s);
if (s > 1) scale.setValue(s);
scale.setEnabled(s > 0);
t = Messages.getString("GameSettingFrame.INTERPOLATE"); //$NON-NLS-1$
plf.make(interpolatecolors = new JCheckBox(t),PGameSettings.INTERPOLATE);
JLabel backcolor = new JLabel(Messages.getString("GameSettingFrame.BACKCOLOR")); //$NON-NLS-1$
plf.make(colorbutton = new ColorSelect(),PGameSettings.COLOR_OUTSIDE_ROOM);
resizeWindow = new JCheckBox(Messages.getString("GameSettingFrame.RESIZE")); //$NON-NLS-1$
stayOnTop = new JCheckBox(Messages.getString("GameSettingFrame.STAYONTOP")); //$NON-NLS-1$
noWindowBorder = new JCheckBox(Messages.getString("GameSettingFrame.NOBORDER")); //$NON-NLS-1$
noWindowButtons = new JCheckBox(Messages.getString("GameSettingFrame.NOBUTTONS")); //$NON-NLS-1$
displayMouse = new JCheckBox(Messages.getString("GameSettingFrame.DISPLAYCURSOR")); //$NON-NLS-1$
freezeGame = new JCheckBox(Messages.getString("GameSettingFrame.FREEZE")); //$NON-NLS-1$
plf.make(resizeWindow,PGameSettings.ALLOW_WINDOW_RESIZE);
plf.make(stayOnTop,PGameSettings.ALWAYS_ON_TOP);
plf.make(noWindowBorder,PGameSettings.DONT_DRAW_BORDER);
plf.make(noWindowButtons,PGameSettings.DONT_SHOW_BUTTONS);
plf.make(displayMouse,PGameSettings.DISPLAY_CURSOR);
plf.make(freezeGame,PGameSettings.FREEZE_ON_LOSE_FOCUS);
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addComponent(startFullscreen)
/**/.addComponent(scalegroup)
/**/.addComponent(interpolatecolors)
/**/.addGroup(layout.createSequentialGroup()
/* */.addComponent(backcolor)
/* */.addComponent(colorbutton,DEFAULT_SIZE,DEFAULT_SIZE,120))
/**/.addComponent(resizeWindow)
/**/.addComponent(stayOnTop)
/**/.addComponent(noWindowBorder)
/**/.addComponent(noWindowButtons)
/**/.addComponent(displayMouse)
/**/.addComponent(freezeGame));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addComponent(startFullscreen)
/**/.addComponent(scalegroup)
/**/.addComponent(interpolatecolors)
/**/.addGroup(layout.createParallelGroup(Alignment.BASELINE,false)
/* */.addComponent(backcolor)
/* */.addComponent(colorbutton))
/**/.addComponent(resizeWindow)
/**/.addComponent(stayOnTop)
/**/.addComponent(noWindowBorder)
/**/.addComponent(noWindowButtons)
/**/.addComponent(displayMouse)
/**/.addComponent(freezeGame)
/**/.addGap(4,4,MAX_VALUE));
return panel;
}
public JCheckBox synchronised;
public JCheckBox setResolution;
public ButtonGroup colorDepth;
public ButtonGroup resolution;
public ButtonGroup frequency;
public JPanel resolutionPane;
private <V extends Enum<V>>JPanel makeRadioPane(String title, ButtonGroup bg, PGameSettings prop,
Class<V> optsClass, String[] vals)
{
JPanel p = new JPanel();
p.setBorder(BorderFactory.createTitledBorder(title));
p.setLayout(new BoxLayout(p,BoxLayout.PAGE_AXIS));
for (String s : vals)
{
JRadioButton but = new JRadioButton(Messages.getString(s));
bg.add(but);
p.add(but);
}
plf.make(bg,prop,optsClass);
return p;
}
private JPanel makeResolutionPane()
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHonorsVisibility(false);
panel.setLayout(layout);
synchronised = new JCheckBox(Messages.getString("GameSettingFrame.USE_SYNC")); //$NON-NLS-1$
plf.make(synchronised,PGameSettings.USE_SYNCHRONIZATION);
setResolution = new JCheckBox(Messages.getString("GameSettingFrame.SET_RESOLUTION")); //$NON-NLS-1$
plf.make(setResolution,PGameSettings.SET_RESOLUTION);
setResolution.addActionListener(this);
resolutionPane = new JPanel();
GroupLayout rpLayout = new GroupLayout(resolutionPane);
rpLayout.setAutoCreateGaps(true);
resolutionPane.setLayout(rpLayout);
String colDepths[] = { "GameSettingFrame.NO_CHANGE", //$NON-NLS-1$
"GameSettingFrame.16_BIT","GameSettingFrame.32_BIT" }; //$NON-NLS-1$ //$NON-NLS-2$
String resolutions[] = { "GameSettingFrame.NO_CHANGE","GameSettingFrame.320X240", //$NON-NLS-1$ //$NON-NLS-2$
"GameSettingFrame.640X480","GameSettingFrame.800X600","GameSettingFrame.1024X768", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"GameSettingFrame.1280X1024","GameSettingFrame.1600X1200" }; //$NON-NLS-1$ //$NON-NLS-2$
String freqs[] = { "GameSettingFrame.NO_CHANGE","GameSettingFrame.60HZ", //$NON-NLS-1$ //$NON-NLS-2$
"GameSettingFrame.70HZ","GameSettingFrame.85HZ", //$NON-NLS-1$ //$NON-NLS-2$
"GameSettingFrame.100HZ","GameSettingFrame.120HZ", }; //$NON-NLS-1$ //$NON-NLS-2$
JPanel depth = makeRadioPane(Messages.getString("GameSettingFrame.TITLE_COLOR_DEPTH"), //$NON-NLS-1$
colorDepth = new ButtonGroup(),PGameSettings.COLOR_DEPTH,ColorDepth.class,colDepths);
JPanel resol = makeRadioPane(Messages.getString("GameSettingFrame.TITLE_RESOLUTION"), //$NON-NLS-1$
resolution = new ButtonGroup(),PGameSettings.RESOLUTION,Resolution.class,resolutions);
JPanel freq = makeRadioPane(Messages.getString("GameSettingFrame.TITLE_FREQUENCY"), //$NON-NLS-1$
frequency = new ButtonGroup(),PGameSettings.FREQUENCY,Frequency.class,freqs);
rpLayout.setHorizontalGroup(rpLayout.createSequentialGroup()
/**/.addComponent(depth,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/**/.addComponent(resol,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/**/.addComponent(freq,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE));
rpLayout.setVerticalGroup(rpLayout.createParallelGroup(Alignment.LEADING,false)
/**/.addComponent(depth,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/**/.addComponent(resol,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/**/.addComponent(freq,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE));
resolutionPane.setVisible(setResolution.isSelected());
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addComponent(synchronised).addComponent(setResolution).addComponent(resolutionPane));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addComponent(synchronised).addComponent(setResolution).addComponent(resolutionPane));
return panel;
}
public JCheckBox esc, f1, f4, f5, f9;
public ButtonGroup gamePriority;
private JPanel makeOtherPane()
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
String t = Messages.getString("GameSettingFrame.TITLE_KEYS"); //$NON-NLS-1$
JPanel dKeys = new JPanel();
dKeys.setBorder(BorderFactory.createTitledBorder(t));
dKeys.setLayout(new BoxLayout(dKeys,BoxLayout.PAGE_AXIS));
esc = new JCheckBox(Messages.getString("GameSettingFrame.KEY_ENDGAME")); //$NON-NLS-1$
f1 = new JCheckBox(Messages.getString("GameSettingFrame.KEY_INFO")); //$NON-NLS-1$
f4 = new JCheckBox(Messages.getString("GameSettingFrame.KEY_SWITCHFULLSCREEN")); //$NON-NLS-1$
f5 = new JCheckBox(Messages.getString("GameSettingFrame.SAVELOAD")); //$NON-NLS-1$
f9 = new JCheckBox(Messages.getString("GameSettingFrame.KEY_SCREENSHOT")); //$NON-NLS-1$
dKeys.add(esc);
dKeys.add(f1);
dKeys.add(f4);
dKeys.add(f5);
dKeys.add(f9);
plf.make(esc,PGameSettings.LET_ESC_END_GAME);
plf.make(f1,PGameSettings.LET_F1_SHOW_GAME_INFO);
plf.make(f4,PGameSettings.LET_F4_SWITCH_FULLSCREEN);
plf.make(f5,PGameSettings.LET_F5_SAVE_F6_LOAD);
plf.make(f9,PGameSettings.LET_F9_SCREENSHOT);
String priorities[] = { "GameSettingFrame.PRIORITY_NORMAL", //$NON-NLS-1$
"GameSettingFrame.PRIORITY_HIGH","GameSettingFrame.PRIORITY_HIHGEST" }; //$NON-NLS-1$ //$NON-NLS-2$
JPanel priority = makeRadioPane(Messages.getString("GameSettingFrame.TITLE_PRIORITY"), //$NON-NLS-1$
gamePriority = new ButtonGroup(),PGameSettings.GAME_PRIORITY,Priority.class,priorities);
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addComponent(dKeys,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/**/.addComponent(priority,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addComponent(dKeys)
/**/.addComponent(priority));
return panel;
}
public JCheckBox showCustomLoadImage;
public BufferedImage customLoadingImage;
public JButton changeCustomLoad;
public JCheckBox imagePartiallyTransparent;
public NumberField loadImageAlpha;
public ButtonGroup loadBarMode;
public JRadioButton pbCustom;
public JButton backLoad;
public JButton frontLoad;
public BufferedImage backLoadImage;
public BufferedImage frontLoadImage;
public JCheckBox scaleProgressBar;
public JLabel iconPreview;
public ICOFile gameIcon;
public JButton changeIcon;
public NumberField gameId;
public JButton randomise;
private CustomFileChooser iconFc;
private JPanel makeLoadingPane()
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
JPanel loadImage = new JPanel();
String t = Messages.getString("GameSettingFrame.TITLE_LOADING_IMAGE"); //$NON-NLS-1$
loadImage.setBorder(BorderFactory.createTitledBorder(t));
GroupLayout liLayout = new GroupLayout(loadImage);
loadImage.setLayout(liLayout);
showCustomLoadImage = new JCheckBox(Messages.getString("GameSettingFrame.CUSTOM_LOAD_IMAGE")); //$NON-NLS-1$
plf.make(showCustomLoadImage,PGameSettings.SHOW_CUSTOM_LOAD_IMAGE);
showCustomLoadImage.addActionListener(this);
customLoadingImage = res.properties.get(PGameSettings.LOADING_IMAGE);
changeCustomLoad = new JButton(Messages.getString("GameSettingFrame.CHANGE_IMAGE")); //$NON-NLS-1$
changeCustomLoad.setEnabled(showCustomLoadImage.isSelected());
changeCustomLoad.addActionListener(this);
imagePartiallyTransparent = new JCheckBox(
Messages.getString("GameSettingFrame.MAKE_TRANSPARENT")); //$NON-NLS-1$
plf.make(imagePartiallyTransparent,PGameSettings.IMAGE_PARTIALLY_TRANSPARENTY);
JLabel lAlpha = new JLabel(Messages.getString("GameSettingFrame.ALPHA_TRANSPARENCY")); //$NON-NLS-1$
loadImageAlpha = new NumberField(0,255);
plf.make(loadImageAlpha,PGameSettings.LOAD_IMAGE_ALPHA);
liLayout.setHorizontalGroup(liLayout.createParallelGroup()
/**/.addGroup(liLayout.createSequentialGroup()
/* */.addComponent(showCustomLoadImage).addPreferredGap(ComponentPlacement.RELATED)
/* */.addComponent(changeCustomLoad))
/**/.addComponent(imagePartiallyTransparent)
/**/.addGroup(liLayout.createSequentialGroup().addContainerGap()
/* */.addComponent(lAlpha).addPreferredGap(ComponentPlacement.RELATED)
/* */.addComponent(loadImageAlpha,DEFAULT_SIZE,DEFAULT_SIZE,PREFERRED_SIZE)
/* */.addContainerGap()));
liLayout.setVerticalGroup(liLayout.createSequentialGroup()
/**/.addGroup(liLayout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(showCustomLoadImage)
/* */.addComponent(changeCustomLoad))
/**/.addComponent(imagePartiallyTransparent)
/**/.addPreferredGap(ComponentPlacement.UNRELATED)
/**/.addGroup(liLayout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(lAlpha)
/* */.addComponent(loadImageAlpha))
/**/.addContainerGap());
JRadioButton pbNo, pbDef;
JPanel progBar = new JPanel();
GroupLayout pbLayout = new GroupLayout(progBar);
t = Messages.getString("GameSettingFrame.TITLE_LOADING_PROGRESS_BAR"); //$NON-NLS-1$
progBar.setBorder(BorderFactory.createTitledBorder(t));
progBar.setLayout(pbLayout);
loadBarMode = new ButtonGroup();
loadBarMode.add(pbNo = new JRadioButton(Messages.getString("GameSettingFrame.NO_PROGRESS_BAR"))); //$NON-NLS-1$
loadBarMode.add(pbDef = new JRadioButton(
Messages.getString("GameSettingFrame.DEF_PROGRESS_BAR"))); //$NON-NLS-1$
loadBarMode.add(pbCustom = new JRadioButton(
Messages.getString("GameSettingFrame.CUSTOM_PROGRESS_BAR"))); //$NON-NLS-1$
plf.make(loadBarMode,PGameSettings.LOAD_BAR_MODE,ProgressBar.class);
backLoad = new JButton(Messages.getString("GameSettingFrame.BACK_IMAGE")); //$NON-NLS-1$
backLoad.addActionListener(this);
backLoadImage = res.properties.get(PGameSettings.BACK_LOAD_BAR);
frontLoad = new JButton(Messages.getString("GameSettingFrame.FRONT_IMAGE")); //$NON-NLS-1$
frontLoad.addActionListener(this);
frontLoadImage = res.properties.get(PGameSettings.FRONT_LOAD_BAR);
backLoad.setEnabled(pbCustom.isSelected());
frontLoad.setEnabled(backLoad.isEnabled());
scaleProgressBar = new JCheckBox(Messages.getString("GameSettingFrame.SCALE_IMAGE")); //$NON-NLS-1$
plf.make(scaleProgressBar,PGameSettings.SCALE_PROGRESS_BAR);
pbLayout.setHorizontalGroup(pbLayout.createParallelGroup()
/**/.addComponent(pbNo).addComponent(pbDef).addComponent(pbCustom)
/**/.addGroup(pbLayout.createSequentialGroup().addContainerGap()
/* */.addComponent(backLoad).addPreferredGap(ComponentPlacement.RELATED)
/* */.addComponent(frontLoad).addContainerGap())
/**/.addComponent(scaleProgressBar));
pbLayout.setVerticalGroup(pbLayout.createSequentialGroup()
/**/.addComponent(pbNo).addComponent(pbDef).addComponent(pbCustom)
/**/.addGroup(pbLayout.createParallelGroup()
/* */.addComponent(backLoad)
/* */.addComponent(frontLoad))
/**/.addComponent(scaleProgressBar));
gameIcon = res.properties.get(PGameSettings.GAME_ICON);
iconPreview = new JLabel(Messages.getString("GameSettingFrame.GAME_ICON")); //$NON-NLS-1$
if (gameIcon != null) iconPreview.setIcon(new ImageIcon(gameIcon.getDisplayImage()));
iconPreview.setHorizontalTextPosition(SwingConstants.LEFT);
changeIcon = new JButton(Messages.getString("GameSettingFrame.CHANGE_ICON")); //$NON-NLS-1$
changeIcon.addActionListener(this);
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new CustomFileFilter(Messages.getString("GameSettingFrame.ICO_FILES"),".ico")); //$NON-NLS-1$ //$NON-NLS-2$
JLabel lId = new JLabel(Messages.getString("GameSettingFrame.GAME_ID")); //$NON-NLS-1$
gameId = new NumberField(0,100000000);
plf.make(gameId,PGameSettings.GAME_ID);
randomise = new JButton(Messages.getString("GameSettingFrame.RANDOMIZE")); //$NON-NLS-1$
randomise.addActionListener(this);
iconFc = new CustomFileChooser("/org/lateralgm","LAST_ICON_DIR"); //$NON-NLS-1$ //$NON-NLS-2$
iconFc.setFileFilter(new CustomFileFilter(
Messages.getString("GameSettingFrame.ICO_FILES"),".ico")); //$NON-NLS-1$ //$NON-NLS-2$
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addComponent(loadImage,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/**/.addComponent(progBar,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/**/.addGroup(layout.createSequentialGroup()
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(iconPreview)
/* */.addGroup(layout.createSequentialGroup()
/* */.addComponent(lId)
/* */.addComponent(gameId,DEFAULT_SIZE,DEFAULT_SIZE,PREFERRED_SIZE)))
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(changeIcon,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(randomise,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE))));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addComponent(loadImage)
/**/.addComponent(progBar)
/**/.addGroup(layout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(iconPreview)
/* */.addComponent(changeIcon))
/**/.addGroup(layout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(lId)
/* */.addComponent(gameId)
/* */.addComponent(randomise)));
return panel;
}
public JButton importBut;
public JButton exportBut;
public JTable constants;
public ConstantsTableModel cModel;
public JButton add;
public JButton insert;
public JButton delete;
public JButton clear;
public JButton up;
public JButton down;
public JButton sort;
private CustomFileChooser constantsFc;
private JPanel makeConstantsPane(List<Constant> curConstList)
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
importBut = new JButton(Messages.getString("GameSettingFrame.IMPORT")); //$NON-NLS-1$
importBut.addActionListener(this);
exportBut = new JButton(Messages.getString("GameSettingFrame.EXPORT")); //$NON-NLS-1$
exportBut.addActionListener(this);
cModel = new ConstantsTableModel(curConstList);
constants = new JTable(cModel);
JScrollPane scroll = new JScrollPane(constants);
constants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
constants.getTableHeader().setReorderingAllowed(false);
constants.setTransferHandler(null);
//this fixes java bug 4709394, where the cell editor does not commit on focus lost,
//causing the value to remain in-limbo even after the "Save" button is clicked.
constants.putClientProperty("terminateEditOnFocusLost",Boolean.TRUE); //$NON-NLS-1$
add = new JButton(Messages.getString("GameSettingFrame.ADD")); //$NON-NLS-1$
add.addActionListener(this);
insert = new JButton(Messages.getString("GameSettingFrame.INSERT")); //$NON-NLS-1$
insert.addActionListener(this);
delete = new JButton(Messages.getString("GameSettingFrame.DELETE")); //$NON-NLS-1$
delete.addActionListener(this);
clear = new JButton(Messages.getString("GameSettingFrame.CLEAR")); //$NON-NLS-1$
clear.addActionListener(this);
up = new JButton(Messages.getString("GameSettingFrame.UP")); //$NON-NLS-1$
up.addActionListener(this);
down = new JButton(Messages.getString("GameSettingFrame.DOWN")); //$NON-NLS-1$
down.addActionListener(this);
sort = new JButton(Messages.getString("GameSettingFrame.SORT")); //$NON-NLS-1$
sort.addActionListener(this);
constantsFc = new CustomFileChooser("/org/lateralgm","LAST_LGC_DIR"); //$NON-NLS-1$ //$NON-NLS-2$
constantsFc.setFileFilter(new CustomFileFilter(
Messages.getString("GameSettingFrame.LGC_FILES"),".lgc")); //$NON-NLS-1$ //$NON-NLS-2$
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addGroup(layout.createSequentialGroup()
/* */.addComponent(importBut,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(exportBut,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE))
/**/.addComponent(scroll)
/**/.addGroup(layout.createSequentialGroup()
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(add,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(insert,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE))
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(delete,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(clear,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE))
/* */.addPreferredGap(ComponentPlacement.UNRELATED)
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(up,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(down,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE))
/* */.addComponent(sort,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addGroup(layout.createParallelGroup()
/* */.addComponent(importBut)
/* */.addComponent(exportBut))
/**/.addComponent(scroll,DEFAULT_SIZE,120,MAX_VALUE)
/**/.addGroup(layout.createParallelGroup()
/* */.addComponent(add)
/* */.addComponent(delete)
/* */.addComponent(up)
/* */.addComponent(sort))
/**/.addGroup(layout.createParallelGroup()
/* */.addComponent(insert)
/* */.addComponent(clear)
/* */.addComponent(down)));
return panel;
}
private class ConstantsTableModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
List<Constant> constants;
ConstantsTableModel(List<Constant> list)
{
constants = GmFile.copyConstants(list);
}
public int getColumnCount()
{
return 2;
}
public int getRowCount()
{
return constants.size();
}
public Object getValueAt(int rowIndex, int columnIndex)
{
Constant c = constants.get(rowIndex);
return (columnIndex == 0) ? c.name : c.value;
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
Constant c = constants.get(rowIndex);
if (columnIndex == 0)
c.name = aValue.toString();
else
c.value = aValue.toString();
}
public boolean isCellEditable(int row, int col)
{
return true;
}
public String getColumnName(int column)
{
String ind = (column == 0) ? "NAME" : "VALUE"; //$NON-NLS-1$ //$NON-NLS-2$
return Messages.getString("GameSettingFrame." + ind); //$NON-NLS-1$
}
public void removeEmptyConstants()
{
for (int i = constants.size() - 1; i >= 0; i--)
if (constants.get(i).name.equals("")) constants.remove(i); //$NON-NLS-1$
fireTableDataChanged();
}
}
public JList includes;
public IncludesListModel iModel;
public JButton iAdd;
public JButton iDelete;
public JButton iClear;
public ButtonGroup exportFolder;
public JCheckBox overwriteExisting;
public JCheckBox removeAtGameEnd;
private CustomFileChooser includesFc;
private JPanel makeIncludePane(List<Include> curIncludeList)
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
JLabel lFiles = new JLabel(Messages.getString("GameSettingFrame.FILES_TO_INCLUDE")); //$NON-NLS-1$
iModel = new IncludesListModel(curIncludeList);
includes = new JList(iModel);
JScrollPane iScroll = new JScrollPane(includes);
iAdd = new JButton(Messages.getString("GameSettingFrame.ADD_INCLUDE")); //$NON-NLS-1$
iAdd.addActionListener(this);
iDelete = new JButton(Messages.getString("GameSettingFrame.DELETE_INCLUDE")); //$NON-NLS-1$
iDelete.addActionListener(this);
iClear = new JButton(Messages.getString("GameSettingFrame.CLEAR_INCLUDES")); //$NON-NLS-1$
iClear.addActionListener(this);
String incFolders[] = { "GameSettingFrame.SAME_FOLDER","GameSettingFrame.TEMP_DIRECTORY" }; //$NON-NLS-1$ //$NON-NLS-2$
JPanel folderPanel = makeRadioPane(
Messages.getString("GameSettingFrame.EXPORT_TO"), //$NON-NLS-1$
exportFolder = new ButtonGroup(),PGameSettings.INCLUDE_FOLDER,IncludeFolder.class,
incFolders);
overwriteExisting = new JCheckBox(Messages.getString("GameSettingFrame.OVERWRITE_EXISTING")); //$NON-NLS-1$
removeAtGameEnd = new JCheckBox(Messages.getString("GameSettingFrame.REMOVE_FILES_AT_END")); //$NON-NLS-1$
plf.make(overwriteExisting,PGameSettings.OVERWRITE_EXISTING);
plf.make(removeAtGameEnd,PGameSettings.REMOVE_AT_GAME_END);
includesFc = new CustomFileChooser("/org/lateralgm","LAST_INCLUDES_DIR"); //$NON-NLS-1$ //$NON-NLS-2$
includesFc.setMultiSelectionEnabled(true);
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addComponent(lFiles)
/**/.addComponent(iScroll,DEFAULT_SIZE,320,MAX_VALUE)
/**/.addGroup(layout.createSequentialGroup()
/* */.addComponent(iAdd,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(iDelete,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(iClear,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE))
/**/.addGroup(layout.createSequentialGroup()
/* */.addComponent(folderPanel).addGap(4,8,MAX_VALUE)
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(overwriteExisting)
/* */.addComponent(removeAtGameEnd))));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addComponent(lFiles)
/**/.addComponent(iScroll)
/**/.addGroup(layout.createParallelGroup()
/* */.addComponent(iAdd)
/* */.addComponent(iDelete)
/* */.addComponent(iClear))
/**/.addGroup(layout.createParallelGroup()
/* */.addComponent(folderPanel)
/* */.addGroup(layout.createSequentialGroup()
/* */.addComponent(overwriteExisting)
/* */.addComponent(removeAtGameEnd))));
return panel;
}
private class IncludesListModel extends DefaultListModel
{
private static final long serialVersionUID = 1L;
IncludesListModel(List<Include> list)
{
for (Include i : list)
addElement(i.copy());
}
public List<Include> toArrayList()
{
List<Include> list = new ArrayList<Include>();
for (Object o : toArray())
list.add((Include) o);
return list;
}
}
JCheckBox displayErrors;
JCheckBox writeToLog;
JCheckBox abortOnError;
JCheckBox treatUninitialisedAs0;
JCheckBox errorOnArgs;
private JPanel makeErrorPane()
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
displayErrors = new JCheckBox(Messages.getString("GameSettingFrame.ERRORS_DISPLAY")); //$NON-NLS-1$
writeToLog = new JCheckBox(Messages.getString("GameSettingFrame.ERRORS_LOG")); //$NON-NLS-1$
abortOnError = new JCheckBox(Messages.getString("GameSettingFrame.ERRORS_ABORT")); //$NON-NLS-1$
treatUninitialisedAs0 = new JCheckBox(Messages.getString("GameSettingFrame.UNINITZERO")); //$NON-NLS-1$
errorOnArgs = new JCheckBox(Messages.getString("GameSettingFrame.ERRORS_ARGS")); //$NON-NLS-1$
plf.make(displayErrors,PGameSettings.DISPLAY_ERRORS);
plf.make(writeToLog,PGameSettings.WRITE_TO_LOG);
plf.make(abortOnError,PGameSettings.ABORT_ON_ERROR);
plf.make(treatUninitialisedAs0,PGameSettings.TREAT_UNINIT_AS_0);
plf.make(errorOnArgs,PGameSettings.ERROR_ON_ARGS);
layout.setHorizontalGroup(layout.createParallelGroup().
/**/addComponent(displayErrors).addComponent(writeToLog).addComponent(abortOnError).
/**/addComponent(treatUninitialisedAs0).addComponent(errorOnArgs));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addComponent(displayErrors).addComponent(writeToLog).addComponent(abortOnError).
/**/addComponent(treatUninitialisedAs0).addComponent(errorOnArgs));
return panel;
}
JTextField author;
JTextField version;
JTextField lastChanged;
JTextArea information;
private JPanel makeInfoPane()
{
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
panel.setLayout(layout);
JLabel lAuthor = new JLabel(Messages.getString("GameSettingFrame.AUTHOR")); //$NON-NLS-1$
author = new JTextField();
JLabel lVersion = new JLabel(Messages.getString("GameSettingFrame.VERSION")); //$NON-NLS-1$
version = new JTextField();
JLabel lChanged = new JLabel(Messages.getString("GameSettingFrame.LASTCHANGED")); //$NON-NLS-1$
lastChanged = new JTextField(GmFile.gmTimeToString(res.getLastChanged()));
lastChanged.setEditable(false);
JLabel lInfo = new JLabel(Messages.getString("GameSettingFrame.INFORMATION")); //$NON-NLS-1$
information = new JTextArea();
information.setLineWrap(true);
JScrollPane infoScroll = new JScrollPane(information);
plf.make(author.getDocument(),PGameSettings.AUTHOR);
plf.make(version.getDocument(),PGameSettings.VERSION);
plf.make(information.getDocument(),PGameSettings.INFORMATION);
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addGroup(layout.createSequentialGroup()
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(lAuthor)
/* */.addComponent(lVersion)
/* */.addComponent(lChanged))
/* */.addGroup(layout.createParallelGroup()
/* */.addComponent(author,DEFAULT_SIZE,240,MAX_VALUE)
/* */.addComponent(version,DEFAULT_SIZE,240,MAX_VALUE)
/* */.addComponent(lastChanged,DEFAULT_SIZE,240,MAX_VALUE)))
/**/.addComponent(lInfo,DEFAULT_SIZE,320,MAX_VALUE)
/**/.addComponent(infoScroll));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addGroup(layout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(lAuthor)
/* */.addComponent(author))
/**/.addGroup(layout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(lVersion)
/* */.addComponent(version))
/**/.addGroup(layout.createParallelGroup(Alignment.BASELINE)
/* */.addComponent(lChanged)
/* */.addComponent(lastChanged))
/**/.addComponent(lInfo)
/**/.addComponent(infoScroll));
return panel;
}
public JButton discardButton;
public GameSettingFrame(GameSettings res, List<Constant> constants, List<Include> includes)
{
this(res,null,constants,includes);
}
public GameSettingFrame(GameSettings res, ResNode node, List<Constant> constants,
List<Include> includes)
{
super(res,node,Messages.getString("GameSettingFrame.TITLE"),false,true,true,true); //$NON-NLS-1$
setDefaultCloseOperation(HIDE_ON_CLOSE);
GroupLayout layout = new GroupLayout(getContentPane());
layout.setAutoCreateGaps(true);
setLayout(layout);
buildTabs(constants,includes);
String t = Messages.getString("GameSettingFrame.BUTTON_SAVE"); //$NON-NLS-1$
save.setText(t);
t = Messages.getString("GameSettingFrame.BUTTON_DISCARD"); //$NON-NLS-1$
discardButton = new JButton(t);
discardButton.addActionListener(this);
layout.setHorizontalGroup(layout.createParallelGroup()
/**/.addComponent(tabbedPane)
/**/.addGroup(layout.createSequentialGroup()
/* */.addContainerGap()
/* */.addComponent(save,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addComponent(discardButton,DEFAULT_SIZE,DEFAULT_SIZE,MAX_VALUE)
/* */.addContainerGap()));
layout.setVerticalGroup(layout.createSequentialGroup()
/**/.addComponent(tabbedPane)
/**/.addPreferredGap(ComponentPlacement.UNRELATED)
/**/.addGroup(layout.createParallelGroup()
/* */.addComponent(save)
/* */.addComponent(discardButton))
/**/.addContainerGap());
pack();
}
private void buildTabs(List<Constant> constants, List<Include> includes)
{
JComponent pane = makeGraphicsPane();
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_GRAPHICS"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_GRAPHICS")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(0,KeyEvent.VK_1);
pane = makeResolutionPane();
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_RESOLUTION"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_RESOLUTION")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
pane = makeOtherPane();
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_OTHER"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_OTHER")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
pane = makeLoadingPane();
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_LOADING"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_LOADING")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
pane = makeConstantsPane(LGM.currentFile.constants);
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_CONSTANTS"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_CONSTANTS")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
pane = makeIncludePane(LGM.currentFile.includes);
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_INCLUDE"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_INCLUDE")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
pane = makeErrorPane();
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_ERRORS"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_ERRORS")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
pane = makeInfoPane();
tabbedPane.addTab(Messages.getString("GameSettingFrame.TAB_INFO"), //$NON-NLS-1$
null,pane,Messages.getString("GameSettingFrame.HINT_INFO")); //$NON-NLS-1$
tabbedPane.setMnemonicAt(1,KeyEvent.VK_2);
}
public void actionPerformed(ActionEvent e)
{
super.actionPerformed(e);
if (e.getSource() == discardButton)
{
revertResource();
close();
return;
}
switch (tabbedPane.getSelectedIndex())
{
case 0:
if (e.getSource() instanceof JRadioButton) scale.setEnabled(scaling.getValue() > 0);
break;
case 1:
resolutionPane.setVisible(setResolution.isSelected());
break;
case 3:
loadActionPerformed(e);
break;
case 4:
constantsActionPerformed(e);
break;
case 5:
includesActionPerformed(e);
break;
}
}
private void loadActionPerformed(ActionEvent e)
{
if (e.getSource() == showCustomLoadImage)
{
changeCustomLoad.setEnabled(showCustomLoadImage.isSelected());
}
else if (e.getSource() == changeCustomLoad)
{
try
{
customLoadingImage = Util.getValidImage();
imagesChanged = true;
}
catch (Throwable ex)
{
JOptionPane.showMessageDialog(LGM.frame,
Messages.getString("GameSettingFrame.ERROR_LOADING_IMAGE")); //$NON-NLS-1$
}
}
else if (e.getSource() instanceof JRadioButton)
{
backLoad.setEnabled(pbCustom.isSelected());
frontLoad.setEnabled(backLoad.isEnabled());
}
else if (e.getSource() == backLoad)
{
BufferedImage img = Util.getValidImage();
if (img != null)
{
backLoadImage = img;
imagesChanged = true;
}
}
else if (e.getSource() == frontLoad)
{
BufferedImage img = Util.getValidImage();
if (img != null)
{
frontLoadImage = img;
imagesChanged = true;
}
}
else if (e.getSource() == changeIcon)
{
if (iconFc.showOpenDialog(LGM.frame) == JFileChooser.APPROVE_OPTION)
{
File f = iconFc.getSelectedFile();
if (f.exists()) try
{
gameIcon = new ICOFile(new FileInputStream(f));
iconPreview.setIcon(new ImageIcon(gameIcon.getDisplayImage()));
imagesChanged = true;
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
else if (e.getSource() == randomise)
{
gameId.setValue(new Random().nextInt(100000001));
}
}
private void constantsActionPerformed(ActionEvent e)
{
if (e.getSource() == importBut)
{
importConstants();
return;
}
if (e.getSource() == exportBut)
{
exportConstants();
return;
}
if (e.getSource() == add)
{
if (constants.getCellEditor() != null) constants.getCellEditor().stopCellEditing();
cModel.constants.add(new Constant());
int row = cModel.constants.size() - 1;
cModel.fireTableRowsInserted(row,row);
constants.getSelectionModel().setSelectionInterval(row,row);
return;
}
if (e.getSource() == insert)
{
if (constants.getSelectedRow() == -1) return;
if (constants.getCellEditor() != null) constants.getCellEditor().stopCellEditing();
cModel.constants.add(constants.getSelectedRow(),new Constant());
cModel.fireTableRowsInserted(constants.getSelectedRow(),constants.getSelectedRow());
constants.getSelectionModel().setSelectionInterval(0,constants.getSelectedRow() - 1);
return;
}
if (e.getSource() == delete)
{
if (constants.getSelectedRow() == -1) return;
int row = constants.getSelectedRow();
cModel.constants.remove(row);
cModel.fireTableRowsDeleted(row,row);
if (cModel.constants.size() > 0)
constants.getSelectionModel().setSelectionInterval(0,
Math.min(row,cModel.constants.size() - 1));
return;
}
if (e.getSource() == clear)
{
if (cModel.constants.size() == 0) return;
int last = cModel.constants.size() - 1;
cModel.constants.clear();
cModel.fireTableRowsDeleted(0,last);
return;
}
if (e.getSource() == up)
{
int row = constants.getSelectedRow();
if (row <= 0) return;
if (constants.getCellEditor() != null) constants.getCellEditor().stopCellEditing();
Constant c = cModel.constants.get(row - 1);
cModel.constants.set(row - 1,cModel.constants.get(row));
cModel.constants.set(row,c);
cModel.fireTableDataChanged();
constants.getSelectionModel().setSelectionInterval(0,row - 1);
return;
}
if (e.getSource() == down)
{
int row = constants.getSelectedRow();
if (row == -1 || row >= cModel.constants.size() - 1) return;
if (constants.getCellEditor() != null) constants.getCellEditor().stopCellEditing();
Constant c = cModel.constants.get(row + 1);
cModel.constants.set(row + 1,cModel.constants.get(row));
cModel.constants.set(row,c);
cModel.fireTableDataChanged();
constants.getSelectionModel().setSelectionInterval(0,row + 1);
return;
}
if (e.getSource() == sort)
{
if (constants.getCellEditor() != null) constants.getCellEditor().stopCellEditing();
Collections.sort(cModel.constants);
cModel.fireTableDataChanged();
if (cModel.constants.size() > 0) constants.getSelectionModel().setSelectionInterval(0,0);
return;
}
}
private void includesActionPerformed(ActionEvent e)
{
if (e.getSource() == iAdd)
{
if (includesFc.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION)
{
File[] f = includesFc.getSelectedFiles();
for (File file : f)
{
Include inc = new Include();
inc.filepath = file.getAbsolutePath();
iModel.addElement(inc);
}
}
return;
}
if (e.getSource() == iDelete)
{
int[] ind = includes.getSelectedIndices();
for (int i = ind.length - 1; i >= 0; i--)
iModel.removeElementAt(ind[i]);
return;
}
if (e.getSource() == iClear)
{
iModel.clear();
return;
}
}
private void importConstants()
{
if (constantsFc.showOpenDialog(LGM.frame) == JFileChooser.APPROVE_OPTION)
{
cModel.removeEmptyConstants();
GmStreamDecoder in = null;
try
{
File f = constantsFc.getSelectedFile();
if (f == null || !f.exists()) throw new Exception();
in = new GmStreamDecoder(f);
if (in.read3() != ('L' | ('G' << 8) | ('C' << 16))) throw new Exception();
int count = in.read2();
for (int i = 0; i < count; i++)
{
Constant c = new Constant();
c.name = in.readStr1();
c.value = in.readStr1();
if (!cModel.constants.contains(c)) cModel.constants.add(c);
}
cModel.fireTableDataChanged();
if (cModel.constants.size() > 0) constants.getSelectionModel().setSelectionInterval(0,0);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(LGM.frame,
Messages.getString("GameSettingFrame.ERROR_IMPORTING_CONSTANTS"), //$NON-NLS-1$
Messages.getString("GameSettingFrame.TITLE_ERROR"),JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$
}
finally
{
if (in != null) try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
private void exportConstants()
{
while (constantsFc.showSaveDialog(LGM.frame) == JFileChooser.APPROVE_OPTION)
{
File f = constantsFc.getSelectedFile();
if (f == null) return;
if (!f.getPath().endsWith(".lgc")) f = new File(f.getPath() + ".lgc"); //$NON-NLS-1$ //$NON-NLS-2$
int result = 0;
if (f.exists())
{
result = JOptionPane.showConfirmDialog(LGM.frame,
Messages.getString("GameSettingFrame.REPLACE_FILE"), //$NON-NLS-1$
Messages.getString("GameSettingFrame.TITLE_REPLACE_FILE"), //$NON-NLS-1$
JOptionPane.YES_NO_CANCEL_OPTION);
}
if (result == 2) return;
if (result == 1) continue;
cModel.removeEmptyConstants();
GmStreamEncoder out = null;
try
{
out = new GmStreamEncoder(f);
out.write('L');
out.write('G');
out.write('C');
out.write2(cModel.constants.size());
for (Constant c : cModel.constants)
{
out.writeStr1(c.name);
out.writeStr1(c.value);
}
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (out != null) try
{
out.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return;
}
}
public void commitChanges()
{
res.put(PGameSettings.SCALING,scaling.getValue() > 0 ? scale.getIntValue() : scaling.getValue());
res.put(PGameSettings.LOADING_IMAGE,customLoadingImage);
res.put(PGameSettings.BACK_LOAD_BAR,backLoadImage);
res.put(PGameSettings.FRONT_LOAD_BAR,frontLoadImage);
res.put(PGameSettings.GAME_ICON,gameIcon);
//we don't update the lastChanged time - that's only altered on file save/load
//Constants
cModel.removeEmptyConstants();
LGM.currentFile.constants = GmFile.copyConstants(cModel.constants);
//Includes
LGM.currentFile.includes = iModel.toArrayList();
}
public void setComponents(GameSettings g)
{
int s = g.get(PGameSettings.SCALING);
scaling.setValue(s > 1 ? 1 : s);
if (s > 1) scale.setValue(s);
scale.setEnabled(s > 0);
lastChanged.setText(GmFile.gmTimeToString(g.getLastChanged()));
customLoadingImage = g.get(PGameSettings.LOADING_IMAGE);
backLoadImage = g.get(PGameSettings.BACK_LOAD_BAR);
frontLoadImage = g.get(PGameSettings.FRONT_LOAD_BAR);
gameIcon = g.get(PGameSettings.GAME_ICON);
//Constants
cModel = new ConstantsTableModel(LGM.currentFile.constants);
constants.setModel(cModel);
constants.updateUI();
//Includes
iModel = new IncludesListModel(LGM.currentFile.includes);
includes.setModel(iModel);
includes.updateUI();
}
@Override
public String getConfirmationName()
{
return getTitle();
}
@Override
public boolean resourceChanged()
{
commitChanges();
if (imagesChanged) return true;
return !res.properties.equals(resOriginal.properties);
}
@Override
public void revertResource()
{
res.properties.putAll(resOriginal.properties);
setComponents(res);
imagesChanged = false;
}
@Override
public void updateResource()
{
commitChanges();
resOriginal = res.clone();
imagesChanged = false;
}
}
| true |
8290e6a850517739c5eda70081678353b3119a9b | Java | sanjeevkrai1/Java8Feature | /FunctionalInterfaceDemo1/src/com/test/functionalinterface/method/ref/TestMethodReferences.java | UTF-8 | 838 | 3.734375 | 4 | [] | no_license | package com.test.functionalinterface.method.ref;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class TestMethodReferences {
public static void main(String args[]) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Mac", 33));
studentList.add(new Student("Sean", 34));
studentList.add(new Student("Andrew", 40));
studentList.add(new Student("Martin", 44));
System.out.println("Without using method refernce with consumer funcitonal interface ");
studentList.forEach(new Consumer<Student>() {
@Override
public void accept(Student t) {
System.out.println(t);
}
});
System.out.println("*************method references**************");
studentList.forEach(System.out :: println);
}
}
| true |
9d6d9718d02138eab6df0dffc2ef04b14ae24df1 | Java | q3972551/LoginSv | /src/db/wxuser/entity/WXUserData.java | UTF-8 | 3,694 | 2.28125 | 2 | [] | no_license | package db.wxuser.entity;
public class WXUserData {
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database column user_wx.id
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
private String id;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database column user_wx.regtime
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
private Long regtime;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database column user_wx.logintime
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
private Long logintime;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database column user_wx.token
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
private String token;
/**
* This method was generated by Abator for iBATIS.
* This method returns the value of the database column user_wx.id
*
* @return the value of user_wx.id
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public String getId() {
return id;
}
/**
* This method was generated by Abator for iBATIS.
* This method sets the value of the database column user_wx.id
*
* @param id the value for user_wx.id
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public void setId(String id) {
this.id = id;
}
/**
* This method was generated by Abator for iBATIS.
* This method returns the value of the database column user_wx.regtime
*
* @return the value of user_wx.regtime
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public Long getRegtime() {
return regtime;
}
/**
* This method was generated by Abator for iBATIS.
* This method sets the value of the database column user_wx.regtime
*
* @param regtime the value for user_wx.regtime
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public void setRegtime(Long regtime) {
this.regtime = regtime;
}
/**
* This method was generated by Abator for iBATIS.
* This method returns the value of the database column user_wx.logintime
*
* @return the value of user_wx.logintime
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public Long getLogintime() {
return logintime;
}
/**
* This method was generated by Abator for iBATIS.
* This method sets the value of the database column user_wx.logintime
*
* @param logintime the value for user_wx.logintime
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public void setLogintime(Long logintime) {
this.logintime = logintime;
}
/**
* This method was generated by Abator for iBATIS.
* This method returns the value of the database column user_wx.token
*
* @return the value of user_wx.token
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public String getToken() {
return token;
}
/**
* This method was generated by Abator for iBATIS.
* This method sets the value of the database column user_wx.token
*
* @param token the value for user_wx.token
*
* @abatorgenerated Wed Oct 25 17:47:27 CST 2017
*/
public void setToken(String token) {
this.token = token;
}
} | true |
373667f07025f850a6a1a02e7f0dcddc3e30daad | Java | vlad107/MLHW | /src/ru/ifmo/ctddev/podtelkin/mathlogic/expression/Next.java | UTF-8 | 1,878 | 2.625 | 3 | [] | no_license | package ru.ifmo.ctddev.podtelkin.mathlogic.expression;
import javafx.util.Pair;
import ru.ifmo.ctddev.podtelkin.mathlogic.exceptions.ArithmeticMatcherException;
import ru.ifmo.ctddev.podtelkin.mathlogic.exceptions.SubstitutionException;
import java.util.Map;
import java.util.Set;
/**
* Created by vlad107 on 04.05.16.
*/
public class Next extends AbstractExpression {
private Expression A;
public Next(Expression A) {
this.A = A;
}
@Override
public boolean matchSchemaRec(Expression schema, Map<String, Integer> mapper) {
if (schema instanceof Next) {
return A.matchSchemaRec(((Next)schema).getA(), mapper);
}
if (schema instanceof Variable) {
return ((Variable)schema).matchExpression(mapper, hashCode());
}
return false;
}
@Override
public Pair<String, Expression> arithmeticMatcherRec(Expression expr, Set<String> bound) throws ArithmeticMatcherException {
if (expr instanceof Next) {
return A.arithmeticMatcherRec(((Next)expr).getA(), bound);
}
throw new ArithmeticMatcherException("Did not match");
}
@Override
public Expression substituteAll(Map<String, Expression> substitutions, Set<String> bound) throws SubstitutionException {
return new Next(A.substituteAll(substitutions, bound));
}
@Override
public void getFreeVariablesRec(Set<String> bound, Set<String> freeVariables, boolean isPropositional) {
A.getFreeVariablesRec(bound, freeVariables, isPropositional);
}
@Override
public void toStringRec(StringBuilder result) {
result.append("(");
A.toStringRec(result);
result.append("')");
}
@Override
public Expression clone() {
return new Next(A.clone());
}
public Expression getA() {
return A;
}
}
| true |
f367bd62c657a021222f9aa76a2c6acd31951d4b | Java | vvasiloud/QorderWS | /QorderWS/src/main/java/com/qorder/qorderws/dto/BusinessDTO.java | UTF-8 | 737 | 2.140625 | 2 | [] | no_license | package com.qorder.qorderws.dto;
import com.qorder.qorderws.model.EEntity;
import com.qorder.qorderws.utils.providers.EDomainLinkProvider;
public class BusinessDTO {
private String id;
private String name;
private String menuId;
private final String menuRequestURI = EDomainLinkProvider.INSTANCE.getHttpPathFor(EEntity.MENU);
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 getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public String getMenuRequestURI() {
return menuRequestURI + id;
}
}
| true |
e5bec485caca1accb55d2b281d4326232c666028 | Java | loveexception/config_manager | /src/main/java/cn/tico/iot/configmanger/module/iot/graphql/KafkaBlock.java | UTF-8 | 4,212 | 1.945313 | 2 | [] | no_license | package cn.tico.iot.configmanger.module.iot.graphql;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@IocBean(create = "init", depose = "depose")
public class KafkaBlock {
@Inject
public PropertiesProxy conf;
public Producer<String, String> producer ;
public KafkaConsumer<String, String> consumer;
public static final String TOPIC ="config";
public static final String TOPIC_DEPT="dept_config";
public static final String KEY_SNO="sno";
public static final String KEY_EXT_SNO ="extsno";
public void init() {
if(consumer!=null){
return;
}
String serializer = StringSerializer.class.getName();
String deserializer = StringDeserializer.class.getName();
Properties props = new Properties();
props.put("bootstrap.servers", conf.get("kafka.brokers"));
props.put("group.id", conf.get("kafka.group"));
props.put("enable.auto.end", "true");
props.put("auto.end.interval.ms", "1000");
props.put("auto.offset.reset", "earliest");
props.put("session.timeout.ms", "30001");
props.put("key.deserializer", deserializer);
props.put("value.deserializer", deserializer);
props.put("key.serializer", serializer);
props.put("value.serializer", serializer);
producer = new KafkaProducer<>(props);
consumer = new KafkaConsumer<>(props);
}
public void consume(Map<String,Block> map) {
consumer.subscribe(map.keySet());
while ( true ) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1l));
try {
for (ConsumerRecord<String, String> record : records) {
Block block= map.get(record.topic());
if(Lang.isNotEmpty(block)){
block.exec(record.topic(),record.key(),record.value(),record.offset());
}
}
Thread.sleep(2000);
} catch (InterruptedException e) {
Logs.get().error(e);
}
}
}
// public void consume(List topic , List<Block> blocks ) {
// consumer.subscribe(topic);
// while (true) {
// ConsumerRecords<String, String> records = consumer.poll(1000);
// for (ConsumerRecord<String, String> record : records) {
// if(Strings.equals("config",record.topic())){
// //block.exec(record.topic(), record.key(), record.value(), record.offset());
// Logs.get().infof("config record : %s",record);
// continue;
// }
// if(Strings.equals("register",record.topic())){
// Logs.get().infof("register , record: %s",record);
// //block.exec(record.topic(), record.key(), record.value(), record.offset());
// continue;
// }
//
// }
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// Logs.get().error(e);
// }
// }
// }
public void produce(String topic ,String key , String value ) {
producer.send(new ProducerRecord<>(topic, key,value));
}
public void depose(){
}
} | true |
d8125346f22b0d3be108efcb770152f2ded36450 | Java | zkiss/series-portal | /web/src/hu/bme/viaum105/web/shared/dto/persistent/SubtitleDto.java | UTF-8 | 1,119 | 2.3125 | 2 | [] | no_license | package hu.bme.viaum105.web.shared.dto.persistent;
import java.util.Date;
public class SubtitleDto extends EntityBaseDto {
private static final long serialVersionUID = 2591448942227135745L;
private EpisodeDto episode;
private String fileName;
private Date addedAt;
private SubtitleDataDto subtitleData;
public Date getAddedAt() {
return this.addedAt;
}
public EpisodeDto getEpisode() {
return this.episode;
}
public String getFileName() {
return this.fileName;
}
public SubtitleDataDto getSubtitleData() {
return this.subtitleData;
}
public void setAddedAt(Date addedAt) {
this.addedAt = addedAt;
}
public void setEpisode(EpisodeDto episode) {
this.episode = episode;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setSubtitleData(SubtitleDataDto subtitleData) {
this.subtitleData = subtitleData;
}
@Override
public String toString() {
return this.toString("SubtitleDto") + "[" + this.fileName + "]";
}
}
| true |
8820caac9e8128a377c7b546027d2a50bf3f966b | Java | TZHANHONG/AptAutoBindView | /app/src/main/java/com/example/aptsample/MainActivity.java | UTF-8 | 583 | 1.929688 | 2 | [
"Apache-2.0"
] | permissive | package com.example.aptsample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.apt.BindView;
import com.example.apt_sdk.DataApi;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv)
TextView textView;
@BindView(R.id.tv_1)
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataApi.bindView(this);
tv.setText("a");
}
}
| true |
d3b2e23d12b38d45690089f23e76e2e13ea286c5 | Java | MartemyanovR/JavaEE-Spring | /testApp2/src/testApp2/package1/HelloServlet.java | WINDOWS-1251 | 1,867 | 2.59375 | 3 | [] | no_license | package testApp2.package1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
@WebServlet(urlPatterns = "/HelloServlet", initParams = @WebInitParam(name = "id", value = "1"))
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// id - null!
String id = request.getParameter("id");
if(id == null) {
String path = request.getContextPath() + "/notFound";
response.sendRedirect(path);
}
else {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
try {
writer.println("<h2>Value ID define</h2>");
writer.println("<h2>Hello Id " + id + "</h2>");
} finally {
writer.close();
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
06732a1ebaab4c7d31f245d9d485fb7c317f0add | Java | jmsCompany/jms-server1 | /jms-webservice/jms-webservice-maintenance/src/main/java/com/jms/service/maintenance/MMachineGroupService.java | UTF-8 | 3,440 | 2.046875 | 2 | [] | no_license | package com.jms.service.maintenance;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jms.domain.db.Company;
import com.jms.domain.db.MMachineGroup;
import com.jms.domain.db.PBom;
import com.jms.domain.db.PCheckPlan;
import com.jms.domain.db.SGenderDic;
import com.jms.domain.ws.Valid;
import com.jms.domain.ws.m.WSMachineGroup;
import com.jms.domain.ws.p.WSPCheckPlan;
import com.jms.domainadapter.BeanUtil;
import com.jms.repositories.company.CompanyRepository;
import com.jms.repositories.m.MMachineGroupRepository;
import com.jms.repositories.s.SGenderDicRepository;
import com.jms.web.security.SecurityUtils;
@Service
@Transactional
public class MMachineGroupService {
private static final Logger logger = LogManager.getLogger(MMachineGroupService.class
.getCanonicalName());
@Autowired
private MMachineGroupRepository sMachineGroupRepository;
@Autowired
private CompanyRepository companyRepository;
@Autowired private SecurityUtils securityUtils;
public void loadMMachineGroupForSandVik() {
Company company = companyRepository.findByCompanyName("SandVik");
String[] machineGroups = new String[] { "pulleys", "roller line","facility"};
for (String m : machineGroups) {
MMachineGroup mg = new MMachineGroup();
mg.setGroupName(m);
sMachineGroupRepository.save(mg);
}
}
public WSMachineGroup saveMachineGroup(WSMachineGroup wsMachineGroup) throws Exception
{
MMachineGroup mMachineGroup;
if(wsMachineGroup.getIdGroup()!=null&&!wsMachineGroup.getIdGroup().equals(0l))
{
mMachineGroup = sMachineGroupRepository.findOne(wsMachineGroup.getIdGroup());
}
else
{
mMachineGroup = new MMachineGroup();
}
MMachineGroup dbMMachineGroup= toDBMMachineGroup(wsMachineGroup,mMachineGroup);
dbMMachineGroup.setIdCompany(securityUtils.getCurrentDBUser().getCompany().getIdCompany());
dbMMachineGroup = sMachineGroupRepository.save(dbMMachineGroup);
wsMachineGroup.setIdGroup(dbMMachineGroup.getIdGroup());
return wsMachineGroup;
}
@Transactional(readOnly=true)
public WSMachineGroup getWSMachineGroup(Long idMachineGroup) throws Exception
{
MMachineGroup mMachineGroup = sMachineGroupRepository.findOne(idMachineGroup);
return toWSMachineGroup(mMachineGroup);
}
@Transactional(readOnly=false)
public Valid deleteWSMachineGroup(Long idMachineGroup)
{
Valid valid = new Valid();
MMachineGroup mMachineGroup = sMachineGroupRepository.findOne(idMachineGroup);
if(!mMachineGroup.getMMachines().isEmpty())
{
valid.setValid(false);
valid.setMsg("该机组有设备,故不能删除!");
return valid;
}
else
{
sMachineGroupRepository.delete(idMachineGroup);
valid.setValid(true);
return valid;
}
}
protected MMachineGroup toDBMMachineGroup(WSMachineGroup wsMachineGroup,MMachineGroup mMachineGroup) throws Exception
{
MMachineGroup dbMMachineGroup = (MMachineGroup)BeanUtil.shallowCopy(wsMachineGroup, MMachineGroup.class, mMachineGroup);
return dbMMachineGroup;
}
protected WSMachineGroup toWSMachineGroup(MMachineGroup mMachineGroup) throws Exception
{
WSMachineGroup pc = (WSMachineGroup)BeanUtil.shallowCopy(mMachineGroup, WSMachineGroup.class, null);
return pc;
}
}
| true |
f724eb1ac375974c66834cf2f3556c82e5542323 | Java | Fed-Abreu/AbreuSeymour-a02 | /exercise11/src/main/java/Solution11.java | UTF-8 | 1,262 | 4 | 4 | [] | no_license |
import java.util.Scanner;
/*
* UCF COP3330 Fall 2021 Assignment 2 Solution
* Copyright 2021 Federico Abreu Seymour
*/
public class Solution11 {
private void statement(double euros, double exchangeRate){
System.out.println(euros + " eruos at at exchange rate of " + exchangeRate + " is ");
}
private void calculations (double euros, double exchangeRate){
//Calculate the amount to US dollars and round
double usDollars = euros * exchangeRate;
double roundedUS = Math.ceil(usDollars * 100)/100.0;
//Display US dollars
System.out.print(roundedUS +" U.S. dollars.");
}
public static void main(String[] args) {
Solution11 sol = new Solution11();
Scanner input = new Scanner(System.in);
//Display How many euros the user is exchanging and Scan double
System.out.print("How many euros are you exchanging? ");
double euros = input.nextDouble();
//Display What the exchange rate is and Scan Double
System.out.print("What is the exchange rate? ");
double exchangeRate = input.nextDouble();
//Display the amount euros and the exchange rate
sol.statement(euros, exchangeRate);
sol.calculations(euros, exchangeRate);
}
}
| true |
a0ae4581cc74f610e06f2b48d8b43c92c37685a0 | Java | sunxuanxuan/MangZhaiMang | /Bookit/app/src/main/java/com/example/mangzhaimang/bookit/CommunityFragment.java | UTF-8 | 7,454 | 1.84375 | 2 | [] | no_license | package com.example.mangzhaimang.bookit;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.List;
public class CommunityFragment extends Fragment implements ViewPager.OnPageChangeListener{
private RefreshLayout refreshLayout;
private ViewPager viewPager;
private CommunityViewPagerAdapter mAdapter;
private List<ImageView> mItems;
private LinearLayout mIndicator;
private ImageView [] mIimages;
private String [] titles = {"全部动态","借还物品","话题讨论","意见反馈"};
private ViewPager newsViewPager;
private TabLayout tabLayout;
private FloatingActionButton faBtn;
public static CommunityFragment newInstance(){
Bundle args = new Bundle();
args.putString("name","社区");
CommunityFragment fragment = new CommunityFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.community_layout, container, false);
refreshLayout = view.findViewById(R.id.community_refresh_layout);
viewPager = (ViewPager) view.findViewById(R.id.community_viewpager);
mIndicator = (LinearLayout)view.findViewById(R.id.community_indictor);
faBtn = (FloatingActionButton)view.findViewById(R.id.float_btn);
refreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
delay();
refreshlayout.finishRefresh();
}
});
refreshLayout.setEnableRefresh(true);
refreshLayout.finishRefresh();
mItems = new ArrayList<>();
addImageView();
mAdapter = new CommunityViewPagerAdapter(mItems,getActivity());
viewPager.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
mIimages = new ImageView[mItems.size()];
for(int i=0;i<mIimages.length;i++){
ImageView imageView = new ImageView(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(20,20);
lp.setMargins(15,0,15,0);
imageView.setLayoutParams(lp);
if(i==0){
imageView.setImageResource(R.drawable.indictor_select);
}else{
imageView.setImageResource(R.drawable.indicator_no_select);
}
mIimages[i] = imageView;
mIndicator.addView(imageView);
}
viewPager.addOnPageChangeListener(this);
faBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PopupMenu pop = new PopupMenu(getActivity(),faBtn);
pop.getMenuInflater().inflate(R.menu.popupmenu,pop.getMenu());
pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
if(menuItem.getItemId()==R.id.pop_item2){
Intent intent = new Intent(getActivity(),WritePaperStripsActivity.class);
startActivity(intent);
}else if(menuItem.getItemId()==R.id.pop_item1){
Intent intent = new Intent(getActivity(),XZTActivity.class);
startActivity(intent);
}
return true;
}
});
setBackgroundAlpha(0.5f,getActivity());
pop.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu popupMenu) {
setBackgroundAlpha(1.0f,getActivity());
}
});
pop.show();
}
});
return view;
}
@Override
public void onViewCreated(View viw, @Nullable Bundle savedInstanceState){
super.onViewCreated(viw,savedInstanceState);
tabLayout = (TabLayout) viw.findViewById(R.id.news_tab);
newsViewPager = (ViewPager)viw.findViewById(R.id.news_viewPager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
List<Fragment> list = new ArrayList<>();
list.add(NewsFragment.newInstance("全部动态"));
list.add(NewsFragment.newInstance("借还物品"));
list.add(NewsFragment.newInstance("话题讨论"));
list.add(NewsFragment.newInstance("意见反馈"));
adapter.setList(list);
newsViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(newsViewPager);
for(int i=0;i<4;i++){
tabLayout.getTabAt(i).setText(titles[i]);
}
}
private void addImageView(){
ImageView img0 = new ImageView(getActivity());
img0.setImageResource(R.drawable.bg1);
ImageView img1 = new ImageView(getActivity());
img1.setImageResource(R.drawable.bg1);
ImageView img2 = new ImageView(getActivity());
img2.setImageResource(R.drawable.bg1);
img0.setScaleType(ImageView.ScaleType.CENTER_CROP);
img1.setScaleType(ImageView.ScaleType.CENTER_CROP);
img2.setScaleType(ImageView.ScaleType.CENTER_CROP);
mItems.add(img0);
mItems.add(img1);
mItems.add(img2);
}
@Override
public void onPageScrolled(int position,float positionOffset,int positionOffsetPixels){
}
@Override
public void onPageSelected(int position) {
int currentViewPagerItem = position;
if (mItems != null) {
position %= mIimages.length;
int total = mIimages.length;
for (int i = 0; i < total; i++) {
if (i == position) {
mIimages[i].setImageResource(R.drawable.indictor_select);
} else {
mIimages[i].setImageResource(R.drawable.indicator_no_select);
}
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
private void delay(){
double time = 500;
while (time>0){time--;};
}
private void setBackgroundAlpha(float sAlpha,Context mContext){
WindowManager.LayoutParams lp =((Activity)mContext).getWindow().getAttributes();
lp.alpha = sAlpha;
((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
((Activity) mContext).getWindow().setAttributes(lp);
}
}
| true |
df5aebc7f262cc9879f1446b9b20be33cd17d93a | Java | tvdstorm/sea-of-saf | /mrjorrit/src/saf/structure/MoveAction.java | UTF-8 | 629 | 3.078125 | 3 | [] | no_license | package saf.structure;
import saf.Checker.Check;
public class MoveAction extends Action
{
public MoveAction(String moveActionTypeString)
{
super(moveActionTypeString);
}
public MoveActionType getMoveActionType()
{
return MoveActionType.valueOf(actionTypeString);
}
@Override
public void check(Check checker)
{
boolean moveActionExists = false;
for(MoveActionType moveActionType : MoveActionType.values())
{
if(actionTypeString.equals(moveActionType.name()))
moveActionExists = true;
}
if(!moveActionExists)
checker.addError("'" + actionTypeString + "' isn't a valid move action");
}
}
| true |
462114171badbbd79ecc792edcb64f23b3fbb63c | Java | hanframework/han | /han-core/src/main/java/org/hanframework/beans/annotation/PostConstruct.java | UTF-8 | 279 | 1.734375 | 2 | [
"Apache-2.0",
"ICU"
] | permissive | package org.hanframework.beans.annotation;
import java.lang.annotation.*;
/**
* @author liuxin
* @version Id: PostConstruct.java, v 0.1 2018/10/30 10:03 AM
*/
@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PostConstruct {
}
| true |
f43245d0219e6352068abf72ff7402c5fd966123 | Java | markjava/spring-boot-sample | /src/main/java/com/boot/sample/config/SecretKeySourceConfig.java | UTF-8 | 2,421 | 2.0625 | 2 | [] | no_license | package com.boot.sample.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
/**
* mybatis配置
* @author xu.yong
*
*/
@Configuration
@PropertySources(value={@PropertySource("classpath:jdbc.properties")})
@MapperScan(basePackages = "com.boot.sample.mapper", sqlSessionTemplateRef = "secretKeySqlSessionTemplate")
@EntityScan("com.boot.sample.entity")
public class SecretKeySourceConfig {
@Primary
@Bean("secretKeyDataSource")
@ConfigurationProperties(prefix="spring.datasource.secretkey_service")
public DataSource secretKeyDataSource() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
@Primary
@Bean(name = "secretKeySqlSessionFactory")
public SqlSessionFactory secretKeySqlSessionFactory(@Qualifier("secretKeyDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/*Mapper.xml"));
return bean.getObject();
}
@Primary
@Bean(name = "secretKeySqlSessionTemplate")
public SqlSessionTemplate secretKeySqlSessionTemplate(@Qualifier("secretKeySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Primary
@Bean
public PlatformTransactionManager memberTransactionManager() {
return new DataSourceTransactionManager(secretKeyDataSource());
}
}
| true |
ce00af674d6647a88d6256f927e4a8ea3a4e9699 | Java | BBK-PiJ-2015-01/cw-cm | /TestSerializableFilePersistenceUnit.java | UTF-8 | 8,234 | 2.8125 | 3 | [] | no_license | import org.junit.*;
import static org.junit.Assert.*;
import java.io.*;
import java.util.*;
//
// Don't forget org.junit.runner.JUnitCore !
//
public class TestSerializableFilePersistenceUnit {
private PersistenceUnit instance;
private final String expectedFileName = "contacts.txt";
@Before
public void init() {
// instance = getInstance() ;
}
// ****************************************************************
// constructor tests
// ****************************************************************
@Test(expected=IllegalArgumentException.class)
public void constructor_NullFile() throws PersistenceUnitException {
instance = getInstance(null);
}
@Test(expected=IllegalArgumentException.class)
public void constructor_EmptyFilename() throws PersistenceUnitException {
instance = getInstance("");
}
// ****************************************************************
// load tests
// ****************************************************************
@Test
public void load_UnknownFile() throws PersistenceUnitException{
instance = getInstance(expectedFileName) ;
try {
instance.load();
ContactManagerModel model = instance.getModel();
assertNotNull(model);
} catch(PersistenceUnitException ex) {
ex.printStackTrace();
}
}
// ****************************************************************
// get Model tests
// ****************************************************************
// ****************************************************************
// commit tests
// ****************************************************************
// ****************************************************************
// sequence tests
// ****************************************************************
@Test
public void crudSequence_NoCommit() throws PersistenceUnitException {
final String testFileName = String.format("%d.txt", System.nanoTime());
instance = getInstance(testFileName);
ContactManagerModel model = instance.getModel();
assertNotNull(model);
int contactId = model.addContact("name", "notes");
ModelContact contact = model.getContact(contactId);
assertNotNull(contact);
File expectedFile = new File(testFileName);
assertFalse(expectedFile.exists());
}
@Test
public void crudSequence_WithCommit() throws PersistenceUnitException {
final String testFileName = String.format("%d.txt", System.nanoTime());
try {
instance = getInstance(testFileName);
ContactManagerModel model = instance.getModel();
assertNotNull(model);
int contactId = model.addContact("name", "notes");
ModelContact contact = model.getContact(contactId);
assertNotNull(contact);
instance.commit();
} finally {
// cleanup
cleanUpFile(testFileName);
}
}
@Test
public void crudSequence_NonNullsContactWithCommitAndReload() throws PersistenceUnitException {
final String testFileName = String.format("%d.txt", System.nanoTime());
try {
instance = getInstance(testFileName);
ContactManagerModel model = instance.getModel();
assertNotNull(model);
String expectedContactName = "name";
String expectedContactNotes = "notes";
int contactId = model.addContact(expectedContactName, expectedContactNotes);
instance.commit();
// new instance
instance = getInstance(testFileName);
model = instance.getModel();
assertNotNull(model);
ModelContact resultContact = model.getContact(contactId);
assertNotNull(resultContact);
assertEquals(expectedContactName, resultContact.getName());
assertEquals(expectedContactNotes, resultContact.getNotes());
} finally {
// cleanup
cleanUpFile(testFileName);
}
}
@Test
public void crudSequence_NullsMeetingWithCommitAndReload() throws PersistenceUnitException {
final String testFileName = String.format("%d.txt", System.nanoTime());
try {
instance = getInstance(testFileName);
ContactManagerModel model = instance.getModel();
assertNotNull(model);
int meetingId = model.addMeeting(null, null, null);
instance.commit();
// new instance
instance = getInstance(testFileName);
model = instance.getModel();
assertNotNull(model);
ModelMeeting resultMeeting = model.getMeeting(meetingId);
assertNotNull(resultMeeting);
assertNull(resultMeeting.getDate());
assertNull(resultMeeting.getContacts());
assertNull(resultMeeting.getNotes());
} finally {
// cleanup
cleanUpFile(testFileName);
}
}
@Test
public void crudSequence_NonNullsMeetingWithCommitAndReload() throws PersistenceUnitException {
final String testFileName = String.format("%d.txt", System.nanoTime());
try {
instance = getInstance(testFileName);
ContactManagerModel model = instance.getModel();
assertNotNull(model);
//Create a contact
String expectedContactName = "Contact name";
String expectedContactNotes = "Contact notes";
int contactId = model.addContact(expectedContactName, expectedContactNotes);
ModelContact resultContact = model.getContact(contactId);
// Create a meeting
Calendar expectedMeetingDate = Calendar.getInstance();
String expectedMeetingNotes = "Meeting notes";
Set<Contact> expectedContacts = new HashSet<>();
expectedContacts.add(resultContact);
int meetingId = model.addMeeting(expectedMeetingDate, expectedContacts, expectedMeetingNotes);
instance.commit();
// new instance
instance = getInstance(testFileName);
model = instance.getModel();
assertNotNull(model);
ModelMeeting resultMeeting = model.getMeeting(meetingId);
assertNotNull(resultMeeting);
assertEquals(expectedMeetingDate, resultMeeting.getDate());
assertEquals(expectedContacts, resultMeeting.getContacts());
assertEquals(expectedMeetingNotes, resultMeeting.getNotes());
//
ModelContact setContact = (ModelContact) resultMeeting.getContacts().stream().findFirst().get();
assertEquals(expectedContactName, setContact.getName());
assertEquals(expectedContactNotes, setContact.getNotes());
} finally {
// cleanup
cleanUpFile(testFileName);
}
}
@Test
public void crudSequence_AddMeetingsAndReloadBeforeCommit() throws PersistenceUnitException {
final String testFileName = String.format("%d.txt", System.nanoTime());
try {
instance = getInstance(testFileName);
ContactManagerModel model = instance.getModel();
assertNotNull(model);
// Create a meeting
int meetingId = model.addMeeting(null, null, null);
Set<ModelMeeting> meetings = model.getMeetings();
assertEquals(1, meetings.size());
// Reload the model
instance.load();
model = instance.getModel();
meetings = model.getMeetings();
assertTrue(meetings.isEmpty());
} finally {
// cleanup not required (no commit)
File expectedFile = new File(testFileName);
assertFalse(expectedFile.exists());
}
}
@Test
public void crudSequence_AddMeetingsBeforeReOpeningFileToTestIds() throws PersistenceUnitException {
final String testFileName = String.format("%d.txt", System.nanoTime());
try {
final int count = 5;
instance = getInstance(testFileName);
ContactManagerModel model = instance.getModel();
assertNotNull(model);
// Create some meetings
for (int i = 0; i < count; i++ ) {
int meetingId = model.addMeeting(null, null, null);
}
instance.commit();
// Re-open the file
instance = getInstance(testFileName);
model = instance.getModel();
assertNotNull(model);
//
// Create some meetings
for (int i = 0; i < count; i++ ) {
int meetingId = model.addMeeting(null, null, null);
}
//
Set<ModelMeeting> meetings = model.getMeetings();
assertEquals(2 * count, meetings.size());
} finally {
// cleanup
cleanUpFile(testFileName);
}
}
@Test
public void commit_AfterLoad() throws PersistenceUnitException {
instance = getInstance(expectedFileName) ;
instance.load();
instance.commit();
}
protected PersistenceUnit getInstance(String fileName) throws PersistenceUnitException {
return new SerializableFilePersistenceUnit(fileName);
}
protected void cleanUpFile(String fileName) {
File expectedFile = new File(fileName);
assertTrue(expectedFile.exists());
expectedFile.delete();
assertFalse(expectedFile.exists());
}
}
| true |
59f517ff500ade56d85d344a787936a9ba30c91a | Java | kingj1261/oa | /oa-common-dal/src/main/java/com/wantai/oa/common/dal/mappings/dos/performance/RevenueDo.java | UTF-8 | 1,170 | 1.960938 | 2 | [] | no_license | /**
* Wantai.com Inc.
* Copyright (c) 2004-2012 All Rights Reserved.
*/
package com.wantai.oa.common.dal.mappings.dos.performance;
import com.wantai.oa.common.dal.mappings.dos.BaseDo;
/**
* 个税配置对象
*
* @author maping.mp
* @version $Id: RevenueDo.groovy, v 0.1 2015-1-04 下午09:36:49 maping.mp Exp $
*/
public class RevenueDo extends BaseDo {
/** 区间最小值*/
private String fromValue;
/** 区间最大值*/
private String toValue;
/** 税率*/
private String ratio;
/** 速算扣除数*/
private String deducts;
public String getFromValue() {
return fromValue;
}
public void setFromValue(String fromValue) {
this.fromValue = fromValue;
}
public String getToValue() {
return toValue;
}
public void setToValue(String toValue) {
this.toValue = toValue;
}
public String getRatio() {
return ratio;
}
public void setRatio(String ratio) {
this.ratio = ratio;
}
public String getDeducts() {
return deducts;
}
public void setDeducts(String deducts) {
this.deducts = deducts;
}
}
| true |
d32a8df42df626e83b6eb65a311d2c8dc61b141e | Java | benkim1028/CodingInterview | /leetcode/Sum of Left.java | UTF-8 | 712 | 3.40625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) return 0;
return helper(root, false);
}
private int helper(TreeNode root, boolean isLeft){
if(root.left == null && root.right == null)
return isLeft ? root.val : 0;
int leftValue = 0;
int rightValue = 0;
if(root.left != null) leftValue = helper(root.left, true);
if(root.right != null) rightValue = helper(root.right, false);
return leftValue + rightValue;
}
}
| true |
43b529df1862bb0f6ae8ffc8fe7e27a209ff2f4d | Java | anrysliusar/Java-Homeworks | /homework6/src/Main.java | UTF-8 | 2,155 | 3.171875 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
User vasya = new User(1, "vasya", 31, Sex.MALE);
User petya = new User(2, "petya", 29, Sex.MALE);
User kolya = new User(3, "kolya", 28, Sex.MALE);
User olya = new User(4, "olya", 30, Sex.FEMALE);
User max = new User(5, "max", 31, Sex.OTHER);
User anya = new User(6, "anya", 12, Sex.FEMALE);
User oleg = new User(7, "oleg", 3, Sex.MALE);
User andrey = new User(8, "andrey", 24, Sex.MALE);
User masha = new User(9, "masha", 67, Sex.FEMALE);
User olia = new User(10, "olia", 21, Sex.FEMALE);
ArrayList<User> users = new ArrayList<>();
users.add(vasya);
users.add(petya);
users.add(kolya);
users.add(olya);
users.add(max);
users.add(anya);
users.add(oleg);
users.add(andrey);
users.add(masha);
users.add(olia);
// - Проітерувати колекцію юзерів, вивевши тільки юзерів з парним значенням ід
List<User> collect = users.stream()
.filter(user -> user.getId() % 2 == 0)
.collect(Collectors.toList());
System.out.println(collect);
// - Проітерувати колекцію юзерів, вивевши тільки юзерів з ім'ям , довжина якого більше ніж 5 символів
List<User> collect2 = users.stream()
.filter(user -> user.getName().length() > 5)
.collect(Collectors.toList());
System.out.println(collect2);
// - Проітерувати колекцію юзерів, вивевши тільки юзерів жінок
List<User> collect3 = users.stream()
.filter(user -> user.getSex().equals(Sex.FEMALE))
.collect(Collectors.toList());
System.out.println(collect3);
}
}
| true |
943baff7d340402cbccbf36bbe7f600a856dd824 | Java | googleapis/google-cloud-java | /java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/BfdStatusOrBuilder.java | UTF-8 | 11,529 | 1.710938 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | permissive | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
public interface BfdStatusOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.BfdStatus)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The BFD session initialization mode for this BGP peer. If set to ACTIVE, the Cloud Router will initiate the BFD session for this BGP peer. If set to PASSIVE, the Cloud Router will wait for the peer router to initiate the BFD session for this BGP peer. If set to DISABLED, BFD is disabled for this BGP peer.
* Check the BfdSessionInitializationMode enum for the list of possible values.
* </pre>
*
* <code>optional string bfd_session_initialization_mode = 218156954;</code>
*
* @return Whether the bfdSessionInitializationMode field is set.
*/
boolean hasBfdSessionInitializationMode();
/**
*
*
* <pre>
* The BFD session initialization mode for this BGP peer. If set to ACTIVE, the Cloud Router will initiate the BFD session for this BGP peer. If set to PASSIVE, the Cloud Router will wait for the peer router to initiate the BFD session for this BGP peer. If set to DISABLED, BFD is disabled for this BGP peer.
* Check the BfdSessionInitializationMode enum for the list of possible values.
* </pre>
*
* <code>optional string bfd_session_initialization_mode = 218156954;</code>
*
* @return The bfdSessionInitializationMode.
*/
java.lang.String getBfdSessionInitializationMode();
/**
*
*
* <pre>
* The BFD session initialization mode for this BGP peer. If set to ACTIVE, the Cloud Router will initiate the BFD session for this BGP peer. If set to PASSIVE, the Cloud Router will wait for the peer router to initiate the BFD session for this BGP peer. If set to DISABLED, BFD is disabled for this BGP peer.
* Check the BfdSessionInitializationMode enum for the list of possible values.
* </pre>
*
* <code>optional string bfd_session_initialization_mode = 218156954;</code>
*
* @return The bytes for bfdSessionInitializationMode.
*/
com.google.protobuf.ByteString getBfdSessionInitializationModeBytes();
/**
*
*
* <pre>
* Unix timestamp of the most recent config update.
* </pre>
*
* <code>optional int64 config_update_timestamp_micros = 457195569;</code>
*
* @return Whether the configUpdateTimestampMicros field is set.
*/
boolean hasConfigUpdateTimestampMicros();
/**
*
*
* <pre>
* Unix timestamp of the most recent config update.
* </pre>
*
* <code>optional int64 config_update_timestamp_micros = 457195569;</code>
*
* @return The configUpdateTimestampMicros.
*/
long getConfigUpdateTimestampMicros();
/**
*
*
* <pre>
* Control packet counts for the current BFD session.
* </pre>
*
* <code>
* optional .google.cloud.compute.v1.BfdStatusPacketCounts control_packet_counts = 132573561;
* </code>
*
* @return Whether the controlPacketCounts field is set.
*/
boolean hasControlPacketCounts();
/**
*
*
* <pre>
* Control packet counts for the current BFD session.
* </pre>
*
* <code>
* optional .google.cloud.compute.v1.BfdStatusPacketCounts control_packet_counts = 132573561;
* </code>
*
* @return The controlPacketCounts.
*/
com.google.cloud.compute.v1.BfdStatusPacketCounts getControlPacketCounts();
/**
*
*
* <pre>
* Control packet counts for the current BFD session.
* </pre>
*
* <code>
* optional .google.cloud.compute.v1.BfdStatusPacketCounts control_packet_counts = 132573561;
* </code>
*/
com.google.cloud.compute.v1.BfdStatusPacketCountsOrBuilder getControlPacketCountsOrBuilder();
/**
*
*
* <pre>
* Inter-packet time interval statistics for control packets.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.PacketIntervals control_packet_intervals = 500806649;
* </code>
*/
java.util.List<com.google.cloud.compute.v1.PacketIntervals> getControlPacketIntervalsList();
/**
*
*
* <pre>
* Inter-packet time interval statistics for control packets.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.PacketIntervals control_packet_intervals = 500806649;
* </code>
*/
com.google.cloud.compute.v1.PacketIntervals getControlPacketIntervals(int index);
/**
*
*
* <pre>
* Inter-packet time interval statistics for control packets.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.PacketIntervals control_packet_intervals = 500806649;
* </code>
*/
int getControlPacketIntervalsCount();
/**
*
*
* <pre>
* Inter-packet time interval statistics for control packets.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.PacketIntervals control_packet_intervals = 500806649;
* </code>
*/
java.util.List<? extends com.google.cloud.compute.v1.PacketIntervalsOrBuilder>
getControlPacketIntervalsOrBuilderList();
/**
*
*
* <pre>
* Inter-packet time interval statistics for control packets.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.PacketIntervals control_packet_intervals = 500806649;
* </code>
*/
com.google.cloud.compute.v1.PacketIntervalsOrBuilder getControlPacketIntervalsOrBuilder(
int index);
/**
*
*
* <pre>
* The diagnostic code specifies the local system's reason for the last change in session state. This allows remote systems to determine the reason that the previous session failed, for example. These diagnostic codes are specified in section 4.1 of RFC5880
* Check the LocalDiagnostic enum for the list of possible values.
* </pre>
*
* <code>optional string local_diagnostic = 463737083;</code>
*
* @return Whether the localDiagnostic field is set.
*/
boolean hasLocalDiagnostic();
/**
*
*
* <pre>
* The diagnostic code specifies the local system's reason for the last change in session state. This allows remote systems to determine the reason that the previous session failed, for example. These diagnostic codes are specified in section 4.1 of RFC5880
* Check the LocalDiagnostic enum for the list of possible values.
* </pre>
*
* <code>optional string local_diagnostic = 463737083;</code>
*
* @return The localDiagnostic.
*/
java.lang.String getLocalDiagnostic();
/**
*
*
* <pre>
* The diagnostic code specifies the local system's reason for the last change in session state. This allows remote systems to determine the reason that the previous session failed, for example. These diagnostic codes are specified in section 4.1 of RFC5880
* Check the LocalDiagnostic enum for the list of possible values.
* </pre>
*
* <code>optional string local_diagnostic = 463737083;</code>
*
* @return The bytes for localDiagnostic.
*/
com.google.protobuf.ByteString getLocalDiagnosticBytes();
/**
*
*
* <pre>
* The current BFD session state as seen by the transmitting system. These states are specified in section 4.1 of RFC5880
* Check the LocalState enum for the list of possible values.
* </pre>
*
* <code>optional string local_state = 149195453;</code>
*
* @return Whether the localState field is set.
*/
boolean hasLocalState();
/**
*
*
* <pre>
* The current BFD session state as seen by the transmitting system. These states are specified in section 4.1 of RFC5880
* Check the LocalState enum for the list of possible values.
* </pre>
*
* <code>optional string local_state = 149195453;</code>
*
* @return The localState.
*/
java.lang.String getLocalState();
/**
*
*
* <pre>
* The current BFD session state as seen by the transmitting system. These states are specified in section 4.1 of RFC5880
* Check the LocalState enum for the list of possible values.
* </pre>
*
* <code>optional string local_state = 149195453;</code>
*
* @return The bytes for localState.
*/
com.google.protobuf.ByteString getLocalStateBytes();
/**
*
*
* <pre>
* Negotiated transmit interval for control packets.
* </pre>
*
* <code>optional uint32 negotiated_local_control_tx_interval_ms = 21768340;</code>
*
* @return Whether the negotiatedLocalControlTxIntervalMs field is set.
*/
boolean hasNegotiatedLocalControlTxIntervalMs();
/**
*
*
* <pre>
* Negotiated transmit interval for control packets.
* </pre>
*
* <code>optional uint32 negotiated_local_control_tx_interval_ms = 21768340;</code>
*
* @return The negotiatedLocalControlTxIntervalMs.
*/
int getNegotiatedLocalControlTxIntervalMs();
/**
*
*
* <pre>
* The most recent Rx control packet for this BFD session.
* </pre>
*
* <code>optional .google.cloud.compute.v1.BfdPacket rx_packet = 505069729;</code>
*
* @return Whether the rxPacket field is set.
*/
boolean hasRxPacket();
/**
*
*
* <pre>
* The most recent Rx control packet for this BFD session.
* </pre>
*
* <code>optional .google.cloud.compute.v1.BfdPacket rx_packet = 505069729;</code>
*
* @return The rxPacket.
*/
com.google.cloud.compute.v1.BfdPacket getRxPacket();
/**
*
*
* <pre>
* The most recent Rx control packet for this BFD session.
* </pre>
*
* <code>optional .google.cloud.compute.v1.BfdPacket rx_packet = 505069729;</code>
*/
com.google.cloud.compute.v1.BfdPacketOrBuilder getRxPacketOrBuilder();
/**
*
*
* <pre>
* The most recent Tx control packet for this BFD session.
* </pre>
*
* <code>optional .google.cloud.compute.v1.BfdPacket tx_packet = 111386275;</code>
*
* @return Whether the txPacket field is set.
*/
boolean hasTxPacket();
/**
*
*
* <pre>
* The most recent Tx control packet for this BFD session.
* </pre>
*
* <code>optional .google.cloud.compute.v1.BfdPacket tx_packet = 111386275;</code>
*
* @return The txPacket.
*/
com.google.cloud.compute.v1.BfdPacket getTxPacket();
/**
*
*
* <pre>
* The most recent Tx control packet for this BFD session.
* </pre>
*
* <code>optional .google.cloud.compute.v1.BfdPacket tx_packet = 111386275;</code>
*/
com.google.cloud.compute.v1.BfdPacketOrBuilder getTxPacketOrBuilder();
/**
*
*
* <pre>
* Session uptime in milliseconds. Value will be 0 if session is not up.
* </pre>
*
* <code>optional int64 uptime_ms = 125398365;</code>
*
* @return Whether the uptimeMs field is set.
*/
boolean hasUptimeMs();
/**
*
*
* <pre>
* Session uptime in milliseconds. Value will be 0 if session is not up.
* </pre>
*
* <code>optional int64 uptime_ms = 125398365;</code>
*
* @return The uptimeMs.
*/
long getUptimeMs();
}
| true |
c3a336144630a98312006a8481fa4b35447a1da8 | Java | ushaheu/ticket-manager-gateway | /src/main/java/com/odilium/ticket/management/repository/TicketLogsRepository.java | UTF-8 | 673 | 1.96875 | 2 | [] | no_license | package com.odilium.ticket.management.repository;
import com.odilium.ticket.management.mongo.entities.TicketLogs;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;
@Repository
public interface TicketLogsRepository extends MongoRepository<TicketLogs, String> {
List<TicketLogs> findByTicketIDOrConsumerPhoneNumber(String ticketID, String phoneNumber);
List<TicketLogs> findByticketID(String ticketID);
Stream<TicketLogs> findByTicketIssuedDateTimeBetween(Date transactionStartTime, Date transactionEndTime);
}
| true |
a9ae845e13636137fd5d52373fdbdfde3aa03c18 | Java | Demonip/GaugeSyncData | /src/main/java/com/easted/data/entity/oracleDSEntity/ProjectclassinfoEntity.java | UTF-8 | 5,217 | 2.265625 | 2 | [] | no_license | package com.easted.data.entity.oracleDSEntity;
import javax.persistence.*;
/**
* Created by admin on 2017/10/10.
*/
@Entity
@Table(name = "PROJECTCLASSINFO", schema = "DGHY", catalog = "")
public class ProjectclassinfoEntity {
@Id
private String projectCode;
private String projectName;
private String xmflsxxm;
private String xmflphqgzxm;
private String xmflzyysntzxm;
private String xmflzxjsjjsjzjxm;
private String xmfldfzfxzzqzjxm;
private String xmflzftzlxm;
private String xmflqytzlxm;
private String xmflszfjdlrxm;
@Basic
@Column(name = "PROJECT_CODE")
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
@Basic
@Column(name = "PROJECT_NAME")
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
@Basic
@Column(name = "XMFLSXXM")
public String getXmflsxxm() {
return xmflsxxm;
}
public void setXmflsxxm(String xmflsxxm) {
this.xmflsxxm = xmflsxxm;
}
@Basic
@Column(name = "XMFLPHQGZXM")
public String getXmflphqgzxm() {
return xmflphqgzxm;
}
public void setXmflphqgzxm(String xmflphqgzxm) {
this.xmflphqgzxm = xmflphqgzxm;
}
@Basic
@Column(name = "XMFLZYYSNTZXM")
public String getXmflzyysntzxm() {
return xmflzyysntzxm;
}
public void setXmflzyysntzxm(String xmflzyysntzxm) {
this.xmflzyysntzxm = xmflzyysntzxm;
}
@Basic
@Column(name = "XMFLZXJSJJSJZJXM")
public String getXmflzxjsjjsjzjxm() {
return xmflzxjsjjsjzjxm;
}
public void setXmflzxjsjjsjzjxm(String xmflzxjsjjsjzjxm) {
this.xmflzxjsjjsjzjxm = xmflzxjsjjsjzjxm;
}
@Basic
@Column(name = "XMFLDFZFXZZQZJXM")
public String getXmfldfzfxzzqzjxm() {
return xmfldfzfxzzqzjxm;
}
public void setXmfldfzfxzzqzjxm(String xmfldfzfxzzqzjxm) {
this.xmfldfzfxzzqzjxm = xmfldfzfxzzqzjxm;
}
@Basic
@Column(name = "XMFLZFTZLXM")
public String getXmflzftzlxm() {
return xmflzftzlxm;
}
public void setXmflzftzlxm(String xmflzftzlxm) {
this.xmflzftzlxm = xmflzftzlxm;
}
@Basic
@Column(name = "XMFLQYTZLXM")
public String getXmflqytzlxm() {
return xmflqytzlxm;
}
public void setXmflqytzlxm(String xmflqytzlxm) {
this.xmflqytzlxm = xmflqytzlxm;
}
@Basic
@Column(name = "XMFLSZFJDLRXM")
public String getXmflszfjdlrxm() {
return xmflszfjdlrxm;
}
public void setXmflszfjdlrxm(String xmflszfjdlrxm) {
this.xmflszfjdlrxm = xmflszfjdlrxm;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProjectclassinfoEntity that = (ProjectclassinfoEntity) o;
if (projectCode != null ? !projectCode.equals(that.projectCode) : that.projectCode != null) return false;
if (projectName != null ? !projectName.equals(that.projectName) : that.projectName != null) return false;
if (xmflsxxm != null ? !xmflsxxm.equals(that.xmflsxxm) : that.xmflsxxm != null) return false;
if (xmflphqgzxm != null ? !xmflphqgzxm.equals(that.xmflphqgzxm) : that.xmflphqgzxm != null) return false;
if (xmflzyysntzxm != null ? !xmflzyysntzxm.equals(that.xmflzyysntzxm) : that.xmflzyysntzxm != null)
return false;
if (xmflzxjsjjsjzjxm != null ? !xmflzxjsjjsjzjxm.equals(that.xmflzxjsjjsjzjxm) : that.xmflzxjsjjsjzjxm != null)
return false;
if (xmfldfzfxzzqzjxm != null ? !xmfldfzfxzzqzjxm.equals(that.xmfldfzfxzzqzjxm) : that.xmfldfzfxzzqzjxm != null)
return false;
if (xmflzftzlxm != null ? !xmflzftzlxm.equals(that.xmflzftzlxm) : that.xmflzftzlxm != null) return false;
if (xmflqytzlxm != null ? !xmflqytzlxm.equals(that.xmflqytzlxm) : that.xmflqytzlxm != null) return false;
if (xmflszfjdlrxm != null ? !xmflszfjdlrxm.equals(that.xmflszfjdlrxm) : that.xmflszfjdlrxm != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = projectCode != null ? projectCode.hashCode() : 0;
result = 31 * result + (projectName != null ? projectName.hashCode() : 0);
result = 31 * result + (xmflsxxm != null ? xmflsxxm.hashCode() : 0);
result = 31 * result + (xmflphqgzxm != null ? xmflphqgzxm.hashCode() : 0);
result = 31 * result + (xmflzyysntzxm != null ? xmflzyysntzxm.hashCode() : 0);
result = 31 * result + (xmflzxjsjjsjzjxm != null ? xmflzxjsjjsjzjxm.hashCode() : 0);
result = 31 * result + (xmfldfzfxzzqzjxm != null ? xmfldfzfxzzqzjxm.hashCode() : 0);
result = 31 * result + (xmflzftzlxm != null ? xmflzftzlxm.hashCode() : 0);
result = 31 * result + (xmflqytzlxm != null ? xmflqytzlxm.hashCode() : 0);
result = 31 * result + (xmflszfjdlrxm != null ? xmflszfjdlrxm.hashCode() : 0);
return result;
}
}
| true |
b160d66853f334ea1194ebaffa1b39a5d104f2a5 | Java | bukajsytlos/faf-java-server | /src/main/java/com/faforever/server/entity/Player.java | UTF-8 | 1,922 | 2.015625 | 2 | [] | no_license | package com.faforever.server.entity;
import com.faforever.server.client.ClientConnection;
import com.faforever.server.client.ConnectionAware;
import com.faforever.server.game.PlayerGameState;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.Nullable;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "login")
@Getter
@Setter
public class Player extends Login implements ConnectionAware {
@OneToOne(mappedBy = "player")
@Nullable
private Ladder1v1Rating ladder1v1Rating;
@OneToOne(mappedBy = "player")
@Nullable
private GlobalRating globalRating;
@ManyToMany
@JoinTable(name = "unique_id_users",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "uniqueid_hash", referencedColumnName = "id"))
private Set<HardwareInformation> hardwareInformations;
@OneToOne(mappedBy = "player")
private MatchMakerBanDetails matchMakerBanDetails;
@ManyToMany
@JoinTable(name = "avatars",
joinColumns = @JoinColumn(name = "idUser", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "idAvatar", referencedColumnName = "id"))
private List<AvatarAssociation> availableAvatars;
@Transient
private Game currentGame;
@Transient
private PlayerGameState gameState = PlayerGameState.NONE;
@Transient
private ClientConnection clientConnection;
public void setGameState(PlayerGameState gameState) {
PlayerGameState.verifyTransition(this.gameState, gameState);
this.gameState = gameState;
}
@Override
public String toString() {
return "Player(" + getId() + ", " + getLogin() + ")";
}
}
| true |
93adb7057c3e9ec846b8f29f33bf779ed23b6b6a | Java | ZepaMZarp/Trabalho-Final-DS1 | /src/Model/Administrador.java | UTF-8 | 199 | 2.125 | 2 | [] | no_license | package Model;
public class Administrador extends Usuario {
public Administrador(int id, String login, String senha, String nome) {
super(id, login, senha, nome, true);
}
}
| true |
98fe463586ed1c39e0104193de09e51c49610c5e | Java | quachs/529Project | /src/classification/RankedClass.java | UTF-8 | 1,276 | 2.890625 | 3 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | package classification;
// See README for references
import retrievals.rankedRetrieval.*;
import indexes.diskPart.DiskPosting;
/**
*
* A class that maintains an accumulated document score for
* every relevant document found through a ranked query.
*
*/
public class RankedClass implements Comparable<RankedClass>{
private double centroid;
private RocchioClassifier.authors author;
public RankedClass(double centroid, RocchioClassifier.authors author){
this.centroid = centroid;
this.author = author;
}
public void setCentroid(double centroid){
this.centroid = centroid;
}
public double getCentroid(){
return centroid;
}
public RocchioClassifier.authors getAuthor(){
return author;
}
/**
* Method of comparison that allows documents
* to be ranked by document score and presented
* to a user in ranked order.
*
* @param ri
* @return
*/
@Override
public int compareTo(RankedClass ri){
if (ri.centroid > this.centroid){
return -1;
}
if (this.centroid == ri.centroid) {
return 0;
}
else {
return 1;
}
}
} | true |
45f4a5ce0177347855f4dd9671756def70fa0847 | Java | Coyote188/cccfmis | /src/cccf/myenum/ProductEnabledStatus.java | UTF-8 | 119 | 1.703125 | 2 | [] | no_license | package cccf.myenum;
public enum ProductEnabledStatus {
不启用,启用;//启用状态下企业才能看到
}
| true |
fdd84189345f2bd1c5c73f383b22984967e3746f | Java | GuiJunz/sctu-java-2019 | /1806101030甘露露JAVA/src/day20190905/Test01.java | UTF-8 | 448 | 3.5625 | 4 | [] | no_license | package lab_02.day20190905;
public class Test01 {
//调用了main函数,前面需要static修饰符
//add(){}前面加上返回值的类型如int ,()里面写啥
//{}里面写啥如返回return
static int add(int a,int b){
return a + b;
}
//main函数,程序运行的入口
public static void main(String[] args) {
System.out.println("hello,world");
int c = add(1,2);
}
}
| true |
bbb851dc52a15b65e00b4ea544540111a5727006 | Java | awesman/MyFirstJava | /homeWork/src/lesson2/Task3DopTable.java | UTF-8 | 312 | 2.921875 | 3 | [] | no_license | package lesson2;
public class Task3DopTable {
public static void main(String[] args) {
// Вывод таблицы умножения 10 чисел
for(int i=1;i<11;i++){
for(int j=1;j<11;j++){
System.out.printf("%4d",i*j );
}
System.out.println();
}
}
} | true |
ce206597eb3dce304b8f1eb15904ee1541e79a55 | Java | beraki/blog-project-api | /src/main/java/info/beraki/CustomSuccessMessage.java | UTF-8 | 407 | 2.359375 | 2 | [] | no_license | package info.beraki;
import com.google.gson.Gson;
public class CustomSuccessMessage {
int error;
String message;
int lastId;
CustomSuccessMessage(int error, String error_message, int lastId){
this.error = error;
this.message = error_message;
this.lastId= lastId;
}
@Override
public String toString() {
return new Gson().toJson(this);
}
}
| true |
245574baebd6ce6d1fbe9cbccd2b7988bd02aed7 | Java | owenleexiaoyu/WanAndroid | /app/src/main/java/cc/lixiaoyu/wanandroid/core/project/ProjectFragment.java | UTF-8 | 2,650 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | package cc.lixiaoyu.wanandroid.core.project;
import android.annotation.SuppressLint;
import android.view.View;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import cc.lixiaoyu.wanandroid.R;
import cc.lixiaoyu.wanandroid.base.BaseFragment;
import cc.lixiaoyu.wanandroid.entity.ProjectTitle;
import cc.lixiaoyu.wanandroid.util.network.RetrofitManager;
import cc.lixiaoyu.wanandroid.util.ToastUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
public class ProjectFragment extends BaseFragment {
@BindView(R.id.fproject_tablayout)
TabLayout mTabLayout;
@BindView(R.id.fproject_viewpager)
ViewPager mViewPager;
private ProjectAdapter mAdapter;
private List<ProjectTitle> mDataList;
//当前加载的子fragment的序号
private int mCurrentChildFragmentIndex = 0;
public static ProjectFragment newInstance() {
return new ProjectFragment();
}
@Override
protected void initData() {
}
@SuppressLint("CheckResult")
@Override
protected void initView(View view) {
mDataList = new ArrayList<>();
mAdapter = new ProjectAdapter(getChildFragmentManager(), mDataList);
mViewPager.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
mCurrentChildFragmentIndex = i;
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
RetrofitManager.getInstance().getWanAndroidService().getProjectsData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
mDataList.addAll(result.getData());
mAdapter.notifyDataSetChanged();
}, throwable -> {
throwable.printStackTrace();
ToastUtil.showToast("出错了");
});
}
@Override
protected int attachLayout() {
return R.layout.fragment_project;
}
/**
* 回到列表顶部
*/
public void jumpToListTop() {
//将置顶功能进一步交给Adapter实现
mAdapter.jumpToListTop(mCurrentChildFragmentIndex);
}
}
| true |
b50eb645388c9e15f103c16aaf0a298699e9cb34 | Java | PowerEdgware/baseJava | /src/main/java/c3p0/Test.java | UTF-8 | 666 | 2.5 | 2 | [] | no_license | package c3p0;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class Test {
static int x=11;
static ComboPooledDataSource datasource;
static{
datasource=new ComboPooledDataSource("mysql");
}
static void close(){
datasource.close();
}
static Connection getConn() throws SQLException{
return datasource.getConnection();
}
public static void main(String[] args)throws Exception {
System.out.println(Test.x);
try {
//NewProxyConnection
Connection con=Test.getConn();
System.out.println(con.getClass());
System.in.read();
} finally {
Test.close();
}
}
}
| true |
1296115a4f5261c72bb8ccc4e54ab1c7a67e89e9 | Java | DreamBoom/Lock | /app/src/main/java/com/lock/bean/MoneyResult.java | UTF-8 | 1,078 | 2.03125 | 2 | [] | no_license | package com.lock.bean;
public class MoneyResult {
/**
* success : false
* code : 0028
* message : 充值操作失败,查询充值结果出错、请稍后再试!
* module : null
* query : null
*/
private boolean success;
private String code;
private String message;
private Object module;
private Object query;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getModule() {
return module;
}
public void setModule(Object module) {
this.module = module;
}
public Object getQuery() {
return query;
}
public void setQuery(Object query) {
this.query = query;
}
}
| true |
85455f1a99608b0501a2c9558e692a9eb4d0a0b2 | Java | Uncontainer/proto | /mage4j/mage4j-php-parser/src/main/java/com/naver/mage4j/php/mage/converter/access/MageAccessClass.java | UTF-8 | 1,180 | 2.125 | 2 | [] | no_license | package com.naver.mage4j.php.mage.converter.access;
import com.naver.mage4j.php.lang.PhpType;
import com.naver.mage4j.php.lang.PhpTypeFactory;
import com.naver.mage4j.php.mage.MageAccessConstant;
import com.naver.mage4j.php.mage.MageExpression;
import com.naver.mage4j.php.mage.visitor.JavaCodeGenerateContext;
public class MageAccessClass extends MageAccessComposite {
public MageAccessClass(MageExpression name, MageExpression index) {
super(name, index);
}
@Override
public String toString() {
return name + "." + index;
}
@Override
public void visitJava(JavaCodeGenerateContext context) {
if (name instanceof MageAccessConstant) {
String className = ((MageAccessConstant)name).getValue();
if (!"self".equals(className)) {
context.addImport(PhpTypeFactory.get(className));
context.visit(name).appendCode(".");
}
} else {
context.visit(name).appendCode(".");
}
context.visit(index);
}
@Override
public PhpType getType() {
return index.getType();
}
@Override
public void setType(PhpType type) {
index.setType(type);
}
//
// @Override
// public int getAccessTypes() {
// return super.getAccessTypes() | CLASS;
// }
}
| true |
42326601deb4ebf055ea725c489f26596fb6d366 | Java | shweta2704/crossbrowser | /corejavafundamentals/src/com/sdlc/javaprograms/Calculator.java | UTF-8 | 206 | 3 | 3 | [] | no_license | package com.sdlc.javaprograms;
public class Calculator {
public int add(int a,int b)
{
int c = a+b;
return c;
}
public int sub(int a, int b)
{ int c = a-b;
return c;
}
}
| true |
38126f73b6fb662b2be969a7d52e1860543c8c10 | Java | wudingchao/HFUT__APK | /moban/src/main/java/helpsoft/HPAndroidAudioPlayer.java | UTF-8 | 15,891 | 2.21875 | 2 | [] | no_license | package com.helpsoft;
import android.media.AudioTrack;
import android.util.Log;
import java.nio.ByteBuffer;
public class HPAndroidAudioPlayer implements Runnable {
private AudioTrack m_audioTrack = null;
private final int m_bufferCount = 15;
private int m_bufferSize = 0;
private int m_cacheTime = 1;
private boolean m_exitThread = false;
private boolean m_exitThreaded = true;
private int m_playTime = 0;
private ByteBuffer m_playerBuffer = null;
private ByteBuffer[] m_playerBuffers = new ByteBuffer[15];
private int[] m_playerTimes = new int[15];
private int m_rindex = 0;
private long m_startMs = 0L;
private int m_startMs2 = 0;
private Thread m_thread = null;
private int m_windex = 0;
public void closePlayer() { // Byte code:
// 0: aload_0
// 1: getfield m_audioTrack : Landroid/media/AudioTrack;
// 4: ifnull -> 41
// 7: aload_0
// 8: iconst_1
// 9: putfield m_exitThread : Z
// 12: aload_0
// 13: getfield m_exitThreaded : Z
// 16: istore_1
// 17: iload_1
// 18: ifne -> 57
// 21: lconst_1
// 22: invokestatic sleep : (J)V
// 25: goto -> 12
// 28: astore_2
// 29: aload_2
// 30: invokevirtual printStackTrace : ()V
// 33: goto -> 12
// 36: astore_2
// 37: aload_2
// 38: invokevirtual printStackTrace : ()V
// 41: aload_0
// 42: aconst_null
// 43: putfield m_playerBuffers : [Ljava/nio/ByteBuffer;
// 46: aload_0
// 47: aconst_null
// 48: putfield m_playerTimes : [I
// 51: aload_0
// 52: aconst_null
// 53: putfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 56: return
// 57: aload_0
// 58: aconst_null
// 59: putfield m_thread : Ljava/lang/Thread;
// 62: aload_0
// 63: getfield m_audioTrack : Landroid/media/AudioTrack;
// 66: invokevirtual stop : ()V
// 69: aload_0
// 70: getfield m_audioTrack : Landroid/media/AudioTrack;
// 73: invokevirtual release : ()V
// 76: aload_0
// 77: aconst_null
// 78: putfield m_audioTrack : Landroid/media/AudioTrack;
// 81: goto -> 41
// Exception table:
// from to target type
// 0 12 36 java/lang/Exception
// 12 17 36 java/lang/Exception
// 21 25 28 java/lang/InterruptedException
// 21 25 36 java/lang/Exception
// 29 33 36 java/lang/Exception
// 57 81 36 java/lang/Exception }
public boolean openPlayer(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
if (paramInt3 == 16) {
paramInt3 = 2;
} else {
paramInt3 = 3;
}
if (paramInt2 == 1) {
paramInt2 = 2;
} else {
paramInt2 = 3;
}
try {
this.m_bufferSize = AudioTrack.getMinBufferSize(paramInt1, paramInt2, paramInt3);
Log.e("m_bufferSize", "" + this.m_bufferSize + " audioSessionId = " + paramInt4);
this.m_audioTrack = new AudioTrack(0, paramInt1, paramInt2, paramInt3, this.m_bufferSize, 1, paramInt4);
if (this.m_bufferSize < 12800)
this.m_bufferSize = 12800;
if (this.m_audioTrack == null)
return false;
this.m_thread = new Thread(this);
if (this.m_thread == null) {
this.m_audioTrack.release();
this.m_audioTrack = null;
return false;
}
} catch (Exception exception) {
exception.printStackTrace();
return false;
}
for (paramInt1 = 0; paramInt1 < 15; paramInt1++)
this.m_playerBuffers[paramInt1] = ByteBuffer.allocate(this.m_bufferSize);
this.m_playerBuffer = ByteBuffer.allocate(this.m_bufferSize);
this.m_thread.start();
this.m_audioTrack.play();
this.m_playTime = 0;
this.m_startMs = 0L;
this.m_startMs2 = 0;
return true;
}
public boolean playFrame(byte[] paramArrayOfbyte, int paramInt1, int paramInt2) {
if (paramInt2 == 0) {
this.m_playTime += 20;
} else {
this.m_playTime += paramInt2;
}
try {
synchronized (this.m_playerBuffers) {
ByteBuffer byteBuffer2 = this.m_playerBuffers[this.m_windex];
ByteBuffer byteBuffer1 = byteBuffer2;
if (byteBuffer2 == null)
byteBuffer1 = ByteBuffer.allocate(this.m_bufferSize);
if (byteBuffer1.position() > 0)
return false;
byteBuffer1.clear();
byteBuffer1.put(paramArrayOfbyte);
this.m_playerTimes[this.m_windex] = this.m_playTime;
this.m_windex++;
if (this.m_windex >= 15)
this.m_windex = 0;
return true;
}
} catch (Exception exception) {
exception.printStackTrace();
return false;
}
}
public void run() { // Byte code:
// 0: aload_0
// 1: getfield m_exitThread : Z
// 4: istore_2
// 5: iload_2
// 6: ifne -> 309
// 9: lconst_1
// 10: invokestatic sleep : (J)V
// 13: aload_0
// 14: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 17: iconst_0
// 18: invokevirtual position : (I)Ljava/nio/Buffer;
// 21: pop
// 22: aload_0
// 23: getfield m_playerBuffers : [Ljava/nio/ByteBuffer;
// 26: astore #5
// 28: aload #5
// 30: monitorenter
// 31: aload_0
// 32: getfield m_playerBuffers : [Ljava/nio/ByteBuffer;
// 35: aload_0
// 36: getfield m_rindex : I
// 39: aaload
// 40: astore #4
// 42: aload #4
// 44: astore_3
// 45: aload #4
// 47: ifnonnull -> 58
// 50: aload_0
// 51: getfield m_bufferSize : I
// 54: invokestatic allocate : (I)Ljava/nio/ByteBuffer;
// 57: astore_3
// 58: aload_3
// 59: invokevirtual position : ()I
// 62: ifle -> 358
// 65: aload_0
// 66: getfield m_playerTimes : [I
// 69: aload_0
// 70: getfield m_rindex : I
// 73: iaload
// 74: istore_1
// 75: aload_0
// 76: getfield m_startMs : J
// 79: lconst_0
// 80: lcmp
// 81: ifne -> 102
// 84: aload_0
// 85: invokestatic currentTimeMillis : ()J
// 88: aload_0
// 89: getfield m_cacheTime : I
// 92: i2l
// 93: ladd
// 94: putfield m_startMs : J
// 97: aload_0
// 98: iload_1
// 99: putfield m_startMs2 : I
// 102: iload_1
// 103: aload_0
// 104: getfield m_startMs2 : I
// 107: isub
// 108: i2l
// 109: invokestatic currentTimeMillis : ()J
// 112: aload_0
// 113: getfield m_startMs : J
// 116: lsub
// 117: lsub
// 118: invokestatic abs : (J)J
// 121: ldc2_w 500
// 124: lcmp
// 125: iflt -> 146
// 128: aload_0
// 129: invokestatic currentTimeMillis : ()J
// 132: aload_0
// 133: getfield m_cacheTime : I
// 136: i2l
// 137: ladd
// 138: putfield m_startMs : J
// 141: aload_0
// 142: iload_1
// 143: putfield m_startMs2 : I
// 146: invokestatic currentTimeMillis : ()J
// 149: aload_0
// 150: getfield m_startMs : J
// 153: lsub
// 154: iload_1
// 155: aload_0
// 156: getfield m_startMs2 : I
// 159: isub
// 160: i2l
// 161: lcmp
// 162: ifge -> 323
// 165: aload_0
// 166: aload_0
// 167: getfield m_rindex : I
// 170: iconst_1
// 171: iadd
// 172: putfield m_rindex : I
// 175: aload_0
// 176: getfield m_rindex : I
// 179: bipush #15
// 181: if_icmplt -> 189
// 184: aload_0
// 185: iconst_0
// 186: putfield m_rindex : I
// 189: aload_0
// 190: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 193: invokevirtual clear : ()Ljava/nio/Buffer;
// 196: pop
// 197: aload_0
// 198: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 201: aload_3
// 202: invokevirtual array : ()[B
// 205: iconst_0
// 206: aload_3
// 207: invokevirtual position : ()I
// 210: invokevirtual put : ([BII)Ljava/nio/ByteBuffer;
// 213: pop
// 214: aload_3
// 215: iconst_0
// 216: invokevirtual position : (I)Ljava/nio/Buffer;
// 219: pop
// 220: aload_0
// 221: aload_0
// 222: getfield m_cacheTime : I
// 225: bipush #10
// 227: isub
// 228: putfield m_cacheTime : I
// 231: aload_0
// 232: getfield m_cacheTime : I
// 235: bipush #100
// 237: if_icmpgt -> 246
// 240: aload_0
// 241: bipush #100
// 243: putfield m_cacheTime : I
// 246: aload #5
// 248: monitorexit
// 249: aload_0
// 250: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 253: invokevirtual position : ()I
// 256: ifle -> 389
// 259: aload_0
// 260: getfield m_audioTrack : Landroid/media/AudioTrack;
// 263: aload_0
// 264: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 267: invokevirtual array : ()[B
// 270: iconst_0
// 271: aload_0
// 272: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 275: invokevirtual position : ()I
// 278: invokevirtual write : ([BII)I
// 281: pop
// 282: aload_0
// 283: aload_0
// 284: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 287: invokevirtual position : ()I
// 290: putfield m_bufferSize : I
// 293: goto -> 0
// 296: astore_3
// 297: aload_3
// 298: invokevirtual printStackTrace : ()V
// 301: goto -> 0
// 304: astore_3
// 305: aload_3
// 306: invokevirtual printStackTrace : ()V
// 309: aload_0
// 310: iconst_1
// 311: putfield m_exitThreaded : Z
// 314: return
// 315: astore_3
// 316: aload_3
// 317: invokevirtual printStackTrace : ()V
// 320: goto -> 13
// 323: aload_0
// 324: aload_0
// 325: getfield m_cacheTime : I
// 328: bipush #10
// 330: isub
// 331: putfield m_cacheTime : I
// 334: aload_0
// 335: getfield m_cacheTime : I
// 338: bipush #100
// 340: if_icmpgt -> 246
// 343: aload_0
// 344: bipush #100
// 346: putfield m_cacheTime : I
// 349: goto -> 246
// 352: astore_3
// 353: aload #5
// 355: monitorexit
// 356: aload_3
// 357: athrow
// 358: aload_0
// 359: aload_0
// 360: getfield m_cacheTime : I
// 363: bipush #10
// 365: iadd
// 366: putfield m_cacheTime : I
// 369: aload_0
// 370: getfield m_cacheTime : I
// 373: sipush #2000
// 376: if_icmplt -> 246
// 379: aload_0
// 380: sipush #2000
// 383: putfield m_cacheTime : I
// 386: goto -> 246
// 389: aload_0
// 390: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 393: invokevirtual clear : ()Ljava/nio/Buffer;
// 396: pop
// 397: iconst_0
// 398: istore_1
// 399: iload_1
// 400: aload_0
// 401: getfield m_bufferSize : I
// 404: if_icmpge -> 424
// 407: aload_0
// 408: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 411: invokevirtual array : ()[B
// 414: iload_1
// 415: iconst_0
// 416: bastore
// 417: iload_1
// 418: iconst_1
// 419: iadd
// 420: istore_1
// 421: goto -> 399
// 424: aload_0
// 425: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 428: aload_0
// 429: getfield m_bufferSize : I
// 432: invokevirtual position : (I)Ljava/nio/Buffer;
// 435: pop
// 436: aload_0
// 437: getfield m_audioTrack : Landroid/media/AudioTrack;
// 440: aload_0
// 441: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 444: invokevirtual array : ()[B
// 447: iconst_0
// 448: aload_0
// 449: getfield m_playerBuffer : Ljava/nio/ByteBuffer;
// 452: invokevirtual position : ()I
// 455: invokevirtual write : ([BII)I
// 458: pop
// 459: goto -> 0
// Exception table:
// from to target type
// 0 5 304 java/lang/Exception
// 9 13 315 java/lang/InterruptedException
// 9 13 304 java/lang/Exception
// 13 31 296 java/lang/Exception
// 31 42 352 finally
// 50 58 352 finally
// 58 102 352 finally
// 102 146 352 finally
// 146 189 352 finally
// 189 246 352 finally
// 246 249 352 finally
// 249 293 296 java/lang/Exception
// 297 301 304 java/lang/Exception
// 316 320 304 java/lang/Exception
// 323 349 352 finally
// 353 356 352 finally
// 356 358 296 java/lang/Exception
// 358 386 352 finally
// 389 397 296 java/lang/Exception
// 399 417 296 java/lang/Exception
// 424 459 296 java/lang/Exception }
}
| true |
9cf827edf87d812dc493175bc406ca5566240178 | Java | ddpatel6469/Groupinder-SE-Project | /src/com/dao/EditReminderDAO.java | UTF-8 | 1,400 | 2.96875 | 3 | [] | no_license |
/* @authors Shaunak Sangdod, Nayanika Bhargava
* Team 7 || Software Engineering
* Copyright 2017, all right reserved.
* Last modified: 08/14/2017
* version 7
* Groupinder Web-application.
* References:
*/
package com.dao;
import com.bean.Reminder;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import com.dao.DbConnection;
/*
* The class EditReminderDAO creates a currentConnection to connect with database
* Success variables to check if the query executes.
*/
public class EditReminderDAO {
static Connection CurrentConnection = null;
static int succsess = 0;
/*
* The method creates connection with the database. Updates the reminder as
* per the new time and date executes the update query and updates reminder
* in the database if query is executed it returns true otherwise throws an
* exception
*/
public static boolean edit(Reminder new_reminder) {
Statement statement = null;
try {
CurrentConnection = DbConnection.getConnection();
statement = CurrentConnection.createStatement();
String updateReminder = "UPDATE reminder SET time ='" + new_reminder.date + "', message = '"
+ new_reminder.message + "' " + "WHERE reminder_id = '" + new_reminder.reminder_id + "'";
succsess = statement.executeUpdate(updateReminder);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
| true |
f7ffba2841c883a52ba363b593913bad3e807f34 | Java | johnskpark/jss-research | /JSS_Research/src/ec/app/QCSP/GPqcspLOCALSEARCH.java | UTF-8 | 5,580 | 2.203125 | 2 | [] | no_license | /*
Copyright 2006 by Sean Luke
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.app.QCSP;
import SmallStatistics.SmallStatistics;
import ec.util.*;
import ec.*;
import ec.app.QCSP.Core.QCSP;
import ec.gp.*;
import ec.gp.koza.*;
import ec.simple.*;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GPqcspLOCALSEARCH extends GPProblem implements SimpleProblemForm {
QCSP[][] train;
int from = 5;
int fromInstance = 4;
int maxStep = 50;
int nTop = 100;
double best = Integer.MAX_VALUE;
public qcspData input;
public Random rnd = new Random(99999);
public double[][] topSol = new double[nTop][];
public double[] topGPobj = new double[nTop];
public Object clone(){
GPqcspLOCALSEARCH newobj = (GPqcspLOCALSEARCH) (super.clone());
newobj.input = (qcspData)(input.clone());
return newobj;
}
public void setup(final EvolutionState state,final Parameter base) {
// very important, remember this
super.setup(state,base);
//input training data;
train = new QCSP[1][1];
for (int i = 0; i < train.length; i++) {
for (int j = 0; j < train[i].length; j++) {
DecimalFormat df2 = new DecimalFormat( "000" );
try {
System.out.println(QCSP.dataset[i+from] + df2.format(j + fromInstance + 1));
train[i][j] = new QCSP(QCSP.dataset[i+from] + df2.format(j + fromInstance + 1) + ".txt");
} catch (IOException ex) {
Logger.getLogger(GPqcspLOCALSEARCH.class.getName()).log(Level.SEVERE, null, ex);
}
for (int k = 0; k < topSol.length; k++) {
topSol[k] = new double[train[i][j].getNumberOfTask()];
topGPobj[k] = Double.POSITIVE_INFINITY;
}
}
}
// set up our input -- don't want to use the default base, it's unsafe here
input = (qcspData) state.parameters.getInstanceForParameterEq(
base.push(P_DATA), null, qcspData.class);
input.setup(state,base.push(P_DATA));
}
public void evaluate(final EvolutionState state,
final Individual ind,
final int subpopulation,
final int threadnum)
{
if (!ind.evaluated) // don't bother reevaluating
{
int hits = 0;
SmallStatistics result = new SmallStatistics();
for (int i = 0; i < train.length; i++) {
for (int j = 0; j < train[i].length; j++) {
train[i][j].setupGPIndividual((GPIndividual) ind,input, threadnum, state, stack, this);
train[i][j].LOCAL_MODE = false;
double obj = train[i][j].constructSchedule();
double[] sol = train[i][j].getOrder(train[i][j].sequence);
result.add(obj);
updateTopSol(obj, sol);
}
}
// the fitness better be KozaFitness!
KozaFitnessOriginal f = ((KozaFitnessOriginal)ind.fitness);
f.setStandardizedFitness(state, (float)result.getAverage());
f.min = result.getMin();
f.average = result.getAverage();
f.max = result.getMax();
f.hits = hits;
ind.evaluated = true;
}
}
void updateTopSol(double obj, double[] sol){
for (int i = 0; i < nTop; i++) {
if (obj<topGPobj[i]) {
for (int j = nTop-1; j > i; j--) {
topGPobj[j] = topGPobj[j-1];
System.arraycopy(topSol[j-1], 0, topSol[j], 0, topSol[j].length);
}
topGPobj[i] = obj;
System.arraycopy(sol, 0, topSol[i], 0, sol.length);
break;
} else if (obj==topGPobj[i]) break;
}
}
public void finishEvaluating(final EvolutionState state, final int threadnum)
{
for (int i = 0; i < nTop; i++) {
train[0][0].LOCAL_MODE = true;
double obj = train[0][0].LS1(2000, (int)topGPobj[i], topSol[i]);
if (obj<best) best = obj;
}
System.out.println("Best makespan is " + best);
for (int k = 0; k < topSol.length; k++) {
topSol[k] = new double[train[0][0].getNumberOfTask()];
topGPobj[k] = Double.POSITIVE_INFINITY;
}
if (state.generation == state.numGenerations-1) {
Individual best_i;
SimpleShortStatistics stats = (SimpleShortStatistics) state.statistics;
//*
best_i = stats.getBestSoFar()[0];
for (int y = 0; y < state.population.subpops[0].individuals.length; y++) {
// best individual
if (state.population.subpops[0].individuals[y].fitness.betterThan(best_i.fitness)) {
best_i = state.population.subpops[0].individuals[y];
}
}
//*
KozaFitnessOriginal f = (KozaFitnessOriginal)(best_i.fitness);
KozaFitnessOriginal.results+= "\n" + getTestPerformance(state, threadnum, best_i, 2, 105); //la
}
}
private String getTestPerformance(final EvolutionState state, final int threadnum, Individual best_i, int startIndex, int nInstances){
return "BEST OBJ = " + best;
}
}
| true |
6449e8a65f2d1c797ebef88ffca162baaeb4518f | Java | onooma/SlidingButton | /slidingbutton/src/main/java/taxi/tap30/slidingbutton/StateValue.java | UTF-8 | 826 | 2.703125 | 3 | [] | no_license | package taxi.tap30.slidingbutton;
/**
* Created by onooma on 3/12/16.
*/
public class StateValue {
private String text;
private int startColor;
private int endColor;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getStartColor() {
return startColor;
}
public void setStartColor(int startColor) {
this.startColor = startColor;
}
public int getEndColor() {
return endColor;
}
public void setEndColor(int endColor) {
this.endColor = endColor;
}
public StateValue(String text, int startColor, int endColor) {
this.text = text;
this.startColor = startColor;
this.endColor = endColor;
}
public StateValue() {
}
}
| true |