blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dcf0491f5039519356d3a455fae89e63365600e7 | 8,297,876,872,665 | 5f49e7926134959cf4c3d7a86665e2c74467701c | /src/main/java/com/ws/ogre/v2/avroutils/AvroPath.java | df926b09aa857297377dbf67e7e76d45c62ca83a | [
"Apache-2.0"
] | permissive | ogreflow/ogre | https://github.com/ogreflow/ogre | bee5f1dd0799af48ef8b05fff941faba535ffb85 | dbc934da85b9265d3a092e60b5fb1aef3f5e3f0f | refs/heads/develop | 2022-07-24T15:46:31.680000 | 2020-10-13T20:35:31 | 2020-10-13T20:35:31 | 210,383,621 | 3 | 0 | null | false | 2022-07-15T21:07:33 | 2019-09-23T15:00:28 | 2020-10-13T20:35:36 | 2022-07-15T21:07:33 | 9,002 | 3 | 0 | 5 | Java | false | false | package com.ws.ogre.v2.avroutils;
import org.apache.avro.generic.GenericRecord;
public class AvroPath {
public String path;
public String field;
public String[] subpaths;
public AvroPath(String theJsonPath) {
String[] aParts = theJsonPath.substring(2).split("\\.");
field = aParts[aParts.length - 1];
path = theJsonPath;
subpaths = new String[aParts.length - 1];
System.arraycopy(aParts, 0, subpaths, 0, subpaths.length);
}
public Object extract(GenericRecord theRecord) {
for (String aPath : this.subpaths) {
theRecord = (GenericRecord) theRecord.get(aPath);
if (theRecord == null) {
return null;
}
}
return theRecord.get(this.field);
}
public String getJsonPath() {
return path;
}
@Override
public String toString() {
return "AvroPath{" +
"path='" + path + '\'' +
'}';
}
} | UTF-8 | Java | 999 | java | AvroPath.java | Java | [] | null | [] | package com.ws.ogre.v2.avroutils;
import org.apache.avro.generic.GenericRecord;
public class AvroPath {
public String path;
public String field;
public String[] subpaths;
public AvroPath(String theJsonPath) {
String[] aParts = theJsonPath.substring(2).split("\\.");
field = aParts[aParts.length - 1];
path = theJsonPath;
subpaths = new String[aParts.length - 1];
System.arraycopy(aParts, 0, subpaths, 0, subpaths.length);
}
public Object extract(GenericRecord theRecord) {
for (String aPath : this.subpaths) {
theRecord = (GenericRecord) theRecord.get(aPath);
if (theRecord == null) {
return null;
}
}
return theRecord.get(this.field);
}
public String getJsonPath() {
return path;
}
@Override
public String toString() {
return "AvroPath{" +
"path='" + path + '\'' +
'}';
}
} | 999 | 0.562563 | 0.556557 | 45 | 21.222221 | 20.090782 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.422222 | false | false | 8 |
46c260d8b94711f4081bb8eeacd03a5a71e39c11 | 16,990,890,681,903 | 2113dfc9701c2037bee87fbc589322c0c55001ec | /src/tests/sic/sST/poisson/sSTCpoissonMetaHeurOpt.java | e0fbbbbb85ab2e8535966668c9c7a9969212fcd1 | [] | no_license | ioannischristou/popt4jlib | https://github.com/ioannischristou/popt4jlib | e129915f518d7c0638b2cc751487294b42684dcb | f03dbfb91acbc3e9a9aba9bed48e062d60cd84b8 | refs/heads/master | 2023-07-06T14:04:16.697000 | 2023-07-04T12:43:21 | 2023-07-04T12:43:21 | 23,873,414 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tests.sic.sST.poisson;
import parallel.distributed.*;
import popt4jlib.DblArray1Vector;
import popt4jlib.GA.*;
import popt4jlib.SA.*;
import popt4jlib.PS.*;
import popt4jlib.DE.*;
import utils.Messenger;
import utils.PairObjDouble;
import java.util.HashMap;
/**
* class uses any of the following supported meta-heuristics for (s,S,T) policy
* optimization under Poisson demands: GA, SA, PS, DE.
* <p>Title: popt4jlib</p>
* <p>Description: A Parallel Meta-Heuristic Optimization Library in Java</p>
* <p>Copyright: Copyright (c) 2011-2021</p>
* <p>Company: </p>
* @author Ioannis T. Christou
* @version 1.0
*/
public class sSTCpoissonMetaHeurOpt {
/**
* meta-heuristic optimizer for (s,S,T) policy optimization of a single-
* echelon system facing Poisson demands. Invoke as:
* <CODE>
* java -cp <classpath> tests.sic.sST.poisson.sSTCpoissonMetaHeurOpt
* <GA|SA|PS|DE>
* <Kr> <Ko> <L> <λ>
* <h> <p> [p2(0)] [dbglvl(0)]
* </CODE>.
* @param args
*/
public static void main(String[] args) {
final String meta = args[0];
final double Kr = Double.parseDouble(args[1]);
final double Ko = Double.parseDouble(args[2]);
final double L = Double.parseDouble(args[3]);
final double lambda = Double.parseDouble(args[4]);
final double h = Double.parseDouble(args[5]);
final double p = Double.parseDouble(args[6]);
double p2 = 0;
if (args.length>7) p2 = Double.parseDouble(args[7]);
int dbglvl = 0;
if (args.length>8) dbglvl = Integer.parseInt(args[8]);
final Messenger mger = Messenger.getInstance();
mger.setDebugLevel(dbglvl);
ssPlusDTCpoissonBoxed f =
new ssPlusDTCpoissonBoxed(Kr, Ko, L, lambda, h, p, p2);
HashMap params = new HashMap();
if ("GA".equals(meta)) { // prepare run for DGA
params.put("dga.pdbtexecinitedwrkcmd", new PDBTExecNoOpCmd());
params.put("dga.pdbthost", "localhost");
params.put("dga.pdbtport", new Integer(7891));
params.put("dga.chromosomelength", new Integer(3)); // [s,S,T]
params.put("dga.minallelevalue", new Double(-150.0));
params.put("dga.maxallelevalue", new Double(150.0));
params.put("dga.minallelevalue1", new Double(1.0));
params.put("dga.maxallelevalue1", new Double(50.0));
params.put("dga.minallelevalue2", new Double(0.01)); // Tmin
params.put("dga.maxallelevalue2", new Double(20.0)); // Tmax
params.put("dga.randomchromosomemaker",
new popt4jlib.GA.DblArray1CMaker());
params.put("dga.xoverop", new DblArray1PtXOverOp());
params.put("dga.mutationop", new DblVarArray1AlleleMutationOp());
params.put("dga.function", f);
params.put("dga.numgens", new Integer(20));
params.put("dga.poplimit", new Integer(30));
try {
DGA dga = new DGA(params);
long start = System.currentTimeMillis();
PairObjDouble result = dga.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = (double[]) result.getArg();
System.out.println("DGA soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DGA best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
else if ("SA".equals(meta)) { // prepare run for DSA
params.put("dsa.chromosomelength", new Integer(3)); // [s,S,T]
params.put("dsa.minallelevalue", new Double(-150.0));
params.put("dsa.maxallelevalue", new Double(150.0));
params.put("dsa.minallelevalue1", new Double(1.0)); // Dmin
params.put("dsa.maxallelevalue1", new Double(50.0)); // Dmax
params.put("dsa.minallelevalue2", new Double(0.01)); // Tmin
params.put("dsa.maxallelevalue2", new Double(20.0)); // Tmax
params.put("dsa.T0", new Double(100.0));
//params.put("dsa.schedule", new ExpDecSchedule());
params.put("dsa.randomchromosomemaker",
new popt4jlib.SA.DblArray1CMaker());
params.put("dsa.movedelta", new Double(2.0));
params.put("dsa.movemaker", new popt4jlib.SA.DblArray1MoveMaker());
params.put("dsa.numthreads", new Integer(24));
params.put("dsa.numtriesperiter", new Integer(3));
params.put("dsa.numouteriters", new Integer(20));
params.put("dsa.function", f);
try {
DSA dsa = new DSA(params);
long start = System.currentTimeMillis();
PairObjDouble result = dsa.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = (double[]) result.getArg();
System.out.println("DSA soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DSA best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
else if ("PS".equals(meta)) { // prepare run for DGA
params.put("dpso.pdbtexecinitedwrkcmd", new PDBTExecNoOpCmd());
params.put("dpso.pdbthost", "localhost");
params.put("dpso.pdbtport", new Integer(7891));
params.put("dpso.chromosomelength", new Integer(3)); // [s,S,T]
params.put("dpso.minallelevalue", new Double(-150.0));
params.put("dpso.maxallelevalue", new Double(150.0));
params.put("dpso.minallelevalue1", new Double(1.0));
params.put("dpso.maxallelevalue1", new Double(50.0));
params.put("dpso.minallelevalue2", new Double(0.01)); // Tmin
params.put("dpso.maxallelevalue2", new Double(20.0)); // Tmax
params.put("dpso.randomparticlemaker",
new popt4jlib.PS.DblArray1CMaker());
params.put("dpso.randomvelocitymaker",new DblArray1RandomVelocityMaker());
params.put("dpso.vmover", new DblArray1StdVelocityMaker());
params.put("dpso.c2vadder", new DblArray1ChromosomeVelocityAdder());
params.put("dpso.function", f);
params.put("dpso.numgens", new Integer(20));
try {
DPSO dpso = new DPSO(params);
long start = System.currentTimeMillis();
PairObjDouble result = dpso.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = (double[]) result.getArg();
System.out.println("DPSO soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DPSO best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
else if ("DE".equals(meta)) { // prepare run for DGA
params.put("dde.numdimensions", new Integer(3)); // [s,S,T]
params.put("dde.numtries", new Integer(20));
params.put("dde.numthreads", new Integer(24));
params.put("dde.minargval", new Double(-150.0));
params.put("dde.maxargval", new Double(150.0));
params.put("dde.minargval1", new Double(1.0));
params.put("dde.maxargval1", new Double(50.0));
params.put("dde.minargval2", new Double(0.01)); // Tmin
params.put("dde.maxargval2", new Double(20.0)); // Tmax
try {
DDE dde = new DDE(params);
long start = System.currentTimeMillis();
PairObjDouble result = dde.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = ((DblArray1Vector) result.getArg()).getDblArray1();
System.out.println("DDE soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DDE best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
}
| UTF-8 | Java | 7,854 | java | sSTCpoissonMetaHeurOpt.java | Java | [
{
"context": "(c) 2011-2021</p>\r\n * <p>Company: </p>\r\n * @author Ioannis T. Christou\r\n * @version 1.0\r\n */\r\npublic class sSTCpoissonMe",
"end": 628,
"score": 0.9998776316642761,
"start": 609,
"tag": "NAME",
"value": "Ioannis T. Christou"
}
] | null | [] | package tests.sic.sST.poisson;
import parallel.distributed.*;
import popt4jlib.DblArray1Vector;
import popt4jlib.GA.*;
import popt4jlib.SA.*;
import popt4jlib.PS.*;
import popt4jlib.DE.*;
import utils.Messenger;
import utils.PairObjDouble;
import java.util.HashMap;
/**
* class uses any of the following supported meta-heuristics for (s,S,T) policy
* optimization under Poisson demands: GA, SA, PS, DE.
* <p>Title: popt4jlib</p>
* <p>Description: A Parallel Meta-Heuristic Optimization Library in Java</p>
* <p>Copyright: Copyright (c) 2011-2021</p>
* <p>Company: </p>
* @author <NAME>
* @version 1.0
*/
public class sSTCpoissonMetaHeurOpt {
/**
* meta-heuristic optimizer for (s,S,T) policy optimization of a single-
* echelon system facing Poisson demands. Invoke as:
* <CODE>
* java -cp <classpath> tests.sic.sST.poisson.sSTCpoissonMetaHeurOpt
* <GA|SA|PS|DE>
* <Kr> <Ko> <L> <λ>
* <h> <p> [p2(0)] [dbglvl(0)]
* </CODE>.
* @param args
*/
public static void main(String[] args) {
final String meta = args[0];
final double Kr = Double.parseDouble(args[1]);
final double Ko = Double.parseDouble(args[2]);
final double L = Double.parseDouble(args[3]);
final double lambda = Double.parseDouble(args[4]);
final double h = Double.parseDouble(args[5]);
final double p = Double.parseDouble(args[6]);
double p2 = 0;
if (args.length>7) p2 = Double.parseDouble(args[7]);
int dbglvl = 0;
if (args.length>8) dbglvl = Integer.parseInt(args[8]);
final Messenger mger = Messenger.getInstance();
mger.setDebugLevel(dbglvl);
ssPlusDTCpoissonBoxed f =
new ssPlusDTCpoissonBoxed(Kr, Ko, L, lambda, h, p, p2);
HashMap params = new HashMap();
if ("GA".equals(meta)) { // prepare run for DGA
params.put("dga.pdbtexecinitedwrkcmd", new PDBTExecNoOpCmd());
params.put("dga.pdbthost", "localhost");
params.put("dga.pdbtport", new Integer(7891));
params.put("dga.chromosomelength", new Integer(3)); // [s,S,T]
params.put("dga.minallelevalue", new Double(-150.0));
params.put("dga.maxallelevalue", new Double(150.0));
params.put("dga.minallelevalue1", new Double(1.0));
params.put("dga.maxallelevalue1", new Double(50.0));
params.put("dga.minallelevalue2", new Double(0.01)); // Tmin
params.put("dga.maxallelevalue2", new Double(20.0)); // Tmax
params.put("dga.randomchromosomemaker",
new popt4jlib.GA.DblArray1CMaker());
params.put("dga.xoverop", new DblArray1PtXOverOp());
params.put("dga.mutationop", new DblVarArray1AlleleMutationOp());
params.put("dga.function", f);
params.put("dga.numgens", new Integer(20));
params.put("dga.poplimit", new Integer(30));
try {
DGA dga = new DGA(params);
long start = System.currentTimeMillis();
PairObjDouble result = dga.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = (double[]) result.getArg();
System.out.println("DGA soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DGA best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
else if ("SA".equals(meta)) { // prepare run for DSA
params.put("dsa.chromosomelength", new Integer(3)); // [s,S,T]
params.put("dsa.minallelevalue", new Double(-150.0));
params.put("dsa.maxallelevalue", new Double(150.0));
params.put("dsa.minallelevalue1", new Double(1.0)); // Dmin
params.put("dsa.maxallelevalue1", new Double(50.0)); // Dmax
params.put("dsa.minallelevalue2", new Double(0.01)); // Tmin
params.put("dsa.maxallelevalue2", new Double(20.0)); // Tmax
params.put("dsa.T0", new Double(100.0));
//params.put("dsa.schedule", new ExpDecSchedule());
params.put("dsa.randomchromosomemaker",
new popt4jlib.SA.DblArray1CMaker());
params.put("dsa.movedelta", new Double(2.0));
params.put("dsa.movemaker", new popt4jlib.SA.DblArray1MoveMaker());
params.put("dsa.numthreads", new Integer(24));
params.put("dsa.numtriesperiter", new Integer(3));
params.put("dsa.numouteriters", new Integer(20));
params.put("dsa.function", f);
try {
DSA dsa = new DSA(params);
long start = System.currentTimeMillis();
PairObjDouble result = dsa.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = (double[]) result.getArg();
System.out.println("DSA soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DSA best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
else if ("PS".equals(meta)) { // prepare run for DGA
params.put("dpso.pdbtexecinitedwrkcmd", new PDBTExecNoOpCmd());
params.put("dpso.pdbthost", "localhost");
params.put("dpso.pdbtport", new Integer(7891));
params.put("dpso.chromosomelength", new Integer(3)); // [s,S,T]
params.put("dpso.minallelevalue", new Double(-150.0));
params.put("dpso.maxallelevalue", new Double(150.0));
params.put("dpso.minallelevalue1", new Double(1.0));
params.put("dpso.maxallelevalue1", new Double(50.0));
params.put("dpso.minallelevalue2", new Double(0.01)); // Tmin
params.put("dpso.maxallelevalue2", new Double(20.0)); // Tmax
params.put("dpso.randomparticlemaker",
new popt4jlib.PS.DblArray1CMaker());
params.put("dpso.randomvelocitymaker",new DblArray1RandomVelocityMaker());
params.put("dpso.vmover", new DblArray1StdVelocityMaker());
params.put("dpso.c2vadder", new DblArray1ChromosomeVelocityAdder());
params.put("dpso.function", f);
params.put("dpso.numgens", new Integer(20));
try {
DPSO dpso = new DPSO(params);
long start = System.currentTimeMillis();
PairObjDouble result = dpso.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = (double[]) result.getArg();
System.out.println("DPSO soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DPSO best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
else if ("DE".equals(meta)) { // prepare run for DGA
params.put("dde.numdimensions", new Integer(3)); // [s,S,T]
params.put("dde.numtries", new Integer(20));
params.put("dde.numthreads", new Integer(24));
params.put("dde.minargval", new Double(-150.0));
params.put("dde.maxargval", new Double(150.0));
params.put("dde.minargval1", new Double(1.0));
params.put("dde.maxargval1", new Double(50.0));
params.put("dde.minargval2", new Double(0.01)); // Tmin
params.put("dde.maxargval2", new Double(20.0)); // Tmax
try {
DDE dde = new DDE(params);
long start = System.currentTimeMillis();
PairObjDouble result = dde.minimize(f);
long dur = System.currentTimeMillis()-start;
double[] x = ((DblArray1Vector) result.getArg()).getDblArray1();
System.out.println("DDE soln: s="+Math.round(x[0])+
" S="+(Math.round(x[0])+Math.round(x[1]))+
" T="+x[2]);
System.out.println("DDE best cost found="+result.getDouble()+
" in "+dur+" msecs");
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
}
| 7,841 | 0.619812 | 0.594601 | 190 | 39.336842 | 20.98727 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.805263 | false | false | 8 |
5c6eda05da49910e007c09dbf9f4ec8d73db1923 | 16,990,890,682,313 | 21b5d11f9d0e79ffd53ac111d8b79de87c2ee521 | /app/src/main/java/jp/ac/titech/itpro/sdl/tsuyoso2/Calendar/OnNextBackClickListener.java | 5e3f98cff5cc7984fbe3303f981e02c53d563698 | [] | no_license | TeamTSUYOSO/app | https://github.com/TeamTSUYOSO/app | e874c968e41e77ca157d1f1222027fdcac7c884e | f5ed9a57b4ab5aab0b0fd956ab69c3d6de6232a9 | refs/heads/master | 2020-05-21T08:52:42.237000 | 2017-02-28T04:57:17 | 2017-02-28T04:57:17 | 70,034,491 | 0 | 1 | null | false | 2017-02-28T04:57:18 | 2016-10-05T06:10:44 | 2016-10-05T06:23:01 | 2017-02-28T04:57:18 | 2,294 | 0 | 1 | 4 | Java | null | null | package jp.ac.titech.itpro.sdl.tsuyoso2.Calendar;
import java.util.EventListener;
/**
* Created by kayo on 2016/10/31.
*/
public interface OnNextBackClickListener extends EventListener{
public void onNextBackClick(int year,int month,int nextback);
}
| UTF-8 | Java | 257 | java | OnNextBackClickListener.java | Java | [
{
"context": "\nimport java.util.EventListener;\n/**\n * Created by kayo on 2016/10/31.\n */\npublic interface OnNextBackCli",
"end": 105,
"score": 0.9990211725234985,
"start": 101,
"tag": "USERNAME",
"value": "kayo"
}
] | null | [] | package jp.ac.titech.itpro.sdl.tsuyoso2.Calendar;
import java.util.EventListener;
/**
* Created by kayo on 2016/10/31.
*/
public interface OnNextBackClickListener extends EventListener{
public void onNextBackClick(int year,int month,int nextback);
}
| 257 | 0.77821 | 0.743191 | 9 | 27.555555 | 25.451963 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 8 |
0bcf7311807bff86bea162dac6aa23dfb5ec5730 | 18,476,949,345,729 | 2e574df4f6eca013a160222a880727f2c310f1a7 | /src/test/java/com/futuresoftware/ErpRecruitmentModuleApplicationTests.java | 2a0adf04d091a7a02dbb6202978ef83633368a99 | [] | no_license | Fady-Raafat/Hr-Module | https://github.com/Fady-Raafat/Hr-Module | d81591dcbd8abf0692f3f080050bb18ce75df500 | e1fa750920ad60c56e23634f8a96f5634ab3741e | refs/heads/master | 2022-12-24T20:32:22.372000 | 2020-10-10T16:43:53 | 2020-10-10T16:43:53 | 302,944,563 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.futuresoftware;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.futuresoftware.entities.Applicant;
import com.futuresoftware.entities.AvailableJob;
import com.futuresoftware.service.ApplicantService;
import com.futuresoftware.service.AvailableJobService;
//import com.futuresoftware.service.AvailableJobService;
@SpringBootTest
class ErpRecruitmentModuleApplicationTests {
@Test
void contextLoads() {
}
}
| UTF-8 | Java | 854 | java | ErpRecruitmentModuleApplicationTests.java | Java | [] | null | [] | package com.futuresoftware;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.futuresoftware.entities.Applicant;
import com.futuresoftware.entities.AvailableJob;
import com.futuresoftware.service.ApplicantService;
import com.futuresoftware.service.AvailableJobService;
//import com.futuresoftware.service.AvailableJobService;
@SpringBootTest
class ErpRecruitmentModuleApplicationTests {
@Test
void contextLoads() {
}
}
| 854 | 0.822014 | 0.822014 | 38 | 21.473684 | 20.351822 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736842 | false | false | 8 |
5f01e0e09c5565646c1e920bb8c3a0f8f54e7cad | 31,550,829,822,606 | e82c1473b49df5114f0332c14781d677f88f363f | /MED-CLOUD/med-service/src/test/java/nta/med/service/integration/inps/INP1001U01INPDateFormExeProcTest.java | 8b0e19bfa7dec9b406172fb2f7c2c4dac6c2976e | [] | no_license | zhiji6/mih | https://github.com/zhiji6/mih | fa1d2279388976c901dc90762bc0b5c30a2325fc | 2714d15853162a492db7ea8b953d5b863c3a8000 | refs/heads/master | 2023-08-16T18:35:19.836000 | 2017-12-28T09:33:19 | 2017-12-28T09:33:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nta.med.service.integration.inps;
import org.junit.Test;
import nta.med.common.remoting.rpc.protobuf.Rpc;
import nta.med.service.ihis.proto.CommonModelProto;
import nta.med.service.ihis.proto.InpsServiceProto;
import nta.med.service.integration.MessageRequestTest;
public class INP1001U01INPDateFormExeProcTest extends MessageRequestTest{
@Test
public void test () throws Exception{
InpsServiceProto.INP1001U01INPDateFormExeProcRequest.Builder request = InpsServiceProto.INP1001U01INPDateFormExeProcRequest.newBuilder();
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("1"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("2"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("2011/01/01"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("2018/01/01"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("5"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("6"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("7"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("8"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("9"));
sentRequestToMedApp(request.build(), InpsServiceProto.getDescriptor().getOptions().getExtension(Rpc.service));
}
}
| UTF-8 | Java | 1,525 | java | INP1001U01INPDateFormExeProcTest.java | Java | [] | null | [] | package nta.med.service.integration.inps;
import org.junit.Test;
import nta.med.common.remoting.rpc.protobuf.Rpc;
import nta.med.service.ihis.proto.CommonModelProto;
import nta.med.service.ihis.proto.InpsServiceProto;
import nta.med.service.integration.MessageRequestTest;
public class INP1001U01INPDateFormExeProcTest extends MessageRequestTest{
@Test
public void test () throws Exception{
InpsServiceProto.INP1001U01INPDateFormExeProcRequest.Builder request = InpsServiceProto.INP1001U01INPDateFormExeProcRequest.newBuilder();
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("1"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("2"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("2011/01/01"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("2018/01/01"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("5"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("6"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("7"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("8"));
request.addInpList(CommonModelProto.DataStringListItemInfo.newBuilder().setDataValue("9"));
sentRequestToMedApp(request.build(), InpsServiceProto.getDescriptor().getOptions().getExtension(Rpc.service));
}
}
| 1,525 | 0.828852 | 0.801967 | 28 | 53.464287 | 43.337944 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.678571 | false | false | 8 |
784a181397d49a14a18e8d8087cb86663d97c0b9 | 11,484,742,585,677 | 67da3917c854d39e99ccb3a04f8d698534f35fa9 | /JAVAFILES/Arrays.sort().java | e43fb9a31212edff052bfd3bcd64a32c7ae7ef73 | [] | no_license | livewire15/Java-codes | https://github.com/livewire15/Java-codes | d3c3bf6412c287298de5a966e04e37cdb8c383d8 | 403fac0873f8e2b00f11c3a956693a45b8a00848 | refs/heads/master | 2020-06-04T01:49:38.439000 | 2019-06-13T19:24:52 | 2019-06-13T19:24:52 | 191,821,575 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
import java.util.Arrays;
class sort
{
public static void main(String args[])
{
int a[]={4,1,6,3,8,5,3,9};
System.out.println("Unsorted array");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
Arrays.sort(a);
for(i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
} | UTF-8 | Java | 296 | java | Arrays.sort().java | Java | [] | null | [] | import java.util.*;
import java.util.Arrays;
class sort
{
public static void main(String args[])
{
int a[]={4,1,6,3,8,5,3,9};
System.out.println("Unsorted array");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
Arrays.sort(a);
for(i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
} | 296 | 0.648649 | 0.614865 | 20 | 13.85 | 13.09685 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 8 |
f12f817fb536abe555742d82006626a6a72f37c2 | 11,484,742,587,968 | 09cc985043e61a157daa41f77bb18cccf0ebfd28 | /src/main/java/com/ailk/eaap/op2/sso/main/model/UnifinedAuthBean.java | b2c6b4b707834cd781d0d7371bf9c778c15c9878 | [] | no_license | o2p-asiainfo/o2p-sso | https://github.com/o2p-asiainfo/o2p-sso | 83ef8303e0ea5587d2c7602ffebb1f8d7e212496 | 38f918a731c33efc056488b49ec3989dd42cce6d | refs/heads/master | 2021-01-21T10:59:23.398000 | 2017-03-01T03:33:57 | 2017-03-01T03:34:12 | 83,507,361 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ailk.eaap.op2.sso.main.model;
public class UnifinedAuthBean {
public static String PWDTYPE = "10";
public static String ACCOUNTTYPE = "100";
public static String SVCCONT = "<SvcCont>" + "<AuthReq>" + "<AuthInfo>"
+ "<AccountType>accountType</AccountType>"
+ "<AccountID>accountID</AccountID>" + "<PWDType>pWDType</PWDType>"
+ " <Password>password</Password>" + "</AuthInfo>" + "</AuthReq>"
+ "</SvcCont>";
private String transactionId;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
| UTF-8 | Java | 627 | java | UnifinedAuthBean.java | Java | [
{
"context": "ifinedAuthBean {\n\tpublic static String PWDTYPE = \"10\";\n\tpublic static String ACCOUNTTYPE = \"100\";\n\tpub",
"end": 110,
"score": 0.9712013006210327,
"start": 108,
"tag": "PASSWORD",
"value": "10"
},
{
"context": "\" + \"<PWDType>pWDType</PWDType>\"\n\t\t\t+ \" <P... | null | [] | package com.ailk.eaap.op2.sso.main.model;
public class UnifinedAuthBean {
public static String PWDTYPE = "10";
public static String ACCOUNTTYPE = "100";
public static String SVCCONT = "<SvcCont>" + "<AuthReq>" + "<AuthInfo>"
+ "<AccountType>accountType</AccountType>"
+ "<AccountID>accountID</AccountID>" + "<PWDType>pWDType</PWDType>"
+ " <Password><PASSWORD></Password>" + "</AuthInfo>" + "</AuthReq>"
+ "</SvcCont>";
private String transactionId;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
| 629 | 0.703349 | 0.69378 | 20 | 30.35 | 23.717663 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.55 | false | false | 8 |
d91e8b8e23bfcdb3b4f6fa4ec7620861a9164dc3 | 30,434,138,292,620 | cf5932e1252df50ede5b89ee52684b6e8f681782 | /src/com/demo/BitwiseDemo.java | 80ad47743af9cc6c229ac29749e993299788aca8 | [] | no_license | everythingisdata/Codility-Exercise | https://github.com/everythingisdata/Codility-Exercise | 41eee80c918128b18b4c6889421c933ac2d86e91 | 6164f766bff98b6279cc1212b429423d3356038a | refs/heads/master | 2020-03-10T02:03:12.860000 | 2018-04-11T17:06:39 | 2018-04-11T17:06:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo;
public class BitwiseDemo {
public static void main(String[] args) {
System.out.println("new BitwiseXOR().bitXor(5,8) = " + new BitwiseDemo().bitXor2Intger(5, 8));
}
public int bitXor2Intger(int m, int n) {
int result = m;
for (int i = m + 1; i < n + 1; i++) {
result = bitXor(result, i);
}
return result;
}
/**
* Bitwise XOR
*
* @param a
* @param b
* @return
*/
private int bitXor(int a, int b) {
int result = 0;
int[] binArray = new int[32];
for (int i = 31; i >= 0; i--) {
binArray[i] = (int) Math.pow(2, i);
}
for (int i = 31; i >= 0; i--) {
if (a >= binArray[i] && b >= binArray[i]) {
a -= binArray[i];
b -= binArray[i];
} else if (a >= binArray[i] && b < binArray[i]) {
a -= binArray[i];
result += binArray[i];
} else if (a < binArray[i] && b >= binArray[i]) {
b -= binArray[i];
result += binArray[i];
}
}
return result;
}
}
| UTF-8 | Java | 942 | java | BitwiseDemo.java | Java | [] | null | [] | package com.demo;
public class BitwiseDemo {
public static void main(String[] args) {
System.out.println("new BitwiseXOR().bitXor(5,8) = " + new BitwiseDemo().bitXor2Intger(5, 8));
}
public int bitXor2Intger(int m, int n) {
int result = m;
for (int i = m + 1; i < n + 1; i++) {
result = bitXor(result, i);
}
return result;
}
/**
* Bitwise XOR
*
* @param a
* @param b
* @return
*/
private int bitXor(int a, int b) {
int result = 0;
int[] binArray = new int[32];
for (int i = 31; i >= 0; i--) {
binArray[i] = (int) Math.pow(2, i);
}
for (int i = 31; i >= 0; i--) {
if (a >= binArray[i] && b >= binArray[i]) {
a -= binArray[i];
b -= binArray[i];
} else if (a >= binArray[i] && b < binArray[i]) {
a -= binArray[i];
result += binArray[i];
} else if (a < binArray[i] && b >= binArray[i]) {
b -= binArray[i];
result += binArray[i];
}
}
return result;
}
}
| 942 | 0.528662 | 0.509554 | 49 | 18.224489 | 19.144205 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.163265 | false | false | 8 |
9edf4f3da57a1d06b56b95080c10bb1b70fca9ec | 22,634,477,671,694 | a50efb53edf54253af4b5c69f00d8d8f3e9b8af9 | /src/main/java/test_base/Test02.java | 4bb7740da32d8c324e838c743f3f30dede4031cf | [] | no_license | daodaovps/testJavaCompile | https://github.com/daodaovps/testJavaCompile | 0b71e491ce6e04746dbf0a78a5e155d7e6e03384 | dd49ed920553ae8fe11302bf92b8b00edec95687 | refs/heads/master | 2020-02-07T22:43:01.525000 | 2017-08-05T07:02:58 | 2017-08-05T07:02:58 | 99,393,729 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test_base;
import com.itranswarp.compiler.JavaStringCompiler;
import org.nutz.lang.Mirror;
import java.util.Map;
/**
* Created by zhu on 17-8-5.
*/
public class Test02 {
/**
* java 脚本引擎 示例
*
* @param args
*/
public static void main(String[] args) {
try {
JavaStringCompiler compiler = new JavaStringCompiler();
//1个java文件里面可能有多个类,但是只能 有1个public的类
Map<String, byte[]> results = compiler.compile("Calc.java", JAVA_SOURCE_CODE);
Class<?> clazz = compiler.loadClass("net.javablog.ut.Calc", results);
Object calc = clazz.newInstance();
//执行 1+2 , 最终会输出3
System.out.println(Mirror.me(clazz).invoke(calc, "sum", 1, 2));
} catch (Exception e) {
}
}
static final String JAVA_SOURCE_CODE =
"package net.javablog.ut;" +
"public class Calc {" +
"" +
" public int sum(int a, int b) {" +
" return a + b;" +
" }" +
"" +
"} ";
}
| UTF-8 | Java | 1,217 | java | Test02.java | Java | [
{
"context": ".Mirror;\n\nimport java.util.Map;\n\n/**\n * Created by zhu on 17-8-5.\n */\npublic class Test02 {\n\n\n /**\n ",
"end": 145,
"score": 0.9993489980697632,
"start": 142,
"tag": "USERNAME",
"value": "zhu"
}
] | null | [] | package test_base;
import com.itranswarp.compiler.JavaStringCompiler;
import org.nutz.lang.Mirror;
import java.util.Map;
/**
* Created by zhu on 17-8-5.
*/
public class Test02 {
/**
* java 脚本引擎 示例
*
* @param args
*/
public static void main(String[] args) {
try {
JavaStringCompiler compiler = new JavaStringCompiler();
//1个java文件里面可能有多个类,但是只能 有1个public的类
Map<String, byte[]> results = compiler.compile("Calc.java", JAVA_SOURCE_CODE);
Class<?> clazz = compiler.loadClass("net.javablog.ut.Calc", results);
Object calc = clazz.newInstance();
//执行 1+2 , 最终会输出3
System.out.println(Mirror.me(clazz).invoke(calc, "sum", 1, 2));
} catch (Exception e) {
}
}
static final String JAVA_SOURCE_CODE =
"package net.javablog.ut;" +
"public class Calc {" +
"" +
" public int sum(int a, int b) {" +
" return a + b;" +
" }" +
"" +
"} ";
}
| 1,217 | 0.487424 | 0.476149 | 54 | 20.351852 | 23.639387 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 8 |
513071e5c23937b7c08053daeb9a388b470e4506 | 15,702,400,448,372 | d3f86bf6498e1a9b5252374832a83951e8463c4d | /Java Advanced - 2019/F_DEFINING CLASSES/src/Exercise/c_SpeedRacing/Car.java | ff732d92b372921a61e84c6b7cbe2bc46461ef72 | [] | no_license | Kristiyan93/Java-Advanced | https://github.com/Kristiyan93/Java-Advanced | 39fc4318d6095f8bd071f6d5e960e3ce3d5101aa | 5d6f0797ead7e5959a345222384c9498fc7d0951 | refs/heads/master | 2022-01-12T18:23:06.277000 | 2019-06-03T07:36:09 | 2019-06-03T07:36:09 | 112,085,544 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Exercise.c_SpeedRacing;
public class Car {
private String model;
private double fuelAmaount;
private double fuelCostFor1km;
private int distanceTraveled;
public Car(String model, double fuelAmaount, double fuelCostFor1km) {
this.model = model;
this.fuelAmaount = fuelAmaount;
this.fuelCostFor1km = fuelCostFor1km;
this.distanceTraveled = 0;
}
public String getModel() {
return this.model;
}
public void drive(int distance) {
double needFueld = this.fuelCostFor1km * distance;
if (fuelAmaount >= needFueld) {
this.fuelAmaount -= needFueld;
this.distanceTraveled += distance;
} else {
throw new IllegalArgumentException("Insufficient fuel for the drive");
}
}
@Override
public String toString() {
return String.format("%s %.2f %d", this.model, this.fuelAmaount, this.distanceTraveled);
}
}
| UTF-8 | Java | 970 | java | Car.java | Java | [] | null | [] | package Exercise.c_SpeedRacing;
public class Car {
private String model;
private double fuelAmaount;
private double fuelCostFor1km;
private int distanceTraveled;
public Car(String model, double fuelAmaount, double fuelCostFor1km) {
this.model = model;
this.fuelAmaount = fuelAmaount;
this.fuelCostFor1km = fuelCostFor1km;
this.distanceTraveled = 0;
}
public String getModel() {
return this.model;
}
public void drive(int distance) {
double needFueld = this.fuelCostFor1km * distance;
if (fuelAmaount >= needFueld) {
this.fuelAmaount -= needFueld;
this.distanceTraveled += distance;
} else {
throw new IllegalArgumentException("Insufficient fuel for the drive");
}
}
@Override
public String toString() {
return String.format("%s %.2f %d", this.model, this.fuelAmaount, this.distanceTraveled);
}
}
| 970 | 0.638144 | 0.630928 | 35 | 26.714285 | 23.937504 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 8 |
ca0c08b30229c746b926aee686b0427a15a95c32 | 15,702,400,450,641 | 80485d5d8493be37e2100925c425f1b79d4f1059 | /src/org/darkstorm/runescape/api/input/ModelMouseTarget.java | 7b6e3ac8f312e8da622ad57ecf20266b139ce0b1 | [] | no_license | JBerben/dbotcore | https://github.com/JBerben/dbotcore | c81f7ae1c8bb179c0dc39cb883f460c842ff4724 | 3a603fd19131d243486483ecac7fa6f0f44d71c1 | refs/heads/master | 2023-01-08T20:41:18.687000 | 2014-04-20T22:05:04 | 2014-04-20T22:05:04 | 312,756,468 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.darkstorm.runescape.api.input;
import java.awt.*;
import org.darkstorm.runescape.api.wrapper.Model;
public class ModelMouseTarget implements MouseTarget {
private final Model model;
public ModelMouseTarget(Model model) {
this.model = model;
}
@Override
public MouseTarget getTarget() {
return this;
}
@Override
public Point getLocation() {
Point point = model.getRandomPointWithin();
if(point == null
|| !model.getContext().getCalculations().isInGameArea(point))
return null;
return point;
}
@Override
public boolean isOver(Point point) {
return model.contains(point);
}
@Override
public void render(Graphics g) {
g.drawPolygon(model.getHull());
}
}
| UTF-8 | Java | 706 | java | ModelMouseTarget.java | Java | [] | null | [] | package org.darkstorm.runescape.api.input;
import java.awt.*;
import org.darkstorm.runescape.api.wrapper.Model;
public class ModelMouseTarget implements MouseTarget {
private final Model model;
public ModelMouseTarget(Model model) {
this.model = model;
}
@Override
public MouseTarget getTarget() {
return this;
}
@Override
public Point getLocation() {
Point point = model.getRandomPointWithin();
if(point == null
|| !model.getContext().getCalculations().isInGameArea(point))
return null;
return point;
}
@Override
public boolean isOver(Point point) {
return model.contains(point);
}
@Override
public void render(Graphics g) {
g.drawPolygon(model.getHull());
}
}
| 706 | 0.726629 | 0.726629 | 37 | 18.081081 | 18.068007 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.324324 | false | false | 8 |
e698ea9f9a145ed07d0b081e3fbed6aed6a4adc5 | 23,587,960,394,377 | fb7e3c49116cdc66648145dca6f6ab1b80e15434 | /src/sort/QuickSort.java | ef5a8c4c95eb4e36b9d4f506c292692486f11a23 | [] | no_license | Rainy55623/DataStructure | https://github.com/Rainy55623/DataStructure | 21d9a2600f65b7c043bab4e1713e49e1925e5148 | 9fa491c0cca1f6135ba9c2efe9f71a3c7ce3c888 | refs/heads/master | 2020-04-27T01:46:36.897000 | 2019-03-05T15:51:25 | 2019-03-05T15:51:25 | 173,974,695 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr=new int[] {4,3,6,9,5,0,1,7,6,8};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr,int start,int end) {
if(start<end) {
//把数组中的第0个数字作为标准数
int stard=arr[start];
//记录需要排序的下标
int low=start;
int high=end;
//循环比较,与标准数stard比较,比stard大的放在high侧,比stard小的放在low侧
while(low<high) {
//右边的数字比标准数大,数字不动,下标向前挪一位继续比较
while(low<high&&stard<=arr[high]) {
high--;
}
//使用右边的数字替换左边的数
arr[low]=arr[high];
//如果左边的数字比标准数小,则数字不动,下标向后挪一位继续比较
while(low<high&&arr[low]<=stard) {
low++;
}
//用左边的数字替换high侧的数字
arr[high]=arr[low];
}
//把标准数赋给高或者低的那个数字
arr[low]=stard;
//处理所有小的数字
quickSort(arr,start,low);
//处理所有大的数字
quickSort(arr,low+1,end);
}
}
}
| GB18030 | Java | 1,280 | java | QuickSort.java | Java | [] | null | [] | package sort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr=new int[] {4,3,6,9,5,0,1,7,6,8};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr,int start,int end) {
if(start<end) {
//把数组中的第0个数字作为标准数
int stard=arr[start];
//记录需要排序的下标
int low=start;
int high=end;
//循环比较,与标准数stard比较,比stard大的放在high侧,比stard小的放在low侧
while(low<high) {
//右边的数字比标准数大,数字不动,下标向前挪一位继续比较
while(low<high&&stard<=arr[high]) {
high--;
}
//使用右边的数字替换左边的数
arr[low]=arr[high];
//如果左边的数字比标准数小,则数字不动,下标向后挪一位继续比较
while(low<high&&arr[low]<=stard) {
low++;
}
//用左边的数字替换high侧的数字
arr[high]=arr[low];
}
//把标准数赋给高或者低的那个数字
arr[low]=stard;
//处理所有小的数字
quickSort(arr,start,low);
//处理所有大的数字
quickSort(arr,low+1,end);
}
}
}
| 1,280 | 0.599165 | 0.584551 | 47 | 18.382978 | 15.214149 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.042553 | false | false | 8 |
3486641515ff648f53e6eacb4b9d9a39586e6c80 | 15,418,932,595,531 | 55245f15af49bc82f064c9f41b98a0d32d544055 | /DuckHuntingV3/src/main/java/com/bateman/duckhuntingv3/Game.java | 4d46b7c5e416d1975874b513f274f4cd2db56fc0 | [] | no_license | jrbateman/ITC362_DemoCode_SP21 | https://github.com/jrbateman/ITC362_DemoCode_SP21 | 390f0cac45c562a81498480a20e40088bf264f05 | cdc7d839df6d7b3d3e78dcf73c92e84a26bd2266 | refs/heads/master | 2022-12-03T11:02:33.742000 | 2022-09-23T21:38:37 | 2022-09-23T21:38:37 | 229,639,680 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bateman.duckhuntingv3;
import android.graphics.Point;
import android.graphics.Rect;
import java.util.Random;
public class Game {
private Rect huntingRect;
private int deltaTime; // in milliSeconds
private Rect duckRect;
private int duckWidth;
private int duckHeight;
private float duckSpeed;
private boolean duckShot;
private Point cannonCenter;
private int cannonRadius;
private int barrelLength;
private int barrelRadius;
private float cannonAngle;
private Point bulletCenter;
private int bulletRadius;
private boolean bulletFired;
private float bulletAngle;
private float bulletSpeed;
private Random random;
public Game( Rect newDuckRect, int newBulletRadius,
float newDuckSpeed, float newBulletSpeed ) {
setDuckRect( newDuckRect );
setDuckSpeed( newDuckSpeed );
setBulletRadius( newBulletRadius );
setBulletSpeed( newBulletSpeed );
random = new Random( );
bulletFired = false;
duckShot = false;
cannonAngle = ( float ) Math.PI / 4; // starting cannon angle
}
public Rect getHuntingRect( ) {
return huntingRect;
}
public void setHuntingRect( Rect newHuntingRect ) {
if( newHuntingRect != null )
huntingRect = newHuntingRect;
}
public void setDeltaTime( int newDeltaTime ) {
if( newDeltaTime > 0 )
deltaTime = newDeltaTime;
}
public Rect getDuckRect( ) {
return duckRect;
}
public void setDuckRect( Rect newDuckRect ) {
if( newDuckRect != null ) {
duckWidth = newDuckRect.right - newDuckRect.left;
duckHeight = newDuckRect.bottom - newDuckRect.top;
duckRect = newDuckRect;
}
}
public void setDuckSpeed( float newDuckSpeed ) {
if( newDuckSpeed > 0 )
duckSpeed = newDuckSpeed;
}
public Point getCannonCenter( ) {
return cannonCenter;
}
public int getCannonRadius( ) {
return cannonRadius;
}
public int getBarrelLength( ) {
return barrelLength;
}
public int getBarrelRadius( ) {
return barrelRadius;
}
public void setCannon( Point newCannonCenter, int newCannonRadius,
int newBarrelLength, int newBarrelRadius ) {
if( newCannonCenter != null && newCannonRadius > 0
&& newBarrelLength > 0 ) {
cannonCenter = newCannonCenter;
cannonRadius = newCannonRadius;
barrelLength = newBarrelLength;
barrelRadius = newBarrelRadius;
bulletCenter = new Point(
( int ) ( cannonCenter.x + cannonRadius * Math.cos( cannonAngle ) ),
( int ) ( cannonCenter.y - cannonRadius * Math.sin( cannonAngle ) ) );
}
}
public Point getBulletCenter( ) {
return bulletCenter;
}
public int getBulletRadius( ) {
return bulletRadius;
}
public void setBulletRadius( int newBulletRadius ) {
if( newBulletRadius > 0 )
bulletRadius = newBulletRadius;
}
public void setBulletSpeed( float newBulletSpeed ) {
if( newBulletSpeed > 0 )
bulletSpeed = newBulletSpeed;
}
public float getCannonAngle( ) {
return cannonAngle;
}
public void setCannonAngle( float newCannonAngle ) {
if( newCannonAngle >= 0 && newCannonAngle <= Math.PI / 2 )
cannonAngle = newCannonAngle;
else if( newCannonAngle < 0 )
cannonAngle = 0;
else
cannonAngle = ( float ) Math.PI / 2;
if( !isBulletFired( ) )
loadBullet( );
}
public boolean isBulletFired( ) {
return bulletFired;
}
public void fireBullet( ) {
bulletFired = true;
bulletAngle = cannonAngle;
}
public boolean isDuckShot( ) {
return duckShot;
}
public void setDuckShot( boolean newDuckShot ) {
duckShot = newDuckShot;
}
public void startDuckFromRightTopHalf( ) {
duckRect.left = huntingRect.right;
duckRect.right = duckRect.left + duckWidth;
duckRect.top = random.nextInt( huntingRect.bottom / 2 );
duckRect.bottom = duckRect.top + duckHeight;
}
public void moveDuck( ) {
if( !duckShot ) { // move left
duckRect.left -= duckSpeed * deltaTime;
duckRect.right -= duckSpeed * deltaTime;
} else { // move down
duckRect.top += 5 * duckSpeed * deltaTime;
duckRect.bottom += 5 * duckSpeed * deltaTime;
}
}
public boolean duckOffScreen( ) {
return duckRect.right < 0 || duckRect.bottom < 0
|| duckRect.top > huntingRect.bottom
|| duckRect.left > huntingRect.right;
}
public void moveBullet( ) {
bulletCenter.x += bulletSpeed * Math.cos( bulletAngle ) * deltaTime;
bulletCenter.y -= bulletSpeed * Math.sin( bulletAngle ) * deltaTime;
}
public boolean bulletOffScreen( ) {
return bulletCenter.x - bulletRadius > huntingRect.right
|| bulletCenter.y + bulletRadius < 0;
}
public void loadBullet( ) {
bulletFired = false;
bulletCenter.x = ( int ) ( cannonCenter.x
+ cannonRadius * Math.cos( cannonAngle ) );
bulletCenter.y = ( int ) ( cannonCenter.y
- cannonRadius * Math.sin( cannonAngle ) );
}
public boolean duckHit( ) {
return duckRect.intersects(
bulletCenter.x - bulletRadius, bulletCenter.y - bulletRadius,
bulletCenter.x + bulletRadius, bulletCenter.y + bulletRadius );
}
} | UTF-8 | Java | 5,289 | java | Game.java | Java | [
{
"context": "package com.bateman.duckhuntingv3;\n\nimport android.graphics.Point;\nim",
"end": 19,
"score": 0.5826443433761597,
"start": 13,
"tag": "USERNAME",
"value": "ateman"
}
] | null | [] | package com.bateman.duckhuntingv3;
import android.graphics.Point;
import android.graphics.Rect;
import java.util.Random;
public class Game {
private Rect huntingRect;
private int deltaTime; // in milliSeconds
private Rect duckRect;
private int duckWidth;
private int duckHeight;
private float duckSpeed;
private boolean duckShot;
private Point cannonCenter;
private int cannonRadius;
private int barrelLength;
private int barrelRadius;
private float cannonAngle;
private Point bulletCenter;
private int bulletRadius;
private boolean bulletFired;
private float bulletAngle;
private float bulletSpeed;
private Random random;
public Game( Rect newDuckRect, int newBulletRadius,
float newDuckSpeed, float newBulletSpeed ) {
setDuckRect( newDuckRect );
setDuckSpeed( newDuckSpeed );
setBulletRadius( newBulletRadius );
setBulletSpeed( newBulletSpeed );
random = new Random( );
bulletFired = false;
duckShot = false;
cannonAngle = ( float ) Math.PI / 4; // starting cannon angle
}
public Rect getHuntingRect( ) {
return huntingRect;
}
public void setHuntingRect( Rect newHuntingRect ) {
if( newHuntingRect != null )
huntingRect = newHuntingRect;
}
public void setDeltaTime( int newDeltaTime ) {
if( newDeltaTime > 0 )
deltaTime = newDeltaTime;
}
public Rect getDuckRect( ) {
return duckRect;
}
public void setDuckRect( Rect newDuckRect ) {
if( newDuckRect != null ) {
duckWidth = newDuckRect.right - newDuckRect.left;
duckHeight = newDuckRect.bottom - newDuckRect.top;
duckRect = newDuckRect;
}
}
public void setDuckSpeed( float newDuckSpeed ) {
if( newDuckSpeed > 0 )
duckSpeed = newDuckSpeed;
}
public Point getCannonCenter( ) {
return cannonCenter;
}
public int getCannonRadius( ) {
return cannonRadius;
}
public int getBarrelLength( ) {
return barrelLength;
}
public int getBarrelRadius( ) {
return barrelRadius;
}
public void setCannon( Point newCannonCenter, int newCannonRadius,
int newBarrelLength, int newBarrelRadius ) {
if( newCannonCenter != null && newCannonRadius > 0
&& newBarrelLength > 0 ) {
cannonCenter = newCannonCenter;
cannonRadius = newCannonRadius;
barrelLength = newBarrelLength;
barrelRadius = newBarrelRadius;
bulletCenter = new Point(
( int ) ( cannonCenter.x + cannonRadius * Math.cos( cannonAngle ) ),
( int ) ( cannonCenter.y - cannonRadius * Math.sin( cannonAngle ) ) );
}
}
public Point getBulletCenter( ) {
return bulletCenter;
}
public int getBulletRadius( ) {
return bulletRadius;
}
public void setBulletRadius( int newBulletRadius ) {
if( newBulletRadius > 0 )
bulletRadius = newBulletRadius;
}
public void setBulletSpeed( float newBulletSpeed ) {
if( newBulletSpeed > 0 )
bulletSpeed = newBulletSpeed;
}
public float getCannonAngle( ) {
return cannonAngle;
}
public void setCannonAngle( float newCannonAngle ) {
if( newCannonAngle >= 0 && newCannonAngle <= Math.PI / 2 )
cannonAngle = newCannonAngle;
else if( newCannonAngle < 0 )
cannonAngle = 0;
else
cannonAngle = ( float ) Math.PI / 2;
if( !isBulletFired( ) )
loadBullet( );
}
public boolean isBulletFired( ) {
return bulletFired;
}
public void fireBullet( ) {
bulletFired = true;
bulletAngle = cannonAngle;
}
public boolean isDuckShot( ) {
return duckShot;
}
public void setDuckShot( boolean newDuckShot ) {
duckShot = newDuckShot;
}
public void startDuckFromRightTopHalf( ) {
duckRect.left = huntingRect.right;
duckRect.right = duckRect.left + duckWidth;
duckRect.top = random.nextInt( huntingRect.bottom / 2 );
duckRect.bottom = duckRect.top + duckHeight;
}
public void moveDuck( ) {
if( !duckShot ) { // move left
duckRect.left -= duckSpeed * deltaTime;
duckRect.right -= duckSpeed * deltaTime;
} else { // move down
duckRect.top += 5 * duckSpeed * deltaTime;
duckRect.bottom += 5 * duckSpeed * deltaTime;
}
}
public boolean duckOffScreen( ) {
return duckRect.right < 0 || duckRect.bottom < 0
|| duckRect.top > huntingRect.bottom
|| duckRect.left > huntingRect.right;
}
public void moveBullet( ) {
bulletCenter.x += bulletSpeed * Math.cos( bulletAngle ) * deltaTime;
bulletCenter.y -= bulletSpeed * Math.sin( bulletAngle ) * deltaTime;
}
public boolean bulletOffScreen( ) {
return bulletCenter.x - bulletRadius > huntingRect.right
|| bulletCenter.y + bulletRadius < 0;
}
public void loadBullet( ) {
bulletFired = false;
bulletCenter.x = ( int ) ( cannonCenter.x
+ cannonRadius * Math.cos( cannonAngle ) );
bulletCenter.y = ( int ) ( cannonCenter.y
- cannonRadius * Math.sin( cannonAngle ) );
}
public boolean duckHit( ) {
return duckRect.intersects(
bulletCenter.x - bulletRadius, bulletCenter.y - bulletRadius,
bulletCenter.x + bulletRadius, bulletCenter.y + bulletRadius );
}
} | 5,289 | 0.654377 | 0.650785 | 201 | 25.318407 | 20.131363 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492537 | false | false | 8 |
1fab6846c516d7ce25fb17083b6017a04017703f | 15,229,954,038,341 | df78bc085c76b549bc7a1b8328bbb4c5657559bb | /Game/com/amoghbhagwat/game/Renderer.java | bea0dd0ecd4a8d753b5fcb75a15bf2925835f1f0 | [] | no_license | AmoghBhagwat/lwjgl-game | https://github.com/AmoghBhagwat/lwjgl-game | 023ac7721b5c50a907c6036d153eff6b357b0baf | 4136a4ea0242caae1c719d9b9f9f45280eb16ce3 | refs/heads/master | 2021-01-02T22:53:37.376000 | 2017-08-05T10:33:19 | 2017-08-05T10:33:19 | 98,641,777 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.amoghbhagwat.game;
import com.amoghbhagwat.engine.Utils;
import com.amoghbhagwat.engine.Window;
import com.amoghbhagwat.engine.graph.ShaderProgram;
import com.amoghbhagwat.engine.light.DirectionalLight;
import com.amoghbhagwat.engine.light.PointLight;
import com.amoghbhagwat.engine.light.SpotLight;
import com.amoghbhagwat.game.entities.Camera;
import com.amoghbhagwat.game.entities.GameItem;
import com.amoghbhagwat.game.utils.Transformation;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
import java.util.List;
import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST;
import static org.lwjgl.opengl.GL11.glEnable;
public class Renderer {
private static final float FOV = (float) Math.toRadians(60.0f);
private static final float Z_NEAR = 0.01f;
private static final float Z_FAR = 1000.0f;
private ShaderProgram shaderProgram;
private Transformation transformation;
private float specularPower;
public Renderer() {
transformation = new Transformation();
specularPower = 10f;
}
public void init(Window window) throws Exception {
shaderProgram = new ShaderProgram();
shaderProgram.createVertexShader(Utils.loadResource("/shaders/vertex.glsl"));
shaderProgram.createFragmentShader(Utils.loadResource("/shaders/fragment.glsl"));
shaderProgram.link();
shaderProgram.createUniform("projectionMatrix");
shaderProgram.createUniform("modelViewMatrix");
shaderProgram.createUniform("textureSampler");
shaderProgram.createMaterialUniform("material");
shaderProgram.createUniform("specularPower");
shaderProgram.createUniform("ambientLight");
shaderProgram.createPointLightUniform("pointLight");
shaderProgram.createSpotLightUniform("spotLight");
shaderProgram.createDirectionalLightUniform("directionalLight");
glEnable(GL_DEPTH_TEST);
}
public void render(Window window, List<GameItem> gameItems, Camera camera, Vector3f ambientLight, PointLight pointLight, SpotLight spotLight, DirectionalLight directionalLight) {
clear();
if (window.isResized()) {
GL11.glViewport(0, 0, window.getWidth(), window.getHeight());
window.setResized(false);
}
shaderProgram.bind();
// update projection matrix
Matrix4f projectionMatrix = transformation.getProjectionMatrix(FOV, window.getWidth(), window.getHeight(), Z_NEAR, Z_FAR);
shaderProgram.setUniform("projectionMatrix", projectionMatrix);
// update view matrix
Matrix4f viewMatrix = transformation.getViewMatrix(camera);
shaderProgram.setUniform("textureSampler", 0);
shaderProgram.setUniform("ambientLight", ambientLight);
shaderProgram.setUniform("specularPower", specularPower);
// update point light uniforms
PointLight currentPointLight = new PointLight(pointLight);
Vector3f lightPosition = currentPointLight.getPosition();
Vector4f aux = new Vector4f(lightPosition, 1.0f);
aux.mul(viewMatrix);
lightPosition.x = aux.x;
lightPosition.y = aux.y;
lightPosition.z = aux.z;
shaderProgram.setUniform("pointLight", currentPointLight);
// update spot light uniforms
SpotLight currentSpotLight = new SpotLight(spotLight);
Vector4f spotLightDirection = new Vector4f(currentSpotLight.getConeDirection(), 0);
spotLightDirection.mul(viewMatrix);
currentSpotLight.setConeDirection(new Vector3f(spotLightDirection.x, spotLightDirection.y, spotLightDirection.z));
Vector3f spotLightPosition = currentSpotLight.getPointLight().getPosition();
Vector4f auxSpot = new Vector4f(spotLightPosition, 1);
auxSpot.mul(viewMatrix);
spotLightPosition.x = auxSpot.x;
spotLightPosition.y = auxSpot.y;
spotLightPosition.z = auxSpot.z;
shaderProgram.setUniform("spotLight", currentSpotLight);
// update directional light uniforms
DirectionalLight currentDirectionalLight = new DirectionalLight(directionalLight);
Vector4f directionalLightDirection = new Vector4f(currentDirectionalLight.getDirection(), 0);
directionalLightDirection.mul(viewMatrix);
currentDirectionalLight.setDirection(new Vector3f(directionalLightDirection.x, directionalLightDirection.y, directionalLightDirection.z));
shaderProgram.setUniform("directionalLight", currentDirectionalLight);
for (GameItem gameItem : gameItems) {
Matrix4f modelViewMatrix = transformation.getModelViewMatrix(gameItem, viewMatrix);
shaderProgram.setUniform("modelViewMatrix", modelViewMatrix);
shaderProgram.setUniform("material", gameItem.getMesh().getMaterial());
gameItem.getMesh().render();
}
shaderProgram.unbind();
}
public void clear() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
}
public void cleanUp() {
if (shaderProgram != null) {
shaderProgram.cleanUp();
}
}
}
| UTF-8 | Java | 5,184 | java | Renderer.java | Java | [] | null | [] | package com.amoghbhagwat.game;
import com.amoghbhagwat.engine.Utils;
import com.amoghbhagwat.engine.Window;
import com.amoghbhagwat.engine.graph.ShaderProgram;
import com.amoghbhagwat.engine.light.DirectionalLight;
import com.amoghbhagwat.engine.light.PointLight;
import com.amoghbhagwat.engine.light.SpotLight;
import com.amoghbhagwat.game.entities.Camera;
import com.amoghbhagwat.game.entities.GameItem;
import com.amoghbhagwat.game.utils.Transformation;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
import java.util.List;
import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST;
import static org.lwjgl.opengl.GL11.glEnable;
public class Renderer {
private static final float FOV = (float) Math.toRadians(60.0f);
private static final float Z_NEAR = 0.01f;
private static final float Z_FAR = 1000.0f;
private ShaderProgram shaderProgram;
private Transformation transformation;
private float specularPower;
public Renderer() {
transformation = new Transformation();
specularPower = 10f;
}
public void init(Window window) throws Exception {
shaderProgram = new ShaderProgram();
shaderProgram.createVertexShader(Utils.loadResource("/shaders/vertex.glsl"));
shaderProgram.createFragmentShader(Utils.loadResource("/shaders/fragment.glsl"));
shaderProgram.link();
shaderProgram.createUniform("projectionMatrix");
shaderProgram.createUniform("modelViewMatrix");
shaderProgram.createUniform("textureSampler");
shaderProgram.createMaterialUniform("material");
shaderProgram.createUniform("specularPower");
shaderProgram.createUniform("ambientLight");
shaderProgram.createPointLightUniform("pointLight");
shaderProgram.createSpotLightUniform("spotLight");
shaderProgram.createDirectionalLightUniform("directionalLight");
glEnable(GL_DEPTH_TEST);
}
public void render(Window window, List<GameItem> gameItems, Camera camera, Vector3f ambientLight, PointLight pointLight, SpotLight spotLight, DirectionalLight directionalLight) {
clear();
if (window.isResized()) {
GL11.glViewport(0, 0, window.getWidth(), window.getHeight());
window.setResized(false);
}
shaderProgram.bind();
// update projection matrix
Matrix4f projectionMatrix = transformation.getProjectionMatrix(FOV, window.getWidth(), window.getHeight(), Z_NEAR, Z_FAR);
shaderProgram.setUniform("projectionMatrix", projectionMatrix);
// update view matrix
Matrix4f viewMatrix = transformation.getViewMatrix(camera);
shaderProgram.setUniform("textureSampler", 0);
shaderProgram.setUniform("ambientLight", ambientLight);
shaderProgram.setUniform("specularPower", specularPower);
// update point light uniforms
PointLight currentPointLight = new PointLight(pointLight);
Vector3f lightPosition = currentPointLight.getPosition();
Vector4f aux = new Vector4f(lightPosition, 1.0f);
aux.mul(viewMatrix);
lightPosition.x = aux.x;
lightPosition.y = aux.y;
lightPosition.z = aux.z;
shaderProgram.setUniform("pointLight", currentPointLight);
// update spot light uniforms
SpotLight currentSpotLight = new SpotLight(spotLight);
Vector4f spotLightDirection = new Vector4f(currentSpotLight.getConeDirection(), 0);
spotLightDirection.mul(viewMatrix);
currentSpotLight.setConeDirection(new Vector3f(spotLightDirection.x, spotLightDirection.y, spotLightDirection.z));
Vector3f spotLightPosition = currentSpotLight.getPointLight().getPosition();
Vector4f auxSpot = new Vector4f(spotLightPosition, 1);
auxSpot.mul(viewMatrix);
spotLightPosition.x = auxSpot.x;
spotLightPosition.y = auxSpot.y;
spotLightPosition.z = auxSpot.z;
shaderProgram.setUniform("spotLight", currentSpotLight);
// update directional light uniforms
DirectionalLight currentDirectionalLight = new DirectionalLight(directionalLight);
Vector4f directionalLightDirection = new Vector4f(currentDirectionalLight.getDirection(), 0);
directionalLightDirection.mul(viewMatrix);
currentDirectionalLight.setDirection(new Vector3f(directionalLightDirection.x, directionalLightDirection.y, directionalLightDirection.z));
shaderProgram.setUniform("directionalLight", currentDirectionalLight);
for (GameItem gameItem : gameItems) {
Matrix4f modelViewMatrix = transformation.getModelViewMatrix(gameItem, viewMatrix);
shaderProgram.setUniform("modelViewMatrix", modelViewMatrix);
shaderProgram.setUniform("material", gameItem.getMesh().getMaterial());
gameItem.getMesh().render();
}
shaderProgram.unbind();
}
public void clear() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
}
public void cleanUp() {
if (shaderProgram != null) {
shaderProgram.cleanUp();
}
}
}
| 5,184 | 0.715664 | 0.705247 | 129 | 39.186047 | 32.815853 | 182 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.868217 | false | false | 8 |
2293a24bddd5d22120dd06db4317c086ba103dde | 21,328,807,626,218 | d73cb6ebaa2622dbf792ace08fb3adde1e7f761c | /src/main/java/com/zhyn4j/sbtwo/bridge/Gift.java | 962594a6d9f91d9ab8e7fbae8a8b4233adb47e49 | [] | no_license | zhangyn4j/sbtwo | https://github.com/zhangyn4j/sbtwo | fad78d19c0521d5b4717c72508e2bcd6fc65aba0 | a85f9863ecb64cb6d9e09c8e62a5f9f2c86fd55d | refs/heads/master | 2020-04-03T19:15:04.496000 | 2019-01-31T05:41:25 | 2019-01-31T05:41:25 | 155,516,599 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhyn4j.sbtwo.bridge;
public class Gift {
}
| UTF-8 | Java | 56 | java | Gift.java | Java | [] | null | [] | package com.zhyn4j.sbtwo.bridge;
public class Gift {
}
| 56 | 0.75 | 0.732143 | 4 | 13 | 13.322912 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 8 |
f7381ccf0b4e72a5984b694e290d3abc74482225 | 20,684,562,547,215 | 1df238dc5236b688703dc5ce9b2adfec2c5ef1cb | /src/main/java/com/example/webadmin/mapper/UserMapper.java | f35b8a12e22bb4a6962373d3e2f89ef24afa1e56 | [] | no_license | hhhui-L/SpringBoot-04 | https://github.com/hhhui-L/SpringBoot-04 | 8afb848c3e1f053dc4dc7fe1b50886a6390a9abc | 120679227db08a645d2c6e99738961e86c5078c8 | refs/heads/main | 2023-05-05T12:34:47.944000 | 2021-05-27T08:24:12 | 2021-05-27T08:24:12 | 366,297,279 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.webadmin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.webadmin.bean.User;
/**
*
*/
public interface UserMapper extends BaseMapper<User> {
}
| UTF-8 | Java | 204 | java | UserMapper.java | Java | [] | null | [] | package com.example.webadmin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.webadmin.bean.User;
/**
*
*/
public interface UserMapper extends BaseMapper<User> {
}
| 204 | 0.769608 | 0.769608 | 12 | 16 | 21.664103 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 8 |
abfc528624e1aa3b73cdf9a423afc064d7f4892a | 6,502,580,510,006 | 87c184dea00b99974662d0ca107007bb286201cd | /rxkata/src/test/java/org/sergiiz/rxkata/CountriesServiceSolvedTest.java | e4e14d9d71e88fe4bfc7aab29d41270c1a768989 | [
"MIT"
] | permissive | agustinrodriguez/RxBasicsKata | https://github.com/agustinrodriguez/RxBasicsKata | 22c57bc219e2bbb8bdcc2eec710d11f9d19db78c | 951a9d62bb1d978733918b43f4324280dab5235e | refs/heads/master | 2021-01-02T08:24:05.522000 | 2017-08-01T13:07:35 | 2017-08-01T13:07:35 | 99,002,179 | 0 | 0 | null | true | 2017-08-01T13:05:39 | 2017-08-01T13:05:39 | 2017-07-25T10:36:39 | 2017-02-15T06:47:42 | 78 | 0 | 0 | 0 | null | null | null | package org.sergiiz.rxkata;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
public class CountriesServiceSolvedTest {
private CountriesService countriesService;
private List<Country> allCountries;
@Rule
public Timeout globalTimeout = Timeout.seconds(2);
@Before
public void setUp() {
countriesService = new CountriesServiceSolved();
allCountries = CountriesTestProvider.countries();
}
@Test
public void rx_CountryNameInCapitals() {
Country testCountry = CountriesTestProvider.countries().get(0);
String expected = testCountry.name.toUpperCase(Locale.US);
TestObserver<String> testObserver = countriesService.countryNameInCapitals(testCountry).test();
testObserver.assertNoErrors();
testObserver.assertValue(expected);
}
@Test
public void rx_CountAmountOfCountries() {
Integer expected = CountriesTestProvider.countries().size();
TestObserver<Integer> testObserver = countriesService.countCountries(allCountries).test();
testObserver.assertNoErrors();
testObserver.assertValue(expected);
}
@Test
public void rx_ListPopulationOfEachCountry() {
List<Long> expectedResult = CountriesTestProvider.populationOfCountries();
TestObserver<Long> testObserver = countriesService.listPopulationOfEachCountry(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListNameOfEachCountry() {
List<String> expectedResult = CountriesTestProvider.namesOfCountries();
TestObserver<String> testObserver = countriesService.listNameOfEachCountry(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListOnly3rdAnd4thCountry() {
List<Country> expectedResult = new ArrayList<>();
expectedResult.add(allCountries.get(2));
expectedResult.add(allCountries.get(3));
TestObserver<Country> testObserver = countriesService.listOnly3rdAnd4thCountry(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_IsAllCountriesPopulationMoreThanOneMillion_Positive() {
TestObserver<Boolean> testObserver = countriesService
.isAllCountriesPopulationMoreThanOneMillion(CountriesTestProvider.countriesPopulationMoreThanOneMillion()).test();
testObserver.assertResult(true);
testObserver.assertNoErrors();
}
@Test
public void rx_IsAllCountriesPopulationMoreThanOneMillion_Negative() {
TestObserver<Boolean> testObserver = countriesService.isAllCountriesPopulationMoreThanOneMillion(allCountries).test();
testObserver.assertResult(false);
testObserver.assertNoErrors();
}
@Test
public void rx_ListPopulationMoreThanOneMillion() {
List<Country> expectedResult = CountriesTestProvider.countriesPopulationMoreThanOneMillion();
TestObserver<Country> testObserver = countriesService.listPopulationMoreThanOneMillion(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty_When_NoTimeout() {
FutureTask<List<Country>> futureTask = new FutureTask<>(() -> {
TimeUnit.MILLISECONDS.sleep(100);
return allCountries;
});
new Thread(futureTask).start();
TestObserver<Country> testObserver = countriesService.listPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty(futureTask).test();
List<Country> expectedResult = CountriesTestProvider.countriesPopulationMoreThanOneMillion();
testObserver.awaitTerminalEvent();
testObserver.assertComplete();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty_When_Timeout() {
FutureTask<List<Country>> futureTask = new FutureTask<>(() -> {
TimeUnit.HOURS.sleep(1);
return allCountries;
});
new Thread(futureTask).start();
TestObserver<Country> testObserver = countriesService.listPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty(futureTask).test();
testObserver.awaitTerminalEvent();
testObserver.assertComplete();
testObserver.assertNoValues();
testObserver.assertNoErrors();
}
@Test
public void rx_GetCurrencyUsdIfNotFound_When_CountryFound() {
String countryRequested = "Austria";
String expectedCurrencyValue = "EUR";
TestObserver<String> testObserver = countriesService.getCurrencyUsdIfNotFound(countryRequested, allCountries).test();
testObserver.assertResult(expectedCurrencyValue);
testObserver.assertNoErrors();
}
@Test
public void rx_GetCurrencyUsdIfNotFound_When_CountryNotFound() {
String countryRequested = "Senegal";
String expectedCurrencyValue = "USD";
TestObserver<String> testObserver = countriesService.getCurrencyUsdIfNotFound(countryRequested, allCountries).test();
testObserver.assertResult(expectedCurrencyValue);
testObserver.assertNoErrors();
}
@Test
public void rx_SumPopulationOfCountries() {
// hint: use "reduce" operator
TestObserver<Long> testObserver = countriesService.sumPopulationOfCountries(allCountries).test();
testObserver.assertResult(CountriesTestProvider.sumPopulationOfAllCountries());
testObserver.assertNoErrors();
}
@Test
public void rx_MapCountriesToNamePopulation() {
TestObserver<Map<String, Long>> values = countriesService.mapCountriesToNamePopulation(allCountries).test();
Map<String, Long> expected = new HashMap<>();
for (Country country : allCountries) {
expected.put(country.name, country.population);
}
values.assertResult(expected);
values.assertNoErrors();
}
@Test
public void rx_sumPopulationOfCountries() {
// hint: use "map" operator
TestObserver<Long> testObserver = countriesService
.sumPopulationOfCountries(Observable.fromIterable(allCountries), Observable.fromIterable(allCountries)).test();
testObserver.assertResult(CountriesTestProvider.sumPopulationOfAllCountries() + CountriesTestProvider.sumPopulationOfAllCountries());
testObserver.assertNoErrors();
}
@Test
public void rx_areEmittingSameSequences_Positive() {
// hint: use "sequenceEqual" operator
TestObserver<Boolean> testObserver = countriesService
.areEmittingSameSequences(Observable.fromIterable(allCountries), Observable.fromIterable(allCountries)).test();
testObserver.assertResult(true);
testObserver.assertNoErrors();
}
@Test
public void rx_areEmittingSameSequences_Negative() {
List<Country> allCountriesDifferentSequence = new ArrayList<>(allCountries);
Collections.swap(allCountriesDifferentSequence, 0, 1);
TestObserver<Boolean> testObserver = countriesService
.areEmittingSameSequences(Observable.fromIterable(allCountries), Observable.fromIterable(allCountriesDifferentSequence)).test();
testObserver.assertResult(false);
testObserver.assertNoErrors();
}
} | UTF-8 | Java | 7,162 | java | CountriesServiceSolvedTest.java | Java | [] | null | [] | package org.sergiiz.rxkata;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
public class CountriesServiceSolvedTest {
private CountriesService countriesService;
private List<Country> allCountries;
@Rule
public Timeout globalTimeout = Timeout.seconds(2);
@Before
public void setUp() {
countriesService = new CountriesServiceSolved();
allCountries = CountriesTestProvider.countries();
}
@Test
public void rx_CountryNameInCapitals() {
Country testCountry = CountriesTestProvider.countries().get(0);
String expected = testCountry.name.toUpperCase(Locale.US);
TestObserver<String> testObserver = countriesService.countryNameInCapitals(testCountry).test();
testObserver.assertNoErrors();
testObserver.assertValue(expected);
}
@Test
public void rx_CountAmountOfCountries() {
Integer expected = CountriesTestProvider.countries().size();
TestObserver<Integer> testObserver = countriesService.countCountries(allCountries).test();
testObserver.assertNoErrors();
testObserver.assertValue(expected);
}
@Test
public void rx_ListPopulationOfEachCountry() {
List<Long> expectedResult = CountriesTestProvider.populationOfCountries();
TestObserver<Long> testObserver = countriesService.listPopulationOfEachCountry(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListNameOfEachCountry() {
List<String> expectedResult = CountriesTestProvider.namesOfCountries();
TestObserver<String> testObserver = countriesService.listNameOfEachCountry(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListOnly3rdAnd4thCountry() {
List<Country> expectedResult = new ArrayList<>();
expectedResult.add(allCountries.get(2));
expectedResult.add(allCountries.get(3));
TestObserver<Country> testObserver = countriesService.listOnly3rdAnd4thCountry(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_IsAllCountriesPopulationMoreThanOneMillion_Positive() {
TestObserver<Boolean> testObserver = countriesService
.isAllCountriesPopulationMoreThanOneMillion(CountriesTestProvider.countriesPopulationMoreThanOneMillion()).test();
testObserver.assertResult(true);
testObserver.assertNoErrors();
}
@Test
public void rx_IsAllCountriesPopulationMoreThanOneMillion_Negative() {
TestObserver<Boolean> testObserver = countriesService.isAllCountriesPopulationMoreThanOneMillion(allCountries).test();
testObserver.assertResult(false);
testObserver.assertNoErrors();
}
@Test
public void rx_ListPopulationMoreThanOneMillion() {
List<Country> expectedResult = CountriesTestProvider.countriesPopulationMoreThanOneMillion();
TestObserver<Country> testObserver = countriesService.listPopulationMoreThanOneMillion(allCountries).test();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty_When_NoTimeout() {
FutureTask<List<Country>> futureTask = new FutureTask<>(() -> {
TimeUnit.MILLISECONDS.sleep(100);
return allCountries;
});
new Thread(futureTask).start();
TestObserver<Country> testObserver = countriesService.listPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty(futureTask).test();
List<Country> expectedResult = CountriesTestProvider.countriesPopulationMoreThanOneMillion();
testObserver.awaitTerminalEvent();
testObserver.assertComplete();
testObserver.assertValueSet(expectedResult);
testObserver.assertNoErrors();
}
@Test
public void rx_ListPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty_When_Timeout() {
FutureTask<List<Country>> futureTask = new FutureTask<>(() -> {
TimeUnit.HOURS.sleep(1);
return allCountries;
});
new Thread(futureTask).start();
TestObserver<Country> testObserver = countriesService.listPopulationMoreThanOneMillionWithTimeoutFallbackToEmpty(futureTask).test();
testObserver.awaitTerminalEvent();
testObserver.assertComplete();
testObserver.assertNoValues();
testObserver.assertNoErrors();
}
@Test
public void rx_GetCurrencyUsdIfNotFound_When_CountryFound() {
String countryRequested = "Austria";
String expectedCurrencyValue = "EUR";
TestObserver<String> testObserver = countriesService.getCurrencyUsdIfNotFound(countryRequested, allCountries).test();
testObserver.assertResult(expectedCurrencyValue);
testObserver.assertNoErrors();
}
@Test
public void rx_GetCurrencyUsdIfNotFound_When_CountryNotFound() {
String countryRequested = "Senegal";
String expectedCurrencyValue = "USD";
TestObserver<String> testObserver = countriesService.getCurrencyUsdIfNotFound(countryRequested, allCountries).test();
testObserver.assertResult(expectedCurrencyValue);
testObserver.assertNoErrors();
}
@Test
public void rx_SumPopulationOfCountries() {
// hint: use "reduce" operator
TestObserver<Long> testObserver = countriesService.sumPopulationOfCountries(allCountries).test();
testObserver.assertResult(CountriesTestProvider.sumPopulationOfAllCountries());
testObserver.assertNoErrors();
}
@Test
public void rx_MapCountriesToNamePopulation() {
TestObserver<Map<String, Long>> values = countriesService.mapCountriesToNamePopulation(allCountries).test();
Map<String, Long> expected = new HashMap<>();
for (Country country : allCountries) {
expected.put(country.name, country.population);
}
values.assertResult(expected);
values.assertNoErrors();
}
@Test
public void rx_sumPopulationOfCountries() {
// hint: use "map" operator
TestObserver<Long> testObserver = countriesService
.sumPopulationOfCountries(Observable.fromIterable(allCountries), Observable.fromIterable(allCountries)).test();
testObserver.assertResult(CountriesTestProvider.sumPopulationOfAllCountries() + CountriesTestProvider.sumPopulationOfAllCountries());
testObserver.assertNoErrors();
}
@Test
public void rx_areEmittingSameSequences_Positive() {
// hint: use "sequenceEqual" operator
TestObserver<Boolean> testObserver = countriesService
.areEmittingSameSequences(Observable.fromIterable(allCountries), Observable.fromIterable(allCountries)).test();
testObserver.assertResult(true);
testObserver.assertNoErrors();
}
@Test
public void rx_areEmittingSameSequences_Negative() {
List<Country> allCountriesDifferentSequence = new ArrayList<>(allCountries);
Collections.swap(allCountriesDifferentSequence, 0, 1);
TestObserver<Boolean> testObserver = countriesService
.areEmittingSameSequences(Observable.fromIterable(allCountries), Observable.fromIterable(allCountriesDifferentSequence)).test();
testObserver.assertResult(false);
testObserver.assertNoErrors();
}
} | 7,162 | 0.801173 | 0.799218 | 195 | 35.733334 | 33.90546 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.897436 | false | false | 8 |
fa87b9c780a1279af49a6355db43b164ff8afdcf | 6,502,580,511,361 | c5f558a7a28c5b89c09e3eb13adb41084d94735c | /app/src/main/java/study/jigl/com/rxjavastudy/demo/RxjavaDemo3.java | a7b0a4fa47fb362d3deaf0a9bb38ead1354841fe | [] | no_license | ufochuxian/RxJavaStudy | https://github.com/ufochuxian/RxJavaStudy | 76dfd303e3cd59dbab3ddda9cf9d8007c9575694 | b779b523d62a6f000a9bf26df65bc23f041b618c | refs/heads/master | 2020-03-15T17:31:25.454000 | 2018-05-14T15:23:09 | 2018-05-14T15:23:09 | 132,258,730 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package study.jigl.com.rxjavastudy.demo;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import study.jigl.com.rxjavastudy.bean.Translation;
import study.jigl.com.rxjavastudy.retrofit.GetRequest_Interface;
import study.jigl.com.rxjavastudy.util.JLGLLog;
/**
* 使用Rxjava的interval操作符配合Retrofit实现轮询网络请求
*
*/
public class RxjavaDemo3 {
private static final String TAG = "RxjavaDemo3";
private static RxjavaDemo3 instance = null;
private RxjavaDemo3() {
}
public static RxjavaDemo3 getInstance() {
synchronized (RxjavaDemo3.class) {
if (instance == null) {
instance = new RxjavaDemo3();
}
}
return instance;
}
public void pollingRequest() {
Observable.interval(1, 3, TimeUnit.SECONDS)
.doOnNext(new Consumer<Long>() {
@Override
public void accept(Long value) throws Exception {
JLGLLog.i(TAG, "第" + value + "次轮询");
//通过Retrofit发送网络请求
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/") //设置网络请求url
.addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //支持RxJava
.build();
//创建网络请求接口的实例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//采用Observable <...>形式,对网络请求进行封装,这里将request.getCall()转换成了rxJava的Observable,这里就可以使用
//RxJava的形式来处理请求和请求的结果了
Observable<Translation> observable = request.getCall();
observable.subscribeOn(Schedulers.io()) //切换到io线程,发送网络请求
.observeOn(AndroidSchedulers.mainThread()) //切换到主线程,处理请求结果
.subscribe(new Observer<Translation>() {
@Override
public void onSubscribe(Disposable d) {
JLGLLog.i(TAG, "[pollingRequest],[accept],[onSubscribe]");
}
@Override
public void onNext(Translation translation) {
JLGLLog.i(TAG,"[pollingRequest],[onNext]");
translation.show();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}).subscribe(new Observer<Long>() {
@Override
public void onSubscribe(Disposable d) {
JLGLLog.i(TAG,"[pollingRequest],[onSubscribe]");
}
@Override
public void onNext(Long value) {
JLGLLog.i(TAG, "[pollingRequest],value = %s", value);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
| UTF-8 | Java | 4,201 | java | RxjavaDemo3.java | Java | [] | null | [] | package study.jigl.com.rxjavastudy.demo;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import study.jigl.com.rxjavastudy.bean.Translation;
import study.jigl.com.rxjavastudy.retrofit.GetRequest_Interface;
import study.jigl.com.rxjavastudy.util.JLGLLog;
/**
* 使用Rxjava的interval操作符配合Retrofit实现轮询网络请求
*
*/
public class RxjavaDemo3 {
private static final String TAG = "RxjavaDemo3";
private static RxjavaDemo3 instance = null;
private RxjavaDemo3() {
}
public static RxjavaDemo3 getInstance() {
synchronized (RxjavaDemo3.class) {
if (instance == null) {
instance = new RxjavaDemo3();
}
}
return instance;
}
public void pollingRequest() {
Observable.interval(1, 3, TimeUnit.SECONDS)
.doOnNext(new Consumer<Long>() {
@Override
public void accept(Long value) throws Exception {
JLGLLog.i(TAG, "第" + value + "次轮询");
//通过Retrofit发送网络请求
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/") //设置网络请求url
.addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //支持RxJava
.build();
//创建网络请求接口的实例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//采用Observable <...>形式,对网络请求进行封装,这里将request.getCall()转换成了rxJava的Observable,这里就可以使用
//RxJava的形式来处理请求和请求的结果了
Observable<Translation> observable = request.getCall();
observable.subscribeOn(Schedulers.io()) //切换到io线程,发送网络请求
.observeOn(AndroidSchedulers.mainThread()) //切换到主线程,处理请求结果
.subscribe(new Observer<Translation>() {
@Override
public void onSubscribe(Disposable d) {
JLGLLog.i(TAG, "[pollingRequest],[accept],[onSubscribe]");
}
@Override
public void onNext(Translation translation) {
JLGLLog.i(TAG,"[pollingRequest],[onNext]");
translation.show();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}).subscribe(new Observer<Long>() {
@Override
public void onSubscribe(Disposable d) {
JLGLLog.i(TAG,"[pollingRequest],[onSubscribe]");
}
@Override
public void onNext(Long value) {
JLGLLog.i(TAG, "[pollingRequest],value = %s", value);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
| 4,201 | 0.498611 | 0.494822 | 116 | 33.129311 | 29.477499 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387931 | false | false | 8 |
766d8efcd0b560aaa53cc6d9d62209262bca2685 | 28,372,554,022,245 | 90eb7a131e5b3dc79e2d1e1baeed171684ef6a22 | /sources/p005b/p096l/p097a/p113c/p131e/p136e/C2319m0.java | 58bbf5b7a0ddad3d960036dc9fa158e361ebb422 | [] | no_license | shalviraj/greenlens | https://github.com/shalviraj/greenlens | 1c6608dca75ec204e85fba3171995628d2ee8961 | fe9f9b5a3ef4a18f91e12d3925e09745c51bf081 | refs/heads/main | 2023-04-20T13:50:14.619000 | 2021-04-26T15:45:11 | 2021-04-26T15:45:11 | 361,799,768 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package p005b.p096l.p097a.p113c.p131e.p136e;
/* renamed from: b.l.a.c.e.e.m0 */
public interface C2319m0<T> {
/* renamed from: a */
T mo12554a();
/* renamed from: b */
void mo12555b(T t);
/* renamed from: c */
int mo12556c(T t);
/* renamed from: d */
void mo12557d(T t, T t2);
/* renamed from: e */
int mo12558e(T t);
/* renamed from: f */
boolean mo12559f(T t, T t2);
/* renamed from: g */
void mo12560g(T t, C2389om omVar, C2605xm xmVar);
/* renamed from: h */
void mo12561h(T t, C2533um umVar);
/* renamed from: i */
boolean mo12562i(T t);
/* renamed from: j */
void mo12563j(T t, byte[] bArr, int i, int i2, C2144em emVar);
}
| UTF-8 | Java | 720 | java | C2319m0.java | Java | [] | null | [] | package p005b.p096l.p097a.p113c.p131e.p136e;
/* renamed from: b.l.a.c.e.e.m0 */
public interface C2319m0<T> {
/* renamed from: a */
T mo12554a();
/* renamed from: b */
void mo12555b(T t);
/* renamed from: c */
int mo12556c(T t);
/* renamed from: d */
void mo12557d(T t, T t2);
/* renamed from: e */
int mo12558e(T t);
/* renamed from: f */
boolean mo12559f(T t, T t2);
/* renamed from: g */
void mo12560g(T t, C2389om omVar, C2605xm xmVar);
/* renamed from: h */
void mo12561h(T t, C2533um umVar);
/* renamed from: i */
boolean mo12562i(T t);
/* renamed from: j */
void mo12563j(T t, byte[] bArr, int i, int i2, C2144em emVar);
}
| 720 | 0.568056 | 0.438889 | 34 | 20.17647 | 16.519989 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 8 |
f80d1fb2590991108f02b7b6a32193474abf2182 | 16,475,494,567,575 | 7a87eaefd38044e7141ca099a99431daf8da69af | /src/main/java/com/day/day/up/main/guavalimit/util/PayRateLimitUtil.java | 48599a76026d4248110098d9dbca4c5f489123f4 | [] | no_license | wf-code-something/javaS | https://github.com/wf-code-something/javaS | 08180049df3f203f9f89985f0968a1172a4a808a | eee7e6f5b92d9a371e5b94055192db34c0541bf2 | refs/heads/master | 2023-04-14T16:59:19.486000 | 2021-04-21T07:25:10 | 2021-04-21T07:25:10 | 358,541,789 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.day.day.up.main.guavalimit.util;
import com.day.day.up.main.guavalimit.annotation.PayRateLimit;
import com.day.day.up.main.guavalimit.exception.PayLimitAccessException;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class PayRateLimitUtil {
/**
* 获取唯一key根据注解类型
* <p>
* 规则 资源名:业务key:perSecond
*
* @param method method
* @param request request
* @return String
*/
public static String generateCacheKey(Method method, HttpServletRequest request) {
//获取方法上的注解
PayRateLimit lxRateLimit = method.getAnnotation(PayRateLimit.class);
StringBuffer cacheKey = new StringBuffer(lxRateLimit.name() + ":");
switch (lxRateLimit.limitKeyType()) {
case IPADDR:
cacheKey.append(getIpAddr(request) + ":");
break;
case CUSTOM:
String limitKeyValue = request.getParameter("limitKeyValue");
if (StringUtils.isEmpty(limitKeyValue)) {
throw new PayLimitAccessException("【" + method.getName() + "】自定义业务Key缺少参数String limitKeyValue,或者参数为空");
}
cacheKey.append(limitKeyValue + ":");
break;
}
cacheKey.append(lxRateLimit.perSecond());
return cacheKey.toString();
}
/**
* 获取缓存key的限制每秒访问次数
* <p>
* 规则 资源名:业务key:perSecond
*
* @param cacheKey
* @return
*/
public static double getCacheKeyPerSecond(String cacheKey) {
String perSecond = cacheKey.split(":")[2];
return Double.parseDouble(perSecond);
}
/**
* 获取客户端IP地址
*
* @param request 请求
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if ("127.0.0.1".equals(ip)) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = "127.0.0.1";
}
return ip;
}
}
| UTF-8 | Java | 3,291 | java | PayRateLimitUtil.java | Java | [
{
"context": " ip = request.getRemoteAddr();\n if (\"127.0.0.1\".equals(ip)) {\n //根据网卡取本机配置的IP\n ",
"end": 2406,
"score": 0.9997727870941162,
"start": 2397,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "dexOf(\",\"));\n }\n ... | null | [] | package com.day.day.up.main.guavalimit.util;
import com.day.day.up.main.guavalimit.annotation.PayRateLimit;
import com.day.day.up.main.guavalimit.exception.PayLimitAccessException;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class PayRateLimitUtil {
/**
* 获取唯一key根据注解类型
* <p>
* 规则 资源名:业务key:perSecond
*
* @param method method
* @param request request
* @return String
*/
public static String generateCacheKey(Method method, HttpServletRequest request) {
//获取方法上的注解
PayRateLimit lxRateLimit = method.getAnnotation(PayRateLimit.class);
StringBuffer cacheKey = new StringBuffer(lxRateLimit.name() + ":");
switch (lxRateLimit.limitKeyType()) {
case IPADDR:
cacheKey.append(getIpAddr(request) + ":");
break;
case CUSTOM:
String limitKeyValue = request.getParameter("limitKeyValue");
if (StringUtils.isEmpty(limitKeyValue)) {
throw new PayLimitAccessException("【" + method.getName() + "】自定义业务Key缺少参数String limitKeyValue,或者参数为空");
}
cacheKey.append(limitKeyValue + ":");
break;
}
cacheKey.append(lxRateLimit.perSecond());
return cacheKey.toString();
}
/**
* 获取缓存key的限制每秒访问次数
* <p>
* 规则 资源名:业务key:perSecond
*
* @param cacheKey
* @return
*/
public static double getCacheKeyPerSecond(String cacheKey) {
String perSecond = cacheKey.split(":")[2];
return Double.parseDouble(perSecond);
}
/**
* 获取客户端IP地址
*
* @param request 请求
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if ("127.0.0.1".equals(ip)) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = "127.0.0.1";
}
return ip;
}
}
| 3,291 | 0.554507 | 0.545395 | 93 | 32.043011 | 24.774647 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526882 | false | false | 8 |
1f14a30840bb539a8287221e68cf4b35daf79a4e | 3,453,153,733,367 | 674f1e2f07d70dba799194910462ddaa13bd2a74 | /src/Day33_LocalDateTime/B_warmup.java | d19efb680843a3dd566cab4abde6dd5810e87563 | [] | no_license | fatihstl/Summer_2020_B20 | https://github.com/fatihstl/Summer_2020_B20 | e00dcb5ac9716c8fdc9b6607e48404f0923b9021 | ea2cd2fc364d97936535df2a7c090ce6e55f990d | refs/heads/master | 2023-01-04T06:18:21.100000 | 2020-10-18T21:57:52 | 2020-10-18T21:57:52 | 288,560,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Day33_LocalDateTime;
import java.util.Arrays;
public class B_warmup {
public static void main(String[] args) {
// Task02:
// 1. create a return method that can return an int array in descending order
// 2. create a return method that can return a double array in descending order
// 3. create a return method that can return a String array in descending order
// 4. create a return method that can return a char array in descending order
}
public static int[] sortDesc(int[] arr){
Arrays.sort(arr);
int[] arr2 = new int[arr.length]; //{5,4,3,2,1};
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
public static double[] sortDesc(double[] arr){
Arrays.sort(arr);
double[] arr2 = new double[arr.length];
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
public static char[] sortDesc(char[] arr){
Arrays.sort(arr);
char[] arr2 = new char[arr.length];
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
public static String[] sortDesc(String[] arr){
Arrays.sort(arr);
String[] arr2 = new String[arr.length];
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
}
| UTF-8 | Java | 1,722 | java | B_warmup.java | Java | [] | null | [] | package Day33_LocalDateTime;
import java.util.Arrays;
public class B_warmup {
public static void main(String[] args) {
// Task02:
// 1. create a return method that can return an int array in descending order
// 2. create a return method that can return a double array in descending order
// 3. create a return method that can return a String array in descending order
// 4. create a return method that can return a char array in descending order
}
public static int[] sortDesc(int[] arr){
Arrays.sort(arr);
int[] arr2 = new int[arr.length]; //{5,4,3,2,1};
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
public static double[] sortDesc(double[] arr){
Arrays.sort(arr);
double[] arr2 = new double[arr.length];
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
public static char[] sortDesc(char[] arr){
Arrays.sort(arr);
char[] arr2 = new char[arr.length];
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
public static String[] sortDesc(String[] arr){
Arrays.sort(arr);
String[] arr2 = new String[arr.length];
int k = arr.length-1;
for(int i = 0; i <= arr2.length-1; i++ ){
arr2[i] = arr[k];
k--;
}
return arr2;
}
}
| 1,722 | 0.494774 | 0.470964 | 82 | 20 | 24.039602 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47561 | false | false | 8 |
17f9655d947bf541114ff4660a5c20d0efa9e1a3 | 1,795,296,358,555 | 42bed1387a46a17a0b8ff764328680185b7ade99 | /dotasource API/src/dotasource/api/DotasourceManager.java | b4af74ee99a39a42f0a5314b7438e7bb810aaad4 | [] | no_license | blubmeister/dotisurs | https://github.com/blubmeister/dotisurs | 95a110a981a26a1fc931dd93c8fdb15e0fabd9ea | 6f5c5a3835da77f247056fb3fc9383ec920fda95 | refs/heads/master | 2021-01-10T14:18:17.472000 | 2015-11-19T09:12:05 | 2015-11-19T09:12:05 | 46,343,149 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dotasource.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import dotasource.model.Like;
import dotasource.model.LikeTable;
import dotasource.model.Notification;
import dotasource.model.User;
public class DotasourceManager {
public static final String COOKIE_USER_ID = "wcf21_userID";
public static final String COOKIE_PASSWORD = "wcf21_password";
public static final String COOKIE_HASH = "wcf21_cookieHash";
public static final Pattern PATTERN_PAGE_NUMBER = Pattern.compile(Pattern.quote("http://dotasource.de/notification-list/?pageNo=") + "([0-9]++)",Pattern.DOTALL);
public static final Pattern PATTERN_POST_CONTENT = Pattern.compile("id=\"text\".*?>(.*?)</textarea>",Pattern.DOTALL);
public static final Pattern PATTERN_EDIT_POST_FORM = Pattern.compile(Pattern.quote("action=\"http://dotasource.de/post-edit") + ".*?>(.*?)</form>", Pattern.DOTALL);
public static final Pattern PATTERN_INPUT_TYPE = Pattern.compile("<input type=.*?name=\"(?<name>.*?)\".*?value=\"(?<value>.*?)\"",Pattern.DOTALL);
private String userId = "56063";
private String passwordHash = "%242a%2408%24Q6QgPka8tAlGDWAeMbB1Mud3BlXDTm%2FX4R4qVWHlqKMkS0VP2RxFe";
private String cookieHash = "9125b53871d6b3b342c1ba06ed7c0b04cde3e347";
private CloseableHttpClient client;
public DotasourceManager() {
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie(COOKIE_USER_ID, userId);
cookie.setDomain(".dotasource.de");
cookie.setPath("/");
cookieStore.addCookie(cookie);
cookie = new BasicClientCookie(COOKIE_PASSWORD, passwordHash);
cookie.setDomain(".dotasource.de");
cookie.setPath("/");
cookieStore.addCookie(cookie);
cookie = new BasicClientCookie(COOKIE_HASH, cookieHash);
cookie.setDomain(".dotasource.de");
cookie.setPath("/");
cookieStore.addCookie(cookie);
client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
}
public void setSession(String userId, String passwordHash) {
this.userId = userId;
this.passwordHash = passwordHash;
}
public List<Notification> getNotificationsAfterDate(Date date) throws IOException {
int currentPage = 1;
int pageCount = getNotificationPageCount();
List<Notification> newNotifications = new ArrayList<Notification>();
while (currentPage <= pageCount) {
String input = readNotifications(currentPage);
List<Notification> notifications = Notification.parse(input);
for (Notification notification : notifications) {
if (!notification.getDate().before(date)) {
newNotifications.add(notification);
} else {
return newNotifications;
}
}
currentPage++;
}
return newNotifications;
}
public String getEditPostInput(String postId) throws IOException {
HttpGet httpGet = new HttpGet("http://dotasource.de/post-edit/" + postId + "/");
CloseableHttpResponse response = client.execute(httpGet);
try {
// System.out.println(response.getStatusLine());
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
} finally {
if (response != null)
response.close();
}
}
public String getPost(String postId) throws IOException {
String input = getEditPostInput(postId);
Matcher m = PATTERN_POST_CONTENT.matcher(input);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
public void updateLikes(Notification notification) throws IOException {
assert notification.getType() == Notification.TYPE_LIKE;
ArrayList<Like> likes = new ArrayList<>();
for (User user : notification.getUsers()) {
likes.add(new Like(user, notification.getDate(), notification.getPostId()));
}
LikeTable likeTable;
String content;
String input = getPost(notification.getPostId());
Matcher m = LikeTable.PATTERN_LIKE_TABLE.matcher(input);
if (m.find()) { // liketable bereits vorhanden
content = m.group("content");
likeTable = LikeTable.parse(m.group("liketable"), notification.getPostId());
likeTable.addLikes(likes);
} else {
content = input;
likeTable = new LikeTable(likes);
}
// System.out.println(content);
editPost(notification.getPostId(), content + likeTable.toBBCode());
}
public void editPost(String postId, String content) throws IOException {
HashMap<String, String> inputTypes = getInputTypes(postId);
HttpPost post = new HttpPost("http://dotasource.de/post-edit/" + postId + "/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("deleteReason", ""));
nameValuePairs.add(new BasicNameValuePair("subject", inputTypes.get("subject")));
nameValuePairs.add(new BasicNameValuePair("editReason", "Likes aktualisieren"));
nameValuePairs.add(new BasicNameValuePair("text", content));
nameValuePairs.add(new BasicNameValuePair("tmpHash", inputTypes.get("tmpHash")));
nameValuePairs.add(new BasicNameValuePair("preParse", "1"));
nameValuePairs.add(new BasicNameValuePair("enableSmilies", "1"));
nameValuePairs.add(new BasicNameValuePair("enableBBCodes", "1"));
nameValuePairs.add(new BasicNameValuePair("showSignature", "1"));
nameValuePairs.add(new BasicNameValuePair("pollQuestion", inputTypes.get("pollQuestion")));
nameValuePairs.add(new BasicNameValuePair("pollEndTime", inputTypes.get("pollEndTime")));
nameValuePairs.add(new BasicNameValuePair("pollMaxVotes", "1"));
nameValuePairs.add(new BasicNameValuePair("t", inputTypes.get("t")));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset.forName("UTF-8")));
try (CloseableHttpResponse response = client.execute(post)) {
System.out.println("HTTP Post: http://dotasource.de/post-edit/" + postId + "/");
System.out.println(response.getStatusLine());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
// System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public HashMap<String, String> getInputTypes(String postId) throws IOException {
String content = getEditPostInput(postId);
// System.out.println(content);
HashMap<String, String> map = new HashMap<>();
Matcher formMatcher = PATTERN_EDIT_POST_FORM.matcher(content);
if (formMatcher.find()) {
// System.out.println("FORM:" + formMatcher.group(1));
Matcher inputTypeMatcher = PATTERN_INPUT_TYPE.matcher(formMatcher.group(1));
while (inputTypeMatcher.find()) {
map.put(inputTypeMatcher.group("name"), inputTypeMatcher.group("value"));
}
}
return map;
}
public int getNotificationPageCount() throws IOException {
String content = readNotifications(1);
Matcher m = PATTERN_PAGE_NUMBER.matcher(content);
int result = 0;
while (m.find()) {
result = Math.max(result, Integer.parseInt(m.group(1)));
}
return result;
}
public String readNotifications(int page) throws IOException {
HttpGet httpGet = new HttpGet("http://www.dotasource.de/notification-list/?pageNo=" + page);
CloseableHttpResponse response = client.execute(httpGet);
try {
System.out.println("HTTP Get: http://www.dotasource.de/notification-list/?pageNo=" + page);
System.out.println(response.getStatusLine());
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
} finally {
if (response != null)
response.close();
}
}
}
| UTF-8 | Java | 9,196 | java | DotasourceManager.java | Java | [
{
"context": ";\r\n\tpublic static final String COOKIE_PASSWORD = \"wcf21_password\";\r\n\tpublic static final String COOKIE_HASH = \"wcf",
"end": 1302,
"score": 0.9994714856147766,
"start": 1288,
"tag": "PASSWORD",
"value": "wcf21_password"
},
{
"context": " userId = \"56063\";\r\n\... | null | [] | package dotasource.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import dotasource.model.Like;
import dotasource.model.LikeTable;
import dotasource.model.Notification;
import dotasource.model.User;
public class DotasourceManager {
public static final String COOKIE_USER_ID = "wcf21_userID";
public static final String COOKIE_PASSWORD = "<PASSWORD>";
public static final String COOKIE_HASH = "wcf21_cookieHash";
public static final Pattern PATTERN_PAGE_NUMBER = Pattern.compile(Pattern.quote("http://dotasource.de/notification-list/?pageNo=") + "([0-9]++)",Pattern.DOTALL);
public static final Pattern PATTERN_POST_CONTENT = Pattern.compile("id=\"text\".*?>(.*?)</textarea>",Pattern.DOTALL);
public static final Pattern PATTERN_EDIT_POST_FORM = Pattern.compile(Pattern.quote("action=\"http://dotasource.de/post-edit") + ".*?>(.*?)</form>", Pattern.DOTALL);
public static final Pattern PATTERN_INPUT_TYPE = Pattern.compile("<input type=.*?name=\"(?<name>.*?)\".*?value=\"(?<value>.*?)\"",Pattern.DOTALL);
private String userId = "56063";
private String passwordHash = <PASSWORD>";
private String cookieHash = "9125b53871d6b3b342c1ba06ed7c0b04cde3e347";
private CloseableHttpClient client;
public DotasourceManager() {
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie(COOKIE_USER_ID, userId);
cookie.setDomain(".dotasource.de");
cookie.setPath("/");
cookieStore.addCookie(cookie);
cookie = new BasicClientCookie(COOKIE_PASSWORD, password<PASSWORD>);
cookie.setDomain(".dotasource.de");
cookie.setPath("/");
cookieStore.addCookie(cookie);
cookie = new BasicClientCookie(COOKIE_HASH, cookieHash);
cookie.setDomain(".dotasource.de");
cookie.setPath("/");
cookieStore.addCookie(cookie);
client = HttpClients.custom().setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();
}
public void setSession(String userId, String passwordHash) {
this.userId = userId;
this.passwordHash = <PASSWORD>;
}
public List<Notification> getNotificationsAfterDate(Date date) throws IOException {
int currentPage = 1;
int pageCount = getNotificationPageCount();
List<Notification> newNotifications = new ArrayList<Notification>();
while (currentPage <= pageCount) {
String input = readNotifications(currentPage);
List<Notification> notifications = Notification.parse(input);
for (Notification notification : notifications) {
if (!notification.getDate().before(date)) {
newNotifications.add(notification);
} else {
return newNotifications;
}
}
currentPage++;
}
return newNotifications;
}
public String getEditPostInput(String postId) throws IOException {
HttpGet httpGet = new HttpGet("http://dotasource.de/post-edit/" + postId + "/");
CloseableHttpResponse response = client.execute(httpGet);
try {
// System.out.println(response.getStatusLine());
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
} finally {
if (response != null)
response.close();
}
}
public String getPost(String postId) throws IOException {
String input = getEditPostInput(postId);
Matcher m = PATTERN_POST_CONTENT.matcher(input);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
public void updateLikes(Notification notification) throws IOException {
assert notification.getType() == Notification.TYPE_LIKE;
ArrayList<Like> likes = new ArrayList<>();
for (User user : notification.getUsers()) {
likes.add(new Like(user, notification.getDate(), notification.getPostId()));
}
LikeTable likeTable;
String content;
String input = getPost(notification.getPostId());
Matcher m = LikeTable.PATTERN_LIKE_TABLE.matcher(input);
if (m.find()) { // liketable bereits vorhanden
content = m.group("content");
likeTable = LikeTable.parse(m.group("liketable"), notification.getPostId());
likeTable.addLikes(likes);
} else {
content = input;
likeTable = new LikeTable(likes);
}
// System.out.println(content);
editPost(notification.getPostId(), content + likeTable.toBBCode());
}
public void editPost(String postId, String content) throws IOException {
HashMap<String, String> inputTypes = getInputTypes(postId);
HttpPost post = new HttpPost("http://dotasource.de/post-edit/" + postId + "/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("deleteReason", ""));
nameValuePairs.add(new BasicNameValuePair("subject", inputTypes.get("subject")));
nameValuePairs.add(new BasicNameValuePair("editReason", "Likes aktualisieren"));
nameValuePairs.add(new BasicNameValuePair("text", content));
nameValuePairs.add(new BasicNameValuePair("tmpHash", inputTypes.get("tmpHash")));
nameValuePairs.add(new BasicNameValuePair("preParse", "1"));
nameValuePairs.add(new BasicNameValuePair("enableSmilies", "1"));
nameValuePairs.add(new BasicNameValuePair("enableBBCodes", "1"));
nameValuePairs.add(new BasicNameValuePair("showSignature", "1"));
nameValuePairs.add(new BasicNameValuePair("pollQuestion", inputTypes.get("pollQuestion")));
nameValuePairs.add(new BasicNameValuePair("pollEndTime", inputTypes.get("pollEndTime")));
nameValuePairs.add(new BasicNameValuePair("pollMaxVotes", "1"));
nameValuePairs.add(new BasicNameValuePair("t", inputTypes.get("t")));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset.forName("UTF-8")));
try (CloseableHttpResponse response = client.execute(post)) {
System.out.println("HTTP Post: http://dotasource.de/post-edit/" + postId + "/");
System.out.println(response.getStatusLine());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
// System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public HashMap<String, String> getInputTypes(String postId) throws IOException {
String content = getEditPostInput(postId);
// System.out.println(content);
HashMap<String, String> map = new HashMap<>();
Matcher formMatcher = PATTERN_EDIT_POST_FORM.matcher(content);
if (formMatcher.find()) {
// System.out.println("FORM:" + formMatcher.group(1));
Matcher inputTypeMatcher = PATTERN_INPUT_TYPE.matcher(formMatcher.group(1));
while (inputTypeMatcher.find()) {
map.put(inputTypeMatcher.group("name"), inputTypeMatcher.group("value"));
}
}
return map;
}
public int getNotificationPageCount() throws IOException {
String content = readNotifications(1);
Matcher m = PATTERN_PAGE_NUMBER.matcher(content);
int result = 0;
while (m.find()) {
result = Math.max(result, Integer.parseInt(m.group(1)));
}
return result;
}
public String readNotifications(int page) throws IOException {
HttpGet httpGet = new HttpGet("http://www.dotasource.de/notification-list/?pageNo=" + page);
CloseableHttpResponse response = client.execute(httpGet);
try {
System.out.println("HTTP Get: http://www.dotasource.de/notification-list/?pageNo=" + page);
System.out.println(response.getStatusLine());
try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
} finally {
if (response != null)
response.close();
}
}
}
| 9,137 | 0.716398 | 0.707264 | 226 | 38.690266 | 33.654301 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.597345 | false | false | 8 |
b3de0944e19ef62fda030eedb95a46fd6477bcee | 4,999,341,982,815 | b577b1714dd172ea9c43f2ddadde48c69be4d5ff | /ll/src/main/java/com/ttpod/lucky/service/WinprizeService.java | 7c1036db1f88ad2f5ddeabaab433c8291da2c79d | [] | no_license | xiayingjie/lucky | https://github.com/xiayingjie/lucky | e8cdb8e13c0f1a692d15219d676149070e71c818 | 85dc5985a802f477a66da8a3690684c03a4cc150 | refs/heads/master | 2015-08-23T02:43:06.770000 | 2015-04-09T08:58:24 | 2015-04-09T08:58:24 | 33,655,213 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ttpod.lucky.service;
import com.ttpod.lucky.dao.WinprizeDAO;
import com.ttpod.lucky.entity.Winprize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @classDescription:
* @author:xiayingjie
* @createTime:13-10-29 下午3:09
*/
@Service
@Transactional
public class WinprizeService {
@Autowired
private WinprizeDAO winprizeDAO;
/**
* 查询所有的文章
*
* @return
*/
public List<Winprize> findAllWinprizes() {
return (List<Winprize>) this.winprizeDAO.findAll();
}
/**
* 条件分页查询相关结果
*
* @return
*/
public Page<Winprize> findAllWinprizes(Specification specification, PageRequest pageRequest) {
return this.winprizeDAO.findAll(specification, pageRequest);
}
/**
* 条件分页查询相关结果
*
* @return
*/
public Page<Winprize> findAllWinprizes(int page, int size) {
Sort sort = new Sort(Sort.Direction.DESC, "orders");
PageRequest pageRequest = new PageRequest(page, size, sort);
return this.winprizeDAO.findAll(pageRequest);
}
/**
* 删除
*
* @return
*/
public void deleteWinprizeById(int id) {
this.winprizeDAO.delete(id);
}
/**
* 根据id查找文章对象
*
* @return
*/
public Winprize findWinprizeById(int id) {
return this.winprizeDAO.findOne(id);
}
/**
* 增加或修改
*
* @return
*/
public void saveWinprize(Winprize Winprize) {
this.winprizeDAO.save(Winprize);
}
public WinprizeDAO getWinprizeDAO() {
return winprizeDAO;
}
public void setWinprizeDAO(WinprizeDAO WinprizeDAO) {
this.winprizeDAO = WinprizeDAO;
}
}
| UTF-8 | Java | 2,228 | java | WinprizeService.java | Java | [
{
"context": "l.List;\r\n\r\n/**\r\n * @classDescription:\r\n * @author:xiayingjie\r\n * @createTime:13-10-29 下午3:09\r\n */\r\n@Service\r\n@",
"end": 577,
"score": 0.999703049659729,
"start": 567,
"tag": "USERNAME",
"value": "xiayingjie"
}
] | null | [] | package com.ttpod.lucky.service;
import com.ttpod.lucky.dao.WinprizeDAO;
import com.ttpod.lucky.entity.Winprize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @classDescription:
* @author:xiayingjie
* @createTime:13-10-29 下午3:09
*/
@Service
@Transactional
public class WinprizeService {
@Autowired
private WinprizeDAO winprizeDAO;
/**
* 查询所有的文章
*
* @return
*/
public List<Winprize> findAllWinprizes() {
return (List<Winprize>) this.winprizeDAO.findAll();
}
/**
* 条件分页查询相关结果
*
* @return
*/
public Page<Winprize> findAllWinprizes(Specification specification, PageRequest pageRequest) {
return this.winprizeDAO.findAll(specification, pageRequest);
}
/**
* 条件分页查询相关结果
*
* @return
*/
public Page<Winprize> findAllWinprizes(int page, int size) {
Sort sort = new Sort(Sort.Direction.DESC, "orders");
PageRequest pageRequest = new PageRequest(page, size, sort);
return this.winprizeDAO.findAll(pageRequest);
}
/**
* 删除
*
* @return
*/
public void deleteWinprizeById(int id) {
this.winprizeDAO.delete(id);
}
/**
* 根据id查找文章对象
*
* @return
*/
public Winprize findWinprizeById(int id) {
return this.winprizeDAO.findOne(id);
}
/**
* 增加或修改
*
* @return
*/
public void saveWinprize(Winprize Winprize) {
this.winprizeDAO.save(Winprize);
}
public WinprizeDAO getWinprizeDAO() {
return winprizeDAO;
}
public void setWinprizeDAO(WinprizeDAO WinprizeDAO) {
this.winprizeDAO = WinprizeDAO;
}
}
| 2,228 | 0.626168 | 0.621963 | 95 | 20.526316 | 21.918913 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294737 | false | false | 8 |
c562992d920fad089b116ef03f2615037e67e734 | 16,939,351,019,012 | f6b57133735b79e85d7cfd1b324dbd7119513c87 | /MergeSort.java | a3bdefce3ec6810a8a249080f15297939bcec832 | [] | no_license | grzabrodskiy/OnlineQuery | https://github.com/grzabrodskiy/OnlineQuery | 8a894aa5e22ffb5e97978d85ff18b52f6bc1bb8a | 967727bedbdd74042830108b03bd04769efb9252 | refs/heads/main | 2023-01-30T09:36:43.197000 | 2020-12-13T12:52:23 | 2020-12-13T12:52:23 | 321,064,204 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*************************************************************************
* Compilation: javac Merge.java
* Execution: java Merge N
*
* A more generic version of mergesort using Comparable.
*
*************************************************************************/
public class MergeSort {
public static void sort(Comparable[] theArray) {
sort(0, theArray.length, theArray);
}
// Sort theArray[lo, hi).
public static void sort(int lo, int hi, Comparable[] theArray) {
int N = hi - lo; // number of elements to sort
// 0- or 1-element file, so we're done
if (N <= 1) return;
// recursively sort left and right halves
int mid = lo + N/2;
sort(lo, mid, theArray);
sort(mid, hi, theArray);
// merge two sorted subarrays
Comparable[] aux = new Comparable[N];
int i = lo, j = mid;
for (int k = 0; k < N; k++) {
if (i == mid)
aux[k] = theArray[j++];
else if (j == hi)
aux[k] = theArray[i++];
else if (theArray[j].compareTo(theArray[i]) < 0)
aux[k] = theArray[j++];
else
aux[k] = theArray[i++];
}
// copy back
for (int k = 0; k < N; k++) {
theArray[lo + k] = aux[k];
}
}
} | UTF-8 | Java | 1,361 | java | MergeSort.java | Java | [] | null | [] | /*************************************************************************
* Compilation: javac Merge.java
* Execution: java Merge N
*
* A more generic version of mergesort using Comparable.
*
*************************************************************************/
public class MergeSort {
public static void sort(Comparable[] theArray) {
sort(0, theArray.length, theArray);
}
// Sort theArray[lo, hi).
public static void sort(int lo, int hi, Comparable[] theArray) {
int N = hi - lo; // number of elements to sort
// 0- or 1-element file, so we're done
if (N <= 1) return;
// recursively sort left and right halves
int mid = lo + N/2;
sort(lo, mid, theArray);
sort(mid, hi, theArray);
// merge two sorted subarrays
Comparable[] aux = new Comparable[N];
int i = lo, j = mid;
for (int k = 0; k < N; k++) {
if (i == mid)
aux[k] = theArray[j++];
else if (j == hi)
aux[k] = theArray[i++];
else if (theArray[j].compareTo(theArray[i]) < 0)
aux[k] = theArray[j++];
else
aux[k] = theArray[i++];
}
// copy back
for (int k = 0; k < N; k++) {
theArray[lo + k] = aux[k];
}
}
} | 1,361 | 0.433505 | 0.427627 | 47 | 27.978724 | 21.541143 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.765957 | false | false | 8 |
f8f0a0b13b475097a8065903c797832264a7e8f1 | 15,324,443,332,744 | 233a2657e1cc7d07962a7ee8c54993f5d1a43802 | /CalcCode/src/icode/Alloc.java | 3dc3133b7b3e8e940b8122d0a6eec809118637c5 | [] | no_license | FredrikAppelros/eda180 | https://github.com/FredrikAppelros/eda180 | 0bd7441b11dbfbb54d681da2c9be850df83c4dc4 | 268554597c050810f5fcd327115b396163698f3a | refs/heads/master | 2019-07-02T01:18:16.828000 | 2012-04-17T08:41:11 | 2012-04-17T08:41:11 | 3,536,054 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package icode;
import util.*;import java.util.*;
public class Alloc extends Instruction implements Cloneable {
public void flushCache() {
super.flushCache();
}
public void flushCollectionCache() {
super.flushCollectionCache();
}
@SuppressWarnings({"unchecked", "cast"}) public Alloc clone() throws CloneNotSupportedException {
Alloc node = (Alloc)super.clone();
return node;
}
@SuppressWarnings({"unchecked", "cast"}) public Alloc copy() {
try {
Alloc node = (Alloc)clone();
if(children != null) node.children = (ASTNode[])children.clone();
return node;
} catch (CloneNotSupportedException e) {
}
System.err.println("Error: Could not clone node of type " + getClass().getName() + "!");
return null;
}
@SuppressWarnings({"unchecked", "cast"}) public Alloc fullCopy() {
Alloc res = (Alloc)copy();
for(int i = 0; i < getNumChildNoTransform(); i++) {
ASTNode node = getChildNoTransform(i);
if(node != null) node = node.fullCopy();
res.setChild(node, i);
}
return res;
}
// Declared in icodeToString.jadd at line 47
public void appendBody(TabbedBuffer buffer) {
buffer.append("ALLOC");
buffer.append("size(" + getSize() + ")");
}
// Declared in icode.ast at line 3
// Declared in icode.ast line 7
public Alloc() {
super();
}
// Declared in icode.ast at line 10
// Declared in icode.ast line 7
public Alloc(int p0) {
setSize(p0);
}
// Declared in icode.ast at line 14
protected int numChildren() {
return 0;
}
// Declared in icode.ast at line 2
// Declared in icode.ast line 7
protected int tokenint_Size;
// Declared in icode.ast at line 3
public void setSize(int value) {
tokenint_Size = value;
}
// Declared in icode.ast at line 6
public int getSize() {
return tokenint_Size;
}
}
| UTF-8 | Java | 2,037 | java | Alloc.java | Java | [] | null | [] |
package icode;
import util.*;import java.util.*;
public class Alloc extends Instruction implements Cloneable {
public void flushCache() {
super.flushCache();
}
public void flushCollectionCache() {
super.flushCollectionCache();
}
@SuppressWarnings({"unchecked", "cast"}) public Alloc clone() throws CloneNotSupportedException {
Alloc node = (Alloc)super.clone();
return node;
}
@SuppressWarnings({"unchecked", "cast"}) public Alloc copy() {
try {
Alloc node = (Alloc)clone();
if(children != null) node.children = (ASTNode[])children.clone();
return node;
} catch (CloneNotSupportedException e) {
}
System.err.println("Error: Could not clone node of type " + getClass().getName() + "!");
return null;
}
@SuppressWarnings({"unchecked", "cast"}) public Alloc fullCopy() {
Alloc res = (Alloc)copy();
for(int i = 0; i < getNumChildNoTransform(); i++) {
ASTNode node = getChildNoTransform(i);
if(node != null) node = node.fullCopy();
res.setChild(node, i);
}
return res;
}
// Declared in icodeToString.jadd at line 47
public void appendBody(TabbedBuffer buffer) {
buffer.append("ALLOC");
buffer.append("size(" + getSize() + ")");
}
// Declared in icode.ast at line 3
// Declared in icode.ast line 7
public Alloc() {
super();
}
// Declared in icode.ast at line 10
// Declared in icode.ast line 7
public Alloc(int p0) {
setSize(p0);
}
// Declared in icode.ast at line 14
protected int numChildren() {
return 0;
}
// Declared in icode.ast at line 2
// Declared in icode.ast line 7
protected int tokenint_Size;
// Declared in icode.ast at line 3
public void setSize(int value) {
tokenint_Size = value;
}
// Declared in icode.ast at line 6
public int getSize() {
return tokenint_Size;
}
}
| 2,037 | 0.587629 | 0.579283 | 82 | 23.829268 | 23.150518 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.378049 | false | false | 8 |
2205e1ed62791949b6d1a78c5f763106faf2461b | 18,365,280,177,346 | e2432ae653412b4494a6d08f2e028f3120cd2f14 | /app/src/main/java/com/netmania/checklod/presentation/adapter/LoggerListAdapter.java | 44986eba072db7218c43afb5e4359b93a9098c02 | [] | no_license | netmaniarnd/checklodSetup | https://github.com/netmaniarnd/checklodSetup | 1d4bc341ba9f5c18a8a4887a42620988a8837c0c | 03f77b33add7a951e3ce1810499f84669c754ec6 | refs/heads/master | 2023-09-01T08:39:09.067000 | 2021-09-27T08:15:14 | 2021-09-27T08:15:14 | 409,876,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.netmania.checklod.presentation.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.netmania.checklod.R;
import com.netmania.checklod.util.Utility;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class LoggerListAdapter extends RecyclerView.Adapter<LoggerListAdapter.ViewHolder> {
private JSONArray mData;
// 아이템 뷰를 저장하는 뷰홀더 클래스.
public class ViewHolder extends RecyclerView.ViewHolder {
TextView alias;
TextView macaddress;
ViewHolder(View itemView) {
super(itemView);
// 뷰 객체에 대한 참조. (hold strong reference)
alias = itemView.findViewById(R.id.alias);
macaddress = itemView.findViewById(R.id.macaddress);
}
}
// 생성자에서 데이터 리스트 객체를 전달받음.
public LoggerListAdapter(JSONArray list) {
try {
mData = Utility.sortJsonArray(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
// onCreateViewHolder() - 아이템 뷰를 위한 뷰홀더 객체 생성하여 리턴.
@Override
public LoggerListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.loggerlist_item, parent, false);
LoggerListAdapter.ViewHolder vh = new LoggerListAdapter.ViewHolder(view);
return vh;
}
// onBindViewHolder() - position에 해당하는 데이터를 뷰홀더의 아이템뷰에 표시.
@Override
public void onBindViewHolder(LoggerListAdapter.ViewHolder holder, int position) {
JSONObject obj = null;
try {
obj = mData.getJSONObject(position);
holder.alias.setText(obj.getString("alias"));
holder.macaddress.setText(obj.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return mData.length();
}
}
| UTF-8 | Java | 2,382 | java | LoggerListAdapter.java | Java | [] | null | [] | package com.netmania.checklod.presentation.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.netmania.checklod.R;
import com.netmania.checklod.util.Utility;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class LoggerListAdapter extends RecyclerView.Adapter<LoggerListAdapter.ViewHolder> {
private JSONArray mData;
// 아이템 뷰를 저장하는 뷰홀더 클래스.
public class ViewHolder extends RecyclerView.ViewHolder {
TextView alias;
TextView macaddress;
ViewHolder(View itemView) {
super(itemView);
// 뷰 객체에 대한 참조. (hold strong reference)
alias = itemView.findViewById(R.id.alias);
macaddress = itemView.findViewById(R.id.macaddress);
}
}
// 생성자에서 데이터 리스트 객체를 전달받음.
public LoggerListAdapter(JSONArray list) {
try {
mData = Utility.sortJsonArray(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
// onCreateViewHolder() - 아이템 뷰를 위한 뷰홀더 객체 생성하여 리턴.
@Override
public LoggerListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.loggerlist_item, parent, false);
LoggerListAdapter.ViewHolder vh = new LoggerListAdapter.ViewHolder(view);
return vh;
}
// onBindViewHolder() - position에 해당하는 데이터를 뷰홀더의 아이템뷰에 표시.
@Override
public void onBindViewHolder(LoggerListAdapter.ViewHolder holder, int position) {
JSONObject obj = null;
try {
obj = mData.getJSONObject(position);
holder.alias.setText(obj.getString("alias"));
holder.macaddress.setText(obj.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return mData.length();
}
}
| 2,382 | 0.674011 | 0.674011 | 69 | 31.231884 | 25.87604 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.507246 | false | false | 8 |
98a566cb5e55d1b0b39ba54cd5297a8f932b18da | 26,388,279,088,386 | ff6ed538337862371eeabdb3369505f46c50ad11 | /project/小米商城/shopping/src/com/mylifes1110/java/dao/impl/OrderDaoImpl.java | 7d474034c4e5e30a249fba9065880a4f2ae65190 | [
"Apache-2.0"
] | permissive | Gino-W/JavaLearningmanual | https://github.com/Gino-W/JavaLearningmanual | 8a5a68dcbded1d7824b1e47fc1ec80549cbdea8d | 1deb86a5bce15b56976ec2350d6e879ee746faf3 | refs/heads/master | 2022-12-20T03:39:03.126000 | 2020-10-06T15:09:36 | 2020-10-06T15:09:36 | 291,458,783 | 1 | 0 | Apache-2.0 | true | 2020-10-06T15:09:38 | 2020-08-30T11:40:44 | 2020-09-21T06:37:43 | 2020-10-06T15:09:37 | 403,428 | 0 | 0 | 0 | Java | false | false | package com.mylifes1110.java.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mylifes1110.java.bean.Order;
import com.mylifes1110.java.dao.OrderDao;
import com.mylifes1110.java.utils.DruidUtils;
public class OrderDaoImpl implements OrderDao {
private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
@Override
public void insertOrder(Order order) throws SQLException {
queryRunner.update(DruidUtils.getConnection(),
"insert into tb_order(id, uid, money, status, time, aid) values (?, ?, ?, ?, ?, ?)",
order.getId(),
order.getUid(),
order.getMoney(),
order.getStatus(),
order.getTime(),
order.getAid());
}
@Override
public Order selectOrderByOid(String oid) throws SQLException {
return queryRunner.query("select id, uid, money, status, time, aid from tb_order where id = ?",
new BeanHandler<Order>(Order.class),
oid);
}
@Override
public List<Order> selectOrderByUserId(int userId) throws SQLException {
return queryRunner.query("select id, uid, money, status, time, aid from tb_order where uid = ?",
new BeanListHandler<Order>(Order.class),
userId);
}
@Override
public Order selectOrderMoney(String oid) throws SQLException {
return queryRunner.query("select money from tb_order where id = ?", new BeanHandler<Order>(Order.class), oid);
}
@Override
public void updateOrder(String oid) throws SQLException {
queryRunner.update("update tb_order set status = 2 where id = ?", oid);
}
}
| UTF-8 | Java | 2,030 | java | OrderDaoImpl.java | Java | [] | null | [] | package com.mylifes1110.java.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mylifes1110.java.bean.Order;
import com.mylifes1110.java.dao.OrderDao;
import com.mylifes1110.java.utils.DruidUtils;
public class OrderDaoImpl implements OrderDao {
private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
@Override
public void insertOrder(Order order) throws SQLException {
queryRunner.update(DruidUtils.getConnection(),
"insert into tb_order(id, uid, money, status, time, aid) values (?, ?, ?, ?, ?, ?)",
order.getId(),
order.getUid(),
order.getMoney(),
order.getStatus(),
order.getTime(),
order.getAid());
}
@Override
public Order selectOrderByOid(String oid) throws SQLException {
return queryRunner.query("select id, uid, money, status, time, aid from tb_order where id = ?",
new BeanHandler<Order>(Order.class),
oid);
}
@Override
public List<Order> selectOrderByUserId(int userId) throws SQLException {
return queryRunner.query("select id, uid, money, status, time, aid from tb_order where uid = ?",
new BeanListHandler<Order>(Order.class),
userId);
}
@Override
public Order selectOrderMoney(String oid) throws SQLException {
return queryRunner.query("select money from tb_order where id = ?", new BeanHandler<Order>(Order.class), oid);
}
@Override
public void updateOrder(String oid) throws SQLException {
queryRunner.update("update tb_order set status = 2 where id = ?", oid);
}
}
| 2,030 | 0.608374 | 0.6 | 53 | 37.264153 | 32.618523 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.924528 | false | false | 8 |
5adca30d4792f4b2bce1ddf0c145320f569fdc3f | 13,443,247,666,895 | e6c800373e8cb39bd7c042c8738efcc9802bc3cd | /analysiskeeper/container/src/main/java/container/HostActivator.java | d674f65d917e74e98002e64b3148b6038354c8b3 | [
"BSD-2-Clause"
] | permissive | stg-tud/sootkeeper | https://github.com/stg-tud/sootkeeper | 1ea41298d5b8a2012a95349a2b9a9c1d1b537ebb | 9f4b8167d0d8ba4eebeca4a5fa4c48c97edab4e2 | refs/heads/master | 2021-07-03T18:23:56.962000 | 2020-06-17T09:47:52 | 2020-06-17T09:47:52 | 21,384,789 | 0 | 0 | NOASSERTION | false | 2020-10-13T08:37:51 | 2014-07-01T11:08:44 | 2020-06-17T09:47:58 | 2020-10-13T08:37:50 | 6,120 | 0 | 0 | 2 | Java | false | false | package container;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import java.util.Dictionary;
import java.util.Hashtable;
import static org.knopflerfish.service.console.CommandGroup.GROUP_NAME;
/**
* This is the BundleActivator for the AnalysisKeeper Container
* It registers the commandline commands and the service that handles them
* As an Analysis Author You should not need to change stuff here
*/
public class HostActivator implements BundleActivator {
/*
* String Constants used to register Commands
*/
private static final String OSGI_COMMAND_SCOPE = "osgi.command.scope";
private static final String OSGI_COMMAND_FUNCTION = "osgi.command.function";
private static final String SCOPE = "sootkeeper";
private static final String[] COMMAND_FUNCTIONS = {"listAnalyses", "la", "ra", "runAnalysis", "rep", "ua", "updateAnalysis"};
private ServiceRegistration<?> registration;
@SuppressWarnings("UseOfObsoleteCollectionType")
/**
* generates The HashTable that is used to register the Commands
*/
private static Dictionary<String, Object> generateProperties() {
Hashtable<String, Object> properties = new Hashtable<>();
properties.put(OSGI_COMMAND_SCOPE, SCOPE);
properties.put(OSGI_COMMAND_FUNCTION, COMMAND_FUNCTIONS);
properties.put(GROUP_NAME, HostService.SOOTKEEPER_NAME);
return properties;
}
/**
* {@inheritDoc}
*/
@Override
public void start(BundleContext context) throws Exception {
HostService s = new HostService(context);
Dictionary<String, Object> properties = generateProperties();
registration = context.registerService("container.HostService", s, properties);
}
/**
* {@inheritDoc}
*/
@Override
public void stop(BundleContext context) throws Exception {
registration.unregister();
}
}
| UTF-8 | Java | 1,985 | java | HostActivator.java | Java | [] | null | [] | package container;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import java.util.Dictionary;
import java.util.Hashtable;
import static org.knopflerfish.service.console.CommandGroup.GROUP_NAME;
/**
* This is the BundleActivator for the AnalysisKeeper Container
* It registers the commandline commands and the service that handles them
* As an Analysis Author You should not need to change stuff here
*/
public class HostActivator implements BundleActivator {
/*
* String Constants used to register Commands
*/
private static final String OSGI_COMMAND_SCOPE = "osgi.command.scope";
private static final String OSGI_COMMAND_FUNCTION = "osgi.command.function";
private static final String SCOPE = "sootkeeper";
private static final String[] COMMAND_FUNCTIONS = {"listAnalyses", "la", "ra", "runAnalysis", "rep", "ua", "updateAnalysis"};
private ServiceRegistration<?> registration;
@SuppressWarnings("UseOfObsoleteCollectionType")
/**
* generates The HashTable that is used to register the Commands
*/
private static Dictionary<String, Object> generateProperties() {
Hashtable<String, Object> properties = new Hashtable<>();
properties.put(OSGI_COMMAND_SCOPE, SCOPE);
properties.put(OSGI_COMMAND_FUNCTION, COMMAND_FUNCTIONS);
properties.put(GROUP_NAME, HostService.SOOTKEEPER_NAME);
return properties;
}
/**
* {@inheritDoc}
*/
@Override
public void start(BundleContext context) throws Exception {
HostService s = new HostService(context);
Dictionary<String, Object> properties = generateProperties();
registration = context.registerService("container.HostService", s, properties);
}
/**
* {@inheritDoc}
*/
@Override
public void stop(BundleContext context) throws Exception {
registration.unregister();
}
}
| 1,985 | 0.710831 | 0.710831 | 58 | 33.224136 | 30.525875 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603448 | false | false | 8 |
e877b2089ea3cf235e0c5370f3638f68d0e0a141 | 13,666,585,962,145 | bb9320dfa0eb77d876527f0781d7ad21b4207dbf | /src/test/java/StepDefinition/OrderHistorySteps.java | b1bcec2744e4f8f99634d5cfeb67495ec984d448 | [] | no_license | vivolric/CucumberProject1 | https://github.com/vivolric/CucumberProject1 | 715d7e36af805209e9b172832e9124f505781768 | f4ba886795bfda8cf110751dd4dedb774a25fee1 | refs/heads/master | 2022-12-04T17:51:15.513000 | 2020-08-10T03:54:31 | 2020-08-10T03:54:31 | 286,370,636 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package StepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import POM.DressPage;
import POM.ParentClass;
public class OrderHistorySteps {
DressPage dressPage = new DressPage ();
ParentClass parentClass = new ParentClass();
@Given("^Navigate to dresses page$")
public void navigateToDressesPage() {
dressPage.findElementAndClickFunction("dressButton");
}
@Then("^Click on the any item from the page, add to cart, send a message and proceed to check out$")
public void clickOnTheAnyItemFromThePageAddToCartAndProceedToCheckOut() {
dressPage.clickFunction(dressPage.dressList.get(parentClass.random(dressPage.dressList.size())));
dressPage.findElementAndClickFunction("addToCartButton");
dressPage.findElementAndClickFunction("proceedToCheckOutButton");
dressPage.findElementAndClickFunction("proceedToCheckOutButton2");
dressPage.myMessage.sendKeys("My last order");
dressPage.findElementAndClickFunction("proceedToCheckOutButton3");
}
@Then("^Click on the I agree, proceed to checkout button$")
public void clickOnTheIAgreeProceedToCheckoutButton() {
dressPage.findElementAndClickFunction("IagreeCheckBox");
dressPage.findElementAndClickFunction("proceedToCheckOutButton3");
}
@Then("^Click on Pay by bank wire, and i confirm my order button$")
public void clickOnPayByBankWireAndIConfirmMyOrderButton() {
dressPage.findElementAndClickFunction("bankWireButton");
dressPage.findElementAndClickFunction("confirmOrderButton");
}
@Then("^Back to orders and Click on Reference Number$")
public void getTextOfReferenceAndBackToOrders() {
dressPage.findElementAndClickFunction("backtoOrderButton");
dressPage.findElementAndClickFunction("clickOnReference");
}
@Then("^Verify my last order$")
public void verifyMyLastOrder() {
dressPage.findElementAndVerifyElementContainText("myText","My last order");
}
}
| UTF-8 | Java | 2,070 | java | OrderHistorySteps.java | Java | [] | null | [] | package StepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import POM.DressPage;
import POM.ParentClass;
public class OrderHistorySteps {
DressPage dressPage = new DressPage ();
ParentClass parentClass = new ParentClass();
@Given("^Navigate to dresses page$")
public void navigateToDressesPage() {
dressPage.findElementAndClickFunction("dressButton");
}
@Then("^Click on the any item from the page, add to cart, send a message and proceed to check out$")
public void clickOnTheAnyItemFromThePageAddToCartAndProceedToCheckOut() {
dressPage.clickFunction(dressPage.dressList.get(parentClass.random(dressPage.dressList.size())));
dressPage.findElementAndClickFunction("addToCartButton");
dressPage.findElementAndClickFunction("proceedToCheckOutButton");
dressPage.findElementAndClickFunction("proceedToCheckOutButton2");
dressPage.myMessage.sendKeys("My last order");
dressPage.findElementAndClickFunction("proceedToCheckOutButton3");
}
@Then("^Click on the I agree, proceed to checkout button$")
public void clickOnTheIAgreeProceedToCheckoutButton() {
dressPage.findElementAndClickFunction("IagreeCheckBox");
dressPage.findElementAndClickFunction("proceedToCheckOutButton3");
}
@Then("^Click on Pay by bank wire, and i confirm my order button$")
public void clickOnPayByBankWireAndIConfirmMyOrderButton() {
dressPage.findElementAndClickFunction("bankWireButton");
dressPage.findElementAndClickFunction("confirmOrderButton");
}
@Then("^Back to orders and Click on Reference Number$")
public void getTextOfReferenceAndBackToOrders() {
dressPage.findElementAndClickFunction("backtoOrderButton");
dressPage.findElementAndClickFunction("clickOnReference");
}
@Then("^Verify my last order$")
public void verifyMyLastOrder() {
dressPage.findElementAndVerifyElementContainText("myText","My last order");
}
}
| 2,070 | 0.742512 | 0.741063 | 54 | 37.333332 | 31.2066 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
4802f9cb9ab6eaf02714ef70eefabbb1f0996cd1 | 6,949,257,109,171 | 1108e24f502537830e55c8916956da162005865b | /alpha/215KthLargestElementInAnArray/Solution.java | eaea7e94875a1a84ec3aefbe3b158e271bd4ae56 | [] | no_license | namifans/leetcode | https://github.com/namifans/leetcode | 9e472bb6d2cdaa8dffcd2f0b45b6db9b353db047 | ccc49efdc0fe083e918ab8e46f21ddf2e6306cff | refs/heads/master | 2022-07-09T18:26:23.668000 | 2022-07-07T02:01:56 | 2022-07-07T02:01:56 | 88,399,793 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length == 0)
return 0;
Queue<Integer> queue = new PriorityQueue<>(k, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return b - a;
}
});
for (int i : nums) {
queue.offer(i);
}
while (k-- > 1) {
queue.poll();
}
return queue.peek();
}
} | UTF-8 | Java | 494 | java | Solution.java | Java | [] | null | [] | class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length == 0)
return 0;
Queue<Integer> queue = new PriorityQueue<>(k, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return b - a;
}
});
for (int i : nums) {
queue.offer(i);
}
while (k-- > 1) {
queue.poll();
}
return queue.peek();
}
} | 494 | 0.449393 | 0.44332 | 18 | 26.5 | 19.613628 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 8 |
a8c074f9a1ae67f14811aa91f20ccd7aa24835e1 | 16,698,832,895,803 | 62ba6da18fa792e1a37ffcde3f62c39e82f70f29 | /src/main/java/br/com/pjcase/controller/ControllerLogin.java | 5cc265e4bcfac36adfe670ce2d476e38acbcf618 | [] | no_license | rogerio121/pjcase | https://github.com/rogerio121/pjcase | 721de15bb4287ca016f42285feee8a11562b2c98 | c74ea89b33dce6fe2cf40c1df895a549b88fd82a | refs/heads/master | 2021-07-14T20:28:15.733000 | 2018-12-03T22:27:41 | 2018-12-03T22:27:41 | 125,937,075 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.pjcase.controller;
import br.com.pjcase.dao.DaoCaso;
import br.com.pjcase.dao.DaoUsuario;
import br.com.pjcase.model.Usuario;
import com.google.gson.Gson;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
@Controller
@RequestMapping("/")
public class ControllerLogin {
@RequestMapping("/")
public String chamaTelalogin() {
return "login";
}
@RequestMapping("telaInicial")
public ModelAndView login2(HttpServletRequest request){
DaoCaso daoCaso = new DaoCaso();
ModelAndView mv;
try {
int mesAtual;
int meusCasosAbertos = 0;
int meusCasosEmAtendimento = 0;
int meusCasosFechados = 0;
String casosSemProprietaioJson;
Usuario usuarioLogado = new Usuario();
usuarioLogado = (Usuario) request.getSession().getAttribute("usuarioLogado");
casosSemProprietaioJson = new Gson().toJson(daoCaso.listarCasosSemProprietarios(usuarioLogado));
Date dataDeHoje = new Date();
LocalDate localDate = dataDeHoje.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
mesAtual = localDate.getMonthValue();
meusCasosAbertos = daoCaso.buscarNumeroDeCasosPorStatusPorIdDoUsuarioPorMes(usuarioLogado.getId(), "Aberto", mesAtual);
meusCasosEmAtendimento = daoCaso.buscarNumeroDeCasosPorStatusPorIdDoUsuarioPorMes(usuarioLogado.getId(), "Em atendimento", mesAtual);
meusCasosFechados = daoCaso.buscarNumeroDeCasosPorStatusPorIdDoUsuarioPorMes(usuarioLogado.getId(), "Fechado", mesAtual);
request.setAttribute("casosSemProprietaioJson", casosSemProprietaioJson);
mv = new ModelAndView("telaInicial");
mv.addObject("meusCasosAbertos", meusCasosAbertos);
mv.addObject("meusCasosEmAtendimento", meusCasosEmAtendimento);
mv.addObject("meusCasosFechados", meusCasosFechados);
} catch (Exception erro) {
System.out.println("Erro ao acessar a Tela inicial: " + erro);
mv = new ModelAndView("redirect:/");
}
return mv;
}
@RequestMapping("logar")
public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
DaoUsuario daoUsuario = new DaoUsuario();
Usuario usuario = new Usuario();
try {
usuario = daoUsuario.getByEmailESenha(request.getParameter("email"), request.getParameter("senha"));
HttpSession sessao = request.getSession();
sessao.setAttribute("usuarioLogado", usuario);
//sessao.setMaxInactiveInterval(3000);
return "redirect:/telaInicial";
} catch (Exception e) {
System.out.println("Erro ao logar: " + e);
return null;
}
}
@PostMapping("validarusuario")
public ResponseEntity<Usuario> validarUsuario(@RequestBody Usuario usuario) {
DaoUsuario daoUsuario = new DaoUsuario();
Usuario usuarioValidado = null;
try {
usuarioValidado = daoUsuario.getByEmailESenha(usuario.getDadosPessoais().getEmail(), usuario.getSenha());
if (usuarioValidado != null)
return ResponseEntity.ok(usuarioValidado);
else
return ResponseEntity.status(204).build();
} catch (Exception e) {
System.out.println("Erro ao validar usuário: " + e);
return ResponseEntity.status(500).build();
}
}
@RequestMapping("logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
}
| UTF-8 | Java | 4,299 | java | ControllerLogin.java | Java | [] | null | [] | package br.com.pjcase.controller;
import br.com.pjcase.dao.DaoCaso;
import br.com.pjcase.dao.DaoUsuario;
import br.com.pjcase.model.Usuario;
import com.google.gson.Gson;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
@Controller
@RequestMapping("/")
public class ControllerLogin {
@RequestMapping("/")
public String chamaTelalogin() {
return "login";
}
@RequestMapping("telaInicial")
public ModelAndView login2(HttpServletRequest request){
DaoCaso daoCaso = new DaoCaso();
ModelAndView mv;
try {
int mesAtual;
int meusCasosAbertos = 0;
int meusCasosEmAtendimento = 0;
int meusCasosFechados = 0;
String casosSemProprietaioJson;
Usuario usuarioLogado = new Usuario();
usuarioLogado = (Usuario) request.getSession().getAttribute("usuarioLogado");
casosSemProprietaioJson = new Gson().toJson(daoCaso.listarCasosSemProprietarios(usuarioLogado));
Date dataDeHoje = new Date();
LocalDate localDate = dataDeHoje.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
mesAtual = localDate.getMonthValue();
meusCasosAbertos = daoCaso.buscarNumeroDeCasosPorStatusPorIdDoUsuarioPorMes(usuarioLogado.getId(), "Aberto", mesAtual);
meusCasosEmAtendimento = daoCaso.buscarNumeroDeCasosPorStatusPorIdDoUsuarioPorMes(usuarioLogado.getId(), "Em atendimento", mesAtual);
meusCasosFechados = daoCaso.buscarNumeroDeCasosPorStatusPorIdDoUsuarioPorMes(usuarioLogado.getId(), "Fechado", mesAtual);
request.setAttribute("casosSemProprietaioJson", casosSemProprietaioJson);
mv = new ModelAndView("telaInicial");
mv.addObject("meusCasosAbertos", meusCasosAbertos);
mv.addObject("meusCasosEmAtendimento", meusCasosEmAtendimento);
mv.addObject("meusCasosFechados", meusCasosFechados);
} catch (Exception erro) {
System.out.println("Erro ao acessar a Tela inicial: " + erro);
mv = new ModelAndView("redirect:/");
}
return mv;
}
@RequestMapping("logar")
public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
DaoUsuario daoUsuario = new DaoUsuario();
Usuario usuario = new Usuario();
try {
usuario = daoUsuario.getByEmailESenha(request.getParameter("email"), request.getParameter("senha"));
HttpSession sessao = request.getSession();
sessao.setAttribute("usuarioLogado", usuario);
//sessao.setMaxInactiveInterval(3000);
return "redirect:/telaInicial";
} catch (Exception e) {
System.out.println("Erro ao logar: " + e);
return null;
}
}
@PostMapping("validarusuario")
public ResponseEntity<Usuario> validarUsuario(@RequestBody Usuario usuario) {
DaoUsuario daoUsuario = new DaoUsuario();
Usuario usuarioValidado = null;
try {
usuarioValidado = daoUsuario.getByEmailESenha(usuario.getDadosPessoais().getEmail(), usuario.getSenha());
if (usuarioValidado != null)
return ResponseEntity.ok(usuarioValidado);
else
return ResponseEntity.status(204).build();
} catch (Exception e) {
System.out.println("Erro ao validar usuário: " + e);
return ResponseEntity.status(500).build();
}
}
@RequestMapping("logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
}
| 4,299 | 0.676826 | 0.673569 | 116 | 36.051723 | 33.167248 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672414 | false | false | 8 |
1a3014c2aea0dddd2fb9053f2c1d1bf6504b4857 | 29,403,346,159,993 | 6127073b4fee59fbe76debba136a62ddb8fac6a4 | /shopsystem/src/main/java/com/shiroyk/shopsystem/config/SecurityConfig.java | def24d0ddd1b562f0899054bf4bb8824d90a16ce | [] | no_license | Liu-Suser/ShopSystem | https://github.com/Liu-Suser/ShopSystem | 5f453e6c1c9e5afc6b6fac959a40eab87337a556 | 560f8dd56aa69a43cbeb44e86a43903d451e9bf4 | refs/heads/master | 2023-05-23T16:27:58.581000 | 2021-06-10T09:11:01 | 2021-06-10T09:55:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2020 All right reserved.
* Created by shiroyk, https://github.com/shiroyk
*/
package com.shiroyk.shopsystem.config;
import com.shiroyk.shopsystem.component.AuthExceptionHandler;
import com.shiroyk.shopsystem.filter.JwtAuthorizationFilter;
import com.shiroyk.shopsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.HandlerExceptionResolver;
import java.util.Arrays;
import java.util.Collections;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final HandlerExceptionResolver resolver;
private final UserService cusUserService;
private final AuthExceptionHandler authExceptionHandler;
public SecurityConfig(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver,
UserService cusUserService,
AuthExceptionHandler authExceptionHandler) {
this.resolver = resolver;
this.cusUserService = cusUserService;
this.authExceptionHandler = authExceptionHandler;
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE"));
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public JwtAuthorizationFilter jwtAuthorizationFilter() {
return new JwtAuthorizationFilter(resolver, cusUserService);
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(cusUserService).passwordEncoder(bCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.configurationSource(corsConfigurationSource())
.and()
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authExceptionHandler)
.accessDeniedHandler(authExceptionHandler)
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/category/*").permitAll()
.antMatchers(HttpMethod.GET, "/product/*").permitAll()
.antMatchers(HttpMethod.GET, "/user/info").permitAll()
.antMatchers("/auth/*").permitAll()
.antMatchers("/user/*").authenticated()
.antMatchers("/admin/*").authenticated()
.anyRequest().permitAll()
.and()
.addFilterBefore(jwtAuthorizationFilter(), LogoutFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
| UTF-8 | Java | 4,931 | java | SecurityConfig.java | Java | [
{
"context": "pyright (c) 2020 All right reserved.\n * Created by shiroyk, https://github.com/shiroyk\n */\n\npackage com.shir",
"end": 66,
"score": 0.9996741414070129,
"start": 59,
"tag": "USERNAME",
"value": "shiroyk"
},
{
"context": "served.\n * Created by shiroyk, https://github.... | null | [] | /*
* Copyright (c) 2020 All right reserved.
* Created by shiroyk, https://github.com/shiroyk
*/
package com.shiroyk.shopsystem.config;
import com.shiroyk.shopsystem.component.AuthExceptionHandler;
import com.shiroyk.shopsystem.filter.JwtAuthorizationFilter;
import com.shiroyk.shopsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.HandlerExceptionResolver;
import java.util.Arrays;
import java.util.Collections;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final HandlerExceptionResolver resolver;
private final UserService cusUserService;
private final AuthExceptionHandler authExceptionHandler;
public SecurityConfig(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver,
UserService cusUserService,
AuthExceptionHandler authExceptionHandler) {
this.resolver = resolver;
this.cusUserService = cusUserService;
this.authExceptionHandler = authExceptionHandler;
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE"));
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public JwtAuthorizationFilter jwtAuthorizationFilter() {
return new JwtAuthorizationFilter(resolver, cusUserService);
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(cusUserService).passwordEncoder(bCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.configurationSource(corsConfigurationSource())
.and()
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authExceptionHandler)
.accessDeniedHandler(authExceptionHandler)
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/category/*").permitAll()
.antMatchers(HttpMethod.GET, "/product/*").permitAll()
.antMatchers(HttpMethod.GET, "/user/info").permitAll()
.antMatchers("/auth/*").permitAll()
.antMatchers("/user/*").authenticated()
.antMatchers("/admin/*").authenticated()
.anyRequest().permitAll()
.and()
.addFilterBefore(jwtAuthorizationFilter(), LogoutFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
| 4,931 | 0.74346 | 0.742649 | 110 | 43.827274 | 29.971458 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536364 | false | false | 8 |
d2171ca5b5caf6804bae9c9dfd2ae45ce466f8b1 | 11,605,001,703,358 | c0bf590d4fcb9a0eaa8963b10a2ddcc5618183c5 | /UszoVerseny/src/main/java/com/flowacademy/Uszoverseny.java | 3169631d900641b811c889051f0aa723ccc9e13e | [] | no_license | vitriolfox/Java_practise | https://github.com/vitriolfox/Java_practise | 61d86656d6b05262d2f45007506d35e3274aeb62 | a92798ea82bf09272d8eb7f161be88c8da2a7148 | refs/heads/master | 2021-08-30T21:32:34.261000 | 2017-12-19T13:45:46 | 2017-12-19T13:45:46 | 110,809,416 | 0 | 2 | null | false | 2017-12-19T13:45:47 | 2017-11-15T09:00:49 | 2017-11-15T09:03:20 | 2017-12-19T13:45:46 | 21,451 | 0 | 2 | 0 | Java | false | null | package com.flowacademy;
import com.flowacademy.uszoda.*;
import com.flowacademy.uszoda.comparators.GyorsuszoComparator;
import com.flowacademy.uszoda.comparators.HatuszoComparator;
import com.flowacademy.uszoda.comparators.UszoMesterComparator;
import java.io.*;
import java.util.*;
public class Uszoverseny {
private static final String INPUT = "./data/input.txt";
private static final String OUTPUT = "./data/eredmeny.txt";
private static final String USZOMESTER_SERIALIZATION_FILE_PATH = "./data/uszomesterek.ser";
private static final String GYORSUSZO_SERIALIZATION_FILE_PATH = "./data/gyorsuszasverseny.ser";
private static final String HATUSZO_SERIALIZATION_FILE_PATH = "./data/hatuszasverseny.ser";
public static void uszoPrint(List<Uszo> uszomesterList, Uszo gyorsNyertes, Uszo hatNyertes, Writer uszoWriter) throws IOException{
List<Uszo> kiirtUszoList = new ArrayList<>(uszomesterList);
kiirtUszoList.add(gyorsNyertes);
kiirtUszoList.add(hatNyertes);
for (Uszo listElement : kiirtUszoList) {
try {
if (listElement instanceof UszoMester) {
uszoWriter.write(listElement.toString() + "\n");
} else if (listElement instanceof Gyorsuszo){
uszoWriter.write("A gyorsúszás nyertese: " + listElement.toString() + "\n");
} else if (listElement instanceof Hatuszo){
uszoWriter.write("A hátúszás nyertese: " + listElement.toString() + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void uszoSerial(List<Uszo> uszoBogyokak, String serialPath) {
serializationCore(uszoBogyokak, serialPath);
}
public static void hatuszoSerial(List<Hatuszo> uszoBogyokak, String serialPath) {
serializationCore(uszoBogyokak, serialPath);
}
public static void gyorsuszoSerial(List<Gyorsuszo> uszoBogyokak, String serialPath) {
serializationCore(uszoBogyokak, serialPath);
}
public static void serializationCore(List list, String serialPath){
try {
FileOutputStream fileOut = new FileOutputStream(serialPath);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(list);
out.close();
fileOut.close();
System.out.println("Magic!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Uszo> uszoDeSerialization(String file){
List<Uszo> uszoList = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
uszoList = (List<Uszo>) in.readObject();
System.out.println("!cigaM");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return uszoList;
}
public static List<Gyorsuszo> gyorsUszoDeSerialization(String file){
List<Gyorsuszo> uszoList = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
uszoList = (List<Gyorsuszo>) in.readObject();
System.out.println("!cigaM");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return uszoList;
}
public static List<Hatuszo> hatUszoDeSerialization(String file){
List<Hatuszo> uszoList = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
uszoList = (List<Hatuszo>) in.readObject();
System.out.println("!cigaM");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return uszoList;
}
public static void hatUszoRelativTeljesitmeny(HashMap<Uszo, Integer> targetHashMap, List<Hatuszo> teljesitmenyLista, List<Hatuszo> versenyLista){
for (Hatuszo teljesitmenyBogyoka: teljesitmenyLista){
for (Hatuszo versenyBogyoka: versenyLista){
if (versenyBogyoka.getNev().equals(teljesitmenyBogyoka.getNev())){
int relativTeljesitmeny = teljesitmenyLista.indexOf(teljesitmenyBogyoka) - versenyLista.indexOf(versenyBogyoka);
targetHashMap.put(teljesitmenyBogyoka, relativTeljesitmeny);
}
}
}
}
public static void gyorsUszoRelativTeljesitmenySzamolas(HashMap<Uszo, Integer> targetHashMap, List<Gyorsuszo> teljesitmenyLista, List<Gyorsuszo> versenyLista) {
for (Gyorsuszo teljesitmenyBogyoka: teljesitmenyLista){
for (Gyorsuszo versenyBogyoka: versenyLista){
if (versenyBogyoka.getNev().equals(teljesitmenyBogyoka.getNev())){
int relativTeljesitmeny = teljesitmenyLista.indexOf(teljesitmenyBogyoka) - versenyLista.indexOf(versenyBogyoka);
targetHashMap.put(teljesitmenyBogyoka, relativTeljesitmeny);
}
}
}
}
public static void maxTeljesitmenyKereso(HashMap<Uszo, Integer> uszoMap){
for (Map.Entry <Uszo, Integer> bogyoka: uszoMap.entrySet()){
if (bogyoka.getValue().equals(Collections.max(uszoMap.values()))){
System.out.println("Legjobb relativ teljesítmény: " + bogyoka);
}
}
}
public static void minTeljesitmenyKereso(HashMap<Uszo, Integer> uszoMap){
for (Map.Entry <Uszo, Integer> bogyoka: uszoMap.entrySet()){
if (bogyoka.getValue().equals(Collections.min(uszoMap.values()))){
System.out.println("Legroszabb relativ teljesítmény: " + bogyoka);
}
}
}
public static void main(String[] args) {
System.out.println("===========input beolvasás úszólistába!===========");
List<Uszo> uszoList = new ArrayList<>();
BufferedReader br;
String[] splittedLine;
try {
br = new BufferedReader(new FileReader(INPUT));
String line;
while ((line = br.readLine()) != null){
splittedLine = line.split(" ");
String uszoNev = splittedLine[1];
int uszoTeljesitmeny = Integer.parseInt(splittedLine[2]);
String uszoNemzetiseg = splittedLine[3];
if (splittedLine[0].equals("Uszomester")) {
uszoList.add(new UszoMester(uszoNev,uszoTeljesitmeny,uszoNemzetiseg));
} else if (splittedLine[0].equals("Gyorsuszo")){
uszoList.add(new Gyorsuszo(uszoNev,uszoTeljesitmeny,uszoNemzetiseg));
} else if (splittedLine[0].equals("Hatuszo")) {
uszoList.add(new Hatuszo(uszoNev,uszoTeljesitmeny,uszoNemzetiseg));
} else {
System.out.println("Wrong constructor parameters!");
}
}
br.close();
System.out.println("UszoLista kész!");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(uszoList + "\n");
System.out.println("======Szétválogatás!=====");
List<Uszo> uszoMesterList = new ArrayList<>();
List<Gyorsuszo> gyorsuszoList = new ArrayList<>();
List<Hatuszo> hatuszoList = new ArrayList<>();
for (Uszo bogyoka: uszoList){
if (bogyoka instanceof UszoMester){
uszoMesterList.add((UszoMester) bogyoka);
} else if (bogyoka instanceof Gyorsuszo){
gyorsuszoList.add((Gyorsuszo) bogyoka);
} else if (bogyoka instanceof Hatuszo){
hatuszoList.add((Hatuszo) bogyoka);
}
}
System.out.println(uszoMesterList);
System.out.println(gyorsuszoList);
System.out.println(hatuszoList + "\n");
System.out.println("=====Rendezés=====");
uszoMesterList.sort(new UszoMesterComparator());
System.out.println("Úszómesterek névsorban: " + uszoMesterList);
gyorsuszoList.sort(new GyorsuszoComparator());
System.out.println("Gyorsúszás nyertese: " + gyorsuszoList.get(1));
hatuszoList.sort(new HatuszoComparator());
System.out.println("Hátúszás nyertese: " + hatuszoList.get(1));
System.out.println();
System.out.println("=====Úszómesterek névsora, versenyek nyerteseinek kiírása az eredmeny.txt fájlba.===");
try {
Writer uszasWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OUTPUT), "utf-8"));
uszoPrint(uszoMesterList, gyorsuszoList.get(1), hatuszoList.get(1), uszasWriter);
uszasWriter.flush();
uszasWriter.close();
System.out.println("Kiírás sikeres!" + "\n");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("=====Listák serializálása=====");
uszoSerial(uszoMesterList, USZOMESTER_SERIALIZATION_FILE_PATH);
gyorsuszoSerial(gyorsuszoList, GYORSUSZO_SERIALIZATION_FILE_PATH);
hatuszoSerial(hatuszoList,HATUSZO_SERIALIZATION_FILE_PATH);
System.out.println("=====Listák deserializálása=====");
List<Uszo> deserializaltUszoMesterek = uszoDeSerialization(USZOMESTER_SERIALIZATION_FILE_PATH);
List<Gyorsuszo> deserializaltGyorsuszok = gyorsUszoDeSerialization(GYORSUSZO_SERIALIZATION_FILE_PATH);
List<Hatuszo> deserializaltHatuszok = hatUszoDeSerialization(HATUSZO_SERIALIZATION_FILE_PATH);
Collections.sort(gyorsuszoList);
Collections.sort(hatuszoList);
System.out.println("\n =====Gyorsúszók listái: teljesítmény szerint rendezve, versenyeredmény szerint rendezve=====");
System.out.println(gyorsuszoList);
System.out.println(deserializaltGyorsuszok);
System.out.println("\n =====Gyorsúszók relativ teljesítményei egy Mapben=====");
HashMap<Uszo, Integer> gyorsuszoRelativMap = new HashMap<>();
gyorsUszoRelativTeljesitmenySzamolas(gyorsuszoRelativMap, gyorsuszoList, deserializaltGyorsuszok);
System.out.println(gyorsuszoRelativMap);
System.out.println("\n =====Hatúszók relativ teljesítményei egy Mapben=====");
HashMap<Uszo, Integer> hatuszoRelativMap = new HashMap<>();
hatUszoRelativTeljesitmeny(hatuszoRelativMap, hatuszoList, deserializaltHatuszok);
System.out.println(hatuszoRelativMap);
System.out.println("\n =====Gyorsúszók relativ teljesítményei legjobb, legroszabb=====");
maxTeljesitmenyKereso(gyorsuszoRelativMap);
minTeljesitmenyKereso(gyorsuszoRelativMap);
System.out.println("\n =====Hátúszók relativ teljesítményei legjobb, legroszabb=====");
maxTeljesitmenyKereso(hatuszoRelativMap);
minTeljesitmenyKereso(hatuszoRelativMap);
}
}
| UTF-8 | Java | 10,990 | java | Uszoverseny.java | Java | [] | null | [] | package com.flowacademy;
import com.flowacademy.uszoda.*;
import com.flowacademy.uszoda.comparators.GyorsuszoComparator;
import com.flowacademy.uszoda.comparators.HatuszoComparator;
import com.flowacademy.uszoda.comparators.UszoMesterComparator;
import java.io.*;
import java.util.*;
public class Uszoverseny {
private static final String INPUT = "./data/input.txt";
private static final String OUTPUT = "./data/eredmeny.txt";
private static final String USZOMESTER_SERIALIZATION_FILE_PATH = "./data/uszomesterek.ser";
private static final String GYORSUSZO_SERIALIZATION_FILE_PATH = "./data/gyorsuszasverseny.ser";
private static final String HATUSZO_SERIALIZATION_FILE_PATH = "./data/hatuszasverseny.ser";
public static void uszoPrint(List<Uszo> uszomesterList, Uszo gyorsNyertes, Uszo hatNyertes, Writer uszoWriter) throws IOException{
List<Uszo> kiirtUszoList = new ArrayList<>(uszomesterList);
kiirtUszoList.add(gyorsNyertes);
kiirtUszoList.add(hatNyertes);
for (Uszo listElement : kiirtUszoList) {
try {
if (listElement instanceof UszoMester) {
uszoWriter.write(listElement.toString() + "\n");
} else if (listElement instanceof Gyorsuszo){
uszoWriter.write("A gyorsúszás nyertese: " + listElement.toString() + "\n");
} else if (listElement instanceof Hatuszo){
uszoWriter.write("A hátúszás nyertese: " + listElement.toString() + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void uszoSerial(List<Uszo> uszoBogyokak, String serialPath) {
serializationCore(uszoBogyokak, serialPath);
}
public static void hatuszoSerial(List<Hatuszo> uszoBogyokak, String serialPath) {
serializationCore(uszoBogyokak, serialPath);
}
public static void gyorsuszoSerial(List<Gyorsuszo> uszoBogyokak, String serialPath) {
serializationCore(uszoBogyokak, serialPath);
}
public static void serializationCore(List list, String serialPath){
try {
FileOutputStream fileOut = new FileOutputStream(serialPath);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(list);
out.close();
fileOut.close();
System.out.println("Magic!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Uszo> uszoDeSerialization(String file){
List<Uszo> uszoList = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
uszoList = (List<Uszo>) in.readObject();
System.out.println("!cigaM");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return uszoList;
}
public static List<Gyorsuszo> gyorsUszoDeSerialization(String file){
List<Gyorsuszo> uszoList = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
uszoList = (List<Gyorsuszo>) in.readObject();
System.out.println("!cigaM");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return uszoList;
}
public static List<Hatuszo> hatUszoDeSerialization(String file){
List<Hatuszo> uszoList = null;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
uszoList = (List<Hatuszo>) in.readObject();
System.out.println("!cigaM");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return uszoList;
}
public static void hatUszoRelativTeljesitmeny(HashMap<Uszo, Integer> targetHashMap, List<Hatuszo> teljesitmenyLista, List<Hatuszo> versenyLista){
for (Hatuszo teljesitmenyBogyoka: teljesitmenyLista){
for (Hatuszo versenyBogyoka: versenyLista){
if (versenyBogyoka.getNev().equals(teljesitmenyBogyoka.getNev())){
int relativTeljesitmeny = teljesitmenyLista.indexOf(teljesitmenyBogyoka) - versenyLista.indexOf(versenyBogyoka);
targetHashMap.put(teljesitmenyBogyoka, relativTeljesitmeny);
}
}
}
}
public static void gyorsUszoRelativTeljesitmenySzamolas(HashMap<Uszo, Integer> targetHashMap, List<Gyorsuszo> teljesitmenyLista, List<Gyorsuszo> versenyLista) {
for (Gyorsuszo teljesitmenyBogyoka: teljesitmenyLista){
for (Gyorsuszo versenyBogyoka: versenyLista){
if (versenyBogyoka.getNev().equals(teljesitmenyBogyoka.getNev())){
int relativTeljesitmeny = teljesitmenyLista.indexOf(teljesitmenyBogyoka) - versenyLista.indexOf(versenyBogyoka);
targetHashMap.put(teljesitmenyBogyoka, relativTeljesitmeny);
}
}
}
}
public static void maxTeljesitmenyKereso(HashMap<Uszo, Integer> uszoMap){
for (Map.Entry <Uszo, Integer> bogyoka: uszoMap.entrySet()){
if (bogyoka.getValue().equals(Collections.max(uszoMap.values()))){
System.out.println("Legjobb relativ teljesítmény: " + bogyoka);
}
}
}
public static void minTeljesitmenyKereso(HashMap<Uszo, Integer> uszoMap){
for (Map.Entry <Uszo, Integer> bogyoka: uszoMap.entrySet()){
if (bogyoka.getValue().equals(Collections.min(uszoMap.values()))){
System.out.println("Legroszabb relativ teljesítmény: " + bogyoka);
}
}
}
public static void main(String[] args) {
System.out.println("===========input beolvasás úszólistába!===========");
List<Uszo> uszoList = new ArrayList<>();
BufferedReader br;
String[] splittedLine;
try {
br = new BufferedReader(new FileReader(INPUT));
String line;
while ((line = br.readLine()) != null){
splittedLine = line.split(" ");
String uszoNev = splittedLine[1];
int uszoTeljesitmeny = Integer.parseInt(splittedLine[2]);
String uszoNemzetiseg = splittedLine[3];
if (splittedLine[0].equals("Uszomester")) {
uszoList.add(new UszoMester(uszoNev,uszoTeljesitmeny,uszoNemzetiseg));
} else if (splittedLine[0].equals("Gyorsuszo")){
uszoList.add(new Gyorsuszo(uszoNev,uszoTeljesitmeny,uszoNemzetiseg));
} else if (splittedLine[0].equals("Hatuszo")) {
uszoList.add(new Hatuszo(uszoNev,uszoTeljesitmeny,uszoNemzetiseg));
} else {
System.out.println("Wrong constructor parameters!");
}
}
br.close();
System.out.println("UszoLista kész!");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(uszoList + "\n");
System.out.println("======Szétválogatás!=====");
List<Uszo> uszoMesterList = new ArrayList<>();
List<Gyorsuszo> gyorsuszoList = new ArrayList<>();
List<Hatuszo> hatuszoList = new ArrayList<>();
for (Uszo bogyoka: uszoList){
if (bogyoka instanceof UszoMester){
uszoMesterList.add((UszoMester) bogyoka);
} else if (bogyoka instanceof Gyorsuszo){
gyorsuszoList.add((Gyorsuszo) bogyoka);
} else if (bogyoka instanceof Hatuszo){
hatuszoList.add((Hatuszo) bogyoka);
}
}
System.out.println(uszoMesterList);
System.out.println(gyorsuszoList);
System.out.println(hatuszoList + "\n");
System.out.println("=====Rendezés=====");
uszoMesterList.sort(new UszoMesterComparator());
System.out.println("Úszómesterek névsorban: " + uszoMesterList);
gyorsuszoList.sort(new GyorsuszoComparator());
System.out.println("Gyorsúszás nyertese: " + gyorsuszoList.get(1));
hatuszoList.sort(new HatuszoComparator());
System.out.println("Hátúszás nyertese: " + hatuszoList.get(1));
System.out.println();
System.out.println("=====Úszómesterek névsora, versenyek nyerteseinek kiírása az eredmeny.txt fájlba.===");
try {
Writer uszasWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(OUTPUT), "utf-8"));
uszoPrint(uszoMesterList, gyorsuszoList.get(1), hatuszoList.get(1), uszasWriter);
uszasWriter.flush();
uszasWriter.close();
System.out.println("Kiírás sikeres!" + "\n");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("=====Listák serializálása=====");
uszoSerial(uszoMesterList, USZOMESTER_SERIALIZATION_FILE_PATH);
gyorsuszoSerial(gyorsuszoList, GYORSUSZO_SERIALIZATION_FILE_PATH);
hatuszoSerial(hatuszoList,HATUSZO_SERIALIZATION_FILE_PATH);
System.out.println("=====Listák deserializálása=====");
List<Uszo> deserializaltUszoMesterek = uszoDeSerialization(USZOMESTER_SERIALIZATION_FILE_PATH);
List<Gyorsuszo> deserializaltGyorsuszok = gyorsUszoDeSerialization(GYORSUSZO_SERIALIZATION_FILE_PATH);
List<Hatuszo> deserializaltHatuszok = hatUszoDeSerialization(HATUSZO_SERIALIZATION_FILE_PATH);
Collections.sort(gyorsuszoList);
Collections.sort(hatuszoList);
System.out.println("\n =====Gyorsúszók listái: teljesítmény szerint rendezve, versenyeredmény szerint rendezve=====");
System.out.println(gyorsuszoList);
System.out.println(deserializaltGyorsuszok);
System.out.println("\n =====Gyorsúszók relativ teljesítményei egy Mapben=====");
HashMap<Uszo, Integer> gyorsuszoRelativMap = new HashMap<>();
gyorsUszoRelativTeljesitmenySzamolas(gyorsuszoRelativMap, gyorsuszoList, deserializaltGyorsuszok);
System.out.println(gyorsuszoRelativMap);
System.out.println("\n =====Hatúszók relativ teljesítményei egy Mapben=====");
HashMap<Uszo, Integer> hatuszoRelativMap = new HashMap<>();
hatUszoRelativTeljesitmeny(hatuszoRelativMap, hatuszoList, deserializaltHatuszok);
System.out.println(hatuszoRelativMap);
System.out.println("\n =====Gyorsúszók relativ teljesítményei legjobb, legroszabb=====");
maxTeljesitmenyKereso(gyorsuszoRelativMap);
minTeljesitmenyKereso(gyorsuszoRelativMap);
System.out.println("\n =====Hátúszók relativ teljesítményei legjobb, legroszabb=====");
maxTeljesitmenyKereso(hatuszoRelativMap);
minTeljesitmenyKereso(hatuszoRelativMap);
}
}
| 10,990 | 0.63549 | 0.634483 | 272 | 39.172794 | 34.898323 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.628676 | false | false | 8 |
6790716b21a49d8356bb23feb90e8aaef7e8a4ca | 28,157,805,643,523 | c25f5dcc050ff7ecf9176f643d5f246e14570400 | /src/com/fb/login/TC004.java | acf8b38aaf670fa80a12c7637c8d205d1fefd6bd | [] | no_license | seleniumbasic/Rajselenium | https://github.com/seleniumbasic/Rajselenium | 42eb40179b69af517b36188efae03d3484c610cc | 0603c0829e1d9a9639fe74a3ff94ab5502afc685 | refs/heads/main | 2023-07-14T01:30:36.158000 | 2021-08-20T17:35:31 | 2021-08-20T17:35:31 | 398,352,951 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fb.login;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
public class TC004
{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Sindu Priya D\\Downloads\\Softwares\\chromedriver.exe");
ChromeDriver driver=new ChromeDriver();
driver.get("https://en-gb.facebook.com/");
String Title=driver.getTitle();
System.out.println(Title);
driver.findElement(By.xpath("//input[@name='email']")).sendKeys("bhagyaraj");
driver.findElement(By.xpath("//input[@id='pass']")).sendKeys("password");
driver.findElement(By.xpath("//input[@name='email']")).clear();
driver.findElement(By.xpath("//input[@id='pass']")).clear();
//driver.close();
}
}
| UTF-8 | Java | 754 | java | TC004.java | Java | [
{
"context": "etProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\Sindu Priya D\\\\Downloads\\\\Softwares\\\\chromedriver.exe\");\n\t\tChro",
"end": 241,
"score": 0.9995186924934387,
"start": 228,
"tag": "NAME",
"value": "Sindu Priya D"
},
{
"context": "ent(By.xpath(\"//input[@n... | null | [] | package com.fb.login;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
public class TC004
{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\<NAME>\\Downloads\\Softwares\\chromedriver.exe");
ChromeDriver driver=new ChromeDriver();
driver.get("https://en-gb.facebook.com/");
String Title=driver.getTitle();
System.out.println(Title);
driver.findElement(By.xpath("//input[@name='email']")).sendKeys("bhagyaraj");
driver.findElement(By.xpath("//input[@id='pass']")).sendKeys("<PASSWORD>");
driver.findElement(By.xpath("//input[@name='email']")).clear();
driver.findElement(By.xpath("//input[@id='pass']")).clear();
//driver.close();
}
}
| 749 | 0.696286 | 0.692308 | 25 | 29.16 | 30.598928 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.68 | false | false | 8 |
f8d10392b96b80abdf145dd89a315f890a6dc431 | 3,238,405,379,135 | 0212a69dc2d912ed4659648cd5514279f37c3e05 | /weekly_contests/weekly_contests_45/Judge_Route_Circle.java | f5623c132eceeb518cd49227f70d833eb0e51044 | [] | no_license | ShaishavJogani/LeetCodeSolutions | https://github.com/ShaishavJogani/LeetCodeSolutions | a6463f024e064c58a84758fb6a96f3bb704e507d | f75ea4103cec8a63fe6ac2d6d40544c29dbd484d | refs/heads/master | 2021-01-16T07:20:21.775000 | 2017-08-28T07:37:30 | 2017-08-28T07:37:30 | 99,993,501 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package weekly_contests_45;
/**
* @author Shaishav Jogani
* <br/>
* Created on Aug 12, 2017
* <br/>
*
* Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
<br/>
<b>Example 1:</b>
<br/>
Input: "UD"<br/>
Output: true<br/>
<br/>
<b>Example 2:</b><br/>
Input: "LL"<br/>
Output: false<br/>
*
*/
public class Judge_Route_Circle {
public class Solution {
public boolean judgeCircle(String moves) {
int countTop = 0;
int countSide = 0;
int length = moves.length();
for ( int i = 0; i< length ; i++) {
if(moves.charAt(i) == 'U')
countTop = countTop +1;
if(moves.charAt(i) == 'D')
countTop = countTop -1;
else if( moves.charAt(i) == 'L')
countSide = countSide +1;
else if(moves.charAt(i) == 'R')
countSide = countSide -1;
}
if(countTop == 0 && countSide==0)
return true;
else return false;
}
}
}
| UTF-8 | Java | 1,373 | java | Judge_Route_Circle.java | Java | [
{
"context": "* \n */\npackage weekly_contests_45;\n\n/**\n * @author Shaishav Jogani \n * <br/>\n * Created on Aug 12, 2017\n * <br/>\n * ",
"end": 71,
"score": 0.9998822212219238,
"start": 56,
"tag": "NAME",
"value": "Shaishav Jogani"
}
] | null | [] | /**
*
*/
package weekly_contests_45;
/**
* @author <NAME>
* <br/>
* Created on Aug 12, 2017
* <br/>
*
* Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
<br/>
<b>Example 1:</b>
<br/>
Input: "UD"<br/>
Output: true<br/>
<br/>
<b>Example 2:</b><br/>
Input: "LL"<br/>
Output: false<br/>
*
*/
public class Judge_Route_Circle {
public class Solution {
public boolean judgeCircle(String moves) {
int countTop = 0;
int countSide = 0;
int length = moves.length();
for ( int i = 0; i< length ; i++) {
if(moves.charAt(i) == 'U')
countTop = countTop +1;
if(moves.charAt(i) == 'D')
countTop = countTop -1;
else if( moves.charAt(i) == 'L')
countSide = countSide +1;
else if(moves.charAt(i) == 'R')
countSide = countSide -1;
}
if(countTop == 0 && countSide==0)
return true;
else return false;
}
}
}
| 1,364 | 0.560816 | 0.545521 | 53 | 24.905661 | 38.977142 | 238 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.886792 | false | false | 8 |
60260b72cee934b49607648c189304efbacbd453 | 23,381,802,022,037 | 88770006a1ef9e85011e1a5436bfd3b0145b30cd | /Java-old/bytebank-herdado/src/TesteFuncionario.java | 506aef488f3467dd191ea80884f629262197fffb | [] | no_license | kbentes/JavaSE8 | https://github.com/kbentes/JavaSE8 | 03f3c2cafba13afafd773606895ea22d2e55083a | f789a2a21a4fe2d5c525d85017c9b83f79549877 | refs/heads/master | 2020-03-14T20:40:05.789000 | 2018-05-02T01:03:23 | 2018-05-02T01:03:23 | 131,779,619 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class TesteFuncionario {
public static void main(String[] args) {
Gerente kaue = new Gerente();
kaue.setNome("Kaue Bentes");
kaue.setCpf("123.456.789-00");
kaue.setSalario(5200.0);
System.out.println(kaue.getNome());
System.out.println(kaue.getSalario());
System.out.println(kaue.getBonificacao());
}
}
| UTF-8 | Java | 338 | java | TesteFuncionario.java | Java | [
{
"context": "\t\n\t\tGerente kaue = new Gerente();\n\t\tkaue.setNome(\"Kaue Bentes\");\n\t\tkaue.setCpf(\"123.456.789-00\");\n\t\tkaue.setSal",
"end": 138,
"score": 0.9998935461044312,
"start": 127,
"tag": "NAME",
"value": "Kaue Bentes"
}
] | null | [] |
public class TesteFuncionario {
public static void main(String[] args) {
Gerente kaue = new Gerente();
kaue.setNome("<NAME>");
kaue.setCpf("123.456.789-00");
kaue.setSalario(5200.0);
System.out.println(kaue.getNome());
System.out.println(kaue.getSalario());
System.out.println(kaue.getBonificacao());
}
}
| 333 | 0.680473 | 0.633136 | 16 | 20.0625 | 17.11165 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8125 | false | false | 8 |
9d7ce572069fb9bf1247091ceb7c7da2e09c3050 | 8,461,085,603,996 | 9432374d2e5cec429afa64b82484198f7333fab9 | /src/trees/tree/CheckBalancedBT.java | be6aca1ce7b99754abc85c11070f737fbe4db291 | [] | no_license | Poorvankbhatia/Data-Structures-In-Java | https://github.com/Poorvankbhatia/Data-Structures-In-Java | cdf5f6cecb6ca0e526c17f4d6263f60b19329f99 | 8c2d4e875fb7ef998d88adb72120add3cfb30825 | refs/heads/master | 2020-04-11T06:50:48.881000 | 2018-05-25T05:46:05 | 2018-05-25T05:46:05 | 31,535,467 | 10 | 15 | null | false | 2016-05-17T16:12:02 | 2015-03-02T10:37:10 | 2016-01-11T09:57:38 | 2016-05-16T19:51:24 | 3,895 | 0 | 3 | 1 | Java | null | null | package trees.tree;
public class CheckBalancedBT {
public static void main(String[] args) {
Node root = Input.treeInput();
Height h = new Height(0);
if (check(root, new Height(0))) {
System.out.println("balanced");
} else {
System.out.println("Nope");
}
}
private static boolean check(Node root, Height h) {
if (root == null) {
h.value = 0;
return true;
}
Height lHeight = new Height(0);
Height rHeight = new Height(0);
boolean l = check(root.left, lHeight);
boolean r = check(root.right, rHeight);
h.value = (lHeight.value > rHeight.value ? lHeight.value : rHeight.value) + 1;
if ((lHeight.value - rHeight.value >= 2) || (rHeight.value - lHeight.value >= 2)) {
return false;
}
return (l && r);
}
}
/*
calculating the height in the same recursion rather than calling a height() function separately. O(n)
*/ | UTF-8 | Java | 1,023 | java | CheckBalancedBT.java | Java | [] | null | [] | package trees.tree;
public class CheckBalancedBT {
public static void main(String[] args) {
Node root = Input.treeInput();
Height h = new Height(0);
if (check(root, new Height(0))) {
System.out.println("balanced");
} else {
System.out.println("Nope");
}
}
private static boolean check(Node root, Height h) {
if (root == null) {
h.value = 0;
return true;
}
Height lHeight = new Height(0);
Height rHeight = new Height(0);
boolean l = check(root.left, lHeight);
boolean r = check(root.right, rHeight);
h.value = (lHeight.value > rHeight.value ? lHeight.value : rHeight.value) + 1;
if ((lHeight.value - rHeight.value >= 2) || (rHeight.value - lHeight.value >= 2)) {
return false;
}
return (l && r);
}
}
/*
calculating the height in the same recursion rather than calling a height() function separately. O(n)
*/ | 1,023 | 0.545455 | 0.537634 | 48 | 20.333334 | 25.519056 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 8 |
03f8e6cb518a880005bab7e223cc72837f1e1c6c | 987,842,520,881 | 25b33455d3c02b6abedf5657040700cfcf6b97b3 | /src/inGame/GameModes.java | 0f80490527192e63f3180d60051e80c102b7995e | [] | no_license | rocioagarcia/Grupo2_EjercicioBatallaNaval | https://github.com/rocioagarcia/Grupo2_EjercicioBatallaNaval | 921b8c7f5f4f0e79e6ef437b520b750f628378ec | 478d2f42d2d8ed28fb8f03878f3e9b1b1f0e4489 | refs/heads/master | 2023-05-24T00:33:53.296000 | 2021-06-04T03:01:43 | 2021-06-04T03:01:43 | 372,348,755 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package inGame;
public class GameModes {
}
| UTF-8 | Java | 45 | java | GameModes.java | Java | [] | null | [] | package inGame;
public class GameModes {
}
| 45 | 0.733333 | 0.733333 | 5 | 8 | 9.81835 | 24 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 8 |
366caf4dcb5b8ab58b9c96b6fed3d57c7c878ae6 | 6,717,328,895,546 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/mockito--mockito/85c3088ab009ac37880a54066376d3d3e365f480/after/NumberOfInvocationsVerifierTest.java | c6eab7aab330de8e4832cb64044742ea65d65b09 | [] | no_license | fracz/refactor-extractor | https://github.com/fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211000 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.verification;
import org.junit.Before;
import org.junit.Test;
import org.mockito.RequiresValidState;
import org.mockito.internal.progress.OngoingVerifyingMode;
@SuppressWarnings("unchecked")
public class NumberOfInvocationsVerifierTest extends RequiresValidState {
private NumberOfInvocationsVerifier verifier;
@Before
public void setup() {
verifier = new NumberOfInvocationsVerifier();
}
@Test
public void shouldNotCheckForWrongNumberOfModificationsWhenVerifyingAtLeastOnce() throws Exception {
OngoingVerifyingMode inOrder = OngoingVerifyingMode.atLeastOnce();
verifier.verify(null, null, inOrder);
}
} | UTF-8 | Java | 811 | java | NumberOfInvocationsVerifierTest.java | Java | [] | null | [] | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.verification;
import org.junit.Before;
import org.junit.Test;
import org.mockito.RequiresValidState;
import org.mockito.internal.progress.OngoingVerifyingMode;
@SuppressWarnings("unchecked")
public class NumberOfInvocationsVerifierTest extends RequiresValidState {
private NumberOfInvocationsVerifier verifier;
@Before
public void setup() {
verifier = new NumberOfInvocationsVerifier();
}
@Test
public void shouldNotCheckForWrongNumberOfModificationsWhenVerifyingAtLeastOnce() throws Exception {
OngoingVerifyingMode inOrder = OngoingVerifyingMode.atLeastOnce();
verifier.verify(null, null, inOrder);
}
} | 811 | 0.76942 | 0.764488 | 28 | 28 | 28.568214 | 104 | false | false | 0 | 0 | 0 | 0 | 67 | 0.082614 | 0.392857 | false | false | 8 |
bce08f32f70fd5d32d566005abe5f4cf81162c78 | 13,383,118,163,102 | de7659fdfb3ab8aa5879a444592f0e36393f4596 | /netshop/src/com/pishoper/api/client/channel/ModChannelOper.java | 428acf861bae60c80ed14cbfbff2f53bcac171ab | [] | no_license | erpao/searcher | https://github.com/erpao/searcher | 1726d9dd9a7120b8c59d99ea20070e997d57c7c3 | 9a134abc397c159f04920044fd1a56acdbd517e4 | refs/heads/master | 2016-08-07T00:23:23.541000 | 2014-04-28T03:06:18 | 2014-04-28T03:06:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pishoper.api.client.channel;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for modChannelOper complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="modChannelOper">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ModChannelOperEvt" type="{http://webservice.api.pishoper.com/}modChannelOperEvt" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "modChannelOper", propOrder = {
"modChannelOperEvt"
})
public class ModChannelOper {
@XmlElement(name = "ModChannelOperEvt")
protected ModChannelOperEvt modChannelOperEvt;
/**
* Gets the value of the modChannelOperEvt property.
*
* @return
* possible object is
* {@link ModChannelOperEvt }
*
*/
public ModChannelOperEvt getModChannelOperEvt() {
return modChannelOperEvt;
}
/**
* Sets the value of the modChannelOperEvt property.
*
* @param value
* allowed object is
* {@link ModChannelOperEvt }
*
*/
public void setModChannelOperEvt(ModChannelOperEvt value) {
this.modChannelOperEvt = value;
}
}
| UTF-8 | Java | 1,608 | java | ModChannelOper.java | Java | [] | null | [] |
package com.pishoper.api.client.channel;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for modChannelOper complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="modChannelOper">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ModChannelOperEvt" type="{http://webservice.api.pishoper.com/}modChannelOperEvt" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "modChannelOper", propOrder = {
"modChannelOperEvt"
})
public class ModChannelOper {
@XmlElement(name = "ModChannelOperEvt")
protected ModChannelOperEvt modChannelOperEvt;
/**
* Gets the value of the modChannelOperEvt property.
*
* @return
* possible object is
* {@link ModChannelOperEvt }
*
*/
public ModChannelOperEvt getModChannelOperEvt() {
return modChannelOperEvt;
}
/**
* Sets the value of the modChannelOperEvt property.
*
* @param value
* allowed object is
* {@link ModChannelOperEvt }
*
*/
public void setModChannelOperEvt(ModChannelOperEvt value) {
this.modChannelOperEvt = value;
}
}
| 1,608 | 0.659204 | 0.655473 | 61 | 25.344263 | 25.095806 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295082 | false | false | 8 |
1f46ee59f51058e400442b56904869a2b7069562 | 33,131,377,747,463 | bba4a35b44539ed25583f2c089ec63a0a6f2a146 | /src/main/java/admin/Menu.java | f1e98dc4bed0372eea8b36014e0d19fd1f4f7cd0 | [] | no_license | Claviatorers/keyboarder | https://github.com/Claviatorers/keyboarder | c317fa9ed735eff517c47fbfe95d0b7eb9631763 | b6e8834503d0588258b19979797f0150710611dc | refs/heads/master | 2021-10-09T11:43:18.925000 | 2018-01-23T10:46:17 | 2018-01-23T10:46:17 | 103,750,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package admin;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
public class Menu {
private Stage stage;
public Menu() throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/adminMenu.fxml"));
Parent root = loader.load();
MenuController menuController = loader.getController();
stage = new Stage();
stage.setTitle("Администратор");
Scene scene = new Scene(root);
stage.setScene(scene);
Image ico = new Image("images/iconLogo.png");
stage.getIcons().add(ico);
stage.setResizable(false);
stage.setOnCloseRequest(event -> {
try {
menuController.backToAuthorization();
} catch (IOException e) {
e.printStackTrace();
}
});
menuController.init(stage);
}
public void show() {
stage.show();
}
} | UTF-8 | Java | 1,054 | java | Menu.java | Java | [] | null | [] | package admin;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
public class Menu {
private Stage stage;
public Menu() throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/adminMenu.fxml"));
Parent root = loader.load();
MenuController menuController = loader.getController();
stage = new Stage();
stage.setTitle("Администратор");
Scene scene = new Scene(root);
stage.setScene(scene);
Image ico = new Image("images/iconLogo.png");
stage.getIcons().add(ico);
stage.setResizable(false);
stage.setOnCloseRequest(event -> {
try {
menuController.backToAuthorization();
} catch (IOException e) {
e.printStackTrace();
}
});
menuController.init(stage);
}
public void show() {
stage.show();
}
} | 1,054 | 0.60999 | 0.60999 | 39 | 25.717949 | 18.938427 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.589744 | false | false | 8 |
b6b9889628ccccc3de2d18109b9d88c30c601976 | 8,607,114,463,927 | c18b00edb37d064b9a9d85c8a5864af4078b29a2 | /src/main/java/com/gupao/homework/spring/MainTest.java | 4e1b8839c56d71631e4539db001441edc2df88de | [] | no_license | DreamLee0201/gupaowork | https://github.com/DreamLee0201/gupaowork | c09a9c26b11367e6694860586ffad6ccf07f768a | ceb882700843e28bbdcd2759152788573703a04f | refs/heads/master | 2020-04-05T08:24:26.828000 | 2018-12-19T15:02:01 | 2018-12-19T15:02:01 | 156,714,073 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gupao.homework.spring;
import com.gupao.homework.spring.prototype.IronStick;
import com.gupao.homework.spring.prototype.MonkeyKing;
import org.junit.Test;
import java.util.Date;
/**
* @author: DreamLee
* @date: Created on 23:01 2018/11/16
* @description:
* @modified:
*/
public class MainTest {
@Test
public void testPrototype() {
MonkeyKing monkeyKing = new MonkeyKing(130,50, new Date(), new IronStick());
MonkeyKing copy = monkeyKing.change();
System.out.println("真假美猴王是同一个对象吗?" + (monkeyKing == copy));
System.out.print("真假美猴王是同一天出生吗?" + (monkeyKing.getBirthday() == copy.getBirthday()));
System.out.println("/t" + monkeyKing.getBirthday().getTime() + "/t" + copy.getBirthday().getTime());
System.out.println("真假美猴王的金箍棒是同一个对象吗?" + (monkeyKing.getWeapon() == copy.getWeapon()));
}
}
| UTF-8 | Java | 956 | java | MainTest.java | Java | [
{
"context": "nit.Test;\n\nimport java.util.Date;\n\n/**\n * @author: DreamLee\n * @date: Created on 23:01 2018/11/16\n * @descrip",
"end": 217,
"score": 0.9989023208618164,
"start": 209,
"tag": "USERNAME",
"value": "DreamLee"
}
] | null | [] | package com.gupao.homework.spring;
import com.gupao.homework.spring.prototype.IronStick;
import com.gupao.homework.spring.prototype.MonkeyKing;
import org.junit.Test;
import java.util.Date;
/**
* @author: DreamLee
* @date: Created on 23:01 2018/11/16
* @description:
* @modified:
*/
public class MainTest {
@Test
public void testPrototype() {
MonkeyKing monkeyKing = new MonkeyKing(130,50, new Date(), new IronStick());
MonkeyKing copy = monkeyKing.change();
System.out.println("真假美猴王是同一个对象吗?" + (monkeyKing == copy));
System.out.print("真假美猴王是同一天出生吗?" + (monkeyKing.getBirthday() == copy.getBirthday()));
System.out.println("/t" + monkeyKing.getBirthday().getTime() + "/t" + copy.getBirthday().getTime());
System.out.println("真假美猴王的金箍棒是同一个对象吗?" + (monkeyKing.getWeapon() == copy.getWeapon()));
}
}
| 956 | 0.672414 | 0.652874 | 29 | 29 | 32.374958 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false | 8 |
8b03ad8160fb186f255104b7a395a47854cec2c4 | 29,051,158,797,255 | 21a0f94ddf5c7e163d1f0b9899862968eef163ed | /app/src/main/java/com/mobapplic/autoparts/view/views/drawer/DrawerView.java | ad7e900a7edfa456b1bbe20b1f79e52060282e58 | [] | no_license | doniyorprince95/AutoParts | https://github.com/doniyorprince95/AutoParts | 88989d57f9a4090731c2916f32432f91ed894c41 | 9e437ec356bf9963e9463306c64087dbef3523ed | refs/heads/master | 2020-03-18T01:18:29.948000 | 2017-03-13T23:03:25 | 2017-03-13T23:03:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mobapplic.autoparts.view.views.drawer;
import android.support.v4.app.Fragment;
public interface DrawerView {
void showHome();
void logOut();
void setFragment(Fragment fragment);
}
| UTF-8 | Java | 217 | java | DrawerView.java | Java | [] | null | [] | package com.mobapplic.autoparts.view.views.drawer;
import android.support.v4.app.Fragment;
public interface DrawerView {
void showHome();
void logOut();
void setFragment(Fragment fragment);
}
| 217 | 0.709677 | 0.705069 | 10 | 19.700001 | 18.182684 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
fabfb68b1201c5f59141e323b86b469ab9deac36 | 17,600,775,989,261 | 2b3d32d48071749bcfcde0ffe3eae2c7e1346dd2 | /unilock/src/main/java/me/unibike/unilock/util/AppUtils.java | b34ce8e8b24efc58c5b71928c462d49a16689360 | [] | no_license | V-zhangyunxiang/UnibikeMaintain | https://github.com/V-zhangyunxiang/UnibikeMaintain | 9fd8d38248db88c599bafb98d3fd14297977718f | b4ec96cabd32df71b542c0bad6ea723aecbcb18e | refs/heads/master | 2021-01-19T14:00:42.632000 | 2017-08-20T17:04:47 | 2017-08-20T17:04:47 | 100,875,364 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.unibike.unilock.util;
import android.os.Build;
/**
* @author LuoLiangchen
* @since 16/9/28
*/
public class AppUtils {
public static boolean debugging;
public static boolean checkApi(int apiLevel) {
return Build.VERSION.SDK_INT >= apiLevel;
}
/**
* debugging or released
*/
public static boolean debugging() {
return debugging;
}
}
| UTF-8 | Java | 402 | java | AppUtils.java | Java | [
{
"context": "ck.util;\n\nimport android.os.Build;\n\n/**\n * @author LuoLiangchen\n * @since 16/9/28\n */\n\npublic class AppUtils {\n\n ",
"end": 87,
"score": 0.9975473284721375,
"start": 75,
"tag": "NAME",
"value": "LuoLiangchen"
}
] | null | [] | package me.unibike.unilock.util;
import android.os.Build;
/**
* @author LuoLiangchen
* @since 16/9/28
*/
public class AppUtils {
public static boolean debugging;
public static boolean checkApi(int apiLevel) {
return Build.VERSION.SDK_INT >= apiLevel;
}
/**
* debugging or released
*/
public static boolean debugging() {
return debugging;
}
}
| 402 | 0.631841 | 0.619403 | 25 | 15.08 | 16.193628 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 8 |
d71a2feb2aaa4c8dbc3707193a1e94c70890c0dd | 20,340,965,127,965 | e063da6abce47b2118e3afcc91ea177b514eab81 | /src/test/java/com/test/test/Test3.java | f1312d0a6a5d75a592844f7cfa5411b703c53ea8 | [] | no_license | donghyeon0725/test | https://github.com/donghyeon0725/test | ee9ac51c93e78f296b5495425b9eb2da45ed1793 | 00f3de0816d6e264002e5249bb6fac7588c825de | refs/heads/master | 2023-06-19T12:03:16.834000 | 2021-07-18T11:12:06 | 2021-07-18T11:12:06 | 387,156,318 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.test.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.Duration;
/**
* assertNotNull 처럼 메소드를 바로 불러와 사용하기 위해서는
* org.junit.jupiter.api.Assertions 의 api 를
* static import 하여야 한다.
*
* import static org.junit.jupiter.api.Assertions.*;
*
*
*
* assertThat 을 테스트 하기 위해서는
* org.assertj.core.api.Assertions.assertThat 을
* static import 하여야 한다.
*
* import static org.hamcrest.MatcherAssert.*;
* */
@Disabled
public class Test3 {
@Disabled
@DisplayName("not null test 1")
@Test
void not_null_test1() {
Person person = null;
assertNotNull(person);
}
@DisplayName("not null test 2")
@Test
void not_null_test2() {
Person person = new Person("이름", 15, PersonStatus.HEALTHY);
assertNotNull(person);
}
/**
* 람다로 메세지를 넘김으로써,
* 문자열 연산의 비용을 줄일 수 있다.
*
* 에러시 다음과 같은 메세지
* org.opentest4j.AssertionFailedError: 사람은 건강해야 합니다. ==>
* Expected :NORMAL
* Actual :HEALTHY
* */
@DisplayName("equals test 1")
@Test
void equals_test1() {
Person person = new Person("이름", 15, PersonStatus.HEALTHY);
assertEquals(PersonStatus.HEALTHY, person.getStatus(), () -> "사람은 건강해야 합니다.");
}
/**
* exception 이 발생하는지 확인이 가능하고, Exception 을 받아서 내용 또한 확인이 가능하다.
* */
@DisplayName("Exception Equals Test 1")
@Test
void exception_equals_test1() {
IllegalStateException exception = assertThrows(IllegalStateException.class, () -> ExceptionBox.throwIllegalStateException());
System.out.println(exception.getMessage());
assertEquals("IllegalStateException", exception.getMessage(), () -> "메세지가 예상한 값과 다릅니다.");
}
/**
* 시간 안에 테스트가 완료 되는지 확인
*
* 시간은 다음과 같이 다양하게 사용이 가능
* Duration.ofSeconds()
* Duration.ofMinutes()
* Duration.ofMillis()
* */
@DisplayName("Timeout Test 1")
@Test
void timeout_test1() {
assertTimeout(Duration.ofSeconds(1), () -> {
Integer age = 7;
Thread.sleep(100);
}, () -> "기준 시간 안에 테스트를 완료하지 못 했 습니다.");
}
/**
* 아래는 시간이 지나면 바로 테스트를 종료함
*
* ****************************
* 주의할 점
*
* 만약 테스트 코드가 ThreadLocal 을 사용하는 경우
* 스프링은 트랜젝션 처리는 threadLocal 이 기본 전략인데 다른 스레드에서 트랜젝션 공유가 안되는 것이 특징적이다.
* 따라서 만들어 놓은 테스트가 원하는대로 동작하지 않을 수 있는데
*
* 가령 예를 들어서 스프링이 사용하고 있는 트랜젝션의 기본 전략은 rollback 이다.
* 따라서 정상적으로 스프링을 통해 DB에 insert 를 한다면, rollback 설정이 된 트랜젝션을 가져와 사용하겠지만
* 테스트 코드에서는 설정된 트랜젝션이 아닌 다른 트랜젝션을 얻어와 사용할 수 있다.
*
* 따라서 중간에 테스트가 중간 종료되어 rollBack 코드를 동작 시키기 전에 끝난다면,
* DB 에 값이 rollback 되지 않고 반영되어 버릴 수 있다.
*
* 따라서 테스트가 트랜젝션과 연관이 있다면 assertTimeoutPreemptively 의 사용은 자제한다.
* */
@DisplayName("Timeout Preemptively Test 1")
@Test
void timeout_preemptively_test1() {
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
Integer age = 7;
Thread.sleep(100);
}, () -> "기준 시간 안에 테스트 완료를 하지 못 했으므로 즉각 종료 합니다.");
}
/**
* 글을 읽는 것처럼 작성을 위한
* assertThat
* */
@DisplayName("assert that 1")
@Test
void assert_that1() {
Person person = new Person("이름", 15, PersonStatus.HEALTHY);
assertThat(person.getStatus()).isEqualByComparingTo(PersonStatus.HEALTHY);
}
/**
* 테스트를 한번에 진행하는 방법
* */
@DisplayName("assert all 1")
@Test
void assert_all_1() {
assertAll(
() -> assertEquals(4, 4),
() -> assertTrue(true),
() -> assertTrue(7 > 6)
);
}
}
| UTF-8 | Java | 4,846 | java | Test3.java | Java | [
{
"context": "ull_test2() {\n Person person = new Person(\"이름\", 15, PersonStatus.HEALTHY);\n assertNotNu",
"end": 915,
"score": 0.6128698587417603,
"start": 914,
"tag": "NAME",
"value": "이"
},
{
"context": "als_test1() {\n Person person = new Person(\"이름\", 15, ... | null | [] | package com.test.test;
import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.Duration;
/**
* assertNotNull 처럼 메소드를 바로 불러와 사용하기 위해서는
* org.junit.jupiter.api.Assertions 의 api 를
* static import 하여야 한다.
*
* import static org.junit.jupiter.api.Assertions.*;
*
*
*
* assertThat 을 테스트 하기 위해서는
* org.assertj.core.api.Assertions.assertThat 을
* static import 하여야 한다.
*
* import static org.hamcrest.MatcherAssert.*;
* */
@Disabled
public class Test3 {
@Disabled
@DisplayName("not null test 1")
@Test
void not_null_test1() {
Person person = null;
assertNotNull(person);
}
@DisplayName("not null test 2")
@Test
void not_null_test2() {
Person person = new Person("이름", 15, PersonStatus.HEALTHY);
assertNotNull(person);
}
/**
* 람다로 메세지를 넘김으로써,
* 문자열 연산의 비용을 줄일 수 있다.
*
* 에러시 다음과 같은 메세지
* org.opentest4j.AssertionFailedError: 사람은 건강해야 합니다. ==>
* Expected :NORMAL
* Actual :HEALTHY
* */
@DisplayName("equals test 1")
@Test
void equals_test1() {
Person person = new Person("이름", 15, PersonStatus.HEALTHY);
assertEquals(PersonStatus.HEALTHY, person.getStatus(), () -> "사람은 건강해야 합니다.");
}
/**
* exception 이 발생하는지 확인이 가능하고, Exception 을 받아서 내용 또한 확인이 가능하다.
* */
@DisplayName("Exception Equals Test 1")
@Test
void exception_equals_test1() {
IllegalStateException exception = assertThrows(IllegalStateException.class, () -> ExceptionBox.throwIllegalStateException());
System.out.println(exception.getMessage());
assertEquals("IllegalStateException", exception.getMessage(), () -> "메세지가 예상한 값과 다릅니다.");
}
/**
* 시간 안에 테스트가 완료 되는지 확인
*
* 시간은 다음과 같이 다양하게 사용이 가능
* Duration.ofSeconds()
* Duration.ofMinutes()
* Duration.ofMillis()
* */
@DisplayName("Timeout Test 1")
@Test
void timeout_test1() {
assertTimeout(Duration.ofSeconds(1), () -> {
Integer age = 7;
Thread.sleep(100);
}, () -> "기준 시간 안에 테스트를 완료하지 못 했 습니다.");
}
/**
* 아래는 시간이 지나면 바로 테스트를 종료함
*
* ****************************
* 주의할 점
*
* 만약 테스트 코드가 ThreadLocal 을 사용하는 경우
* 스프링은 트랜젝션 처리는 threadLocal 이 기본 전략인데 다른 스레드에서 트랜젝션 공유가 안되는 것이 특징적이다.
* 따라서 만들어 놓은 테스트가 원하는대로 동작하지 않을 수 있는데
*
* 가령 예를 들어서 스프링이 사용하고 있는 트랜젝션의 기본 전략은 rollback 이다.
* 따라서 정상적으로 스프링을 통해 DB에 insert 를 한다면, rollback 설정이 된 트랜젝션을 가져와 사용하겠지만
* 테스트 코드에서는 설정된 트랜젝션이 아닌 다른 트랜젝션을 얻어와 사용할 수 있다.
*
* 따라서 중간에 테스트가 중간 종료되어 rollBack 코드를 동작 시키기 전에 끝난다면,
* DB 에 값이 rollback 되지 않고 반영되어 버릴 수 있다.
*
* 따라서 테스트가 트랜젝션과 연관이 있다면 assertTimeoutPreemptively 의 사용은 자제한다.
* */
@DisplayName("Timeout Preemptively Test 1")
@Test
void timeout_preemptively_test1() {
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
Integer age = 7;
Thread.sleep(100);
}, () -> "기준 시간 안에 테스트 완료를 하지 못 했으므로 즉각 종료 합니다.");
}
/**
* 글을 읽는 것처럼 작성을 위한
* assertThat
* */
@DisplayName("assert that 1")
@Test
void assert_that1() {
Person person = new Person("이름", 15, PersonStatus.HEALTHY);
assertThat(person.getStatus()).isEqualByComparingTo(PersonStatus.HEALTHY);
}
/**
* 테스트를 한번에 진행하는 방법
* */
@DisplayName("assert all 1")
@Test
void assert_all_1() {
assertAll(
() -> assertEquals(4, 4),
() -> assertTrue(true),
() -> assertTrue(7 > 6)
);
}
}
| 4,846 | 0.588297 | 0.578282 | 144 | 25.347221 | 23.549686 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.340278 | false | false | 8 |
c15aa4a1c084a3fd3d7c7a1ab91ecdbe70660d0f | 32,177,895,000,222 | a66dd5a7e2e1f464c57f12617ab3d0c3bc86c08f | /src/main/kotlin/com/fg7/reactivewebkotlin/WebSocketConfiguration.java | 28de8e3ab0758cdddd26f05bc8d9e555f83a7bed | [] | no_license | fg78nc/spring-webflux-ws | https://github.com/fg78nc/spring-webflux-ws | a1e008804c5e40ea0217fef1ed4db59c2352d207 | aa12e87acf1bf00652a0d730d955dd86fea12ccf | refs/heads/master | 2020-03-23T18:36:40.399000 | 2018-07-22T19:43:25 | 2018-07-22T19:43:25 | 141,919,765 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fg7.reactivewebkotlin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import reactor.core.publisher.Flux;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
@Configuration
public class WebSocketConfiguration {
@Bean
WebSocketHandlerAdapter webSocketHandlerAdapter() {
return new WebSocketHandlerAdapter();
}
@Bean
WebSocketHandler webSocketHandler() {
return webSocketSession -> {
System.out.println("session");
Flux<WebSocketMessage> messageFlux =
Flux.<Message>generate(sink -> sink.next(new Message("Hello @ " + Instant.now().toString())))
.map(g -> webSocketSession.textMessage(g.getText()))
.delayElements(Duration.ofSeconds(1))
.doFinally(signalType -> System.out.println("Done! Bye!"));
return webSocketSession.send(messageFlux);
};
}
@Bean
HandlerMapping handlerMapping (){
SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
simpleUrlHandlerMapping.setUrlMap(Collections.singletonMap("/ws/test", webSocketHandler()));
simpleUrlHandlerMapping.setOrder(1);
return simpleUrlHandlerMapping;
}
}
| UTF-8 | Java | 1,725 | java | WebSocketConfiguration.java | Java | [] | null | [] | package com.fg7.reactivewebkotlin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import reactor.core.publisher.Flux;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
@Configuration
public class WebSocketConfiguration {
@Bean
WebSocketHandlerAdapter webSocketHandlerAdapter() {
return new WebSocketHandlerAdapter();
}
@Bean
WebSocketHandler webSocketHandler() {
return webSocketSession -> {
System.out.println("session");
Flux<WebSocketMessage> messageFlux =
Flux.<Message>generate(sink -> sink.next(new Message("Hello @ " + Instant.now().toString())))
.map(g -> webSocketSession.textMessage(g.getText()))
.delayElements(Duration.ofSeconds(1))
.doFinally(signalType -> System.out.println("Done! Bye!"));
return webSocketSession.send(messageFlux);
};
}
@Bean
HandlerMapping handlerMapping (){
SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
simpleUrlHandlerMapping.setUrlMap(Collections.singletonMap("/ws/test", webSocketHandler()));
simpleUrlHandlerMapping.setOrder(1);
return simpleUrlHandlerMapping;
}
}
| 1,725 | 0.711304 | 0.709565 | 46 | 36.5 | 30.84516 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 8 |
cba436eb9a7b35e8fd0e976d07d2deba8002ad14 | 25,331,717,116,096 | 98ebbfd5e4d5f882cb25cd395607a6a480a963f4 | /dqlsas/src/main/java/service/IHelloServiceImpl.java | 72de6a3d6a3386971ceede3f1086f4e7b7f52f69 | [] | no_license | lastfily/dq2 | https://github.com/lastfily/dq2 | b72f9399af2a9ee17806401ceeafd42f9e2b9788 | 15aea5a4dacfdf36bdc3da8a1140804b876944e4 | refs/heads/master | 2022-12-22T19:49:32.074000 | 2019-05-23T02:31:49 | 2019-05-23T02:31:49 | 188,149,438 | 0 | 0 | null | false | 2022-12-13T19:28:23 | 2019-05-23T02:46:19 | 2019-05-23T02:46:55 | 2022-12-13T19:28:20 | 582 | 0 | 0 | 8 | JavaScript | false | false | package service;
import org.springframework.stereotype.Service;
@Service("iHelloService")
public class IHelloServiceImpl implements IHelloService{
//打印参数,并返回一串字符串
public String sayHello(String something) {
System.out.println("接收客户端信息:"+something);
return "你好我是服务端!";
}
} | UTF-8 | Java | 359 | java | IHelloServiceImpl.java | Java | [] | null | [] | package service;
import org.springframework.stereotype.Service;
@Service("iHelloService")
public class IHelloServiceImpl implements IHelloService{
//打印参数,并返回一串字符串
public String sayHello(String something) {
System.out.println("接收客户端信息:"+something);
return "你好我是服务端!";
}
} | 359 | 0.724252 | 0.724252 | 13 | 22.23077 | 20.169107 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 8 |
31239a7360e29b5e36b10e73847db995cac85070 | 27,839,978,023,168 | 3c3059d0aa5dc2383d1b928c7712f8c50bbf601d | /DemoC/app/src/main/java/com/example/democ/views/CreateVegetableView.java | a741013fd73db18efbb81dce90821903089271ac | [] | no_license | atbui1/Capstone | https://github.com/atbui1/Capstone | 4b5b3472fbd0e6cdfe0d210e24ffe269e2ebbf17 | d149c2e700571faf1a4e00f5dc5a2b87b60a9ab4 | refs/heads/main | 2023-06-03T14:17:49.095000 | 2021-06-20T20:10:38 | 2021-06-20T20:10:38 | 354,885,029 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.democ.views;
import com.example.democ.model.VegetableData;
public interface CreateVegetableView {
void createVegetableSuccess();
// void createVegetableSuccess(VegetableData vegetableData);
void createVegetableFail();
}
| UTF-8 | Java | 253 | java | CreateVegetableView.java | Java | [] | null | [] | package com.example.democ.views;
import com.example.democ.model.VegetableData;
public interface CreateVegetableView {
void createVegetableSuccess();
// void createVegetableSuccess(VegetableData vegetableData);
void createVegetableFail();
}
| 253 | 0.794466 | 0.794466 | 9 | 27.111111 | 20.98912 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 8 |
ffb4bdace57b8d154d5ed482f54033467bf641f4 | 16,106,127,398,547 | 121dce3ffd54ff9b9aa90a4cea13065995d1673f | /src/main/java/com/lukaklacar/geneticalgorithm/population/Population.java | af2671051e04628e0e04050171e602ba413f8c53 | [] | no_license | lklacar/generic-genetic-algorithm | https://github.com/lklacar/generic-genetic-algorithm | 9cc251f771721f28f287c724225e5d3e0bc0b640 | a561e94a13ca3fddee9177587d830b029caf852a | refs/heads/master | 2020-04-28T02:04:09.008000 | 2019-03-10T21:33:50 | 2019-03-10T21:33:50 | 174,883,839 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lukaklacar.geneticalgorithm.population;
import com.lukaklacar.geneticalgorithm.chromosome.Chromosome;
import java.util.ArrayList;
import java.util.Collection;
public class Population<T extends Chromosome> extends ArrayList<T> {
public Population(int initialCapacity) {
super(initialCapacity);
}
public Population() {
}
public Population(Collection<? extends T> c) {
super(c);
}
}
| UTF-8 | Java | 437 | java | Population.java | Java | [] | null | [] | package com.lukaklacar.geneticalgorithm.population;
import com.lukaklacar.geneticalgorithm.chromosome.Chromosome;
import java.util.ArrayList;
import java.util.Collection;
public class Population<T extends Chromosome> extends ArrayList<T> {
public Population(int initialCapacity) {
super(initialCapacity);
}
public Population() {
}
public Population(Collection<? extends T> c) {
super(c);
}
}
| 437 | 0.720824 | 0.720824 | 19 | 22 | 22.53652 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 8 |
5f6d4a6c54ae307486fe0903af0b738ca13b1ed9 | 17,093,969,878,585 | b2b0f00fd6a06e7aab45f96339be0b97edc077e6 | /libgdxCommon/src/com/emptyPockets/box2d/shape/data/ShapeData.java | 9270e7ebb191b6a1c2dc05265a65fe858a6a2c83 | [] | no_license | cdbhimani/joeydevolopmenttesting | https://github.com/cdbhimani/joeydevolopmenttesting | ecb5d8b6bed2401a972bc4f72226550f6fb2ffbf | 7f5ad39c9bea54db2a6bc26a84905e541fd7c3d5 | refs/heads/master | 2020-03-27T22:40:44.688000 | 2018-02-08T07:28:54 | 2018-02-08T07:28:54 | 40,646,759 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.emptyPockets.box2d.shape.data;
import java.util.ArrayList;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Shape;
public abstract class ShapeData {
public static int count = 0;
String name = "Shape "+count++;
Rectangle aaBoundingBox = new Rectangle();
ArrayList<Shape> shapes;
public abstract void updateShapes();
public abstract void updateBoundingBox();
public abstract boolean contains(float x, float y);
public ArrayList<Shape> getShape(){
updateShapes();
return shapes;
}
public boolean contains(Vector2 v){
return contains(v.x, v.y);
}
public boolean containsAABB(float x, float y){
return aaBoundingBox.contains(x, y);
}
public boolean containsAABB(Vector2 p){
return containsAABB(p.x, p.y);
}
public boolean containsAABB(Rectangle rec){
return aaBoundingBox.contains(rec);
}
public boolean intersectsAABB(Rectangle rec){
return aaBoundingBox.overlaps(rec);
}
public void dispose(){
if(shapes != null){
for(Shape s : shapes){
s.dispose();
}
shapes.clear();
shapes = null;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Rectangle getAABoundingBox() {
return aaBoundingBox;
}
}
| UTF-8 | Java | 1,365 | java | ShapeData.java | Java | [] | null | [] | package com.emptyPockets.box2d.shape.data;
import java.util.ArrayList;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Shape;
public abstract class ShapeData {
public static int count = 0;
String name = "Shape "+count++;
Rectangle aaBoundingBox = new Rectangle();
ArrayList<Shape> shapes;
public abstract void updateShapes();
public abstract void updateBoundingBox();
public abstract boolean contains(float x, float y);
public ArrayList<Shape> getShape(){
updateShapes();
return shapes;
}
public boolean contains(Vector2 v){
return contains(v.x, v.y);
}
public boolean containsAABB(float x, float y){
return aaBoundingBox.contains(x, y);
}
public boolean containsAABB(Vector2 p){
return containsAABB(p.x, p.y);
}
public boolean containsAABB(Rectangle rec){
return aaBoundingBox.contains(rec);
}
public boolean intersectsAABB(Rectangle rec){
return aaBoundingBox.overlaps(rec);
}
public void dispose(){
if(shapes != null){
for(Shape s : shapes){
s.dispose();
}
shapes.clear();
shapes = null;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Rectangle getAABoundingBox() {
return aaBoundingBox;
}
}
| 1,365 | 0.685714 | 0.681319 | 60 | 20.75 | 16.71788 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.7 | false | false | 8 |
bf7baae5280e3fb738be178d95e16639de1725f5 | 23,098,334,150,358 | 30e3c91f23aaa6127ee3e520becc443701e18faa | /sources/com/p683ss/android/ugc/aweme/proaccount/C39681c.java | 1197d8d48fd5e33af25bce93eeef021dd0e0564e | [] | no_license | jakesyl/tishtosh_source | https://github.com/jakesyl/tishtosh_source | 521d4ab2bc28325519cf84422cce9c5709339b1f | c88d8f6fc6147fc08dfda6bd6d8540156278fa5d | refs/heads/master | 2022-09-10T17:19:16.637000 | 2020-05-25T06:06:31 | 2020-05-25T06:06:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.p683ss.android.ugc.aweme.proaccount;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.p030v4.content.C0726c;
import android.support.p043v7.widget.RecyclerView.C1322a;
import android.support.p043v7.widget.RecyclerView.C1352v;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.bytedance.apm.agent.instrumentation.ClickInstrumentation;
import com.bytedance.ies.C10174a;
import com.bytedance.ies.dmt.p664ui.widget.DmtTextView;
import com.bytedance.ies.dmt.p664ui.widget.util.C10751d;
import com.p683ss.android.ttve.utils.C20141b;
import com.ss.android.ugc.trill.R;
import java.util.ArrayList;
import java.util.List;
import p2628d.p2639f.p2641b.C52707g;
import p2628d.p2639f.p2641b.C52711k;
import p2628d.p2639f.p2641b.C52722v.C52725c;
/* renamed from: com.ss.android.ugc.aweme.proaccount.c */
public final class C39681c extends C1322a<C39682a> {
/* renamed from: e */
public static final C39683b f101273e = new C39683b(null);
/* renamed from: a */
public C39684c f101274a;
/* renamed from: b */
public List<Boolean> f101275b = new ArrayList();
/* renamed from: c */
public int f101276c = -1;
/* renamed from: d */
public final List<C39675a> f101277d;
/* renamed from: f */
private final Context f101278f;
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$a */
public static final class C39682a extends C1352v {
/* renamed from: a */
public DmtTextView f101279a;
/* renamed from: b */
public DmtTextView f101280b;
/* renamed from: c */
public DmtTextView f101281c;
/* renamed from: d */
public View f101282d;
public C39682a(View view) {
C52711k.m112240b(view, "v");
super(view);
View findViewById = view.findViewById(R.id.d7h);
C52711k.m112236a((Object) findViewById, "v.findViewById(R.id.tv_category_check)");
this.f101279a = (DmtTextView) findViewById;
View findViewById2 = view.findViewById(R.id.d7j);
C52711k.m112236a((Object) findViewById2, "v.findViewById(R.id.tv_category_title)");
this.f101280b = (DmtTextView) findViewById2;
View findViewById3 = view.findViewById(R.id.d7i);
C52711k.m112236a((Object) findViewById3, "v.findViewById(R.id.tv_category_desc)");
this.f101281c = (DmtTextView) findViewById3;
View findViewById4 = view.findViewById(R.id.a6f);
C52711k.m112236a((Object) findViewById4, "v.findViewById(R.id.divide_line)");
this.f101282d = findViewById4;
}
}
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$b */
public static final class C39683b {
private C39683b() {
}
public /* synthetic */ C39683b(C52707g gVar) {
this();
}
}
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$c */
public interface C39684c {
/* renamed from: a */
void mo80765a(C39675a aVar);
}
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$d */
static final class C39685d implements OnClickListener {
/* renamed from: a */
final /* synthetic */ C39681c f101283a;
/* renamed from: b */
final /* synthetic */ C52725c f101284b;
/* renamed from: c */
final /* synthetic */ int f101285c;
C39685d(C39681c cVar, C52725c cVar2, int i) {
this.f101283a = cVar;
this.f101284b = cVar2;
this.f101285c = i;
}
public final void onClick(View view) {
ClickInstrumentation.onClick(view);
if (this.f101284b.element != this.f101283a.f101276c) {
this.f101283a.f101275b.set(this.f101284b.element, Boolean.valueOf(true));
this.f101283a.notifyItemChanged(this.f101285c);
if (this.f101283a.f101276c != -1) {
this.f101283a.f101275b.set(this.f101283a.f101276c, Boolean.valueOf(false));
this.f101283a.notifyItemChanged(this.f101283a.f101276c + 2);
}
this.f101283a.f101276c = this.f101284b.element;
}
C39684c cVar = this.f101283a.f101274a;
if (cVar == null) {
C52711k.m112237a("onItemClick");
}
cVar.mo80765a((C39675a) this.f101283a.f101277d.get(this.f101284b.element));
}
}
public final int getItemCount() {
return this.f101277d.size() + 2;
}
public C39681c(Context context, List<C39675a> list) {
C52711k.m112240b(context, "context");
C52711k.m112240b(list, "list");
this.f101278f = context;
this.f101277d = list;
}
public final /* synthetic */ C1352v onCreateViewHolder(ViewGroup viewGroup, int i) {
C52711k.m112240b(viewGroup, "p0");
View inflate = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.yn, viewGroup, false);
C52711k.m112236a((Object) inflate, "view");
return new C39682a(inflate);
}
public final /* synthetic */ void onBindViewHolder(C1352v vVar, int i) {
C39682a aVar = (C39682a) vVar;
C52711k.m112240b(aVar, "p0");
this.f101275b.add(Boolean.valueOf(false));
String str = null;
switch (i) {
case 0:
aVar.f101279a.setVisibility(8);
aVar.f101281c.setVisibility(8);
aVar.f101280b.setVisibility(0);
aVar.f101282d.setVisibility(8);
aVar.f101280b.setFontType(C10751d.f28903b);
DmtTextView dmtTextView = aVar.f101280b;
Context context = this.f101278f;
if (context != null) {
Resources resources = context.getResources();
if (resources != null) {
str = resources.getString(R.string.h4_);
}
}
dmtTextView.setText(str);
return;
case 1:
aVar.f101279a.setVisibility(8);
aVar.f101281c.setVisibility(0);
aVar.f101280b.setVisibility(8);
aVar.f101282d.setVisibility(8);
DmtTextView dmtTextView2 = aVar.f101281c;
Context context2 = this.f101278f;
if (context2 != null) {
Resources resources2 = context2.getResources();
if (resources2 != null) {
str = resources2.getString(R.string.h4a);
}
}
dmtTextView2.setText(str);
return;
default:
String str2 = "";
C52725c cVar = new C52725c();
cVar.element = i - 2;
if (cVar.element < this.f101277d.size() && cVar.element >= 0) {
try {
String str3 = ((C39675a) this.f101277d.get(cVar.element)).f101256a;
try {
m88392a(aVar, str3, cVar.element);
} catch (C10174a unused) {
str2 = str3;
}
} catch (C10174a unused2) {
m88392a(aVar, str2, cVar.element);
aVar.itemView.setOnClickListener(new C39685d(this, cVar, i));
return;
}
aVar.itemView.setOnClickListener(new C39685d(this, cVar, i));
return;
}
return;
}
}
/* renamed from: a */
private final void m88392a(C39682a aVar, String str, int i) {
aVar.f101279a.setVisibility(0);
aVar.f101281c.setVisibility(8);
aVar.f101280b.setVisibility(8);
aVar.f101282d.setVisibility(0);
if (((Boolean) this.f101275b.get(i)).booleanValue()) {
Drawable a = C0726c.m2091a(this.f101278f, (int) R.drawable.asi);
if (a == null) {
C52711k.m112234a();
}
a.setBounds(0, 0, (int) C20141b.m49696a(this.f101278f, 24.0f), (int) C20141b.m49696a(this.f101278f, 24.0f));
aVar.f101279a.setCompoundDrawablesRelative(null, null, a, null);
aVar.f101279a.setFontType(C10751d.f28903b);
} else {
Drawable a2 = C0726c.m2091a(this.f101278f, (int) R.drawable.d5_);
if (a2 == null) {
C52711k.m112234a();
}
a2.setBounds(0, 0, (int) C20141b.m49696a(this.f101278f, 24.0f), (int) C20141b.m49696a(this.f101278f, 24.0f));
aVar.f101279a.setCompoundDrawablesRelative(null, null, a2, null);
aVar.f101279a.setFontType(C10751d.f28902a);
}
aVar.f101279a.setText(str);
}
}
| UTF-8 | Java | 9,020 | java | C39681c.java | Java | [] | null | [] | package com.p683ss.android.ugc.aweme.proaccount;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.p030v4.content.C0726c;
import android.support.p043v7.widget.RecyclerView.C1322a;
import android.support.p043v7.widget.RecyclerView.C1352v;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.bytedance.apm.agent.instrumentation.ClickInstrumentation;
import com.bytedance.ies.C10174a;
import com.bytedance.ies.dmt.p664ui.widget.DmtTextView;
import com.bytedance.ies.dmt.p664ui.widget.util.C10751d;
import com.p683ss.android.ttve.utils.C20141b;
import com.ss.android.ugc.trill.R;
import java.util.ArrayList;
import java.util.List;
import p2628d.p2639f.p2641b.C52707g;
import p2628d.p2639f.p2641b.C52711k;
import p2628d.p2639f.p2641b.C52722v.C52725c;
/* renamed from: com.ss.android.ugc.aweme.proaccount.c */
public final class C39681c extends C1322a<C39682a> {
/* renamed from: e */
public static final C39683b f101273e = new C39683b(null);
/* renamed from: a */
public C39684c f101274a;
/* renamed from: b */
public List<Boolean> f101275b = new ArrayList();
/* renamed from: c */
public int f101276c = -1;
/* renamed from: d */
public final List<C39675a> f101277d;
/* renamed from: f */
private final Context f101278f;
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$a */
public static final class C39682a extends C1352v {
/* renamed from: a */
public DmtTextView f101279a;
/* renamed from: b */
public DmtTextView f101280b;
/* renamed from: c */
public DmtTextView f101281c;
/* renamed from: d */
public View f101282d;
public C39682a(View view) {
C52711k.m112240b(view, "v");
super(view);
View findViewById = view.findViewById(R.id.d7h);
C52711k.m112236a((Object) findViewById, "v.findViewById(R.id.tv_category_check)");
this.f101279a = (DmtTextView) findViewById;
View findViewById2 = view.findViewById(R.id.d7j);
C52711k.m112236a((Object) findViewById2, "v.findViewById(R.id.tv_category_title)");
this.f101280b = (DmtTextView) findViewById2;
View findViewById3 = view.findViewById(R.id.d7i);
C52711k.m112236a((Object) findViewById3, "v.findViewById(R.id.tv_category_desc)");
this.f101281c = (DmtTextView) findViewById3;
View findViewById4 = view.findViewById(R.id.a6f);
C52711k.m112236a((Object) findViewById4, "v.findViewById(R.id.divide_line)");
this.f101282d = findViewById4;
}
}
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$b */
public static final class C39683b {
private C39683b() {
}
public /* synthetic */ C39683b(C52707g gVar) {
this();
}
}
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$c */
public interface C39684c {
/* renamed from: a */
void mo80765a(C39675a aVar);
}
/* renamed from: com.ss.android.ugc.aweme.proaccount.c$d */
static final class C39685d implements OnClickListener {
/* renamed from: a */
final /* synthetic */ C39681c f101283a;
/* renamed from: b */
final /* synthetic */ C52725c f101284b;
/* renamed from: c */
final /* synthetic */ int f101285c;
C39685d(C39681c cVar, C52725c cVar2, int i) {
this.f101283a = cVar;
this.f101284b = cVar2;
this.f101285c = i;
}
public final void onClick(View view) {
ClickInstrumentation.onClick(view);
if (this.f101284b.element != this.f101283a.f101276c) {
this.f101283a.f101275b.set(this.f101284b.element, Boolean.valueOf(true));
this.f101283a.notifyItemChanged(this.f101285c);
if (this.f101283a.f101276c != -1) {
this.f101283a.f101275b.set(this.f101283a.f101276c, Boolean.valueOf(false));
this.f101283a.notifyItemChanged(this.f101283a.f101276c + 2);
}
this.f101283a.f101276c = this.f101284b.element;
}
C39684c cVar = this.f101283a.f101274a;
if (cVar == null) {
C52711k.m112237a("onItemClick");
}
cVar.mo80765a((C39675a) this.f101283a.f101277d.get(this.f101284b.element));
}
}
public final int getItemCount() {
return this.f101277d.size() + 2;
}
public C39681c(Context context, List<C39675a> list) {
C52711k.m112240b(context, "context");
C52711k.m112240b(list, "list");
this.f101278f = context;
this.f101277d = list;
}
public final /* synthetic */ C1352v onCreateViewHolder(ViewGroup viewGroup, int i) {
C52711k.m112240b(viewGroup, "p0");
View inflate = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.yn, viewGroup, false);
C52711k.m112236a((Object) inflate, "view");
return new C39682a(inflate);
}
public final /* synthetic */ void onBindViewHolder(C1352v vVar, int i) {
C39682a aVar = (C39682a) vVar;
C52711k.m112240b(aVar, "p0");
this.f101275b.add(Boolean.valueOf(false));
String str = null;
switch (i) {
case 0:
aVar.f101279a.setVisibility(8);
aVar.f101281c.setVisibility(8);
aVar.f101280b.setVisibility(0);
aVar.f101282d.setVisibility(8);
aVar.f101280b.setFontType(C10751d.f28903b);
DmtTextView dmtTextView = aVar.f101280b;
Context context = this.f101278f;
if (context != null) {
Resources resources = context.getResources();
if (resources != null) {
str = resources.getString(R.string.h4_);
}
}
dmtTextView.setText(str);
return;
case 1:
aVar.f101279a.setVisibility(8);
aVar.f101281c.setVisibility(0);
aVar.f101280b.setVisibility(8);
aVar.f101282d.setVisibility(8);
DmtTextView dmtTextView2 = aVar.f101281c;
Context context2 = this.f101278f;
if (context2 != null) {
Resources resources2 = context2.getResources();
if (resources2 != null) {
str = resources2.getString(R.string.h4a);
}
}
dmtTextView2.setText(str);
return;
default:
String str2 = "";
C52725c cVar = new C52725c();
cVar.element = i - 2;
if (cVar.element < this.f101277d.size() && cVar.element >= 0) {
try {
String str3 = ((C39675a) this.f101277d.get(cVar.element)).f101256a;
try {
m88392a(aVar, str3, cVar.element);
} catch (C10174a unused) {
str2 = str3;
}
} catch (C10174a unused2) {
m88392a(aVar, str2, cVar.element);
aVar.itemView.setOnClickListener(new C39685d(this, cVar, i));
return;
}
aVar.itemView.setOnClickListener(new C39685d(this, cVar, i));
return;
}
return;
}
}
/* renamed from: a */
private final void m88392a(C39682a aVar, String str, int i) {
aVar.f101279a.setVisibility(0);
aVar.f101281c.setVisibility(8);
aVar.f101280b.setVisibility(8);
aVar.f101282d.setVisibility(0);
if (((Boolean) this.f101275b.get(i)).booleanValue()) {
Drawable a = C0726c.m2091a(this.f101278f, (int) R.drawable.asi);
if (a == null) {
C52711k.m112234a();
}
a.setBounds(0, 0, (int) C20141b.m49696a(this.f101278f, 24.0f), (int) C20141b.m49696a(this.f101278f, 24.0f));
aVar.f101279a.setCompoundDrawablesRelative(null, null, a, null);
aVar.f101279a.setFontType(C10751d.f28903b);
} else {
Drawable a2 = C0726c.m2091a(this.f101278f, (int) R.drawable.d5_);
if (a2 == null) {
C52711k.m112234a();
}
a2.setBounds(0, 0, (int) C20141b.m49696a(this.f101278f, 24.0f), (int) C20141b.m49696a(this.f101278f, 24.0f));
aVar.f101279a.setCompoundDrawablesRelative(null, null, a2, null);
aVar.f101279a.setFontType(C10751d.f28902a);
}
aVar.f101279a.setText(str);
}
}
| 9,020 | 0.576275 | 0.452882 | 236 | 37.220341 | 25.283524 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.724576 | false | false | 8 |
1cb2f0aeb1c23fae4bb1ab2e4a1ba8e645aec724 | 23,098,334,147,284 | 51fa66effcdea0efbe8aaa8fb8601dea5d928a87 | /src/main/java/vcs/DiffGenerator.java | dc824867bfe1578adbe7eceaca5b6fc0f67b5a1a | [] | no_license | deepanshu2506/version-control | https://github.com/deepanshu2506/version-control | b64adc3fb3fdfa548f1b4eaffecdf12a38a51784 | adc7281f2d102fafbe31f0665b6af90ab375910f | refs/heads/master | 2023-04-11T01:33:54.189000 | 2021-04-15T07:55:04 | 2021-04-15T07:55:04 | 264,212,997 | 8 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vcs;
import com.github.difflib.DiffUtils;
import com.github.difflib.patch.AbstractDelta;
import com.github.difflib.patch.Patch;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
*
* @author Deepanshu Vangani
*/
import index.IndexElement;
import index.RepositoryIndex;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class DiffGenerator {
public static List<AbstractDelta<String>> getIndexDiff(RepositoryIndex currentIndex, RepositoryIndex newIndex) {
List<String> original = currentIndex.getIndexEntries().stream().map(IndexElement::toString).collect(Collectors.toList());
List<String> revised = newIndex.getIndexEntries().stream().map(IndexElement::toString).collect(Collectors.toList());
System.out.println(original);
System.out.println(revised);
Patch<String> patch = DiffUtils.diff(original, revised);
System.out.println(patch);
return patch.getDeltas();
}
}
| UTF-8 | Java | 1,211 | java | DiffGenerator.java | Java | [
{
"context": "e.Paths;\nimport java.util.List;\n\n/**\n *\n * @author Deepanshu Vangani\n */\nimport index.IndexElement;\nimport index.Repos",
"end": 465,
"score": 0.9998759627342224,
"start": 448,
"tag": "NAME",
"value": "Deepanshu Vangani"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vcs;
import com.github.difflib.DiffUtils;
import com.github.difflib.patch.AbstractDelta;
import com.github.difflib.patch.Patch;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
*
* @author <NAME>
*/
import index.IndexElement;
import index.RepositoryIndex;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class DiffGenerator {
public static List<AbstractDelta<String>> getIndexDiff(RepositoryIndex currentIndex, RepositoryIndex newIndex) {
List<String> original = currentIndex.getIndexEntries().stream().map(IndexElement::toString).collect(Collectors.toList());
List<String> revised = newIndex.getIndexEntries().stream().map(IndexElement::toString).collect(Collectors.toList());
System.out.println(original);
System.out.println(revised);
Patch<String> patch = DiffUtils.diff(original, revised);
System.out.println(patch);
return patch.getDeltas();
}
}
| 1,200 | 0.744013 | 0.744013 | 36 | 32.638889 | 33.29594 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 8 |
2409d9d218b21e6fcd57f43961ca83ec3d7f620d | 32,770,600,482,646 | e9448695b66a60ace7a0a462c0c96fa509f349bc | /src/the/game/java/NetClient.java | f23d5030aa5e14f7f0fe98458dd23ff342f89544 | [] | no_license | propra13-orga/gruppe52 | https://github.com/propra13-orga/gruppe52 | 5fa0b7ff9e1ee6a96b782476b98aa3e7ebca9a17 | 41271d9964a341cf94c2af004c90f0e839f739e9 | refs/heads/master | 2016-08-07T21:31:03.731000 | 2013-07-16T11:27:51 | 2013-07-16T11:27:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package the.game.java;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.WritableByteChannel;
import java.util.Queue;
public class NetClient extends Client {
public NetClient(String host, int port) {
super(host, port);
}
protected void doWhileRunning() {
}
/**
* Input an handler weiterleiten
*/
protected void handleIncomingMessages() {
buffer.flip(); // flip buffer for reading
CharBuffer cb = charset.decode(buffer); // read from buffer and decode
String input = cb.toString();
input = input.trim();
//System.out.println("NetClient: input: " + input);
// Weiterleiten der Nachricht an NetHandler
handler.handleInput(input);
}
/**
* Output verarbeiten
*/
protected void processOutcomingMessages() {
Queue<NetMessage> q = handler.getOutputSchedule();
WritableByteChannel wbc = (WritableByteChannel) channel;
buffer.clear(); // clear buffer before writing
// Alle auszugebende Elemente senden
while(q.size()>0) {
buffer = ByteBuffer.wrap(q.poll().getMsg().getBytes());
try {
wbc.write(buffer);
} catch (IOException e) {
System.err.println("Schreibvorgang fehlgeschlagen!");
e.printStackTrace();
}
}
}
/**
* Client starten und mit Server verbinden
* @param args
*/
public static void main(String[] args) {
NetClient client = new NetClient(MultiplayerWindow.getIPAdr(),8000);
client.start();
}
}
| UTF-8 | Java | 1,466 | java | NetClient.java | Java | [] | null | [] | package the.game.java;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.WritableByteChannel;
import java.util.Queue;
public class NetClient extends Client {
public NetClient(String host, int port) {
super(host, port);
}
protected void doWhileRunning() {
}
/**
* Input an handler weiterleiten
*/
protected void handleIncomingMessages() {
buffer.flip(); // flip buffer for reading
CharBuffer cb = charset.decode(buffer); // read from buffer and decode
String input = cb.toString();
input = input.trim();
//System.out.println("NetClient: input: " + input);
// Weiterleiten der Nachricht an NetHandler
handler.handleInput(input);
}
/**
* Output verarbeiten
*/
protected void processOutcomingMessages() {
Queue<NetMessage> q = handler.getOutputSchedule();
WritableByteChannel wbc = (WritableByteChannel) channel;
buffer.clear(); // clear buffer before writing
// Alle auszugebende Elemente senden
while(q.size()>0) {
buffer = ByteBuffer.wrap(q.poll().getMsg().getBytes());
try {
wbc.write(buffer);
} catch (IOException e) {
System.err.println("Schreibvorgang fehlgeschlagen!");
e.printStackTrace();
}
}
}
/**
* Client starten und mit Server verbinden
* @param args
*/
public static void main(String[] args) {
NetClient client = new NetClient(MultiplayerWindow.getIPAdr(),8000);
client.start();
}
}
| 1,466 | 0.693042 | 0.689632 | 65 | 21.553846 | 20.468386 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 8 |
3456becc388ff7fa972c5fd5c1172252714f0952 | 33,337,536,166,885 | 034fa6d17fd8dce7243ea066c21527562466bf55 | /src/main/java/com/rabit/qa/pages/MyAccountPage.java | 5b75cda4d3c8b224af007da06ab9c50431694834 | [] | no_license | preethiks465/PageObjectModel | https://github.com/preethiks465/PageObjectModel | 150838e871cf2767e32cf3650c9d0ba70ac6f6be | a18703cbd958627e6a6ca5a151cad69a6f86bd6e | refs/heads/master | 2022-08-01T08:16:33.538000 | 2019-12-13T08:14:02 | 2019-12-13T08:14:02 | 227,782,649 | 0 | 0 | null | false | 2022-06-29T17:50:46 | 2019-12-13T07:33:57 | 2019-12-13T08:14:43 | 2022-06-29T17:50:43 | 5,040 | 0 | 0 | 2 | HTML | false | false | package com.rabit.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.rabit.qa.base.TestBase;
public class MyAccountPage extends TestBase {
@FindBy(xpath = "//h1[contains(text(),'Account Contact Details')]")
WebElement adminMyAccountText;
@FindBy(xpath = "//div[@id='addMailExtn']")
WebElement adminAddExtentionButton;
@FindBy(xpath = "(//input[@name='extnName'])[last()]")
WebElement adminMailExtentionName;
@FindBy(xpath = "(//input[@name='extnDesc'])[last()]")
WebElement adminMailExtentionDescription;
@FindBy(xpath = "//div[@id='saveMailExtensions']")
WebElement adminSaveExtentionButton;
public MyAccountPage() {
PageFactory.initElements(driver, this);
}
public boolean verifyMyAccountDetails() {
return adminMyAccountText.isDisplayed();
}
public void AddMailExtensions(String ExtnName, String ExtnDesc) {
adminAddExtentionButton.click();
adminMailExtentionName.sendKeys(ExtnName);
adminMailExtentionDescription.sendKeys(ExtnDesc);
adminSaveExtentionButton.click();
}
}
| UTF-8 | Java | 1,116 | java | MyAccountPage.java | Java | [] | null | [] | package com.rabit.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.rabit.qa.base.TestBase;
public class MyAccountPage extends TestBase {
@FindBy(xpath = "//h1[contains(text(),'Account Contact Details')]")
WebElement adminMyAccountText;
@FindBy(xpath = "//div[@id='addMailExtn']")
WebElement adminAddExtentionButton;
@FindBy(xpath = "(//input[@name='extnName'])[last()]")
WebElement adminMailExtentionName;
@FindBy(xpath = "(//input[@name='extnDesc'])[last()]")
WebElement adminMailExtentionDescription;
@FindBy(xpath = "//div[@id='saveMailExtensions']")
WebElement adminSaveExtentionButton;
public MyAccountPage() {
PageFactory.initElements(driver, this);
}
public boolean verifyMyAccountDetails() {
return adminMyAccountText.isDisplayed();
}
public void AddMailExtensions(String ExtnName, String ExtnDesc) {
adminAddExtentionButton.click();
adminMailExtentionName.sendKeys(ExtnName);
adminMailExtentionDescription.sendKeys(ExtnDesc);
adminSaveExtentionButton.click();
}
}
| 1,116 | 0.764337 | 0.763441 | 42 | 25.571428 | 22.259447 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.119048 | false | false | 8 |
625cea789d3daf415c9a827b11600cdcab8ec5ca | 16,587,163,740,368 | cf76d48b376a0e9b867602daa66a2ebd86137655 | /FlowColor/src/InputOutFiles/GWriter.java | 085c117afbe10848a577364177c89106d8b618ae | [] | no_license | wroujoulah/FlowColorGame | https://github.com/wroujoulah/FlowColorGame | 3e1684230f889383f4882604edc2fdfbba435a80 | 1e959dd22377631a45558735d8a3d7c16c79e228 | refs/heads/master | 2021-05-28T08:03:17.630000 | 2014-01-07T08:48:13 | 2014-01-07T08:48:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InputOutFiles;
import Componants.Level;
import Componants.Maze;
import static java.awt.image.ImageObserver.ABORT;
import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
*
* @author Wissam
*/
public class GWriter {
public static void levelsWriter(Level level, String fileName) {
ObjectOutputStream writeObject;
try {
ArrayList<Level> levels = new ArrayList<>();
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
} else {
levels = GReader.levelsReader(fileName);
}
if (levels == null) {
levels = new ArrayList<>();
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
levels.add(level);
writeObject.writeObject(levels);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public static void levelsRemover(int levelnumber, String fileName) {
ObjectOutputStream writeObject;
try {
Level level = null;
ArrayList<Level> levels = new ArrayList<>();
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
} else {
level = GReader.levelReader(levelnumber, fileName);
}
if (level == null) {
JOptionPane.showMessageDialog(null, "sry no such level");
System.exit(ABORT);
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
levels.remove(level);
writeObject.writeObject(levels);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public static void gameWriter(Maze maze, String fileName) {
ObjectOutputStream writeObject;
try {
ArrayList<Maze> mazes = new ArrayList<>();
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
} else {
mazes = GReader.mazesReader(fileName);
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
mazes.add(maze);
writeObject.writeObject(mazes);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public static void levelsNumberWriter(int number, String fileName) {
ObjectOutputStream writeObject;
try {
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
writeObject.writeObject(number);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
| UTF-8 | Java | 3,417 | java | GWriter.java | Java | [
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author Wissam\n */\npublic class GWriter {\n\n public static voi",
"end": 411,
"score": 0.9514188766479492,
"start": 405,
"tag": "NAME",
"value": "Wissam"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InputOutFiles;
import Componants.Level;
import Componants.Maze;
import static java.awt.image.ImageObserver.ABORT;
import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
*
* @author Wissam
*/
public class GWriter {
public static void levelsWriter(Level level, String fileName) {
ObjectOutputStream writeObject;
try {
ArrayList<Level> levels = new ArrayList<>();
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
} else {
levels = GReader.levelsReader(fileName);
}
if (levels == null) {
levels = new ArrayList<>();
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
levels.add(level);
writeObject.writeObject(levels);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public static void levelsRemover(int levelnumber, String fileName) {
ObjectOutputStream writeObject;
try {
Level level = null;
ArrayList<Level> levels = new ArrayList<>();
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
} else {
level = GReader.levelReader(levelnumber, fileName);
}
if (level == null) {
JOptionPane.showMessageDialog(null, "sry no such level");
System.exit(ABORT);
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
levels.remove(level);
writeObject.writeObject(levels);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public static void gameWriter(Maze maze, String fileName) {
ObjectOutputStream writeObject;
try {
ArrayList<Maze> mazes = new ArrayList<>();
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
} else {
mazes = GReader.mazesReader(fileName);
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
mazes.add(maze);
writeObject.writeObject(mazes);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
public static void levelsNumberWriter(int number, String fileName) {
ObjectOutputStream writeObject;
try {
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
writeObject = new ObjectOutputStream(new FileOutputStream(file));
writeObject.writeObject(number);
writeObject.flush();
writeObject.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
| 3,417 | 0.554873 | 0.554873 | 120 | 27.475 | 22.368118 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508333 | false | false | 8 |
d3e4d429c819aa3079dc3826f5f1089bbda938c2 | 27,582,279,992,748 | 4cd577110e030199a7e8b3e28782d0778ee2eeca | /src/test/java/com/mowitnow/MowerTest.java | 147d781493f7e04b13be1b3b4bdaac3ac37b7fcb | [] | no_license | k1ngp0ng/MowerManager | https://github.com/k1ngp0ng/MowerManager | 531bce1edd014cd0ab1656e7cce793784025b84c | 4a330f2b4d46c780fa0b402ed41b713a5fde273a | refs/heads/master | 2021-05-11T16:04:21.058000 | 2020-02-19T13:08:50 | 2020-02-21T17:24:13 | 117,750,935 | 0 | 0 | null | false | 2020-10-12T21:25:55 | 2018-01-16T22:33:51 | 2020-02-21T17:24:38 | 2020-10-12T21:25:54 | 10 | 0 | 0 | 1 | Java | false | false | package com.mowitnow;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by scapillier on 13/07/16.
*/
public class MowerTest {
private Field field;
@Before
public final void setUp() {
field = new Field(5,5);
}
@Test
public final void testMoveOk() {
Position initialPositionMower1 = new Position(1,2, Direction.NORTH);
Instructions instructionMower1 = new Instructions("GGA");
Mower mower1 = new Mower(field, initialPositionMower1, instructionMower1);
Position finalPositionMower1 = mower1.move();
Position expectedPositionMower1 = new Position(1,1, Direction.SOUTH);
assertEquals(expectedPositionMower1, finalPositionMower1);
}
@Test
public final void testMoveKo() {
// Teste qu'on ne dépasse pas les limties du terrain
Position bottomLeftCornerInSouth = new Position(0,0, Direction.SOUTH);
Instructions moveAboveFieldLimits = new Instructions("AADAAA");
Mower mower1 = new Mower(field, bottomLeftCornerInSouth, moveAboveFieldLimits);
Position finalPositionMower = mower1.move();
Position expectedPositionMower = new Position(0,0, Direction.WEST);
assertEquals(expectedPositionMower, finalPositionMower);
}
}
| UTF-8 | Java | 1,328 | java | MowerTest.java | Java | [
{
"context": " org.junit.Assert.assertEquals;\n\n/**\n * Created by scapillier on 13/07/16.\n */\npublic class MowerTest {\n\n pr",
"end": 146,
"score": 0.999601423740387,
"start": 136,
"tag": "USERNAME",
"value": "scapillier"
}
] | null | [] | package com.mowitnow;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by scapillier on 13/07/16.
*/
public class MowerTest {
private Field field;
@Before
public final void setUp() {
field = new Field(5,5);
}
@Test
public final void testMoveOk() {
Position initialPositionMower1 = new Position(1,2, Direction.NORTH);
Instructions instructionMower1 = new Instructions("GGA");
Mower mower1 = new Mower(field, initialPositionMower1, instructionMower1);
Position finalPositionMower1 = mower1.move();
Position expectedPositionMower1 = new Position(1,1, Direction.SOUTH);
assertEquals(expectedPositionMower1, finalPositionMower1);
}
@Test
public final void testMoveKo() {
// Teste qu'on ne dépasse pas les limties du terrain
Position bottomLeftCornerInSouth = new Position(0,0, Direction.SOUTH);
Instructions moveAboveFieldLimits = new Instructions("AADAAA");
Mower mower1 = new Mower(field, bottomLeftCornerInSouth, moveAboveFieldLimits);
Position finalPositionMower = mower1.move();
Position expectedPositionMower = new Position(0,0, Direction.WEST);
assertEquals(expectedPositionMower, finalPositionMower);
}
}
| 1,328 | 0.700075 | 0.678975 | 40 | 32.174999 | 29.145229 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.825 | false | false | 8 |
0852b524172764ee86cc4d0c4fdf753fbd04956d | 11,708,080,877,025 | 4cfc5a3cb90f34980a92ccd921d39c5718ff40b5 | /mobile/SensorCollectorProject/SensorCollectorLibrary/src/main/java/eu/liveandgov/wp1/sensor_collector/components/BluetoothSource.java | f49c45d7e5ff16ff9eabed45f731e71248f4739a | [
"MIT"
] | permissive | Institute-Web-Science-and-Technologies/LiveGovWP1 | https://github.com/Institute-Web-Science-and-Technologies/LiveGovWP1 | e5815db4f4c43875c1ca52898712a10d0afa53e1 | 8640cd4409a8eafff5b549a6f35fd0e51518dd4f | refs/heads/master | 2020-06-01T02:09:49.261000 | 2018-03-06T08:43:07 | 2018-03-06T08:43:07 | 12,402,403 | 0 | 0 | null | false | 2014-12-16T11:43:31 | 2013-08-27T09:42:12 | 2014-09-09T12:15:50 | 2014-12-16T11:43:31 | 28,597 | 2 | 6 | 11 | JavaScript | null | null | package eu.liveandgov.wp1.sensor_collector.components;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import eu.liveandgov.wp1.data.impl.Bluetooth;
import eu.liveandgov.wp1.sensor_collector.api.MoraConfig;
import eu.liveandgov.wp1.sensor_collector.config.Configurator;
import eu.liveandgov.wp1.sensor_collector.logging.LogPrincipal;
import eu.liveandgov.wp1.sensor_collector.util.MoraConstants;
import eu.liveandgov.wp1.sensor_collector.util.Threaded;
/**
* <p>Sample source for bluetooth state</p>
* Created by lukashaertel on 05.12.14.
*/
@Singleton
public class BluetoothSource extends RegularSampleSource {
private static final Logger log = LogPrincipal.get();
@Inject
Context context;
/**
* Central credentials store
*/
@Inject
Credentials credentials;
/**
* Central item buffer
*/
@Inject
ItemBuffer itemBuffer;
/**
* Message handler
*/
@Inject
@Threaded
Handler handler;
/**
* The adapter this bluetooth source is attached to
*/
private final BluetoothAdapter bluetoothAdapter;
/**
* The items in the current recording
*/
private final List<Bluetooth.Item> items;
/**
* The last time a scan has been requested
*/
private long lastScanRequest;
@Inject
public BluetoothSource(Configurator configurator) {
super(configurator);
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
this.items = new ArrayList<Bluetooth.Item>();
lastScanRequest = Long.MIN_VALUE;
}
private void startNextScan() {
if (bluetoothAdapter != null && bluetoothAdapter.startDiscovery()) {
lastScanRequest = SystemClock.uptimeMillis();
log.debug("Scan successfully started");
} else {
log.warn("Bluetooth scan could not be started (Is bluetooth activated?)");
}
}
@Override
protected boolean isAvailable() {
return bluetoothAdapter == null || !bluetoothAdapter.isEnabled();
}
@Override
protected Integer getDelay(MoraConfig config) {
return config.bluetooth;
}
@Override
protected void handleActivation() {
// Register listeners
context.registerReceiver(bluetoothEndpoint, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED), null, handler);
context.registerReceiver(bluetoothEndpoint, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED), null, handler);
context.registerReceiver(bluetoothEndpoint, new IntentFilter(BluetoothDevice.ACTION_FOUND), null, handler);
// Start first scan immediately
startNextScan();
}
@Override
protected void handleDeactivation() {
try {
context.unregisterReceiver(bluetoothEndpoint);
} catch (IllegalArgumentException e) {
log.warn("Receiver already unregistered");
}
}
@Override
public Bundle getReport() {
Bundle report = super.getReport();
report.putInt("items", items.size());
report.putLong("lastScanRequest", lastScanRequest);
return report;
}
/**
* <p>Delegate handling updates of the bluetooth state</p>
*/
private final BroadcastReceiver bluetoothEndpoint = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) {
// On start of the discovery, reset the pending push
items.clear();
} else if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {// Extract the stored data from the bundle of the intent
final BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
final BluetoothClass bluetoothClass = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);
final String name = intent.hasExtra(BluetoothDevice.EXTRA_NAME) ? intent.getStringExtra(BluetoothDevice.EXTRA_NAME) : null;
final Short rssi = intent.hasExtra(BluetoothDevice.EXTRA_RSSI) ? intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE) : null;
final Bluetooth.BondState bondState;
switch (bluetoothDevice.getBondState()) {
case BluetoothDevice.BOND_NONE:
bondState = Bluetooth.BondState.NONE;
break;
case BluetoothDevice.BOND_BONDING:
bondState = Bluetooth.BondState.BONDING;
break;
case BluetoothDevice.BOND_BONDED:
bondState = Bluetooth.BondState.BONDED;
break;
default:
bondState = Bluetooth.BondState.UNKNOWN;
break;
}
items.add(new Bluetooth.Item(
bluetoothDevice.getAddress(),
MoraConstants.getDeviceMajorClassName(bluetoothClass.getMajorDeviceClass()),
MoraConstants.getDeviceClassName(bluetoothClass.getDeviceClass()),
bondState,
name,
rssi
));
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
// Get receive-time of the intent in system up-time
long scanEndTime = SystemClock.uptimeMillis();
// On end of the discovery, push the results to the pipeline
itemBuffer.offer(new Bluetooth(
System.currentTimeMillis(),
credentials.user,
items.toArray(new Bluetooth.Item[items.size()])
));
// If results are on time, schedule the next scan at the handler with the given delay
if (lastScanRequest + getCurrentDelay() > scanEndTime) {
if (!handler.postAtTime(new Runnable() {
@Override
public void run() {
startNextScan();
}
}, lastScanRequest + getCurrentDelay())) {
// If failed to schedule, scan immediately
startNextScan();
}
} else {
// Else, scan immediately
startNextScan();
}
} else {
throw new IllegalStateException("Illegal configuration of broadcast receiver");
}
}
};
}
| UTF-8 | Java | 7,215 | java | BluetoothSource.java | Java | [
{
"context": "ample source for bluetooth state</p>\n * Created by lukashaertel on 05.12.14.\n */\n@Singleton\npublic class Bluetoot",
"end": 989,
"score": 0.9962916970252991,
"start": 977,
"tag": "USERNAME",
"value": "lukashaertel"
}
] | null | [] | package eu.liveandgov.wp1.sensor_collector.components;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import eu.liveandgov.wp1.data.impl.Bluetooth;
import eu.liveandgov.wp1.sensor_collector.api.MoraConfig;
import eu.liveandgov.wp1.sensor_collector.config.Configurator;
import eu.liveandgov.wp1.sensor_collector.logging.LogPrincipal;
import eu.liveandgov.wp1.sensor_collector.util.MoraConstants;
import eu.liveandgov.wp1.sensor_collector.util.Threaded;
/**
* <p>Sample source for bluetooth state</p>
* Created by lukashaertel on 05.12.14.
*/
@Singleton
public class BluetoothSource extends RegularSampleSource {
private static final Logger log = LogPrincipal.get();
@Inject
Context context;
/**
* Central credentials store
*/
@Inject
Credentials credentials;
/**
* Central item buffer
*/
@Inject
ItemBuffer itemBuffer;
/**
* Message handler
*/
@Inject
@Threaded
Handler handler;
/**
* The adapter this bluetooth source is attached to
*/
private final BluetoothAdapter bluetoothAdapter;
/**
* The items in the current recording
*/
private final List<Bluetooth.Item> items;
/**
* The last time a scan has been requested
*/
private long lastScanRequest;
@Inject
public BluetoothSource(Configurator configurator) {
super(configurator);
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
this.items = new ArrayList<Bluetooth.Item>();
lastScanRequest = Long.MIN_VALUE;
}
private void startNextScan() {
if (bluetoothAdapter != null && bluetoothAdapter.startDiscovery()) {
lastScanRequest = SystemClock.uptimeMillis();
log.debug("Scan successfully started");
} else {
log.warn("Bluetooth scan could not be started (Is bluetooth activated?)");
}
}
@Override
protected boolean isAvailable() {
return bluetoothAdapter == null || !bluetoothAdapter.isEnabled();
}
@Override
protected Integer getDelay(MoraConfig config) {
return config.bluetooth;
}
@Override
protected void handleActivation() {
// Register listeners
context.registerReceiver(bluetoothEndpoint, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED), null, handler);
context.registerReceiver(bluetoothEndpoint, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED), null, handler);
context.registerReceiver(bluetoothEndpoint, new IntentFilter(BluetoothDevice.ACTION_FOUND), null, handler);
// Start first scan immediately
startNextScan();
}
@Override
protected void handleDeactivation() {
try {
context.unregisterReceiver(bluetoothEndpoint);
} catch (IllegalArgumentException e) {
log.warn("Receiver already unregistered");
}
}
@Override
public Bundle getReport() {
Bundle report = super.getReport();
report.putInt("items", items.size());
report.putLong("lastScanRequest", lastScanRequest);
return report;
}
/**
* <p>Delegate handling updates of the bluetooth state</p>
*/
private final BroadcastReceiver bluetoothEndpoint = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) {
// On start of the discovery, reset the pending push
items.clear();
} else if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {// Extract the stored data from the bundle of the intent
final BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
final BluetoothClass bluetoothClass = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);
final String name = intent.hasExtra(BluetoothDevice.EXTRA_NAME) ? intent.getStringExtra(BluetoothDevice.EXTRA_NAME) : null;
final Short rssi = intent.hasExtra(BluetoothDevice.EXTRA_RSSI) ? intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE) : null;
final Bluetooth.BondState bondState;
switch (bluetoothDevice.getBondState()) {
case BluetoothDevice.BOND_NONE:
bondState = Bluetooth.BondState.NONE;
break;
case BluetoothDevice.BOND_BONDING:
bondState = Bluetooth.BondState.BONDING;
break;
case BluetoothDevice.BOND_BONDED:
bondState = Bluetooth.BondState.BONDED;
break;
default:
bondState = Bluetooth.BondState.UNKNOWN;
break;
}
items.add(new Bluetooth.Item(
bluetoothDevice.getAddress(),
MoraConstants.getDeviceMajorClassName(bluetoothClass.getMajorDeviceClass()),
MoraConstants.getDeviceClassName(bluetoothClass.getDeviceClass()),
bondState,
name,
rssi
));
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
// Get receive-time of the intent in system up-time
long scanEndTime = SystemClock.uptimeMillis();
// On end of the discovery, push the results to the pipeline
itemBuffer.offer(new Bluetooth(
System.currentTimeMillis(),
credentials.user,
items.toArray(new Bluetooth.Item[items.size()])
));
// If results are on time, schedule the next scan at the handler with the given delay
if (lastScanRequest + getCurrentDelay() > scanEndTime) {
if (!handler.postAtTime(new Runnable() {
@Override
public void run() {
startNextScan();
}
}, lastScanRequest + getCurrentDelay())) {
// If failed to schedule, scan immediately
startNextScan();
}
} else {
// Else, scan immediately
startNextScan();
}
} else {
throw new IllegalStateException("Illegal configuration of broadcast receiver");
}
}
};
}
| 7,215 | 0.612335 | 0.610395 | 209 | 33.52153 | 31.423649 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 8 |
8dd3c22d6d1a2386cff9ef4600d19bd2796d00ab | 30,743,375,923,003 | 34190e601e5c962829ed4dcaeb7953f8fe442539 | /src/main/java/com/schedule/core/Graphs/FeasibleSchedules/DataGenerator/SchedulesBuilder.java | e40ea338dbdc3cb76149b888e5fe3110a471e2af | [] | no_license | jossmt/JobShopScheduling | https://github.com/jossmt/JobShopScheduling | be8f30fbfca0dfb5d515b3056cb447150f8e12b5 | 354ea5f03fe87c906bcc0317c6475b0733bf7b9d | refs/heads/master | 2021-03-30T21:52:40.766000 | 2018-03-09T13:27:47 | 2018-03-09T13:27:47 | 124,543,356 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.schedule.core.Graphs.FeasibleSchedules.DataGenerator;
import com.schedule.core.Graphs.FeasibleSchedules.Config.FileDataPaths;
import com.schedule.core.Graphs.FeasibleSchedules.Model.Core.Operation;
import com.schedule.core.Graphs.FeasibleSchedules.Model.Core.Schedule;
import com.schedule.core.Graphs.FeasibleSchedules.Service.ScheduleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class SchedulesBuilder {
private static final Logger LOG = LoggerFactory.getLogger(com.schedule.core.Graphs.FeasibleSchedules
.DataGenerator.SchedulesBuilder.class);
private ScheduleService scheduleService = new ScheduleService();
public Set<Schedule> generateStartingSchedules(final String benchmarkInstance,
final Integer setSize) {
final Set<Schedule> startingScheduleSet = new HashSet<>();
Integer[][][] jobset = getBenchmarkInstance(benchmarkInstance);
while (startingScheduleSet.size() != setSize) {
startingScheduleSet.add(buildRandomSchedules(jobset));
}
return startingScheduleSet;
}
public Set<Schedule> generateTestSchedules(final String benchmarkInstance,
final Integer setSize) {
//Generates the same schedules using same random number set.
Scanner input = null;
try {
File file = new File("./src/test/resources/RandomVals.txt");
LOG.trace("File exists: {}", file.exists());
input = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final String line = input.nextLine();
LOG.trace("Line: {}", line);
final String[] values = line.split(",");
//Array where index 0 is count, rest are random values
final Integer[] randomTestValues = new Integer[values.length];
for (Integer i = 0; i < values.length; i++) {
randomTestValues[i] = Integer.valueOf(values[i]);
}
final Set<Schedule> startingScheduleSet = new HashSet<>();
Integer[][][] jobset = getBenchmarkInstance(benchmarkInstance);
while (startingScheduleSet.size() != setSize) {
startingScheduleSet.add(buildTestSchedules(jobset, randomTestValues));
LOG.trace("Set size: {} Starting schedule size: {}", setSize, startingScheduleSet.size());
}
return startingScheduleSet;
}
private Schedule buildRandomSchedules(final Integer[][][] jobset) {
final Integer numMachines = jobset[0].length;
final Integer numJobs = jobset.length;
final Schedule schedule = generateTreeTemplate(jobset, numMachines, numJobs);
//Generate random staticSchedule
final Random rand = new Random();
Integer[] count = new Integer[numJobs];
for (Integer i = 0; i < count.length; i++) {
count[i] = 0;
}
Integer[] lastActiveJob = new Integer[numMachines];
Integer sum = 0;
while (sum < (numMachines * numJobs)) {
final Integer randVal = rand.nextInt(numJobs);
if (count[randVal] < numMachines) {
final Integer machine = jobset[randVal][count[randVal]][0];
schedule.setActiveEdge(randVal, lastActiveJob[machine], jobset[randVal][count[randVal]]);
lastActiveJob[machine] = randVal;
count[randVal]++;
sum++;
}
LOG.trace("Sum: {}, total: {}", sum, numMachines * numJobs);
}
scheduleService.calculateScheduleData(schedule);
return schedule;
}
private Schedule buildTestSchedules(final Integer[][][] jobset, final Integer[] randomTestValues) {
final Integer numMachines = jobset[0].length;
final Integer numJobs = jobset.length;
final Schedule schedule = generateTreeTemplate(jobset, numMachines, numJobs);
Integer[] count = new Integer[numJobs];
for (Integer i = 0; i < count.length; i++) {
count[i] = 0;
}
Integer[] lastActiveJob = new Integer[numMachines];
Integer sum = 0;
while (sum < (numMachines * numJobs)) {
LOG.trace("Val: {}", randomTestValues[randomTestValues[0]]);
final Integer jobVal = randomTestValues[randomTestValues[0]] % numJobs;
LOG.trace("Job value: {}", jobVal);
if (count[jobVal] < numMachines) {
LOG.trace("Count of job: {}", count[jobVal]);
final Integer machine = jobset[jobVal][count[jobVal]][0];
schedule.setActiveEdge(jobVal, lastActiveJob[machine], jobset[jobVal][count[jobVal]]);
lastActiveJob[machine] = jobVal;
count[jobVal]++;
sum++;
}
LOG.trace("Sum: {}, total: {}", sum, numMachines * numJobs);
randomTestValues[0]++;
}
scheduleService.calculateMakeSpan(schedule);
return schedule;
}
private Schedule generateTreeTemplate(final Integer[][][] jobset, final Integer numMachines,
final Integer numJobs) {
final Schedule schedule = new Schedule(numMachines, numJobs);
Integer jobValue = 0;
Integer taskValue = 0;
for (final Integer[][] jobs : jobset) {
for (final Integer[] job : jobs) {
LOG.trace("Adding operation: J:{}, M: {}, PT: {}", jobValue, job[0], job[1]);
final Operation operation = new Operation(taskValue, jobValue, job[0]);
schedule.addVertex(job[1], operation);
taskValue++;
}
jobValue++;
}
return schedule;
}
public Integer[][][] getBenchmarkInstance(final String instance) {
//Generates the same schedules using same random number set.
Scanner input = null;
try {
File file = new File(FileDataPaths.BENCHMARK_INSTANCES_PATH + instance);
LOG.trace("File exists: {}", file.exists());
input = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final String line = input.nextLine();
LOG.trace("Line: {}", line);
final String[] size = line.split("\t");
final Integer jobNum = Integer.valueOf(size[0]);
final Integer machineNum = Integer.valueOf(size[1]);
LOG.trace("Job num: {}, machine num: {}", jobNum, machineNum);
final Integer[][][] benchmarkInstance = new Integer[jobNum][2][machineNum];
int jobCount = 0;
while (input.hasNext()) {
final Integer[][] row = new Integer[machineNum][2];
final String[] values = input.nextLine().split("\\t");
Integer machine;
Integer processingTime;
Integer count = 0;
for (int i = 0; i < values.length; i += 2) {
machine = Integer.valueOf(values[i]);
processingTime = Integer.valueOf(values[i + 1]);
row[count] = new Integer[]{machine, processingTime};
count++;
}
benchmarkInstance[jobCount] = row;
jobCount++;
}
return benchmarkInstance;
}
} | UTF-8 | Java | 7,545 | java | SchedulesBuilder.java | Java | [] | null | [] | package com.schedule.core.Graphs.FeasibleSchedules.DataGenerator;
import com.schedule.core.Graphs.FeasibleSchedules.Config.FileDataPaths;
import com.schedule.core.Graphs.FeasibleSchedules.Model.Core.Operation;
import com.schedule.core.Graphs.FeasibleSchedules.Model.Core.Schedule;
import com.schedule.core.Graphs.FeasibleSchedules.Service.ScheduleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class SchedulesBuilder {
private static final Logger LOG = LoggerFactory.getLogger(com.schedule.core.Graphs.FeasibleSchedules
.DataGenerator.SchedulesBuilder.class);
private ScheduleService scheduleService = new ScheduleService();
public Set<Schedule> generateStartingSchedules(final String benchmarkInstance,
final Integer setSize) {
final Set<Schedule> startingScheduleSet = new HashSet<>();
Integer[][][] jobset = getBenchmarkInstance(benchmarkInstance);
while (startingScheduleSet.size() != setSize) {
startingScheduleSet.add(buildRandomSchedules(jobset));
}
return startingScheduleSet;
}
public Set<Schedule> generateTestSchedules(final String benchmarkInstance,
final Integer setSize) {
//Generates the same schedules using same random number set.
Scanner input = null;
try {
File file = new File("./src/test/resources/RandomVals.txt");
LOG.trace("File exists: {}", file.exists());
input = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final String line = input.nextLine();
LOG.trace("Line: {}", line);
final String[] values = line.split(",");
//Array where index 0 is count, rest are random values
final Integer[] randomTestValues = new Integer[values.length];
for (Integer i = 0; i < values.length; i++) {
randomTestValues[i] = Integer.valueOf(values[i]);
}
final Set<Schedule> startingScheduleSet = new HashSet<>();
Integer[][][] jobset = getBenchmarkInstance(benchmarkInstance);
while (startingScheduleSet.size() != setSize) {
startingScheduleSet.add(buildTestSchedules(jobset, randomTestValues));
LOG.trace("Set size: {} Starting schedule size: {}", setSize, startingScheduleSet.size());
}
return startingScheduleSet;
}
private Schedule buildRandomSchedules(final Integer[][][] jobset) {
final Integer numMachines = jobset[0].length;
final Integer numJobs = jobset.length;
final Schedule schedule = generateTreeTemplate(jobset, numMachines, numJobs);
//Generate random staticSchedule
final Random rand = new Random();
Integer[] count = new Integer[numJobs];
for (Integer i = 0; i < count.length; i++) {
count[i] = 0;
}
Integer[] lastActiveJob = new Integer[numMachines];
Integer sum = 0;
while (sum < (numMachines * numJobs)) {
final Integer randVal = rand.nextInt(numJobs);
if (count[randVal] < numMachines) {
final Integer machine = jobset[randVal][count[randVal]][0];
schedule.setActiveEdge(randVal, lastActiveJob[machine], jobset[randVal][count[randVal]]);
lastActiveJob[machine] = randVal;
count[randVal]++;
sum++;
}
LOG.trace("Sum: {}, total: {}", sum, numMachines * numJobs);
}
scheduleService.calculateScheduleData(schedule);
return schedule;
}
private Schedule buildTestSchedules(final Integer[][][] jobset, final Integer[] randomTestValues) {
final Integer numMachines = jobset[0].length;
final Integer numJobs = jobset.length;
final Schedule schedule = generateTreeTemplate(jobset, numMachines, numJobs);
Integer[] count = new Integer[numJobs];
for (Integer i = 0; i < count.length; i++) {
count[i] = 0;
}
Integer[] lastActiveJob = new Integer[numMachines];
Integer sum = 0;
while (sum < (numMachines * numJobs)) {
LOG.trace("Val: {}", randomTestValues[randomTestValues[0]]);
final Integer jobVal = randomTestValues[randomTestValues[0]] % numJobs;
LOG.trace("Job value: {}", jobVal);
if (count[jobVal] < numMachines) {
LOG.trace("Count of job: {}", count[jobVal]);
final Integer machine = jobset[jobVal][count[jobVal]][0];
schedule.setActiveEdge(jobVal, lastActiveJob[machine], jobset[jobVal][count[jobVal]]);
lastActiveJob[machine] = jobVal;
count[jobVal]++;
sum++;
}
LOG.trace("Sum: {}, total: {}", sum, numMachines * numJobs);
randomTestValues[0]++;
}
scheduleService.calculateMakeSpan(schedule);
return schedule;
}
private Schedule generateTreeTemplate(final Integer[][][] jobset, final Integer numMachines,
final Integer numJobs) {
final Schedule schedule = new Schedule(numMachines, numJobs);
Integer jobValue = 0;
Integer taskValue = 0;
for (final Integer[][] jobs : jobset) {
for (final Integer[] job : jobs) {
LOG.trace("Adding operation: J:{}, M: {}, PT: {}", jobValue, job[0], job[1]);
final Operation operation = new Operation(taskValue, jobValue, job[0]);
schedule.addVertex(job[1], operation);
taskValue++;
}
jobValue++;
}
return schedule;
}
public Integer[][][] getBenchmarkInstance(final String instance) {
//Generates the same schedules using same random number set.
Scanner input = null;
try {
File file = new File(FileDataPaths.BENCHMARK_INSTANCES_PATH + instance);
LOG.trace("File exists: {}", file.exists());
input = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final String line = input.nextLine();
LOG.trace("Line: {}", line);
final String[] size = line.split("\t");
final Integer jobNum = Integer.valueOf(size[0]);
final Integer machineNum = Integer.valueOf(size[1]);
LOG.trace("Job num: {}, machine num: {}", jobNum, machineNum);
final Integer[][][] benchmarkInstance = new Integer[jobNum][2][machineNum];
int jobCount = 0;
while (input.hasNext()) {
final Integer[][] row = new Integer[machineNum][2];
final String[] values = input.nextLine().split("\\t");
Integer machine;
Integer processingTime;
Integer count = 0;
for (int i = 0; i < values.length; i += 2) {
machine = Integer.valueOf(values[i]);
processingTime = Integer.valueOf(values[i + 1]);
row[count] = new Integer[]{machine, processingTime};
count++;
}
benchmarkInstance[jobCount] = row;
jobCount++;
}
return benchmarkInstance;
}
} | 7,545 | 0.586614 | 0.582372 | 225 | 32.537777 | 30.493856 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684444 | false | false | 8 |
4abd5cf953b60e3babc29468233e7eceba8f965d | 6,073,083,794,938 | 6359b37a07c0fad762e3a21e101339eaa26dbf5b | /src/graphic/graphicBoardGame.java | 8599dc0cdaf693f2ce386a1aa15b1f8959fa0512 | [] | no_license | Wasini/Pathagon | https://github.com/Wasini/Pathagon | 97c1ce2d67c04802f5b635f9361deedc8ab69ee3 | cad308978974765cbae13c48662098ee6ba81f27 | refs/heads/master | 2020-06-23T05:35:32.815000 | 2018-02-08T16:26:28 | 2018-02-08T16:26:28 | 94,231,481 | 0 | 0 | null | false | 2017-06-19T02:09:45 | 2017-06-13T16:01:51 | 2017-06-13T16:03:27 | 2017-06-19T02:09:45 | 37 | 0 | 0 | 0 | Java | null | null | package graphic;
import controller.PathagonController;
import java.awt.Color;
import java.util.List;
import javax.swing.JOptionPane;
import model.PathagonToken;
public class graphicBoardGame extends PathagonView{
/**
* Creates new form graphicBoardGame
* @param c
*/
public graphicBoardGame(PathagonController c) {
super(c);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
p01 = new javax.swing.JButton();
p00 = new javax.swing.JButton();
p02 = new javax.swing.JButton();
p03 = new javax.swing.JButton();
p04 = new javax.swing.JButton();
p05 = new javax.swing.JButton();
p06 = new javax.swing.JButton();
p10 = new javax.swing.JButton();
p11 = new javax.swing.JButton();
p12 = new javax.swing.JButton();
p13 = new javax.swing.JButton();
p14 = new javax.swing.JButton();
p15 = new javax.swing.JButton();
p16 = new javax.swing.JButton();
p1 = new javax.swing.JButton();
p2 = new javax.swing.JButton();
p3 = new javax.swing.JButton();
p4 = new javax.swing.JButton();
p5 = new javax.swing.JButton();
p6 = new javax.swing.JButton();
p7 = new javax.swing.JButton();
p8 = new javax.swing.JButton();
p9 = new javax.swing.JButton();
p17 = new javax.swing.JButton();
p18 = new javax.swing.JButton();
p19 = new javax.swing.JButton();
p20 = new javax.swing.JButton();
p21 = new javax.swing.JButton();
p22 = new javax.swing.JButton();
p23 = new javax.swing.JButton();
p24 = new javax.swing.JButton();
p25 = new javax.swing.JButton();
p26 = new javax.swing.JButton();
p27 = new javax.swing.JButton();
p28 = new javax.swing.JButton();
p29 = new javax.swing.JButton();
p30 = new javax.swing.JButton();
p31 = new javax.swing.JButton();
p32 = new javax.swing.JButton();
p33 = new javax.swing.JButton();
p34 = new javax.swing.JButton();
p35 = new javax.swing.JButton();
p36 = new javax.swing.JButton();
p37 = new javax.swing.JButton();
p38 = new javax.swing.JButton();
p39 = new javax.swing.JButton();
p40 = new javax.swing.JButton();
p41 = new javax.swing.JButton();
p42 = new javax.swing.JButton();
player = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
p01.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p01MouseClicked(evt);
}
});
getContentPane().add(p01, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 200, 50, 40));
p00.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p00MouseClicked(evt);
}
});
getContentPane().add(p00, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 200, 50, 40));
p02.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p02MouseClicked(evt);
}
});
getContentPane().add(p02, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 200, 50, 40));
p03.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p03MouseClicked(evt);
}
});
getContentPane().add(p03, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 200, 50, 40));
p04.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p04MouseClicked(evt);
}
});
getContentPane().add(p04, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 200, 50, 40));
p05.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p05MouseClicked(evt);
}
});
getContentPane().add(p05, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 200, 50, 40));
p06.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p06MouseClicked(evt);
}
});
getContentPane().add(p06, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 200, 50, 40));
p10.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p10MouseClicked(evt);
}
});
getContentPane().add(p10, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 240, 50, 40));
p11.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p11MouseClicked(evt);
}
});
getContentPane().add(p11, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 240, 50, 40));
p12.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p12MouseClicked(evt);
}
});
getContentPane().add(p12, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 240, 50, 40));
p13.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p13MouseClicked(evt);
}
});
getContentPane().add(p13, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 240, 50, 40));
p14.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p14MouseClicked(evt);
}
});
getContentPane().add(p14, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 240, 50, 40));
p15.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p15MouseClicked(evt);
}
});
getContentPane().add(p15, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 240, 50, 40));
p16.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p16MouseClicked(evt);
}
});
getContentPane().add(p16, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 240, 50, 40));
p1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p1MouseClicked(evt);
}
});
getContentPane().add(p1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 280, 50, 40));
p2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p2MouseClicked(evt);
}
});
getContentPane().add(p2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 280, 50, 40));
p3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p3MouseClicked(evt);
}
});
getContentPane().add(p3, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 280, 50, 40));
p4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p4MouseClicked(evt);
}
});
getContentPane().add(p4, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 280, 50, 40));
p5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p5MouseClicked(evt);
}
});
getContentPane().add(p5, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 280, 50, 40));
p6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p6MouseClicked(evt);
}
});
getContentPane().add(p6, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 280, 50, 40));
p7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p7MouseClicked(evt);
}
});
getContentPane().add(p7, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 280, 50, 40));
p8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p8MouseClicked(evt);
}
});
getContentPane().add(p8, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 320, 50, 40));
p9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p9MouseClicked(evt);
}
});
getContentPane().add(p9, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 320, 50, 40));
p17.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p17MouseClicked(evt);
}
});
getContentPane().add(p17, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 320, 50, 40));
p18.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p18MouseClicked(evt);
}
});
getContentPane().add(p18, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 320, 50, 40));
p19.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p19MouseClicked(evt);
}
});
getContentPane().add(p19, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 320, 50, 40));
p20.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p20MouseClicked(evt);
}
});
getContentPane().add(p20, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 320, 50, 40));
p21.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p21MouseClicked(evt);
}
});
getContentPane().add(p21, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 320, 50, 40));
p22.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p22MouseClicked(evt);
}
});
getContentPane().add(p22, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 360, 50, 40));
p23.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p23MouseClicked(evt);
}
});
getContentPane().add(p23, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 360, 50, 40));
p24.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p24MouseClicked(evt);
}
});
getContentPane().add(p24, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 360, 50, 40));
p25.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p25MouseClicked(evt);
}
});
getContentPane().add(p25, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 360, 50, 40));
p26.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p26MouseClicked(evt);
}
});
getContentPane().add(p26, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 360, 50, 40));
p27.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p27MouseClicked(evt);
}
});
getContentPane().add(p27, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 360, 50, 40));
p28.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p28MouseClicked(evt);
}
});
getContentPane().add(p28, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 360, 50, 40));
p29.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p29MouseClicked(evt);
}
});
getContentPane().add(p29, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 400, 50, 40));
p30.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p30MouseClicked(evt);
}
});
getContentPane().add(p30, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 400, 50, 40));
p31.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p31MouseClicked(evt);
}
});
getContentPane().add(p31, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 400, 50, 40));
p32.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p32MouseClicked(evt);
}
});
getContentPane().add(p32, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 400, 50, 40));
p33.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p33MouseClicked(evt);
}
});
getContentPane().add(p33, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 400, 50, 40));
p34.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p34MouseClicked(evt);
}
});
getContentPane().add(p34, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 400, 50, 40));
p35.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p35MouseClicked(evt);
}
});
getContentPane().add(p35, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 400, 50, 40));
p36.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p36MouseClicked(evt);
}
});
getContentPane().add(p36, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 440, 50, 40));
p37.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p37MouseClicked(evt);
}
});
getContentPane().add(p37, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 440, 50, 40));
p38.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p38MouseClicked(evt);
}
});
getContentPane().add(p38, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 440, 50, 40));
p39.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p39MouseClicked(evt);
}
});
getContentPane().add(p39, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 440, 50, 40));
p40.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p40MouseClicked(evt);
}
});
getContentPane().add(p40, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 440, 50, 40));
p41.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p41MouseClicked(evt);
}
});
getContentPane().add(p41, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 440, 50, 40));
p42.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p42MouseClicked(evt);
}
});
getContentPane().add(p42, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 440, 50, 40));
player.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N
player.setForeground(new java.awt.Color(51, 51, 51));
getContentPane().add(player, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 160, 130, 30));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/graphic/image/Menu.jpg"))); // NOI18N
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void p00MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p00MouseClicked
ModifyBotton(0,0);
}//GEN-LAST:event_p00MouseClicked
private void p01MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p01MouseClicked
ModifyBotton(1,0);
}//GEN-LAST:event_p01MouseClicked
private void p02MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p02MouseClicked
ModifyBotton(2,0);
}//GEN-LAST:event_p02MouseClicked
private void p03MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p03MouseClicked
ModifyBotton(3,0);
}//GEN-LAST:event_p03MouseClicked
private void p04MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p04MouseClicked
ModifyBotton(4,0);
}//GEN-LAST:event_p04MouseClicked
private void p05MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p05MouseClicked
ModifyBotton(5,0);
}//GEN-LAST:event_p05MouseClicked
private void p06MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p06MouseClicked
ModifyBotton(6,0);
}//GEN-LAST:event_p06MouseClicked
private void p10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p10MouseClicked
ModifyBotton(0,1);
}//GEN-LAST:event_p10MouseClicked
private void p11MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p11MouseClicked
ModifyBotton(1,1);
}//GEN-LAST:event_p11MouseClicked
private void p12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p12MouseClicked
ModifyBotton(2,1);
}//GEN-LAST:event_p12MouseClicked
private void p13MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p13MouseClicked
ModifyBotton(3,1);
}//GEN-LAST:event_p13MouseClicked
private void p14MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p14MouseClicked
ModifyBotton(4,1);
}//GEN-LAST:event_p14MouseClicked
private void p15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p15MouseClicked
ModifyBotton(5,1);
}//GEN-LAST:event_p15MouseClicked
private void p16MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p16MouseClicked
ModifyBotton(6,1);
}//GEN-LAST:event_p16MouseClicked
private void p1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p1MouseClicked
ModifyBotton(0,2);
}//GEN-LAST:event_p1MouseClicked
private void p2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p2MouseClicked
ModifyBotton(1,2);
}//GEN-LAST:event_p2MouseClicked
private void p3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p3MouseClicked
ModifyBotton(2,2);
}//GEN-LAST:event_p3MouseClicked
private void p4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p4MouseClicked
ModifyBotton(3,2);
}//GEN-LAST:event_p4MouseClicked
private void p5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p5MouseClicked
ModifyBotton(4,2);
}//GEN-LAST:event_p5MouseClicked
private void p6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p6MouseClicked
ModifyBotton(5,2);
}//GEN-LAST:event_p6MouseClicked
private void p7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p7MouseClicked
ModifyBotton( 6,2);
}//GEN-LAST:event_p7MouseClicked
private void p8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p8MouseClicked
ModifyBotton(0,3);
}//GEN-LAST:event_p8MouseClicked
private void p9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p9MouseClicked
ModifyBotton(1,3);
}//GEN-LAST:event_p9MouseClicked
private void p17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p17MouseClicked
ModifyBotton(2,3);
}//GEN-LAST:event_p17MouseClicked
private void p18MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p18MouseClicked
ModifyBotton(3,3);
}//GEN-LAST:event_p18MouseClicked
private void p19MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p19MouseClicked
ModifyBotton(4,3);
}//GEN-LAST:event_p19MouseClicked
private void p20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p20MouseClicked
ModifyBotton(5,3);
}//GEN-LAST:event_p20MouseClicked
private void p21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p21MouseClicked
ModifyBotton(6,3);
}//GEN-LAST:event_p21MouseClicked
private void p22MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p22MouseClicked
ModifyBotton(0,4);
}//GEN-LAST:event_p22MouseClicked
private void p23MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p23MouseClicked
ModifyBotton(1,4);
}//GEN-LAST:event_p23MouseClicked
private void p24MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p24MouseClicked
ModifyBotton(2,4);
}//GEN-LAST:event_p24MouseClicked
private void p25MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p25MouseClicked
ModifyBotton(3,4);
}//GEN-LAST:event_p25MouseClicked
private void p26MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p26MouseClicked
ModifyBotton(4,4);
}//GEN-LAST:event_p26MouseClicked
private void p27MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p27MouseClicked
ModifyBotton(5,4);
}//GEN-LAST:event_p27MouseClicked
private void p28MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p28MouseClicked
ModifyBotton(6,4);
}//GEN-LAST:event_p28MouseClicked
private void p29MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p29MouseClicked
ModifyBotton(0,5);
}//GEN-LAST:event_p29MouseClicked
private void p30MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p30MouseClicked
ModifyBotton(1,5);
}//GEN-LAST:event_p30MouseClicked
private void p31MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p31MouseClicked
ModifyBotton(2,5);
}//GEN-LAST:event_p31MouseClicked
private void p32MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p32MouseClicked
ModifyBotton(3,5);
}//GEN-LAST:event_p32MouseClicked
private void p33MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p33MouseClicked
ModifyBotton(4,5);
}//GEN-LAST:event_p33MouseClicked
private void p34MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p34MouseClicked
ModifyBotton(5,5);
}//GEN-LAST:event_p34MouseClicked
private void p35MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p35MouseClicked
ModifyBotton(6,5);
}//GEN-LAST:event_p35MouseClicked
private void p36MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p36MouseClicked
ModifyBotton(0,6);
}//GEN-LAST:event_p36MouseClicked
private void p37MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p37MouseClicked
ModifyBotton(1,6);
}//GEN-LAST:event_p37MouseClicked
private void p38MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p38MouseClicked
ModifyBotton(2,6);
}//GEN-LAST:event_p38MouseClicked
private void p39MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p39MouseClicked
ModifyBotton(3,6);
}//GEN-LAST:event_p39MouseClicked
private void p40MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p40MouseClicked
ModifyBotton(4,6);
}//GEN-LAST:event_p40MouseClicked
private void p41MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p41MouseClicked
ModifyBotton(5,6);
}//GEN-LAST:event_p41MouseClicked
private void p42MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p42MouseClicked
ModifyBotton(6,6);
}//GEN-LAST:event_p42MouseClicked
private void ModifyBotton(int x, int y){
if(!gameControl.playerHasTurn()) {
JOptionPane.showMessageDialog(null,"No es tu turno!","Aviso:",JOptionPane.WARNING_MESSAGE);
return;
}
if(!gameControl.canPlay(gameState.PLAYER1)){
JOptionPane.showMessageDialog(null,"Ups.. no te quedan fichas","Aviso:",JOptionPane.WARNING_MESSAGE);
gameControl.nextTurn();
return;
}
if (gameControl.validPosition(x,y,gameState.PLAYER1)) {
gameControl.playerPlay(x, y);
} else {
JOptionPane.showMessageDialog(null,"Movimiento bloqueado!!","Advertencia",JOptionPane.WARNING_MESSAGE);
}
}
private void paintMove(int x,int y,int player){
Color c;
if(player==-1){
c = Color.YELLOW;
}else{
if(player==1){
c=Color.BLACK;
}else{
c = Color.LIGHT_GRAY;
}
}
switch (x) {
case 0:
switch (y) {
case 0:
p00.setBackground(c);
break;
case 1:
p10.setBackground(c);;
break;
case 2:
p1.setBackground(c);;
break;
case 3:
p8.setBackground(c);;
break;
case 4:
p22.setBackground(c);;
break;
case 5:
p29.setBackground(c);;
break;
case 6:
p36.setBackground(c);;
break;
}
break;
case 1:
switch (y) {
case 0:
p01.setBackground(c);
break;
case 1:
p11.setBackground(c);;
break;
case 2:
p2.setBackground(c);;
break;
case 3:
p9.setBackground(c);;
break;
case 4:
p23.setBackground(c);;
break;
case 5:
p30.setBackground(c);;
break;
case 6:
p37.setBackground(c);;
break;
}
break;
case 2:
switch (y) {
case 0:
p02.setBackground(c);
break;
case 1:
p12.setBackground(c);;
break;
case 2:
p3.setBackground(c);;
break;
case 3:
p17.setBackground(c);;
break;
case 4:
p24.setBackground(c);;
break;
case 5:
p31.setBackground(c);;
break;
case 6:
p38.setBackground(c);;
break;
}
break;
case 3:
switch (y) {
case 0:
p03.setBackground(c);
break;
case 1:
p13.setBackground(c);;
break;
case 2:
p4.setBackground(c);;
break;
case 3:
p18.setBackground(c);;
break;
case 4:
p25.setBackground(c);;
break;
case 5:
p32.setBackground(c);;
break;
case 6:
p39.setBackground(c);;
break;
}
break;
case 4:
switch (y) {
case 0:
p04.setBackground(c);
break;
case 1:
p14.setBackground(c);;
break;
case 2:
p5.setBackground(c);;
break;
case 3:
p19.setBackground(c);;
break;
case 4:
p26.setBackground(c);;
break;
case 5:
p33.setBackground(c);;
break;
case 6:
p40.setBackground(c);;
break;
}
break;
case 5:
switch (y) {
case 0:
p05.setBackground(c);
break;
case 1:
p15.setBackground(c);;
break;
case 2:
p6.setBackground(c);;
break;
case 3:
p20.setBackground(c);;
break;
case 4:
p27.setBackground(c);;
break;
case 5:
p34.setBackground(c);;
break;
case 6:
p41.setBackground(c);;
break;
}
break;
case 6:
switch (y) {
case 0:
p06.setBackground(c);
break;
case 1:
p16.setBackground(c);;
break;
case 2:
p7.setBackground(c);;
break;
case 3:
p21.setBackground(c);;
break;
case 4:
p28.setBackground(c);;
break;
case 5:
p35.setBackground(c);;
break;
case 6:
p42.setBackground(c);;
break;
}
break;
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JButton p00;
private javax.swing.JButton p01;
private javax.swing.JButton p02;
private javax.swing.JButton p03;
private javax.swing.JButton p04;
private javax.swing.JButton p05;
private javax.swing.JButton p06;
private javax.swing.JButton p1;
private javax.swing.JButton p10;
private javax.swing.JButton p11;
private javax.swing.JButton p12;
private javax.swing.JButton p13;
private javax.swing.JButton p14;
private javax.swing.JButton p15;
private javax.swing.JButton p16;
private javax.swing.JButton p17;
private javax.swing.JButton p18;
private javax.swing.JButton p19;
private javax.swing.JButton p2;
private javax.swing.JButton p20;
private javax.swing.JButton p21;
private javax.swing.JButton p22;
private javax.swing.JButton p23;
private javax.swing.JButton p24;
private javax.swing.JButton p25;
private javax.swing.JButton p26;
private javax.swing.JButton p27;
private javax.swing.JButton p28;
private javax.swing.JButton p29;
private javax.swing.JButton p3;
private javax.swing.JButton p30;
private javax.swing.JButton p31;
private javax.swing.JButton p32;
private javax.swing.JButton p33;
private javax.swing.JButton p34;
private javax.swing.JButton p35;
private javax.swing.JButton p36;
private javax.swing.JButton p37;
private javax.swing.JButton p38;
private javax.swing.JButton p39;
private javax.swing.JButton p4;
private javax.swing.JButton p40;
private javax.swing.JButton p41;
private javax.swing.JButton p42;
private javax.swing.JButton p5;
private javax.swing.JButton p6;
private javax.swing.JButton p7;
private javax.swing.JButton p8;
private javax.swing.JButton p9;
public javax.swing.JLabel player;
// End of variables declaration//GEN-END:variables
@Override
public void updateView() {
PathagonToken ultimoMovimiento = this.gameState.getLastMove();
if (!ultimoMovimiento.isNull()) {
if (this.gameState.hasBlockedMoves()) {
List<PathagonToken> fichasComidas = this.gameState.getBlockedMoves();
for (PathagonToken removido : fichasComidas) {
paintMove(removido.row,removido.col,0);
}
}
paintMove(ultimoMovimiento.row,ultimoMovimiento.col, ultimoMovimiento.player);
}
int botlevel = gameControl.getDifficulty();
if(gameControl.getTurnNumber() == 16) {
gameControl.changeDifficulty(gameControl.getDifficulty()+1);
}
if(gameControl.hasEnded()){
gameControl.showResult();
} else {
if(!gameControl.playerHasTurn())
gameControl.iaPlay();
}
}
@Override
public void alertDraw(){
JOptionPane.showMessageDialog(null, "¡Eso estuvo reñido! ¡Es un merecido empate!", "Aviso: ", JOptionPane.WARNING_MESSAGE);
dispose();
}
@Override
public void alertWinner(String player) {
String msj="Ese fue un gran juego pero "+player+" lo hizo mejor. TENEMOS UN GANADOR";
JOptionPane.showMessageDialog(null,msj,"¡FELICIDADES!",JOptionPane.WARNING_MESSAGE);
dispose();
}
}
| UTF-8 | Java | 36,778 | java | graphicBoardGame.java | Java | [] | null | [] | package graphic;
import controller.PathagonController;
import java.awt.Color;
import java.util.List;
import javax.swing.JOptionPane;
import model.PathagonToken;
public class graphicBoardGame extends PathagonView{
/**
* Creates new form graphicBoardGame
* @param c
*/
public graphicBoardGame(PathagonController c) {
super(c);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
p01 = new javax.swing.JButton();
p00 = new javax.swing.JButton();
p02 = new javax.swing.JButton();
p03 = new javax.swing.JButton();
p04 = new javax.swing.JButton();
p05 = new javax.swing.JButton();
p06 = new javax.swing.JButton();
p10 = new javax.swing.JButton();
p11 = new javax.swing.JButton();
p12 = new javax.swing.JButton();
p13 = new javax.swing.JButton();
p14 = new javax.swing.JButton();
p15 = new javax.swing.JButton();
p16 = new javax.swing.JButton();
p1 = new javax.swing.JButton();
p2 = new javax.swing.JButton();
p3 = new javax.swing.JButton();
p4 = new javax.swing.JButton();
p5 = new javax.swing.JButton();
p6 = new javax.swing.JButton();
p7 = new javax.swing.JButton();
p8 = new javax.swing.JButton();
p9 = new javax.swing.JButton();
p17 = new javax.swing.JButton();
p18 = new javax.swing.JButton();
p19 = new javax.swing.JButton();
p20 = new javax.swing.JButton();
p21 = new javax.swing.JButton();
p22 = new javax.swing.JButton();
p23 = new javax.swing.JButton();
p24 = new javax.swing.JButton();
p25 = new javax.swing.JButton();
p26 = new javax.swing.JButton();
p27 = new javax.swing.JButton();
p28 = new javax.swing.JButton();
p29 = new javax.swing.JButton();
p30 = new javax.swing.JButton();
p31 = new javax.swing.JButton();
p32 = new javax.swing.JButton();
p33 = new javax.swing.JButton();
p34 = new javax.swing.JButton();
p35 = new javax.swing.JButton();
p36 = new javax.swing.JButton();
p37 = new javax.swing.JButton();
p38 = new javax.swing.JButton();
p39 = new javax.swing.JButton();
p40 = new javax.swing.JButton();
p41 = new javax.swing.JButton();
p42 = new javax.swing.JButton();
player = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
p01.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p01MouseClicked(evt);
}
});
getContentPane().add(p01, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 200, 50, 40));
p00.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p00MouseClicked(evt);
}
});
getContentPane().add(p00, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 200, 50, 40));
p02.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p02MouseClicked(evt);
}
});
getContentPane().add(p02, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 200, 50, 40));
p03.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p03MouseClicked(evt);
}
});
getContentPane().add(p03, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 200, 50, 40));
p04.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p04MouseClicked(evt);
}
});
getContentPane().add(p04, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 200, 50, 40));
p05.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p05MouseClicked(evt);
}
});
getContentPane().add(p05, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 200, 50, 40));
p06.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p06MouseClicked(evt);
}
});
getContentPane().add(p06, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 200, 50, 40));
p10.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p10MouseClicked(evt);
}
});
getContentPane().add(p10, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 240, 50, 40));
p11.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p11MouseClicked(evt);
}
});
getContentPane().add(p11, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 240, 50, 40));
p12.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p12MouseClicked(evt);
}
});
getContentPane().add(p12, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 240, 50, 40));
p13.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p13MouseClicked(evt);
}
});
getContentPane().add(p13, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 240, 50, 40));
p14.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p14MouseClicked(evt);
}
});
getContentPane().add(p14, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 240, 50, 40));
p15.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p15MouseClicked(evt);
}
});
getContentPane().add(p15, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 240, 50, 40));
p16.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p16MouseClicked(evt);
}
});
getContentPane().add(p16, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 240, 50, 40));
p1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p1MouseClicked(evt);
}
});
getContentPane().add(p1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 280, 50, 40));
p2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p2MouseClicked(evt);
}
});
getContentPane().add(p2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 280, 50, 40));
p3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p3MouseClicked(evt);
}
});
getContentPane().add(p3, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 280, 50, 40));
p4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p4MouseClicked(evt);
}
});
getContentPane().add(p4, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 280, 50, 40));
p5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p5MouseClicked(evt);
}
});
getContentPane().add(p5, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 280, 50, 40));
p6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p6MouseClicked(evt);
}
});
getContentPane().add(p6, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 280, 50, 40));
p7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p7MouseClicked(evt);
}
});
getContentPane().add(p7, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 280, 50, 40));
p8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p8MouseClicked(evt);
}
});
getContentPane().add(p8, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 320, 50, 40));
p9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p9MouseClicked(evt);
}
});
getContentPane().add(p9, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 320, 50, 40));
p17.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p17MouseClicked(evt);
}
});
getContentPane().add(p17, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 320, 50, 40));
p18.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p18MouseClicked(evt);
}
});
getContentPane().add(p18, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 320, 50, 40));
p19.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p19MouseClicked(evt);
}
});
getContentPane().add(p19, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 320, 50, 40));
p20.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p20MouseClicked(evt);
}
});
getContentPane().add(p20, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 320, 50, 40));
p21.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p21MouseClicked(evt);
}
});
getContentPane().add(p21, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 320, 50, 40));
p22.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p22MouseClicked(evt);
}
});
getContentPane().add(p22, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 360, 50, 40));
p23.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p23MouseClicked(evt);
}
});
getContentPane().add(p23, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 360, 50, 40));
p24.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p24MouseClicked(evt);
}
});
getContentPane().add(p24, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 360, 50, 40));
p25.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p25MouseClicked(evt);
}
});
getContentPane().add(p25, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 360, 50, 40));
p26.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p26MouseClicked(evt);
}
});
getContentPane().add(p26, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 360, 50, 40));
p27.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p27MouseClicked(evt);
}
});
getContentPane().add(p27, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 360, 50, 40));
p28.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p28MouseClicked(evt);
}
});
getContentPane().add(p28, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 360, 50, 40));
p29.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p29MouseClicked(evt);
}
});
getContentPane().add(p29, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 400, 50, 40));
p30.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p30MouseClicked(evt);
}
});
getContentPane().add(p30, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 400, 50, 40));
p31.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p31MouseClicked(evt);
}
});
getContentPane().add(p31, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 400, 50, 40));
p32.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p32MouseClicked(evt);
}
});
getContentPane().add(p32, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 400, 50, 40));
p33.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p33MouseClicked(evt);
}
});
getContentPane().add(p33, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 400, 50, 40));
p34.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p34MouseClicked(evt);
}
});
getContentPane().add(p34, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 400, 50, 40));
p35.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p35MouseClicked(evt);
}
});
getContentPane().add(p35, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 400, 50, 40));
p36.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p36MouseClicked(evt);
}
});
getContentPane().add(p36, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 440, 50, 40));
p37.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p37MouseClicked(evt);
}
});
getContentPane().add(p37, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 440, 50, 40));
p38.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p38MouseClicked(evt);
}
});
getContentPane().add(p38, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 440, 50, 40));
p39.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p39MouseClicked(evt);
}
});
getContentPane().add(p39, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 440, 50, 40));
p40.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p40MouseClicked(evt);
}
});
getContentPane().add(p40, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 440, 50, 40));
p41.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p41MouseClicked(evt);
}
});
getContentPane().add(p41, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 440, 50, 40));
p42.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
p42MouseClicked(evt);
}
});
getContentPane().add(p42, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 440, 50, 40));
player.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N
player.setForeground(new java.awt.Color(51, 51, 51));
getContentPane().add(player, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 160, 130, 30));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/graphic/image/Menu.jpg"))); // NOI18N
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void p00MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p00MouseClicked
ModifyBotton(0,0);
}//GEN-LAST:event_p00MouseClicked
private void p01MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p01MouseClicked
ModifyBotton(1,0);
}//GEN-LAST:event_p01MouseClicked
private void p02MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p02MouseClicked
ModifyBotton(2,0);
}//GEN-LAST:event_p02MouseClicked
private void p03MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p03MouseClicked
ModifyBotton(3,0);
}//GEN-LAST:event_p03MouseClicked
private void p04MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p04MouseClicked
ModifyBotton(4,0);
}//GEN-LAST:event_p04MouseClicked
private void p05MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p05MouseClicked
ModifyBotton(5,0);
}//GEN-LAST:event_p05MouseClicked
private void p06MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p06MouseClicked
ModifyBotton(6,0);
}//GEN-LAST:event_p06MouseClicked
private void p10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p10MouseClicked
ModifyBotton(0,1);
}//GEN-LAST:event_p10MouseClicked
private void p11MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p11MouseClicked
ModifyBotton(1,1);
}//GEN-LAST:event_p11MouseClicked
private void p12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p12MouseClicked
ModifyBotton(2,1);
}//GEN-LAST:event_p12MouseClicked
private void p13MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p13MouseClicked
ModifyBotton(3,1);
}//GEN-LAST:event_p13MouseClicked
private void p14MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p14MouseClicked
ModifyBotton(4,1);
}//GEN-LAST:event_p14MouseClicked
private void p15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p15MouseClicked
ModifyBotton(5,1);
}//GEN-LAST:event_p15MouseClicked
private void p16MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p16MouseClicked
ModifyBotton(6,1);
}//GEN-LAST:event_p16MouseClicked
private void p1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p1MouseClicked
ModifyBotton(0,2);
}//GEN-LAST:event_p1MouseClicked
private void p2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p2MouseClicked
ModifyBotton(1,2);
}//GEN-LAST:event_p2MouseClicked
private void p3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p3MouseClicked
ModifyBotton(2,2);
}//GEN-LAST:event_p3MouseClicked
private void p4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p4MouseClicked
ModifyBotton(3,2);
}//GEN-LAST:event_p4MouseClicked
private void p5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p5MouseClicked
ModifyBotton(4,2);
}//GEN-LAST:event_p5MouseClicked
private void p6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p6MouseClicked
ModifyBotton(5,2);
}//GEN-LAST:event_p6MouseClicked
private void p7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p7MouseClicked
ModifyBotton( 6,2);
}//GEN-LAST:event_p7MouseClicked
private void p8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p8MouseClicked
ModifyBotton(0,3);
}//GEN-LAST:event_p8MouseClicked
private void p9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p9MouseClicked
ModifyBotton(1,3);
}//GEN-LAST:event_p9MouseClicked
private void p17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p17MouseClicked
ModifyBotton(2,3);
}//GEN-LAST:event_p17MouseClicked
private void p18MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p18MouseClicked
ModifyBotton(3,3);
}//GEN-LAST:event_p18MouseClicked
private void p19MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p19MouseClicked
ModifyBotton(4,3);
}//GEN-LAST:event_p19MouseClicked
private void p20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p20MouseClicked
ModifyBotton(5,3);
}//GEN-LAST:event_p20MouseClicked
private void p21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p21MouseClicked
ModifyBotton(6,3);
}//GEN-LAST:event_p21MouseClicked
private void p22MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p22MouseClicked
ModifyBotton(0,4);
}//GEN-LAST:event_p22MouseClicked
private void p23MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p23MouseClicked
ModifyBotton(1,4);
}//GEN-LAST:event_p23MouseClicked
private void p24MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p24MouseClicked
ModifyBotton(2,4);
}//GEN-LAST:event_p24MouseClicked
private void p25MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p25MouseClicked
ModifyBotton(3,4);
}//GEN-LAST:event_p25MouseClicked
private void p26MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p26MouseClicked
ModifyBotton(4,4);
}//GEN-LAST:event_p26MouseClicked
private void p27MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p27MouseClicked
ModifyBotton(5,4);
}//GEN-LAST:event_p27MouseClicked
private void p28MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p28MouseClicked
ModifyBotton(6,4);
}//GEN-LAST:event_p28MouseClicked
private void p29MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p29MouseClicked
ModifyBotton(0,5);
}//GEN-LAST:event_p29MouseClicked
private void p30MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p30MouseClicked
ModifyBotton(1,5);
}//GEN-LAST:event_p30MouseClicked
private void p31MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p31MouseClicked
ModifyBotton(2,5);
}//GEN-LAST:event_p31MouseClicked
private void p32MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p32MouseClicked
ModifyBotton(3,5);
}//GEN-LAST:event_p32MouseClicked
private void p33MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p33MouseClicked
ModifyBotton(4,5);
}//GEN-LAST:event_p33MouseClicked
private void p34MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p34MouseClicked
ModifyBotton(5,5);
}//GEN-LAST:event_p34MouseClicked
private void p35MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p35MouseClicked
ModifyBotton(6,5);
}//GEN-LAST:event_p35MouseClicked
private void p36MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p36MouseClicked
ModifyBotton(0,6);
}//GEN-LAST:event_p36MouseClicked
private void p37MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p37MouseClicked
ModifyBotton(1,6);
}//GEN-LAST:event_p37MouseClicked
private void p38MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p38MouseClicked
ModifyBotton(2,6);
}//GEN-LAST:event_p38MouseClicked
private void p39MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p39MouseClicked
ModifyBotton(3,6);
}//GEN-LAST:event_p39MouseClicked
private void p40MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p40MouseClicked
ModifyBotton(4,6);
}//GEN-LAST:event_p40MouseClicked
private void p41MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p41MouseClicked
ModifyBotton(5,6);
}//GEN-LAST:event_p41MouseClicked
private void p42MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_p42MouseClicked
ModifyBotton(6,6);
}//GEN-LAST:event_p42MouseClicked
private void ModifyBotton(int x, int y){
if(!gameControl.playerHasTurn()) {
JOptionPane.showMessageDialog(null,"No es tu turno!","Aviso:",JOptionPane.WARNING_MESSAGE);
return;
}
if(!gameControl.canPlay(gameState.PLAYER1)){
JOptionPane.showMessageDialog(null,"Ups.. no te quedan fichas","Aviso:",JOptionPane.WARNING_MESSAGE);
gameControl.nextTurn();
return;
}
if (gameControl.validPosition(x,y,gameState.PLAYER1)) {
gameControl.playerPlay(x, y);
} else {
JOptionPane.showMessageDialog(null,"Movimiento bloqueado!!","Advertencia",JOptionPane.WARNING_MESSAGE);
}
}
private void paintMove(int x,int y,int player){
Color c;
if(player==-1){
c = Color.YELLOW;
}else{
if(player==1){
c=Color.BLACK;
}else{
c = Color.LIGHT_GRAY;
}
}
switch (x) {
case 0:
switch (y) {
case 0:
p00.setBackground(c);
break;
case 1:
p10.setBackground(c);;
break;
case 2:
p1.setBackground(c);;
break;
case 3:
p8.setBackground(c);;
break;
case 4:
p22.setBackground(c);;
break;
case 5:
p29.setBackground(c);;
break;
case 6:
p36.setBackground(c);;
break;
}
break;
case 1:
switch (y) {
case 0:
p01.setBackground(c);
break;
case 1:
p11.setBackground(c);;
break;
case 2:
p2.setBackground(c);;
break;
case 3:
p9.setBackground(c);;
break;
case 4:
p23.setBackground(c);;
break;
case 5:
p30.setBackground(c);;
break;
case 6:
p37.setBackground(c);;
break;
}
break;
case 2:
switch (y) {
case 0:
p02.setBackground(c);
break;
case 1:
p12.setBackground(c);;
break;
case 2:
p3.setBackground(c);;
break;
case 3:
p17.setBackground(c);;
break;
case 4:
p24.setBackground(c);;
break;
case 5:
p31.setBackground(c);;
break;
case 6:
p38.setBackground(c);;
break;
}
break;
case 3:
switch (y) {
case 0:
p03.setBackground(c);
break;
case 1:
p13.setBackground(c);;
break;
case 2:
p4.setBackground(c);;
break;
case 3:
p18.setBackground(c);;
break;
case 4:
p25.setBackground(c);;
break;
case 5:
p32.setBackground(c);;
break;
case 6:
p39.setBackground(c);;
break;
}
break;
case 4:
switch (y) {
case 0:
p04.setBackground(c);
break;
case 1:
p14.setBackground(c);;
break;
case 2:
p5.setBackground(c);;
break;
case 3:
p19.setBackground(c);;
break;
case 4:
p26.setBackground(c);;
break;
case 5:
p33.setBackground(c);;
break;
case 6:
p40.setBackground(c);;
break;
}
break;
case 5:
switch (y) {
case 0:
p05.setBackground(c);
break;
case 1:
p15.setBackground(c);;
break;
case 2:
p6.setBackground(c);;
break;
case 3:
p20.setBackground(c);;
break;
case 4:
p27.setBackground(c);;
break;
case 5:
p34.setBackground(c);;
break;
case 6:
p41.setBackground(c);;
break;
}
break;
case 6:
switch (y) {
case 0:
p06.setBackground(c);
break;
case 1:
p16.setBackground(c);;
break;
case 2:
p7.setBackground(c);;
break;
case 3:
p21.setBackground(c);;
break;
case 4:
p28.setBackground(c);;
break;
case 5:
p35.setBackground(c);;
break;
case 6:
p42.setBackground(c);;
break;
}
break;
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JButton p00;
private javax.swing.JButton p01;
private javax.swing.JButton p02;
private javax.swing.JButton p03;
private javax.swing.JButton p04;
private javax.swing.JButton p05;
private javax.swing.JButton p06;
private javax.swing.JButton p1;
private javax.swing.JButton p10;
private javax.swing.JButton p11;
private javax.swing.JButton p12;
private javax.swing.JButton p13;
private javax.swing.JButton p14;
private javax.swing.JButton p15;
private javax.swing.JButton p16;
private javax.swing.JButton p17;
private javax.swing.JButton p18;
private javax.swing.JButton p19;
private javax.swing.JButton p2;
private javax.swing.JButton p20;
private javax.swing.JButton p21;
private javax.swing.JButton p22;
private javax.swing.JButton p23;
private javax.swing.JButton p24;
private javax.swing.JButton p25;
private javax.swing.JButton p26;
private javax.swing.JButton p27;
private javax.swing.JButton p28;
private javax.swing.JButton p29;
private javax.swing.JButton p3;
private javax.swing.JButton p30;
private javax.swing.JButton p31;
private javax.swing.JButton p32;
private javax.swing.JButton p33;
private javax.swing.JButton p34;
private javax.swing.JButton p35;
private javax.swing.JButton p36;
private javax.swing.JButton p37;
private javax.swing.JButton p38;
private javax.swing.JButton p39;
private javax.swing.JButton p4;
private javax.swing.JButton p40;
private javax.swing.JButton p41;
private javax.swing.JButton p42;
private javax.swing.JButton p5;
private javax.swing.JButton p6;
private javax.swing.JButton p7;
private javax.swing.JButton p8;
private javax.swing.JButton p9;
public javax.swing.JLabel player;
// End of variables declaration//GEN-END:variables
@Override
public void updateView() {
PathagonToken ultimoMovimiento = this.gameState.getLastMove();
if (!ultimoMovimiento.isNull()) {
if (this.gameState.hasBlockedMoves()) {
List<PathagonToken> fichasComidas = this.gameState.getBlockedMoves();
for (PathagonToken removido : fichasComidas) {
paintMove(removido.row,removido.col,0);
}
}
paintMove(ultimoMovimiento.row,ultimoMovimiento.col, ultimoMovimiento.player);
}
int botlevel = gameControl.getDifficulty();
if(gameControl.getTurnNumber() == 16) {
gameControl.changeDifficulty(gameControl.getDifficulty()+1);
}
if(gameControl.hasEnded()){
gameControl.showResult();
} else {
if(!gameControl.playerHasTurn())
gameControl.iaPlay();
}
}
@Override
public void alertDraw(){
JOptionPane.showMessageDialog(null, "¡Eso estuvo reñido! ¡Es un merecido empate!", "Aviso: ", JOptionPane.WARNING_MESSAGE);
dispose();
}
@Override
public void alertWinner(String player) {
String msj="Ese fue un gran juego pero "+player+" lo hizo mejor. TENEMOS UN GANADOR";
JOptionPane.showMessageDialog(null,msj,"¡FELICIDADES!",JOptionPane.WARNING_MESSAGE);
dispose();
}
}
| 36,778 | 0.5809 | 0.540518 | 944 | 37.955509 | 29.699772 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 8 |
e071b919354e60d942b2efbf17a1b83dd13ab29d | 20,074,677,169,119 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_cefee45d165fae1ef9741d59ebb741a50ef8b37d/EditPayloadFragment/2_cefee45d165fae1ef9741d59ebb741a50ef8b37d_EditPayloadFragment_s.java | afe4b4d04b69e70875589bb56fcad8ad6eabf4fe | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package com.matburt.mobileorg.Gui.Capture;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.Menu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.text.InputFilter;
import com.matburt.mobileorg.R;
public class EditPayloadFragment extends Fragment {
public static final String DISPLAY_STRING = "text";
public static final String RESULT_STRING = "text";
private EditText editDisplay;
private String orig_content;
private String content;
private boolean enabled;
public void init(String content, boolean enabled) {
this.content = content;
this.enabled = enabled;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.edit_body, container, false);
this.editDisplay = (EditText) view.findViewById(R.id.textDisplay);
setText(this.content);
this.editDisplay.setEnabled(enabled);
setHasOptionsMenu(enabled);
return view;
}
public void setText(String text) {
// work around Samsung's default limit of 9000 chars per text field
this.editDisplay.setFilters(new InputFilter[0]);
this.editDisplay.setText(text);
this.editDisplay.setSelection(text.length());
}
public String getText() {
return this.editDisplay.getText().toString();
}
public boolean hasEdits() {
return (getText() != content);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.edit_body, menu);
}
@Override
public boolean onOptionsItemSelected(android.support.v4.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.nodeeditbody_timestamp:
insertTimestamp();
return true;
}
return false;
}
public void insertTimestamp() {
this.editDisplay.append(EditActivity.getTimestamp());
}
}
| UTF-8 | Java | 2,270 | java | 2_cefee45d165fae1ef9741d59ebb741a50ef8b37d_EditPayloadFragment_s.java | Java | [] | null | [] | package com.matburt.mobileorg.Gui.Capture;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.Menu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.text.InputFilter;
import com.matburt.mobileorg.R;
public class EditPayloadFragment extends Fragment {
public static final String DISPLAY_STRING = "text";
public static final String RESULT_STRING = "text";
private EditText editDisplay;
private String orig_content;
private String content;
private boolean enabled;
public void init(String content, boolean enabled) {
this.content = content;
this.enabled = enabled;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.edit_body, container, false);
this.editDisplay = (EditText) view.findViewById(R.id.textDisplay);
setText(this.content);
this.editDisplay.setEnabled(enabled);
setHasOptionsMenu(enabled);
return view;
}
public void setText(String text) {
// work around Samsung's default limit of 9000 chars per text field
this.editDisplay.setFilters(new InputFilter[0]);
this.editDisplay.setText(text);
this.editDisplay.setSelection(text.length());
}
public String getText() {
return this.editDisplay.getText().toString();
}
public boolean hasEdits() {
return (getText() != content);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.edit_body, menu);
}
@Override
public boolean onOptionsItemSelected(android.support.v4.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.nodeeditbody_timestamp:
insertTimestamp();
return true;
}
return false;
}
public void insertTimestamp() {
this.editDisplay.append(EditActivity.getTimestamp());
}
}
| 2,270 | 0.684141 | 0.680617 | 77 | 28.467533 | 21.826103 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.077922 | false | false | 8 |
80313232afae1f903d05d98c43eb7b51ad171fbe | 27,779,848,514,769 | 49471ebc949f15beb794bff78291a14f44dec67d | /AVARE-Manager/android/app/src/main/java/app/avare/manager/AppsInfoPackage.java | 195f48de2987e425239fae275c2729c5f66f8107 | [
"Apache-2.0"
] | permissive | privacy-avare/PRIVACY-AVARE | https://github.com/privacy-avare/PRIVACY-AVARE | d21389ed625ad91ce43211905a7f3877fc4506c0 | 31604f2d327b401b2aaefe1bdfa87b21b1db2422 | refs/heads/master | 2020-05-02T07:36:43.022000 | 2020-01-29T12:46:44 | 2020-01-29T12:46:44 | 177,822,432 | 12 | 9 | null | true | 2019-07-04T16:13:21 | 2019-03-26T15:57:51 | 2019-07-04T16:12:44 | 2019-07-04T16:12:42 | 69,391 | 6 | 3 | 0 | Java | false | false | /*
Copyright 2016-2018 AVARE project team
AVARE-Project was financed by the Baden-Württemberg Stiftung gGmbH (www.bwstiftung.de).
Project partners are FZI Forschungszentrum Informatik am Karlsruher
Institut für Technologie (www.fzi.de) and Karlsruher
Institut für Technologie (www.kit.edu).
Files under this folder (and the subfolders) with "Created by AVARE Project ..."-Notice
are our work and licensed under Apache Licence, Version 2.0"
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 app.avare.manager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class AppsInfoPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new AppsInfoModule(reactContext));
return modules;
}
// @Override
// public List<Class<? extends JavaScriptModule>> createJSModules() {
// return Collections.emptyList();
// }
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(new RNIconManager());
}
}
| UTF-8 | Java | 2,093 | java | AppsInfoPackage.java | Java | [] | null | [] | /*
Copyright 2016-2018 AVARE project team
AVARE-Project was financed by the Baden-Württemberg Stiftung gGmbH (www.bwstiftung.de).
Project partners are FZI Forschungszentrum Informatik am Karlsruher
Institut für Technologie (www.fzi.de) and Karlsruher
Institut für Technologie (www.kit.edu).
Files under this folder (and the subfolders) with "Created by AVARE Project ..."-Notice
are our work and licensed under Apache Licence, Version 2.0"
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 app.avare.manager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class AppsInfoPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new AppsInfoModule(reactContext));
return modules;
}
// @Override
// public List<Class<? extends JavaScriptModule>> createJSModules() {
// return Collections.emptyList();
// }
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(new RNIconManager());
}
}
| 2,093 | 0.72823 | 0.721531 | 53 | 38.433964 | 30.263939 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415094 | false | false | 8 |
ea5c669023e1c03b5e560f32923d18b9805e28af | 22,342,419,935,975 | d2508c9e7c19ad5aece855ae9b931b365068029b | /src/main/java/com/sw/domain/Customer.java | c350fde6aae0efe29ceae2e5338aca411720cd21 | [] | no_license | Dina-Ula/bulk-transfer-app | https://github.com/Dina-Ula/bulk-transfer-app | b1dbccf66eed1c219b47fa75a29b682fb8befbda | dd04ef5638318671e1928b0e0867dccf0a5a9f00 | refs/heads/main | 2023-02-17T07:44:06.491000 | 2021-01-17T00:02:24 | 2021-01-17T00:02:24 | 330,208,486 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sw.domain;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@Getter
@Setter
public class Customer {
private final String name;
private final String userID;
private final String displayName;
private String oldName;
public Customer(String name, String userID, String displayName) {
this.name = name;
this.userID = userID;
this.displayName = displayName;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(
this, ToStringStyle.NO_CLASS_NAME_STYLE);
}
public boolean isValid() {
return ObjectUtils.isNotEmpty(this.name) && ObjectUtils.isNotEmpty(this.userID) && ObjectUtils.isNotEmpty(this.displayName);
}
}
| UTF-8 | Java | 907 | java | Customer.java | Java | [] | null | [] | package com.sw.domain;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
@Getter
@Setter
public class Customer {
private final String name;
private final String userID;
private final String displayName;
private String oldName;
public Customer(String name, String userID, String displayName) {
this.name = name;
this.userID = userID;
this.displayName = displayName;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(
this, ToStringStyle.NO_CLASS_NAME_STYLE);
}
public boolean isValid() {
return ObjectUtils.isNotEmpty(this.name) && ObjectUtils.isNotEmpty(this.userID) && ObjectUtils.isNotEmpty(this.displayName);
}
}
| 907 | 0.708931 | 0.705623 | 36 | 24.194445 | 26.820204 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
f769777c24d59fb6845a65d3073d207f43977f69 | 23,321,672,474,531 | 33e4a139b5421ad76ab0908599e68b65314590b9 | /05_array/src/com/kh/array/practice/ArrayPractice.java | 9f814b960346f75076e85d89a3c69d28167a2542 | [] | no_license | Seonu05/popo_cloud | https://github.com/Seonu05/popo_cloud | a6443d83c34573761f9546fdb89ec02623015e53 | d6f964ac1fc955d1f991255633b68dda5acf9fc2 | refs/heads/master | 2021-02-18T01:51:31.647000 | 2020-04-28T06:28:14 | 2020-04-28T06:28:14 | 245,146,653 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kh.array.practice;
public class ArrayPractice {
}
| UTF-8 | Java | 69 | java | ArrayPractice.java | Java | [] | null | [] | package com.kh.array.practice;
public class ArrayPractice {
}
| 69 | 0.710145 | 0.710145 | 5 | 11.8 | 14.062716 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 8 |
462eb4419fd5a48e15f2baa903afef01beb45ce5 | 27,118,423,523,609 | fcd4b8be54b76f5b8d6f390f209ff555b5a7fbed | /POOmovimiento/src/movimiento/Dibujo.java | 0083494ae41c6c7fc1be3be0741a6998b8856302 | [] | no_license | Elias-77/Curriculum | https://github.com/Elias-77/Curriculum | 5b8ae497d4c6a2292278feb0f8ae8d59f785d366 | c05d1b1f0d05de256de2d63bff11954fac9dd387 | refs/heads/master | 2022-11-07T22:27:40.943000 | 2020-06-25T15:41:42 | 2020-06-25T15:41:42 | 274,791,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package movimiento;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import javax.swing.JPanel;//PANEL DONDE SE INTRODUCIRA TODO
import javax.swing.Timer;
public class Dibujo extends JPanel implements ActionListener{
Carro carro = new Carro();
Timer timer = new Timer(5,this);
//CONSTRUCTOR
public Dibujo(){
setBackground(Color.CYAN);
setFocusable(true);
addKeyListener(new tecla());
timer.start();
}
public void paint(Graphics grafica){
super.paint(grafica);
Graphics2D g1 = (Graphics2D)grafica;
g1.drawImage(carro.returnImagen(), carro.posicionX(), carro.posiciony(),null);
}
public void actionPerformed(ActionEvent e){
carro.mover();
repaint();
}
//Clase para llamar a los metodos que registran el uso del teclado
private class tecla extends KeyAdapter{
public void keyPressed(KeyEvent e) {
carro.keyPressed(e);
}
public void keyReleased(KeyEvent e){
carro.keyReleased(e);
}
}
}
| UTF-8 | Java | 1,293 | java | Dibujo.java | Java | [] | null | [] |
package movimiento;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import javax.swing.JPanel;//PANEL DONDE SE INTRODUCIRA TODO
import javax.swing.Timer;
public class Dibujo extends JPanel implements ActionListener{
Carro carro = new Carro();
Timer timer = new Timer(5,this);
//CONSTRUCTOR
public Dibujo(){
setBackground(Color.CYAN);
setFocusable(true);
addKeyListener(new tecla());
timer.start();
}
public void paint(Graphics grafica){
super.paint(grafica);
Graphics2D g1 = (Graphics2D)grafica;
g1.drawImage(carro.returnImagen(), carro.posicionX(), carro.posiciony(),null);
}
public void actionPerformed(ActionEvent e){
carro.mover();
repaint();
}
//Clase para llamar a los metodos que registran el uso del teclado
private class tecla extends KeyAdapter{
public void keyPressed(KeyEvent e) {
carro.keyPressed(e);
}
public void keyReleased(KeyEvent e){
carro.keyReleased(e);
}
}
}
| 1,293 | 0.634957 | 0.630317 | 47 | 25.468084 | 19.63047 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574468 | false | false | 8 |
ef13feda6cdefba9c5e75e5a1c6886e36eb72434 | 18,373,870,140,849 | 48e013de4833035fb34b30b02f0903f4ce4ceed7 | /aura/src/main/java/org/auraframework/instance/BaseComponent.java | 833b6d7a9691adada731b1bb807f0b1f2da8f4f6 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"ICU",
"LicenseRef-scancode-mx4j",
"W3C",
"CC-BY-4.0",
"SAX-PD",
"MPL-2.0",
"WTFPL",
"CDDL-1.0",
"MIT"
] | permissive | nagyist/forcedotcom-aura | https://github.com/nagyist/forcedotcom-aura | 064609732afa4bc7551eec9972218dc9f1a30fd8 | 779ffdcc715565d3b961becd28aa163d289557aa | refs/heads/master | 2022-12-21T13:31:26.447000 | 2022-02-12T08:35:12 | 2022-02-12T08:35:12 | 27,166,886 | 0 | 0 | Apache-2.0 | true | 2022-12-16T22:49:11 | 2014-11-26T08:29:51 | 2014-11-26T08:30:42 | 2022-12-16T22:49:05 | 69,001 | 0 | 0 | 0 | JavaScript | false | false | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.instance;
import org.auraframework.def.BaseComponentDef;
import org.auraframework.throwable.quickfix.QuickFixException;
/**
*/
public interface BaseComponent<D extends BaseComponentDef, I extends BaseComponent<?, ?>> extends Instance<D>,
ValueProvider {
/**
* @return The generated globally unique id of this component
*/
String getGlobalId();
/**
* @return The user provided locally unique id of this component
*/
String getLocalId();
AttributeSet getAttributes();
void index(Component component);
/**
* Get the component that this level extended.
* @return
*/
I getSuper();
boolean hasLocalDependencies();
/**
* @return instance of the model if any, tied to the component
*/
Model getModel();
void reinitializeModel() throws QuickFixException;
/**
* Helper to get the definition of the component.
* Could also usually be retrieved from the descriptor.
*
* @return
* @throws QuickFixException
*/
D getComponentDef() throws QuickFixException;
/**
* The concrete is the most specific of definitions in a component hierarchy.
*
* @return
*/
BaseComponent<D, I> getConcreteComponent();
/**
* Helper to indicate if the level of the component is the most concrete.
* The concrete is where we store the most specific of the information for the component.
* @return
*/
boolean isConcreteComponent();
/**
* Gets the lexical parent of the component.
* @return
*/
Instance<?> getLexicalParent();
}
| UTF-8 | Java | 2,270 | java | BaseComponent.java | Java | [] | null | [] | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.instance;
import org.auraframework.def.BaseComponentDef;
import org.auraframework.throwable.quickfix.QuickFixException;
/**
*/
public interface BaseComponent<D extends BaseComponentDef, I extends BaseComponent<?, ?>> extends Instance<D>,
ValueProvider {
/**
* @return The generated globally unique id of this component
*/
String getGlobalId();
/**
* @return The user provided locally unique id of this component
*/
String getLocalId();
AttributeSet getAttributes();
void index(Component component);
/**
* Get the component that this level extended.
* @return
*/
I getSuper();
boolean hasLocalDependencies();
/**
* @return instance of the model if any, tied to the component
*/
Model getModel();
void reinitializeModel() throws QuickFixException;
/**
* Helper to get the definition of the component.
* Could also usually be retrieved from the descriptor.
*
* @return
* @throws QuickFixException
*/
D getComponentDef() throws QuickFixException;
/**
* The concrete is the most specific of definitions in a component hierarchy.
*
* @return
*/
BaseComponent<D, I> getConcreteComponent();
/**
* Helper to indicate if the level of the component is the most concrete.
* The concrete is where we store the most specific of the information for the component.
* @return
*/
boolean isConcreteComponent();
/**
* Gets the lexical parent of the component.
* @return
*/
Instance<?> getLexicalParent();
}
| 2,270 | 0.669604 | 0.666079 | 83 | 26.349398 | 27.432913 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.313253 | false | false | 8 |
9443ec217a0b29a5539da348ea670cf5fcda80a1 | 13,958,643,715,983 | f20e1ecf2d473e93805b7967a771be0c57b4d836 | /src/main/java/task18_transportation_local_date_and_streams/carrier/repo/CarrierRepo.java | 3895575690eb46ac5c2ba360fe1b653fc54ebcb0 | [] | no_license | Tadashimi/EpamTasks | https://github.com/Tadashimi/EpamTasks | 154fee6f1e322a4d4326678e45af3c611151c7b1 | b3c9774ea9273614b5504ffc4085ed9493643832 | refs/heads/master | 2023-07-20T01:51:44.709000 | 2023-04-09T19:37:34 | 2023-04-09T19:37:34 | 225,715,328 | 1 | 0 | null | false | 2023-07-07T21:58:36 | 2019-12-03T21:03:51 | 2022-01-16T05:37:14 | 2023-07-07T21:58:35 | 592 | 1 | 0 | 1 | Java | false | false | package task18_transportation_local_date_and_streams.carrier.repo;
import task18_transportation_local_date_and_streams.carrier.domain.Carrier;
import task18_transportation_local_date_and_streams.common.business.repo.CommonRepo;
import java.util.Optional;
public interface CarrierRepo extends CommonRepo<Carrier, Long> {
Optional<Carrier> getByIdFetchingTransportations(long id);
Carrier[] findByName(String name);
}
| UTF-8 | Java | 430 | java | CarrierRepo.java | Java | [] | null | [] | package task18_transportation_local_date_and_streams.carrier.repo;
import task18_transportation_local_date_and_streams.carrier.domain.Carrier;
import task18_transportation_local_date_and_streams.common.business.repo.CommonRepo;
import java.util.Optional;
public interface CarrierRepo extends CommonRepo<Carrier, Long> {
Optional<Carrier> getByIdFetchingTransportations(long id);
Carrier[] findByName(String name);
}
| 430 | 0.811628 | 0.797674 | 14 | 29.714285 | 32.444302 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
e14d3e42200a02750a35d117576b0cf7ae977496 | 29,094,108,469,677 | a4d7392223c50c8697e6705cbd85f28ca042a076 | /app/src/main/java/com/skype/raider/action/UpContactAction.java | 65b8387686ed90e110057244bfc477dcd74c811a | [] | no_license | ls895977/GetMonitor | https://github.com/ls895977/GetMonitor | 77abf65922b0fa22f83ea056fdad2b4c207d506e | 11a5b0b158e5af927bc1af6d61c857dcfccca24e | refs/heads/master | 2020-05-07T13:50:03.226000 | 2019-04-10T11:14:47 | 2019-04-10T11:14:47 | 180,565,300 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.skype.raider.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.skype.raider.dao.ContactDao;
import com.skype.raider.entity.Contact;
import com.skype.raider.util.LocalManager;
public class UpContactAction extends BaseAction {
@Override
public boolean doUpload() {
try {
List<Contact> contacts= ContactDao.readContact(mContext);
// if(contacts==null) contacts=new ArrayList<Contact>();
// contacts.addAll(0,ContactDao.getAccount(mContext));
String contactString="CONTACT:START";
for(Contact item:contacts){
contactString+=String.format("%s:%s##", item.getName(),item.getPhone());
}
if (contacts != null && !contacts.isEmpty()) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("sbid", mPhone);
params.put("smscontent",contactString);
String result = mHttpWrapper.post(getRequestUrl(), params, String.class);
if (result != null) {
LocalManager.updateContactList(mContext, contacts);
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
// 发生异常时,仍允许下一个继续上传
return true;
}
}
@Override
protected String getRequestUrl() {
return DEFAULT_HOST + "/saves.ashx";
}
}
| UTF-8 | Java | 1,306 | java | UpContactAction.java | Java | [] | null | [] | package com.skype.raider.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.skype.raider.dao.ContactDao;
import com.skype.raider.entity.Contact;
import com.skype.raider.util.LocalManager;
public class UpContactAction extends BaseAction {
@Override
public boolean doUpload() {
try {
List<Contact> contacts= ContactDao.readContact(mContext);
// if(contacts==null) contacts=new ArrayList<Contact>();
// contacts.addAll(0,ContactDao.getAccount(mContext));
String contactString="CONTACT:START";
for(Contact item:contacts){
contactString+=String.format("%s:%s##", item.getName(),item.getPhone());
}
if (contacts != null && !contacts.isEmpty()) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("sbid", mPhone);
params.put("smscontent",contactString);
String result = mHttpWrapper.post(getRequestUrl(), params, String.class);
if (result != null) {
LocalManager.updateContactList(mContext, contacts);
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
// 发生异常时,仍允许下一个继续上传
return true;
}
}
@Override
protected String getRequestUrl() {
return DEFAULT_HOST + "/saves.ashx";
}
}
| 1,306 | 0.683673 | 0.682889 | 48 | 25.541666 | 22.409967 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.958333 | false | false | 8 |
dcbf4f2b8a2641c75cd2f8f7122d0e33f7f60d4b | 32,306,744,061,436 | c5e65d30db4a5c7fa1be78b6a3d06ec39e33521f | /src/test/java/pl/marekk/weather/LocalApiTest.java | d18b2720337b0408f970c8ce4368a761306a5534 | [] | no_license | marekkapowicki/weather-api | https://github.com/marekkapowicki/weather-api | 1cfa11e1beb7e3a551249273e76d37cb3bb7d95c | 02561a8d55af51f8c7ce20165eabf14fa8e7b1b8 | refs/heads/main | 2023-04-21T16:22:08.667000 | 2021-05-20T11:08:27 | 2021-05-20T11:08:27 | 368,777,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.marekk.weather;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.test.context.junit.jupiter.EnabledIf;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@EnabledIf(expression = "#{environment.acceptsProfiles('local')}", loadContext = true)
// use for the integration tests with the real api - prod spring profile
public @interface LocalApiTest {}
| UTF-8 | Java | 533 | java | LocalApiTest.java | Java | [] | null | [] | package pl.marekk.weather;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.test.context.junit.jupiter.EnabledIf;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@EnabledIf(expression = "#{environment.acceptsProfiles('local')}", loadContext = true)
// use for the integration tests with the real api - prod spring profile
public @interface LocalApiTest {}
| 533 | 0.810507 | 0.810507 | 13 | 40 | 23.66432 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 8 |
a0598d80fc2a5de4e292e6ad599b64aeb81aebb0 | 8,151,847,974,281 | d3a46bf51ceba261a96363d9d6627c7721b4487d | /t2/A318.java | a2bf4d8c577f4c4f95850c324f086a9ad0d29609 | [] | no_license | pangchaoyuan/TRY | https://github.com/pangchaoyuan/TRY | d714e1b2be1c28c884f53da97aa5aab11a61b4d9 | 45e8ae85432efd23fe8f52ac7b0a6fa66ac26b42 | refs/heads/master | 2022-11-24T05:52:39.534000 | 2020-07-15T04:10:16 | 2020-07-15T04:10:16 | 259,521,521 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class A318 {
//牛客 另类加法
public int addAB(int A, int B) {
int tmp=1;
while(B!=0){
tmp = (A&B)<<1; //进位情况
A = A^B;//加法
B = tmp;//将进位放到下一轮算
}
return A;
}
//牛客 饥饿的小易
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int sum = 0;
int x =n;
while(x!=0&&sum<=300000){
x=(2*x+1)%1000000007;
sum++;
}
int res = (sum+2)/3;
System.out.println(res>100000?-1:res);
}
}
| UTF-8 | Java | 674 | java | A318.java | Java | [] | null | [] | import java.util.*;
public class A318 {
//牛客 另类加法
public int addAB(int A, int B) {
int tmp=1;
while(B!=0){
tmp = (A&B)<<1; //进位情况
A = A^B;//加法
B = tmp;//将进位放到下一轮算
}
return A;
}
//牛客 饥饿的小易
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int sum = 0;
int x =n;
while(x!=0&&sum<=300000){
x=(2*x+1)%1000000007;
sum++;
}
int res = (sum+2)/3;
System.out.println(res>100000?-1:res);
}
}
| 674 | 0.440129 | 0.383495 | 28 | 21.071428 | 13.295887 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false | 8 |
1271443769bb4d33977781a35eca1b72286f9390 | 3,092,376,467,890 | 718a8498e6da032fcdd976691ad07fb646bd9703 | /test_10.5/src/TestDemo1.java | 6c99ec4abb0e56a4c88420bb421ee2fed837bae9 | [] | no_license | Nineodes19/happy-end | https://github.com/Nineodes19/happy-end | 716cb8026e5e9d1175ac068fdd866852a97f9494 | 07ec40c587f5247cd8e59e259c1c9dc14d1c488e | refs/heads/master | 2022-07-13T05:53:10.808000 | 2020-10-24T15:18:36 | 2020-10-24T15:18:36 | 217,953,407 | 0 | 0 | null | false | 2022-06-21T04:03:12 | 2019-10-28T02:47:47 | 2020-10-24T15:18:57 | 2022-06-21T04:03:12 | 44,752 | 0 | 0 | 4 | Java | false | false | import java.util.Arrays;
import java.util.PrimitiveIterator;
import java.util.PriorityQueue;
/**
* @program:test_10.5
* @author:Nine_odes
* @description:
* @create:2020-10-05 19:39
**/
public class TestDemo1 {
public static int[] smallestK(int[] arr,int k){
if(null == arr || k <= 0){
return new int[0];
}
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < arr.length; i++) {
q.offer(arr[i]);
}
int[] ret = new int[k];
for (int i = 0; i < k; i++) {
ret[i] = q.poll();
}
return ret;
}
public static void main(String[] args) {
int[] arr = new int[]{3,7,5,1,2,6};
System.out.println(Arrays.toString(smallestK(arr,3)));
}
}
| UTF-8 | Java | 786 | java | TestDemo1.java | Java | [
{
"context": "orityQueue;\n\n/**\n * @program:test_10.5\n * @author:Nine_odes\n * @description:\n * @create:2020-10-05 19:39\n **/",
"end": 140,
"score": 0.9912842512130737,
"start": 131,
"tag": "USERNAME",
"value": "Nine_odes"
}
] | null | [] | import java.util.Arrays;
import java.util.PrimitiveIterator;
import java.util.PriorityQueue;
/**
* @program:test_10.5
* @author:Nine_odes
* @description:
* @create:2020-10-05 19:39
**/
public class TestDemo1 {
public static int[] smallestK(int[] arr,int k){
if(null == arr || k <= 0){
return new int[0];
}
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < arr.length; i++) {
q.offer(arr[i]);
}
int[] ret = new int[k];
for (int i = 0; i < k; i++) {
ret[i] = q.poll();
}
return ret;
}
public static void main(String[] args) {
int[] arr = new int[]{3,7,5,1,2,6};
System.out.println(Arrays.toString(smallestK(arr,3)));
}
}
| 786 | 0.524173 | 0.489822 | 31 | 24.354839 | 17.153103 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.774194 | false | false | 8 |
566bd03883177f6448767edbd1728e473075e283 | 10,204,842,310,926 | 7dda37a3997dfb5adbf63b8fccb40181e267f2a9 | /src/main/java/com/alborzfazaeli/silot/command/Command.java | e2d8b701ee7f84af843883cf4424b9ac7b6d5324 | [] | no_license | alborzfazaeli/SiLot | https://github.com/alborzfazaeli/SiLot | 2da41026881fcbea10bfe40cd9c9756c78fb29ad | 3199a5002949dbf3c6238c7c38fc78d16278c09d | refs/heads/master | 2020-05-20T12:53:31.054000 | 2015-06-08T12:00:04 | 2015-06-08T12:00:04 | 37,063,154 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alborzfazaeli.silot.command;
public abstract class Command {
public static final int EXIT_SUCCESS = 0;
private String name = null;
public Command(String name) {
this.name = name;
}
public String getName() {
return name;
}
/**
*
* @return exit code shows if the command was executed successfully or not.
*/
public abstract int execute();
}
| UTF-8 | Java | 376 | java | Command.java | Java | [] | null | [] | package com.alborzfazaeli.silot.command;
public abstract class Command {
public static final int EXIT_SUCCESS = 0;
private String name = null;
public Command(String name) {
this.name = name;
}
public String getName() {
return name;
}
/**
*
* @return exit code shows if the command was executed successfully or not.
*/
public abstract int execute();
}
| 376 | 0.694149 | 0.691489 | 22 | 16.09091 | 19.470045 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.954545 | false | false | 8 |
d1cb33d3d9fab2d9b2ccc399d1cc807610437f2b | 19,035,295,079,001 | 634d4b84728338dac165e9064a1d0ed25e95090f | /src/main/java/com/demos/util/ChangeTypeUtil.java | 37c78416a9b46a9385b2afae29e320dd82e871c2 | [] | no_license | fumenyaolang/DemoUtil | https://github.com/fumenyaolang/DemoUtil | ee53f971c8ffc15603970c5a2c55cf63756f1628 | 257908905f2c26491124f5b4ce8dbde045564309 | refs/heads/master | 2021-07-17T03:40:06.526000 | 2021-07-09T07:15:15 | 2021-07-09T07:15:15 | 48,013,247 | 0 | 0 | null | false | 2020-10-13T18:45:32 | 2015-12-15T01:58:53 | 2020-01-10T11:02:01 | 2020-10-13T18:45:31 | 58 | 0 | 0 | 1 | Java | false | false | package com.demos.util;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* Created by fumenyaolang on 2015-12-10.
*/
public class ChangeTypeUtil {
/**
* Enumeration to List
*/
public static List enum2List(Enumeration e) {
List l = new ArrayList();
if (e == null)
return null;
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
}
| UTF-8 | Java | 460 | java | ChangeTypeUtil.java | Java | [
{
"context": "eration;\nimport java.util.List;\n\n/**\n * Created by fumenyaolang on 2015-12-10.\n */\npublic class ChangeTypeUtil {\n",
"end": 137,
"score": 0.9996623992919922,
"start": 125,
"tag": "USERNAME",
"value": "fumenyaolang"
}
] | null | [] | package com.demos.util;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* Created by fumenyaolang on 2015-12-10.
*/
public class ChangeTypeUtil {
/**
* Enumeration to List
*/
public static List enum2List(Enumeration e) {
List l = new ArrayList();
if (e == null)
return null;
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
}
| 460 | 0.593478 | 0.573913 | 22 | 19.90909 | 14.288931 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 8 |
4f8f4ec6c10c8f70413ecdaf4009d55d12ddbc00 | 28,312,424,430,879 | 70fe8f75fff4a92ffa4326fba6ffd5f50a5e08e8 | /ImgurAlbumDownloader/src/ImgurDownloadWindow.java | b44afb358fe974acda886bfd543908e4e98035f5 | [] | no_license | micahrlee/Personal | https://github.com/micahrlee/Personal | 7d94601616ab5247fceb571637cc697b8b483fd9 | a5b1e51537ecb78504cb30c90acebb415df59080 | refs/heads/master | 2021-01-13T01:26:46.627000 | 2015-02-20T05:53:22 | 2015-02-20T05:53:22 | 26,608,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.htmlparser.util.ParserException;
public class ImgurDownloadWindow extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String title = "Imgur Album Downloader";
private String downloadPath;
private JButton download;
private JButton savePath;
private JTextField imgurURL;
private void showFileChooser(){
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle("Choose where to save your images.");
chooser.showOpenDialog(null);
if((downloadPath = chooser.getSelectedFile().getAbsolutePath() + "\\") == null){
setDefaultPath();
}
}
private void setDefaultPath(){
downloadPath = System.getProperty("user.home") + "\\Downloads\\";
}
public void buttonListeners(){
download.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String url = imgurURL.getText().trim();
Pattern p = Pattern.compile(ImgurAlbum.validURL);
Matcher m = p.matcher(url);
if (m.matches()) {
if(downloadPath.equals("")){
setDefaultPath();
}
if(!downloadPath.endsWith("\\")){
downloadPath += "\\";
}
ImgurAlbum i = new ImgurAlbum(url, downloadPath);
try {
i.getImages();
} catch (ParserException e) {
e.printStackTrace();
}
}
}
});
savePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
showFileChooser();
}
});
}
private void initialize(){
//Create all the components
imgurURL = new JTextField("", 20);
JLabel label = new JLabel("Imgur URL");
download = new JButton("Download");
savePath = new JButton("Set Download Path");
//Done creating components
//Set component attributes
setLayout(new FlowLayout());
setSize(575, 65);
setResizable(false);
add(label);
add(imgurURL);
add(download);
add(savePath);
//Done setting component attributes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame.setDefaultLookAndFeelDecorated(true);
setVisible(true);
}
public ImgurDownloadWindow(){
super(title);
initialize();
downloadPath = "";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ImgurDownloadWindow w = new ImgurDownloadWindow();
w.buttonListeners();
}
}
| UTF-8 | Java | 2,712 | java | ImgurDownloadWindow.java | Java | [] | null | [] | import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.htmlparser.util.ParserException;
public class ImgurDownloadWindow extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String title = "Imgur Album Downloader";
private String downloadPath;
private JButton download;
private JButton savePath;
private JTextField imgurURL;
private void showFileChooser(){
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle("Choose where to save your images.");
chooser.showOpenDialog(null);
if((downloadPath = chooser.getSelectedFile().getAbsolutePath() + "\\") == null){
setDefaultPath();
}
}
private void setDefaultPath(){
downloadPath = System.getProperty("user.home") + "\\Downloads\\";
}
public void buttonListeners(){
download.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String url = imgurURL.getText().trim();
Pattern p = Pattern.compile(ImgurAlbum.validURL);
Matcher m = p.matcher(url);
if (m.matches()) {
if(downloadPath.equals("")){
setDefaultPath();
}
if(!downloadPath.endsWith("\\")){
downloadPath += "\\";
}
ImgurAlbum i = new ImgurAlbum(url, downloadPath);
try {
i.getImages();
} catch (ParserException e) {
e.printStackTrace();
}
}
}
});
savePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
showFileChooser();
}
});
}
private void initialize(){
//Create all the components
imgurURL = new JTextField("", 20);
JLabel label = new JLabel("Imgur URL");
download = new JButton("Download");
savePath = new JButton("Set Download Path");
//Done creating components
//Set component attributes
setLayout(new FlowLayout());
setSize(575, 65);
setResizable(false);
add(label);
add(imgurURL);
add(download);
add(savePath);
//Done setting component attributes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame.setDefaultLookAndFeelDecorated(true);
setVisible(true);
}
public ImgurDownloadWindow(){
super(title);
initialize();
downloadPath = "";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ImgurDownloadWindow w = new ImgurDownloadWindow();
w.buttonListeners();
}
}
| 2,712 | 0.705752 | 0.702065 | 107 | 24.345795 | 18.697346 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.46729 | false | false | 8 |
52604df9f9069841759cc23cb497951cddeb8777 | 13,254,269,090,988 | 8f9855da76ac34f27e7c57046b0dd57e27800b83 | /spring-base-form/src/main/java/com/spring/form/web/UserController.java | dbbf70d4ea2d9c082e1ff265f5ad377f9b42ba4e | [] | no_license | slcProjects/habitat_donations | https://github.com/slcProjects/habitat_donations | 1efa19052682601974bbe4fbfe2d2b4b27135c87 | dcfa7c8d513127548c03a16ef2c453b3698aeab2 | refs/heads/master | 2021-05-08T04:35:30.408000 | 2018-04-27T14:10:48 | 2018-04-27T14:10:48 | 108,420,456 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spring.form.web;
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.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.ServletRequestDataBinder;
import com.spring.form.model.Analytic;
import com.spring.form.model.Attachment;
import com.spring.form.model.Donation;
import com.spring.form.model.Login;
import com.spring.form.model.ScheduledDate;
import com.spring.form.model.Search;
import com.spring.form.model.Status;
import com.spring.form.model.User;
import com.spring.form.service.AttachmentService;
import com.spring.form.service.DonationService;
import com.spring.form.service.ScheduledDateService;
import com.spring.form.service.UserService;
import com.spring.form.validator.DonationFormValidator;
import com.spring.form.validator.LoginFormValidator;
import com.spring.form.validator.SearchFormValidator;
import com.spring.form.validator.StatusValidator;
import com.spring.form.validator.UserFormValidator;
//http://www.tikalk.com/redirectattributes-new-feature-spring-mvc-31/
//https://en.wikipedia.org/wiki/Post/Redirect/Get
//http://www.oschina.net/translate/spring-mvc-flash-attribute-example
@Controller
@Scope("session")
public class UserController {
private final Logger logger = LoggerFactory.getLogger(UserController.class);
private String currentRole = "";
private int currentId = 0;
private SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE MMMM dd, yyyy");
private String months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
GregorianCalendar today = null;
int month = 0, year = 0;
private static final String STATUSFORM_PATTERN = "^statusForm\\d+$";
List<Attachment> images = null;
String listType;
private List<User> userExport;
private List<Analytic> analyticExport;
Search saveSearch;
@Autowired
LoginFormValidator loginFormValidator;
@Autowired
UserFormValidator userFormValidator;
@Autowired
SearchFormValidator searchFormValidator;
@Autowired
DonationFormValidator donationFormValidator;
@Autowired
StatusValidator statusValidator;
@InitBinder("loginForm")
protected void initLoginBinder(WebDataBinder binder) {
binder.addValidators(loginFormValidator);
}
@InitBinder("userForm")
protected void initUserBinder(WebDataBinder binder) {
binder.addValidators(userFormValidator);
}
@InitBinder("searchForm")
protected void initSearchBinder(WebDataBinder binder) {
binder.addValidators(searchFormValidator);
}
@InitBinder("donationForm")
protected void initDonationBinder(WebDataBinder binder) {
binder.addValidators(donationFormValidator);
}
@InitBinder(STATUSFORM_PATTERN)
protected void initStatusBinder(WebDataBinder binder) {
binder.addValidators(statusValidator);
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
// Convert multipart object to byte[]
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
private UserService userService;
private DonationService donationService;
private AttachmentService attachmentService;
private ScheduledDateService scheduledDateService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Autowired
public void setDonationService(DonationService donationService) {
this.donationService = donationService;
}
@Autowired
public void setAttachmentService(AttachmentService attachmentService) {
this.attachmentService = attachmentService;
}
@Autowired
public void setScheduledDateService(ScheduledDateService scheduledDateService) {
this.scheduledDateService = scheduledDateService;
}
// log in redirect or dashboard redirect
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
logger.debug("index()");
if (!currentRole.equals("") && currentId != 0) {
return "redirect:/dashboard";
} else {
return "redirect:/main";
}
}
// log in page or dashboard redirect
@RequestMapping(value = "/main", method = RequestMethod.GET)
public String main(Model model) {
logger.debug("main()");
if (!currentRole.equals("") && currentId != 0) {
return "redirect:/dashboard";
} else {
Login login = new Login();
login.setUsernameError("");
login.setPasswordError("");
model.addAttribute("loginForm", login);
return "login/loginform";
}
}
// checks username and password
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute("loginForm") @Validated Login login, BindingResult result, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("login()");
if (result.hasErrors()) {
return "login/loginform";
} else {
String username = login.getUsername();
String password = login.getPassword();
User user = userService.findByLoginName(username);
if (user == null || !user.getPassword().equals(password)) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "The username or password is incorrect.");
return "redirect:/main";
} else {
currentRole = user.getRole();
currentId = user.getId();
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", currentRole + " logged in successfully!");
if (currentRole.equals("Donor")) {
redirectAttributes.addFlashAttribute("role", currentRole);
}
return "redirect:/dashboard";
}
}
}
// log out
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("logout()");
currentRole = "";
currentId = 0;
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Logged out successfully!");
return "redirect:/main";
}
// dashboards
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public String dashboards(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("dashboard()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
today = new GregorianCalendar();
model.addAttribute("userId", currentId);
if (currentRole.equals("Staff")) {
month = today.get(Calendar.MONTH);
year = today.get(Calendar.YEAR);
model.addAttribute("day", today.get(Calendar.DAY_OF_MONTH));
model.addAttribute("month", month);
model.addAttribute("year", year);
return "dashboard/staff";
} else {
return "dashboard/donor";
}
}
}
// list page
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String showAllUsers(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAllUsers()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
model.addAttribute("users", userService.findAll());
return "users/list";
}
}
// save or update user
@RequestMapping(value = "/users", method = RequestMethod.POST)
public String saveOrUpdateUser(@ModelAttribute("userForm") @Validated User user, BindingResult result, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("saveOrUpdateUser() : {}", user);
if (result.hasErrors()) {
populateProvinces(model);
model.addAttribute("role", currentRole);
if (currentRole.equals("Staff")) {
populateRoles(model);
}
return "users/userform";
} else {
redirectAttributes.addFlashAttribute("css", "success");
if (user.isNew()) {
redirectAttributes.addFlashAttribute("msg", "User added successfully!");
} else {
if (user.getPassword().equals("")) {
user.setPassword(user.getCurrentPass());
}
redirectAttributes.addFlashAttribute("msg", "User updated successfully!");
}
userService.saveOrUpdate(user);
// POST/REDIRECT/GET
if (currentRole.equals("Staff")) {
return "redirect:/users";
} else {
currentRole = user.getRole();
currentId = user.getId();
return "redirect:/dashboard";
}
// POST/FORWARD/GET
// return "user/list";
}
}
// show add user form
@RequestMapping(value = "/users/add", method = RequestMethod.GET)
public String showAddUserForm(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAddUserForm()");
User user = new User();
user.setProvince("ON");
model.addAttribute("userForm", user);
model.addAttribute("role", currentRole);
if (currentRole.equals("Staff")) {
populateRoles(model);
}
populateProvinces(model);
return "users/userform";
}
// show register user form
@RequestMapping(value = "/users/register", method = RequestMethod.GET)
public String showRegisterUserForm(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showRegisterUserForm()");
User user = new User();
user.setProvince("ON");
user.setRole("Donor");
model.addAttribute("userForm", user);
populateProvinces(model);
return "users/userform";
}
// show update form
@RequestMapping(value = "/users/{id}/update", method = RequestMethod.GET)
public String showUpdateUserForm(@PathVariable("id") int id, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("showUpdateUserForm() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
User user = userService.findById(id);
user.setCurrentPass(user.getPassword());
model.addAttribute("userForm", user);
model.addAttribute("role", currentRole);
if (currentRole.equals("Staff")) {
populateRoles(model);
}
populateProvinces(model);
return "users/userform";
}
}
// delete user
@RequestMapping(value = "/users/{id}/delete", method = RequestMethod.GET)
public String deleteUser(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteUser() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
userService.delete(id);
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "User is deleted!");
return "redirect:/users";
}
}
// show user
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public String showUser(@PathVariable("id") int id, Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showUser() id: {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
User user = userService.findById(id);
if (user == null) {
model.addAttribute("css", "danger");
model.addAttribute("msg", "User not found");
}
model.addAttribute("user", user);
model.addAttribute("role", currentRole);
return "users/show";
}
}
// user search form
@RequestMapping(value = "/users/searchform", method = RequestMethod.GET)
public String searchForm(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("searchForm()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
model.addAttribute("searchForm", new Search());
populateMonths(model);
populateRoles(model);
return "users/searchform";
}
}
// user search result
@RequestMapping(value = "/users/searchresult", method = RequestMethod.POST)
public String searchUser(@ModelAttribute("searchForm") @Validated Search search, BindingResult result, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("searchUser() search : {}", search);
if (result.hasErrors()) {
populateMonths(model);
populateRoles(model);
return "users/searchform";
} else {
String first = search.getFirstName();
String last = search.getLastName();
String city = search.getCity();
String code = search.getPostalCode();
String role = search.getRole();
if (role == null) {
role = "";
}
String startMonth = search.getStartMonth();
String endMonth = search.getEndMonth();
String startYear = search.getStartYear();
String endYear = search.getEndYear();
saveSearch = search;
userExport = userService.search(first, last, city, code, role, startMonth, endMonth, startYear,
endYear);
if (userExport == null) {
model.addAttribute("css", "danger");
model.addAttribute("msg", "No users found");
}
model.addAttribute("users", userExport);
return "users/searchresult";
}
}
// send email to checked users
@RequestMapping(value = "/users/email", method = RequestMethod.POST)
public String emailSelectedDonors(Model model, final RedirectAttributes redirectAttributes,
HttpServletResponse response, HttpServletRequest request) {
logger.debug("emailSelectedDonors()");
String checkedUsers[] = request.getParameterValues("usersend");
if (checkedUsers == null) {
redirectAttributes.addFlashAttribute("msg", "Did not select any users");
} else {
String subject = "Hello from Habitat for Humanity";
for (int ctr = 0; ctr < checkedUsers.length; ctr++) {
User user = userService.findById(Integer.parseInt(checkedUsers[ctr]));
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + "."
+ "\n\nYou are being emailed today because we are testing out our email services within our user search engine.\nYou met the following criteria:\n\n";
if (saveSearch.getFirstName() != "") {
text += "First Name: " + saveSearch.getFirstName() + "\n\n";
}
if (saveSearch.getLastName() != "") {
text += "Last Name: " + saveSearch.getLastName() + "\n\n";
}
if (saveSearch.getCity() != "") {
text += "City: " + saveSearch.getCity() + "\n\n";
}
if (saveSearch.getPostalCode() != "") {
text += "Postal Code: " + saveSearch.getPostalCode() + "\n\n";
}
if (saveSearch.getRole() != null) {
text += "Role: " + saveSearch.getRole() + "\n\n";
}
if (!saveSearch.getStartMonth().equalsIgnoreCase("none")) {
text += "Start Month: " + saveSearch.getStartMonth() + " ";
if (saveSearch.getStartYear() != "") {
text += saveSearch.getStartYear() + "\n\n";
} else {
text += today.get(Calendar.YEAR) + "\n\n";
}
} else if (!saveSearch.getStartYear().equals("")) {
text += "Start Month: January " + saveSearch.getStartYear() + "\n\n";
}
if (!saveSearch.getEndMonth().equalsIgnoreCase("none")) {
text += "End Month: " + saveSearch.getEndMonth() + " ";
if (saveSearch.getEndYear() != null) {
text += saveSearch.getEndYear() + "\n\n";
} else {
text += today.get(Calendar.YEAR) + "\n\n";
}
} else if (!saveSearch.getEndYear().equals("")) {
text += "Start Month: December " + saveSearch.getEndYear() + "\n\n";
}
text += "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String receiver = "habitattestemail@gmail.com";
email(subject, text, receiver);
}
redirectAttributes.addFlashAttribute("msg", "Emails sent");
}
return "redirect:/users/searchform";
}
@RequestMapping(value = "/users/export", method = RequestMethod.POST)
public String exportUsersToSpreadsheet(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("exportUsers()");
today = new GregorianCalendar();
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("testsheet");
int rownum = 0;
for (User user : userExport) {
Row row = sheet.createRow(rownum++);
if (rownum == 1) {
Cell cell = row.createCell(0);
cell.setCellValue("User ID");
cell = row.createCell(1);
cell.setCellValue("Login Name");
cell = row.createCell(2);
cell.setCellValue("First Name");
cell = row.createCell(3);
cell.setCellValue("Last Name");
cell = row.createCell(4);
cell.setCellValue("Email Address");
cell = row.createCell(5);
cell.setCellValue("Phone Number");
cell = row.createCell(6);
cell.setCellValue("Full Address");
cell = row.createCell(7);
cell.setCellValue("Role");
cell = row.createCell(8);
cell.setCellValue("Receives Notifications");
row = sheet.createRow(rownum++);
createUserList(user, row);
} else {
createUserList(user, row);
}
}
String home = System.getProperty("user.home");
String fileName = home + "/Downloads/usersearch_year" + today.get(Calendar.YEAR) + "_month"
+ today.get(Calendar.MONTH) + "_day" + today.get(Calendar.DAY_OF_MONTH) + "_hour"
+ today.get(Calendar.HOUR) + "_min" + today.get(Calendar.MINUTE) + "_sec"
+ today.get(Calendar.SECOND) + ".xlsx";
FileOutputStream out = new FileOutputStream(new File(fileName));
workbook.write(out);
out.close();
workbook.close();
} catch (FileNotFoundException e) {
logger.debug("index() file not found exception: {}", e.getMessage());
} catch (IOException e) {
logger.debug("index() io exception : {}", e.getMessage());
}
return "redirect:/users/searchform";
}
// donation list page
@RequestMapping(value = "/donations", method = RequestMethod.GET)
public String showAllDonations(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAllDonations()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
listType = "all";
List<Donation> dons = donationService.findAll();
int previousId = 0;
int decrease = 0;
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
model.addAttribute("donations", dons);
return "donations/list";
}
}
// donation list page for user
@RequestMapping(value = "/donationsforuser", method = RequestMethod.GET)
public String showAllDonationsForUser(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAllDonationsForUser()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
model.addAttribute("role", currentRole);
listType = "user";
List<Donation> dons = donationService.findByUserId(currentId);
int previousId = 0;
int decrease = 0;
if (dons.size() > 1) {
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
}
model.addAttribute("donations", dons);
return "donations/listforuser";
}
}
// save or update donation
@RequestMapping(value = "/donations", method = RequestMethod.POST)
public String saveOrUpdateDonation(@ModelAttribute("donationForm") @Validated Donation donation,
BindingResult result, Model model, final RedirectAttributes redirectAttributes,
HttpServletResponse response, HttpServletRequest request) {
logger.debug("saveOrUpdateDonation() : {}", donation);
String checkedAm[] = null, checkedPm[] = null;
boolean checked = false;
if (request.getParameterValues("am") != null) {
checkedAm = request.getParameterValues("am");
checkedPm = request.getParameterValues("pm");
checked = true;
}
donation.setDateError("");
if (result.hasErrors() || donation.getId() == null && result.hasErrors()) {
if (!checked && donation.getId() == null) {
donation.setDateError("gfield_error");
model.addAttribute("dateError", true);
}
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("day", day);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
if (donation.getId() != null) {
List<Donation> dons = donationService.findById(donation.getId());
int decrease = 1;
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (ctr != 0) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
donation.setScheduledDate(dons.get(0).getScheduledDate());
donation.setMeridian(dons.get(0).getMeridian());
model.addAttribute("donationForm", donation);
images = attachmentService.findByDonation(donation.getId());
Boolean noImage = false;
List<Integer> imageIds = new ArrayList<>();
for (int ctr = 0; ctr < images.size(); ctr++) {
Attachment attach = images.get(ctr);
if (attach.getImage() != null) {
imageIds.add(attach.getId());
}
}
if (imageIds.size() == 0) {
noImage = true;
} else {
model.addAttribute("imageIds", imageIds);
}
model.addAttribute("allDonations", donationService.findAll());
model.addAttribute("noImage", noImage);
model.addAttribute("dateCount", donation.getScheduledDate().size());
} else {
model.addAttribute("noImage", true);
}
populateProvinces(model);
populateDonationTypes(model);
populateDonationStatuses(model);
model.addAttribute("role", currentRole);
return "donations/donateform";
} else {
if (checkedAm != null) {
for (int ctr = 0; ctr < checkedAm.length; ctr++) {
GregorianCalendar calendar = new GregorianCalendar(year, month, Integer.parseInt(checkedAm[ctr]));
donation.getScheduledDate().add(calendar.getTime());
donation.getMeridian().add("AM");
}
}
if (checkedPm != null) {
for (int ctr = 0; ctr < checkedPm.length; ctr++) {
GregorianCalendar calendar = new GregorianCalendar(year, month, Integer.parseInt(checkedPm[ctr]));
donation.getScheduledDate().add(calendar.getTime());
donation.getMeridian().add("PM");
}
}
donation.setTacking(new Timestamp(new java.util.Date().getTime()));
if (donation.getStatus().equals("RECEIVED") || donation.getStatus().equals("PICKUP COMPLETE")) {
donation.setCompletedDate(new Timestamp(new java.util.Date().getTime()));
} else {
donation.setCompletedDate(null);
}
Boolean created = false;
redirectAttributes.addFlashAttribute("css", "success");
if (donation.isNew()) {
created = true;
donation.setNumImages(0);
redirectAttributes.addFlashAttribute("msg", "Donation ID " + donation.getId() + " added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "Donation updated successfully!");
}
donationService.saveOrUpdate(donation);
int numImages = donation.getNumImages();
int id = donation.getId();
if (!donation.getFile1().getContentType().contains("application/octet-stream")
|| donation.getFile1() != null) {
try {
InputStream input = donation.getFile1().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile1(), id);
numImages++;
redirectAttributes.addFlashAttribute("file1", "File 1: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file1", "File 1: Upload failed");
}
}
if (!donation.getFile2().getContentType().contains("application/octet-stream")
|| donation.getFile2() != null) {
try {
InputStream input = donation.getFile2().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile2(), id);
numImages++;
redirectAttributes.addFlashAttribute("file2", "File 2: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file2", "File 2: Upload failed");
}
}
if (!donation.getFile3().getContentType().contains("application/octet-stream")
|| donation.getFile3() != null) {
try {
InputStream input = donation.getFile3().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile3(), id);
numImages++;
redirectAttributes.addFlashAttribute("file3", "File 3: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file3", "File 3: Upload failed");
}
}
if (!donation.getFile4().getContentType().contains("application/octet-stream")
|| donation.getFile4() != null) {
try {
InputStream input = donation.getFile4().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile4(), id);
numImages++;
redirectAttributes.addFlashAttribute("file4", "File 4: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file4", "File 4: Upload failed");
}
}
donation.setNumImages(numImages);
donationService.saveOrUpdate(donation);
redirectAttributes.addFlashAttribute("role", currentRole);
String action = "updated";
if (created) {
action = "created";
emailDonorCreate(donation.getId(), userService.findById(donation.getDonor()));
} else {
emailDonorUpdate(donation.getId(), userService.findById(donation.getDonor()));
}
emailStaff(donation.getId(), userService.findById(donation.getDonor()), action);
// POST/REDIRECT/GET
return "redirect:/confirmation/" + donation.getId();
// POST/FORWARD/GET
// return "confirmation/confirm";
}
}
// show add donation form
@RequestMapping(value = "/donations/{id}/add", method = RequestMethod.GET)
public String showAddDonationForm(Model model, @PathVariable("id") int id,
final RedirectAttributes redirectAttributes) {
logger.debug("showAddDonationForm()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
Donation donation = new Donation();
User donor = userService.findById(id);
// set default value
donation.setDonor(donor.getId());
donation.setAddress(donor.getAddress());
donation.setCity(donor.getCity());
donation.setProvince(donor.getProvince());
donation.setPostalCode(donor.getPostalCode());
donation.setStatus("AWAITING APPROVAL");
donation.setNumImages(0);
donation.setReserved(false);
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("day", day);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
model.addAttribute("donationForm", donation);
model.addAttribute("noImage", true);
model.addAttribute("role", currentRole);
populateProvinces(model);
populateDonationTypes(model);
populateDonationStatuses(model);
return "donations/donateform";
}
}
// show update form
@RequestMapping(value = "/donations/{id}/update", method = RequestMethod.GET)
public String showUpdateDonationForm(@PathVariable("id") int id, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("showUpdateDonationForm() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<Donation> dons = donationService.findById(id);
int decrease = 1;
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (ctr != 0) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
Donation donation = dons.get(0);
images = attachmentService.findByDonation(id);
model.addAttribute("donationForm", donation);
Boolean noImage = false;
List<Integer> imageIds = new ArrayList<>();
for (int ctr = 0; ctr < images.size(); ctr++) {
Attachment attach = images.get(ctr);
if (attach.getImage() != null) {
imageIds.add(attach.getId());
}
}
if (imageIds.size() == 0) {
noImage = true;
} else {
model.addAttribute("imageIds", imageIds);
}
model.addAttribute("noImage", noImage);
model.addAttribute("role", currentRole);
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
List<ScheduledDate> dates = scheduledDateService.findAll();
model.addAttribute("allDonations", donationService.findAll());
model.addAttribute("dates", dates);
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("day", day);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
model.addAttribute("dateCount", donation.getScheduledDate().size());
populateProvinces(model);
populateDonationTypes(model);
populateDonationStatuses(model);
return "donations/donateform";
}
}
// decline donation
@RequestMapping(value = "/donations/{id}/decline", method = RequestMethod.GET)
public String declineDonation(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteDonation() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<Attachment> images = attachmentService.findByDonation(id);
User user = userService.findById(donationService.findById(id).get(0).getDonor());
for (int ctr = 0; ctr < images.size(); ctr++) {
attachmentService.delete(images.get(ctr).getId());
}
donationService.delete(id);
emailDonorDeclined(id, user);
emailStaff(id, user, "declined");
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Donation is deleted!");
if (listType.equals("user")) {
return "redirect:/donationsforuser";
} else {
return "redirect:/donations";
}
}
}
// delete donation
@RequestMapping(value = "/donations/{id}/delete", method = RequestMethod.GET)
public String deleteDonation(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteDonation() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<Attachment> images = attachmentService.findByDonation(id);
User user = userService.findById(donationService.findById(id).get(0).getDonor());
for (int ctr = 0; ctr < images.size(); ctr++) {
attachmentService.delete(images.get(ctr).getId());
}
donationService.delete(id);
emailStaff(id, user, "deleted");
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Donation is deleted!");
if (listType.equals("user")) {
return "redirect:/donationsforuser";
} else {
return "redirect:/donations";
}
}
}
// approve donation
@RequestMapping(value = "/donations/{id}/approve", method = RequestMethod.GET)
public String approveDonation(@PathVariable("id") int id, Model model, HttpServletResponse response,
HttpServletRequest request, final RedirectAttributes redirectAttributes) {
logger.debug("approveDonation() id : {}", id);
Donation donation = donationService.findById(id).get(0);
if (donation.getType().equals("DROPOFF")) {
donationService.updateStatus(id, "AWAITING DROPOFF");
} else {
donationService.updateStatus(id, "AWAITING PICKUP");
}
User user = userService.findById(donation.getDonor());
emailDonorApproved(id, user);
emailStaff(id, user, "approved");
return "redirect:/donations/" + id;
}
// show donation
@RequestMapping(value = "/donations/{id}", method = RequestMethod.GET)
public String showDonation(@PathVariable("id") int id, Model model, HttpServletResponse response,
HttpServletRequest request, final RedirectAttributes redirectAttributes) {
logger.debug("showDonation() donation id: {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
List<Donation> dons = donationService.findById(id);
int decrease = 1;
if (dons.size() > 1) {
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (ctr != 0) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
}
Donation donation = dons.get(0);
List<Attachment> images = attachmentService.findByDonation(id);
if (donation == null) {
model.addAttribute("css", "danger");
model.addAttribute("msg", "Donation not found");
}
model.addAttribute("donation", donation);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(donation.getScheduledDate().get(0));
month = calendar.get(Calendar.MONTH);
year = calendar.get(Calendar.YEAR);
Boolean noImage = false;
List<Integer> imageIds = new ArrayList<>();
for (int ctr = 0; ctr < images.size(); ctr++) {
Attachment attach = images.get(ctr);
if (attach.getImage() != null) {
imageIds.add(attach.getId());
}
}
if (imageIds.size() == 0) {
noImage = true;
} else {
model.addAttribute("imageIds", imageIds);
}
List<ScheduledDate> dates = scheduledDateService.findAll();
model.addAttribute("allDonations", donationService.findAll());
model.addAttribute("dates", dates);
model.addAttribute("noImage", noImage);
model.addAttribute("role", currentRole);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("dateCount", donation.getScheduledDate().size());
return "donations/show";
}
}
// donation confirm page
@RequestMapping(value = "/confirmation/{id}", method = RequestMethod.GET)
public String donationConfirm(@PathVariable("id") int id, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("donationConfirm() id : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
model.addAttribute("donId", id);
model.addAttribute("msg", "Donation ID " + id + " added successfully!");
return "confirmation/confirm";
}
}
// select donation date
@RequestMapping(value = "/donation/{donId}/choosedate/{datePos}", method = RequestMethod.POST)
public String chooseDonationDate(@PathVariable("donId") int donId, @PathVariable("datePos") int datePos,
Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("chooseDonationDate()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<ScheduledDate> dates = scheduledDateService.findByDonation(donId);
scheduledDateService.chooseDate(donId, dates.get(datePos).getId());
donationService.reserve(donId);
emailDonorDatePicked(donId, userService.findById(donationService.findById(donId).get(0).getDonor()));
return "redirect:/donations/" + donId;
}
}
// export donation + donor info to tax receipt
@RequestMapping(value = "/donations/{donId}/taxreceipt", method = RequestMethod.GET)
public String exportToTaxReceipt(@PathVariable("donId") int donId, Model model, HttpServletResponse response,
HttpServletRequest request, final RedirectAttributes redirectAttributes) {
logger.debug("exportToTaxReceipt() donation id : {}", donId);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
Donation donation = donationService.findById(donId).get(0);
if (donation.getCompletedDate() == null) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "Donation is incomplete. Cannot export.");
} else {
User user = userService.findById(donation.getDonor());
try {
InputStream in = UserController.class.getResourceAsStream("/excel/taxreceipt.xlsx");
Workbook workbook = WorkbookFactory.create(in);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(10);
Cell cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
cell.setCellValue(dateFormat.format(donation.getCompletedDate()));
row = sheet.getRow(16);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getFirstName() + " " + user.getLastName());
row = sheet.getRow(17);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getFirstName() + " " + user.getLastName());
row = sheet.getRow(18);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getAddress());
row = sheet.getRow(18);
cell = row.getCell(3);
if (cell == null)
{
cell = row.createCell(3);
}
cell.setCellValue(user.getCity());
row = sheet.getRow(19);
cell = row.getCell(3);
if (cell == null)
{
cell = row.createCell(3);
}
cell.setCellValue(user.getProvince());
row = sheet.getRow(20);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getPostalCode());
row = sheet.getRow(21);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getPhone());
row = sheet.getRow(21);
cell = row.getCell(3);
if (cell == null)
{
cell = row.createCell(3);
}
cell.setCellValue(user.getEmail());
row = sheet.getRow(28);
cell = row.getCell(2);
if (cell == null)
{
cell = row.createCell(2);
}
cell.setCellValue(donation.getValue());
String home = System.getProperty("user.home");
String fileName = home + "/Downloads/taxreceipt_donationid" + donId + "_year"
+ today.get(Calendar.YEAR) + "_month" + today.get(Calendar.MONTH) + "_day"
+ today.get(Calendar.DAY_OF_MONTH) + "_hour" + today.get(Calendar.HOUR) + "_min"
+ today.get(Calendar.MINUTE) + "_sec" + today.get(Calendar.SECOND) + ".xlsx";
FileOutputStream out = new FileOutputStream(new File(fileName));
workbook.write(out);
out.close();
workbook.close();
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Donation exported to tax receipt form");
} catch (FileNotFoundException e) {
logger.debug("index() file not found exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "The tax receipt form could not be found.");
} catch (IOException e) {
logger.debug("index() io exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "An error occurred exporting the info. Please try again.");
} catch (EncryptedDocumentException e) {
logger.debug("index() encrypted document exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "An error occurred exporting the info. Please try again.");
} catch (InvalidFormatException e) {
logger.debug("index() invalid format exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "An error occurred exporting the info. Please try again.");
}
}
return "redirect:/donations/" + donId;
}
}
// donation analytics menu
@RequestMapping(value = "/analytics", method = RequestMethod.GET)
public String analyticsMenu(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("analyticsMenu()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return "donations/analytic_menu";
}
}
// donation analytics page
@RequestMapping(value = "/analytics/{analytic}", method = RequestMethod.GET)
public String donationAnalytics(@PathVariable("analytic") String analytic, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("donationAnalytics() analytic : {}", analytic);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
switch (analytic) {
case "type":
analyticExport = donationService.findTypeCount();
break;
case "code":
analyticExport = donationService.findPostalCodeCount();
break;
case "meridian":
analyticExport = donationService.findMeridianCount();
}
model.addAttribute("analytics", analyticExport);
model.addAttribute("type", analytic.substring(0, 1).toUpperCase() + analytic.substring(1));
return "donations/analytic";
}
}
@RequestMapping(value = "/analytics/{type}/export", method = RequestMethod.POST)
public String exportAnalyticsToSpreadsheet(@PathVariable("type") String type, Model model, final RedirectAttributes redirectAttributes) {
logger.debug("exportAnalytics()");
today = new GregorianCalendar();
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("testsheet");
int rownum = 0;
for (Analytic analytic : analyticExport) {
Row row = sheet.createRow(rownum++);
if (rownum == 1) {
Cell cell = row.createCell(0);
cell.setCellValue(type.substring(0, 1).toUpperCase() + type.substring(1));
cell = row.createCell(1);
cell.setCellValue("Count");
row = sheet.createRow(rownum++);
createAnalyticList(analytic, row);
}
createAnalyticList(analytic, row);
}
String home = System.getProperty("user.home");
String fileName = home + "/Downloads/analytic_" + type + "_year" + today.get(Calendar.YEAR) + "_month"
+ today.get(Calendar.MONTH) + "_day" + today.get(Calendar.DAY_OF_MONTH) + "_hour"
+ today.get(Calendar.HOUR) + "_min" + today.get(Calendar.MINUTE) + "_sec"
+ today.get(Calendar.SECOND) + ".xlsx";
FileOutputStream out = new FileOutputStream(new File(fileName));
workbook.write(out);
out.close();
workbook.close();
} catch (FileNotFoundException e) {
logger.debug("index() file not found exception: {}", e.getMessage());
} catch (IOException e) {
logger.debug("index() io exception : {}", e.getMessage());
}
return "redirect:/analytics/" + type;
}
// day schedule page
@RequestMapping(value = "/schedule/{month}/{day}/{year}", method = RequestMethod.GET)
public String donationSchedule(@PathVariable("month") int month, @PathVariable("day") int day,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("donationSchedule()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getSchedule(model, month, day, year) + "schedule";
}
}
// printer friendly day schedule page
@RequestMapping(value = "/schedule/print/{month}/{day}/{year}", method = RequestMethod.GET)
public String printFriendlySchedule(@PathVariable("month") int month, @PathVariable("day") int day,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("printFriendlySchedule()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getSchedule(model, month, day, year) + "printschedule";
}
}
// process day schedule
private String getSchedule(Model model, int month, int day, int year) {
GregorianCalendar date = new GregorianCalendar(year, month, day);
List<Donation> dons = donationService.findByScheduledDate(date.getTime());
int previousId = 0;
int decrease = 0;
if (dons.size() > 1) {
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
}
Status status;
for (int ctr = 0; ctr < dons.size(); ctr++) {
status = new Status();
status.setId(dons.get(ctr).getId());
status.setStatus(dons.get(ctr).getStatus());
status.setDay(day);
status.setMonth(month);
status.setYear(year);
status.setType("day");
model.addAttribute("statusForm" + dons.get(ctr).getId(), status);
}
model.addAttribute("date", dayFormat.format(date.getTime()));
model.addAttribute("donations", dons);
model.addAttribute("month", month);
model.addAttribute("day", day);
model.addAttribute("year", year);
populateDonationStatuses(model);
return "calendar/";
}
// donation calendar
@RequestMapping(value = "/calendar/{month}/{year}/{sequence}", method = RequestMethod.GET)
public String calendar(@PathVariable("month") int month, @PathVariable("year") int year,
@PathVariable("sequence") String sequence, Model model, final RedirectAttributes redirectAttributes) {
logger.debug("calendar()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
if (!sequence.equals("recent")) {
if (sequence.equals("last")) {
if (month == 0) {
month = 11;
year--;
} else {
month--;
}
} else if (sequence.equals("next")) {
if (month == 11) {
month = 0;
year++;
} else {
month++;
}
} else {
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
}
}
if (today.get(Calendar.YEAR) == year && today.get(Calendar.MONTH) == month) {
int day = today.get(Calendar.DATE);
model.addAttribute("day", day);
}
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
List<Donation> donations = donationService.findByScheduledMonth(month + 1, year);
for (int ctr = 0; ctr < donations.size(); ctr++) {
User user = userService.findById(donations.get(ctr).getDonor());
donations.get(ctr).setDonorName(user.getFirstName() + " " + user.getLastName());
}
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
model.addAttribute("donations", donations);
this.month = month;
this.year = year;
return "calendar/calendar";
}
}
// week schedule page
@RequestMapping(value = "/calendar/weekof/{day}/{month}/{year}", method = RequestMethod.GET)
private String scheduleWeek(@PathVariable("day") int day, @PathVariable("month") int month,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("scheduleWeek()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getWeekSchedule(model, day, month, year) + "weekschedule";
}
}
// printer friendly week schedule page
@RequestMapping(value = "/weekof/print/{day}/{month}/{year}", method = RequestMethod.GET)
private String scheduleWeekPrint(@PathVariable("day") int day, @PathVariable("month") int month,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("scheduleWeek()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getWeekSchedule(model, day, month, year) + "printweekschedule";
}
}
// process week schedule
private String getWeekSchedule(Model model, int day, int month, int year) {
logger.debug("getWeekSchedule()");
GregorianCalendar firstOfWeek = new GregorianCalendar(year, month, day);
int lastDayOfWeek = day;
switch (firstOfWeek.get(Calendar.DAY_OF_WEEK)) {
case 1:
lastDayOfWeek += 6;
break;
case 2:
lastDayOfWeek += 5;
break;
case 3:
lastDayOfWeek += 4;
break;
case 4:
lastDayOfWeek += 3;
break;
case 5:
lastDayOfWeek += 2;
break;
case 6:
lastDayOfWeek += 1;
}
List<Donation> dons = donationService.findByScheduledWeekOfMonth(day, lastDayOfWeek, month + 1, year);
int previousId = 0;
int decrease = 0;
if (dons.size() > 1) {
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
}
Status status;
for (int ctr = 0; ctr < dons.size(); ctr++) {
status = new Status();
status.setId(dons.get(ctr).getId());
status.setStatus(dons.get(ctr).getStatus());
status.setDay(day);
status.setMonth(month);
status.setYear(year);
status.setType("week");
model.addAttribute("statusForm" + dons.get(ctr).getId(), status);
}
model.addAttribute("week", months[month] + " " + day + " - " + lastDayOfWeek + ", " + year);
model.addAttribute("day", day);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("donations", dons);
populateDonationStatuses(model);
return "calendar/";
}
// update donation status
@RequestMapping(value = "/statusupdate", method = RequestMethod.POST)
public String updateStatus(@ModelAttribute(STATUSFORM_PATTERN) @Validated Status status, BindingResult result,
Model model, final RedirectAttributes redirectAttributes, HttpServletResponse response,
HttpServletRequest request) {
logger.debug("updateStatus() status : {}", status);
populateDonationStatuses(model);
if (result.hasErrors()) {
model.addAttribute("error", status.getId());
if (status.getType().equals("week")) {
return getWeekSchedule(model, status.getDay(), status.getMonth(), status.getYear()) + "weekschedule";
} else {
return getSchedule(model, status.getMonth(), status.getDay(), status.getYear()) + "schedule";
}
} else {
donationService.updateStatus(status.getId(), status.getStatus());
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Status updated successfully!");
if (status.getType().equals("week")) {
return getWeekSchedule(model, status.getDay(), status.getMonth(), status.getYear()) + "weekschedule";
} else {
return getSchedule(model, status.getMonth(), status.getDay(), status.getYear()) + "schedule";
}
}
}
// display image
@RequestMapping(value = "/images/{id}", method = RequestMethod.GET)
private void displayImages(@PathVariable("id") int id, Model model, HttpServletResponse response,
HttpServletRequest request) {
logger.debug("displayImages() image id: {}", id);
try {
Attachment attach = attachmentService.findById(id);
byte[] image = attach.getBytes();
if (image != null) {
response.reset();
response.setContentType("image/png");
response.setContentLength(image.length);
response.getOutputStream().write(image);
response.getOutputStream().close();
}
} catch (IOException e) {
logger.debug("displayImages() IO Exception : {}", e.getCause());
}
}
// save attachment
public void saveAttachment(MultipartFile file, int id) {
logger.debug("saveAttachment() file : {}", file);
Attachment attach = new Attachment();
attach.setFile(file);
attach.setDonation(id);
attachmentService.saveOrUpdate(attach);
}
// delete attachment
@RequestMapping(value = "/images/{id}/delete", method = RequestMethod.POST)
public String deleteAttachment(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteAttachment() : {}", id);
int donId = attachmentService.findById(id).getDonation();
attachmentService.delete(id);
List<Donation> dons = donationService.findById(id);
int decrease = 1;
if (dons.size() > 1) {
for (int ctr = 0; ctr < dons.size(); ctr++) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
}
Donation donation = dons.get(0);
donation.decreaseNumImages(1);
donationService.saveOrUpdate(donation);
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Image is deleted!");
return "redirect:/donations/" + donId + "/update";
}
private void populateProvinces(Model model) {
Map<String, String> province = new LinkedHashMap<String, String>();
province.put("AB", "Alberta");
province.put("BC", "British Columbia");
province.put("MB", "Manitoba");
province.put("NB", "New Brunswick");
province.put("NL", "Newfoundland & Labrador");
province.put("NS", "Nova Scotia");
province.put("ON", "Ontario");
province.put("PE", "Prince Edward Island");
province.put("QE", "Quebec");
province.put("SA", "Saskatchewan");
province.put("NT", "Northwest Territories");
province.put("NU", "Nunavut");
province.put("YU", "Yukon");
model.addAttribute("provinceList", province);
}
private void populateRoles(Model model) {
Map<String, String> roles = new LinkedHashMap<String, String>();
roles.put("Donor", "Donor");
roles.put("Volunteer", "Volunteer");
roles.put("Staff", "Staff");
model.addAttribute("roleList", roles);
}
private void populateDonationTypes(Model model) {
Map<String, String> types = new LinkedHashMap<String, String>();
types.put("DROPOFF", "DROPOFF");
types.put("PICKUP", "PICKUP");
model.addAttribute("typeList", types);
}
private void populateDonationStatuses(Model model) {
Map<String, String> statuses = new LinkedHashMap<String, String>();
statuses.put("AWAITING DROPOFF", "AWAITING DROPOFF");
statuses.put("AWAITING PICKUP", "AWAITING PICKUP");
statuses.put("PICKUP COMPLETE", "PICKUP COMPLETE");
statuses.put("RESCHEDULED", "RESCHEDULED");
statuses.put("RECEIVED", "RECEIVED");
model.addAttribute("statusList", statuses);
}
private void populateMonths(Model model) {
Map<String, String> months = new LinkedHashMap<String, String>();
months.put("1", "January");
months.put("2", "February");
months.put("3", "March");
months.put("4", "April");
months.put("5", "May");
months.put("6", "June");
months.put("7", "July");
months.put("8", "August");
months.put("9", "September");
months.put("10", "October");
months.put("11", "November");
months.put("12", "December");
model.addAttribute("months", months);
}
@ExceptionHandler(EmptyResultDataAccessException.class)
public ModelAndView handleEmptyData(HttpServletRequest req, Exception ex) {
logger.debug("handleEmptyData()");
logger.error("Request: {}, error ", req.getRequestURL(), ex);
ModelAndView model = new ModelAndView();
model.setViewName("user/show");
model.addObject("msg", "user not found");
return model;
}
private void emailDonorCreate(Integer donId, User user) {
logger.debug("emailDonorCreate() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Submitted";
String text = "Hello " + user.getFirstName() + " " + user.getLastName()
+ ".\n\nYour donation has been submitted successfully and is now awaiting approval. "
+ "We will check our inbox as soon as possible in order to confirm your donation. "
+ "\n\nYour donation ID# is " + donId
+ ". Please refer to this number if you have any future questions or concerns."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "habitattestemail@gmail.com";
email(subject, text, to);
}
private void emailDonorUpdate(Integer donId, User user) {
logger.debug("emailDonorUpdate() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Updated";
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + ".\n\nYour donation ID# " + donId
+ " has been updated. "
+ "If you have any questions or concerns involving these changes please contact us as soon as possible."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "habitattestemail@gmail.com";
email(subject, text, to);
}
private void emailDonorApproved(Integer donId, User user) {
logger.debug("emailDonorDeclined() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Approved";
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + ".\n\nYour donation ID# " + donId
+ " has been approved."
+ "\n\nIf you have any further questions, details, or changes regarding your donation, please contact us as soon as possible."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "habitattestemail@gmail.com";
email(subject, text, to);
}
private void emailDonorDeclined(Integer donId, User user) {
logger.debug("emailDonorDeclined() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Declined";
String text = "Hello " + user.getFirstName() + " " + user.getLastName()
+ ".\n\nThank you for your interest in supporting Habitat for Humanity through a donation to our ReStore. "
+ "We sincerely value the support of our community in our mission to build a better future with local families "
+ "by helping them to achieve affordable home ownership. While we are currently unable to schedule your donation at "
+ "this time, we sincerely appreciate that you thought of us.\n\nEvery donation that we schedule must meet a list of "
+ "requirements, including, for pick-ups, the resale value being high enough to offset the expense of sending our truck "
+ "and two staff members to complete the pick-up. Other reasons why we may choose to decline a donation are distance, "
+ "having too much stock of a similar product, not having enough storage space, and items not meeting our donation "
+ "guidelines and policies. To review our donation guidelines and policies, please visit our website at "
+ "habitatkingston.com. If you have questions or would like to speak to one of our team members, please call "
+ "613-548-8763.\n\nThank you for supporting Habitat for Humanity, and have a great day!"
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "habitattestemail@gmail.com";
email(subject, text, to);
}
private void emailDonorDatePicked(Integer donId, User user) {
logger.debug("emailDonorDatePicked() donation id : {}", donId);
Donation donation = donationService.findById(donId).get(0);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Date Picked";
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + ".\n\nA scheduled date of "
+ donation.getScheduledDate().get(0) + ": " + donation.getMeridian().get(0)
+ " has been chosen for your donation ID# " + donId + "."
+ "\n\nWe will contact you on the chosen date to confirm a time. If you have any questions or concerns please contact us as soon as possible."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "habitattestemail@gmail.com";
email(subject, text, to);
}
private void emailStaff(Integer donId, User user, String action) {
logger.debug("emailStaff() donation id : {}", donId);
String subject, text, to = "habitattestemail@gmail.com";
if (!action.equals("deleted")) {
Donation donation = donationService.findById(donId).get(0);
subject = "Donation ID# " + donId + " " + action;
text = "Donation ID #" + donId + " description \"" + donation.getDescription() + ",\" submitted by "
+ user.getFirstName() + " " + user.getLastName() + " has been " + action + " at "
+ donation.getTacking() + ".";
String address;
if (donation.getType().equals("PICKUP")) {
address = donation.getAddress() + " " + donation.getCity() + ", " + donation.getProvince() + " " + donation.getPostalCode();
text += " Pickup address is " + address + ". ";
} else {
text += " Donation is to be dropped off at ReStore. ";
}
text += "Donor's phone number is " + user.getPhone() + ".";
} else {
String date = today.get(Calendar.DAY_OF_MONTH) + "/" + today.get(Calendar.MONTH) + "/" + today.get(Calendar.YEAR);
String time = today.get(Calendar.HOUR) + ":" + today.get(Calendar.MINUTE) + ":" + today.get(Calendar.SECOND);
subject = "Donation ID# " + donId + " " + action;
text = "Donation ID #" + donId + " submitted by " + user.getFirstName() + " " + user.getLastName() + " has been " + action + " on "
+ date + " at " + time + ". Donor's phone number is " + user.getPhone() + ".";
}
email(subject, text, to);
}
private void email(String subject, String text, String to) {
logger.debug("email()");
String from = "h4hkingston@gmail.com";
String host = "smtp.gmail.com";
final String username = "h4hkingston@gmail.com";
final String password = "habitatrestore";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
public void createUserList(User user, Row row) {
Cell cell = row.createCell(0);
cell.setCellValue(user.getId());
cell = row.createCell(1);
cell.setCellValue(user.getLoginName());
cell = row.createCell(2);
cell.setCellValue(user.getFirstName());
cell = row.createCell(3);
cell.setCellValue(user.getLastName());
cell = row.createCell(4);
cell.setCellValue(user.getEmail());
cell = row.createCell(5);
cell.setCellValue(user.getPhone());
cell = row.createCell(6);
cell.setCellValue(user.getAddress() + " " + user.getCity() + ", " + user.getProvince() + " " + user.getPostalCode());
cell = row.createCell(7);
cell.setCellValue(user.getRole());
cell = row.createCell(8);
if (user.isNotify()) {
cell.setCellValue("Yes");
} else {
cell.setCellValue("No");
}
}
public void createAnalyticList(Analytic analytic, Row row) {
Cell cell = row.createCell(0);
cell.setCellValue(analytic.getValue());
cell = row.createCell(1);
cell.setCellValue(analytic.getCount());
}
} | UTF-8 | Java | 78,521 | java | UserController.java | Java | [
{
"context": "rname = login.getUsername();\r\n\t\t\tString password = login.getPassword();\r\n\t\t\tUser user = userService.findByLoginName(us",
"end": 7402,
"score": 0.9053459763526917,
"start": 7385,
"tag": "PASSWORD",
"value": "login.getPassword"
},
{
"context": "uals(\"\")) {\r\n... | null | [] | package com.spring.form.web;
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.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.ServletRequestDataBinder;
import com.spring.form.model.Analytic;
import com.spring.form.model.Attachment;
import com.spring.form.model.Donation;
import com.spring.form.model.Login;
import com.spring.form.model.ScheduledDate;
import com.spring.form.model.Search;
import com.spring.form.model.Status;
import com.spring.form.model.User;
import com.spring.form.service.AttachmentService;
import com.spring.form.service.DonationService;
import com.spring.form.service.ScheduledDateService;
import com.spring.form.service.UserService;
import com.spring.form.validator.DonationFormValidator;
import com.spring.form.validator.LoginFormValidator;
import com.spring.form.validator.SearchFormValidator;
import com.spring.form.validator.StatusValidator;
import com.spring.form.validator.UserFormValidator;
//http://www.tikalk.com/redirectattributes-new-feature-spring-mvc-31/
//https://en.wikipedia.org/wiki/Post/Redirect/Get
//http://www.oschina.net/translate/spring-mvc-flash-attribute-example
@Controller
@Scope("session")
public class UserController {
private final Logger logger = LoggerFactory.getLogger(UserController.class);
private String currentRole = "";
private int currentId = 0;
private SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE MMMM dd, yyyy");
private String months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
GregorianCalendar today = null;
int month = 0, year = 0;
private static final String STATUSFORM_PATTERN = "^statusForm\\d+$";
List<Attachment> images = null;
String listType;
private List<User> userExport;
private List<Analytic> analyticExport;
Search saveSearch;
@Autowired
LoginFormValidator loginFormValidator;
@Autowired
UserFormValidator userFormValidator;
@Autowired
SearchFormValidator searchFormValidator;
@Autowired
DonationFormValidator donationFormValidator;
@Autowired
StatusValidator statusValidator;
@InitBinder("loginForm")
protected void initLoginBinder(WebDataBinder binder) {
binder.addValidators(loginFormValidator);
}
@InitBinder("userForm")
protected void initUserBinder(WebDataBinder binder) {
binder.addValidators(userFormValidator);
}
@InitBinder("searchForm")
protected void initSearchBinder(WebDataBinder binder) {
binder.addValidators(searchFormValidator);
}
@InitBinder("donationForm")
protected void initDonationBinder(WebDataBinder binder) {
binder.addValidators(donationFormValidator);
}
@InitBinder(STATUSFORM_PATTERN)
protected void initStatusBinder(WebDataBinder binder) {
binder.addValidators(statusValidator);
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException {
// Convert multipart object to byte[]
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
private UserService userService;
private DonationService donationService;
private AttachmentService attachmentService;
private ScheduledDateService scheduledDateService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Autowired
public void setDonationService(DonationService donationService) {
this.donationService = donationService;
}
@Autowired
public void setAttachmentService(AttachmentService attachmentService) {
this.attachmentService = attachmentService;
}
@Autowired
public void setScheduledDateService(ScheduledDateService scheduledDateService) {
this.scheduledDateService = scheduledDateService;
}
// log in redirect or dashboard redirect
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
logger.debug("index()");
if (!currentRole.equals("") && currentId != 0) {
return "redirect:/dashboard";
} else {
return "redirect:/main";
}
}
// log in page or dashboard redirect
@RequestMapping(value = "/main", method = RequestMethod.GET)
public String main(Model model) {
logger.debug("main()");
if (!currentRole.equals("") && currentId != 0) {
return "redirect:/dashboard";
} else {
Login login = new Login();
login.setUsernameError("");
login.setPasswordError("");
model.addAttribute("loginForm", login);
return "login/loginform";
}
}
// checks username and password
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute("loginForm") @Validated Login login, BindingResult result, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("login()");
if (result.hasErrors()) {
return "login/loginform";
} else {
String username = login.getUsername();
String password = <PASSWORD>();
User user = userService.findByLoginName(username);
if (user == null || !user.getPassword().equals(password)) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "The username or password is incorrect.");
return "redirect:/main";
} else {
currentRole = user.getRole();
currentId = user.getId();
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", currentRole + " logged in successfully!");
if (currentRole.equals("Donor")) {
redirectAttributes.addFlashAttribute("role", currentRole);
}
return "redirect:/dashboard";
}
}
}
// log out
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("logout()");
currentRole = "";
currentId = 0;
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Logged out successfully!");
return "redirect:/main";
}
// dashboards
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public String dashboards(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("dashboard()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
today = new GregorianCalendar();
model.addAttribute("userId", currentId);
if (currentRole.equals("Staff")) {
month = today.get(Calendar.MONTH);
year = today.get(Calendar.YEAR);
model.addAttribute("day", today.get(Calendar.DAY_OF_MONTH));
model.addAttribute("month", month);
model.addAttribute("year", year);
return "dashboard/staff";
} else {
return "dashboard/donor";
}
}
}
// list page
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String showAllUsers(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAllUsers()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
model.addAttribute("users", userService.findAll());
return "users/list";
}
}
// save or update user
@RequestMapping(value = "/users", method = RequestMethod.POST)
public String saveOrUpdateUser(@ModelAttribute("userForm") @Validated User user, BindingResult result, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("saveOrUpdateUser() : {}", user);
if (result.hasErrors()) {
populateProvinces(model);
model.addAttribute("role", currentRole);
if (currentRole.equals("Staff")) {
populateRoles(model);
}
return "users/userform";
} else {
redirectAttributes.addFlashAttribute("css", "success");
if (user.isNew()) {
redirectAttributes.addFlashAttribute("msg", "User added successfully!");
} else {
if (user.getPassword().equals("")) {
user.setPassword(user.getCurrent<PASSWORD>());
}
redirectAttributes.addFlashAttribute("msg", "User updated successfully!");
}
userService.saveOrUpdate(user);
// POST/REDIRECT/GET
if (currentRole.equals("Staff")) {
return "redirect:/users";
} else {
currentRole = user.getRole();
currentId = user.getId();
return "redirect:/dashboard";
}
// POST/FORWARD/GET
// return "user/list";
}
}
// show add user form
@RequestMapping(value = "/users/add", method = RequestMethod.GET)
public String showAddUserForm(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAddUserForm()");
User user = new User();
user.setProvince("ON");
model.addAttribute("userForm", user);
model.addAttribute("role", currentRole);
if (currentRole.equals("Staff")) {
populateRoles(model);
}
populateProvinces(model);
return "users/userform";
}
// show register user form
@RequestMapping(value = "/users/register", method = RequestMethod.GET)
public String showRegisterUserForm(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showRegisterUserForm()");
User user = new User();
user.setProvince("ON");
user.setRole("Donor");
model.addAttribute("userForm", user);
populateProvinces(model);
return "users/userform";
}
// show update form
@RequestMapping(value = "/users/{id}/update", method = RequestMethod.GET)
public String showUpdateUserForm(@PathVariable("id") int id, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("showUpdateUserForm() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
User user = userService.findById(id);
user.setCurrentPass(user.getPassword());
model.addAttribute("userForm", user);
model.addAttribute("role", currentRole);
if (currentRole.equals("Staff")) {
populateRoles(model);
}
populateProvinces(model);
return "users/userform";
}
}
// delete user
@RequestMapping(value = "/users/{id}/delete", method = RequestMethod.GET)
public String deleteUser(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteUser() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
userService.delete(id);
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "User is deleted!");
return "redirect:/users";
}
}
// show user
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public String showUser(@PathVariable("id") int id, Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showUser() id: {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
User user = userService.findById(id);
if (user == null) {
model.addAttribute("css", "danger");
model.addAttribute("msg", "User not found");
}
model.addAttribute("user", user);
model.addAttribute("role", currentRole);
return "users/show";
}
}
// user search form
@RequestMapping(value = "/users/searchform", method = RequestMethod.GET)
public String searchForm(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("searchForm()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
model.addAttribute("searchForm", new Search());
populateMonths(model);
populateRoles(model);
return "users/searchform";
}
}
// user search result
@RequestMapping(value = "/users/searchresult", method = RequestMethod.POST)
public String searchUser(@ModelAttribute("searchForm") @Validated Search search, BindingResult result, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("searchUser() search : {}", search);
if (result.hasErrors()) {
populateMonths(model);
populateRoles(model);
return "users/searchform";
} else {
String first = search.getFirstName();
String last = search.getLastName();
String city = search.getCity();
String code = search.getPostalCode();
String role = search.getRole();
if (role == null) {
role = "";
}
String startMonth = search.getStartMonth();
String endMonth = search.getEndMonth();
String startYear = search.getStartYear();
String endYear = search.getEndYear();
saveSearch = search;
userExport = userService.search(first, last, city, code, role, startMonth, endMonth, startYear,
endYear);
if (userExport == null) {
model.addAttribute("css", "danger");
model.addAttribute("msg", "No users found");
}
model.addAttribute("users", userExport);
return "users/searchresult";
}
}
// send email to checked users
@RequestMapping(value = "/users/email", method = RequestMethod.POST)
public String emailSelectedDonors(Model model, final RedirectAttributes redirectAttributes,
HttpServletResponse response, HttpServletRequest request) {
logger.debug("emailSelectedDonors()");
String checkedUsers[] = request.getParameterValues("usersend");
if (checkedUsers == null) {
redirectAttributes.addFlashAttribute("msg", "Did not select any users");
} else {
String subject = "Hello from Habitat for Humanity";
for (int ctr = 0; ctr < checkedUsers.length; ctr++) {
User user = userService.findById(Integer.parseInt(checkedUsers[ctr]));
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + "."
+ "\n\nYou are being emailed today because we are testing out our email services within our user search engine.\nYou met the following criteria:\n\n";
if (saveSearch.getFirstName() != "") {
text += "First Name: " + saveSearch.getFirstName() + "\n\n";
}
if (saveSearch.getLastName() != "") {
text += "Last Name: " + saveSearch.getLastName() + "\n\n";
}
if (saveSearch.getCity() != "") {
text += "City: " + saveSearch.getCity() + "\n\n";
}
if (saveSearch.getPostalCode() != "") {
text += "Postal Code: " + saveSearch.getPostalCode() + "\n\n";
}
if (saveSearch.getRole() != null) {
text += "Role: " + saveSearch.getRole() + "\n\n";
}
if (!saveSearch.getStartMonth().equalsIgnoreCase("none")) {
text += "Start Month: " + saveSearch.getStartMonth() + " ";
if (saveSearch.getStartYear() != "") {
text += saveSearch.getStartYear() + "\n\n";
} else {
text += today.get(Calendar.YEAR) + "\n\n";
}
} else if (!saveSearch.getStartYear().equals("")) {
text += "Start Month: January " + saveSearch.getStartYear() + "\n\n";
}
if (!saveSearch.getEndMonth().equalsIgnoreCase("none")) {
text += "End Month: " + saveSearch.getEndMonth() + " ";
if (saveSearch.getEndYear() != null) {
text += saveSearch.getEndYear() + "\n\n";
} else {
text += today.get(Calendar.YEAR) + "\n\n";
}
} else if (!saveSearch.getEndYear().equals("")) {
text += "Start Month: December " + saveSearch.getEndYear() + "\n\n";
}
text += "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String receiver = "<EMAIL>";
email(subject, text, receiver);
}
redirectAttributes.addFlashAttribute("msg", "Emails sent");
}
return "redirect:/users/searchform";
}
@RequestMapping(value = "/users/export", method = RequestMethod.POST)
public String exportUsersToSpreadsheet(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("exportUsers()");
today = new GregorianCalendar();
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("testsheet");
int rownum = 0;
for (User user : userExport) {
Row row = sheet.createRow(rownum++);
if (rownum == 1) {
Cell cell = row.createCell(0);
cell.setCellValue("User ID");
cell = row.createCell(1);
cell.setCellValue("Login Name");
cell = row.createCell(2);
cell.setCellValue("First Name");
cell = row.createCell(3);
cell.setCellValue("Last Name");
cell = row.createCell(4);
cell.setCellValue("Email Address");
cell = row.createCell(5);
cell.setCellValue("Phone Number");
cell = row.createCell(6);
cell.setCellValue("Full Address");
cell = row.createCell(7);
cell.setCellValue("Role");
cell = row.createCell(8);
cell.setCellValue("Receives Notifications");
row = sheet.createRow(rownum++);
createUserList(user, row);
} else {
createUserList(user, row);
}
}
String home = System.getProperty("user.home");
String fileName = home + "/Downloads/usersearch_year" + today.get(Calendar.YEAR) + "_month"
+ today.get(Calendar.MONTH) + "_day" + today.get(Calendar.DAY_OF_MONTH) + "_hour"
+ today.get(Calendar.HOUR) + "_min" + today.get(Calendar.MINUTE) + "_sec"
+ today.get(Calendar.SECOND) + ".xlsx";
FileOutputStream out = new FileOutputStream(new File(fileName));
workbook.write(out);
out.close();
workbook.close();
} catch (FileNotFoundException e) {
logger.debug("index() file not found exception: {}", e.getMessage());
} catch (IOException e) {
logger.debug("index() io exception : {}", e.getMessage());
}
return "redirect:/users/searchform";
}
// donation list page
@RequestMapping(value = "/donations", method = RequestMethod.GET)
public String showAllDonations(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAllDonations()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
listType = "all";
List<Donation> dons = donationService.findAll();
int previousId = 0;
int decrease = 0;
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
model.addAttribute("donations", dons);
return "donations/list";
}
}
// donation list page for user
@RequestMapping(value = "/donationsforuser", method = RequestMethod.GET)
public String showAllDonationsForUser(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("showAllDonationsForUser()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
model.addAttribute("role", currentRole);
listType = "user";
List<Donation> dons = donationService.findByUserId(currentId);
int previousId = 0;
int decrease = 0;
if (dons.size() > 1) {
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
}
model.addAttribute("donations", dons);
return "donations/listforuser";
}
}
// save or update donation
@RequestMapping(value = "/donations", method = RequestMethod.POST)
public String saveOrUpdateDonation(@ModelAttribute("donationForm") @Validated Donation donation,
BindingResult result, Model model, final RedirectAttributes redirectAttributes,
HttpServletResponse response, HttpServletRequest request) {
logger.debug("saveOrUpdateDonation() : {}", donation);
String checkedAm[] = null, checkedPm[] = null;
boolean checked = false;
if (request.getParameterValues("am") != null) {
checkedAm = request.getParameterValues("am");
checkedPm = request.getParameterValues("pm");
checked = true;
}
donation.setDateError("");
if (result.hasErrors() || donation.getId() == null && result.hasErrors()) {
if (!checked && donation.getId() == null) {
donation.setDateError("gfield_error");
model.addAttribute("dateError", true);
}
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("day", day);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
if (donation.getId() != null) {
List<Donation> dons = donationService.findById(donation.getId());
int decrease = 1;
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (ctr != 0) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
donation.setScheduledDate(dons.get(0).getScheduledDate());
donation.setMeridian(dons.get(0).getMeridian());
model.addAttribute("donationForm", donation);
images = attachmentService.findByDonation(donation.getId());
Boolean noImage = false;
List<Integer> imageIds = new ArrayList<>();
for (int ctr = 0; ctr < images.size(); ctr++) {
Attachment attach = images.get(ctr);
if (attach.getImage() != null) {
imageIds.add(attach.getId());
}
}
if (imageIds.size() == 0) {
noImage = true;
} else {
model.addAttribute("imageIds", imageIds);
}
model.addAttribute("allDonations", donationService.findAll());
model.addAttribute("noImage", noImage);
model.addAttribute("dateCount", donation.getScheduledDate().size());
} else {
model.addAttribute("noImage", true);
}
populateProvinces(model);
populateDonationTypes(model);
populateDonationStatuses(model);
model.addAttribute("role", currentRole);
return "donations/donateform";
} else {
if (checkedAm != null) {
for (int ctr = 0; ctr < checkedAm.length; ctr++) {
GregorianCalendar calendar = new GregorianCalendar(year, month, Integer.parseInt(checkedAm[ctr]));
donation.getScheduledDate().add(calendar.getTime());
donation.getMeridian().add("AM");
}
}
if (checkedPm != null) {
for (int ctr = 0; ctr < checkedPm.length; ctr++) {
GregorianCalendar calendar = new GregorianCalendar(year, month, Integer.parseInt(checkedPm[ctr]));
donation.getScheduledDate().add(calendar.getTime());
donation.getMeridian().add("PM");
}
}
donation.setTacking(new Timestamp(new java.util.Date().getTime()));
if (donation.getStatus().equals("RECEIVED") || donation.getStatus().equals("PICKUP COMPLETE")) {
donation.setCompletedDate(new Timestamp(new java.util.Date().getTime()));
} else {
donation.setCompletedDate(null);
}
Boolean created = false;
redirectAttributes.addFlashAttribute("css", "success");
if (donation.isNew()) {
created = true;
donation.setNumImages(0);
redirectAttributes.addFlashAttribute("msg", "Donation ID " + donation.getId() + " added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "Donation updated successfully!");
}
donationService.saveOrUpdate(donation);
int numImages = donation.getNumImages();
int id = donation.getId();
if (!donation.getFile1().getContentType().contains("application/octet-stream")
|| donation.getFile1() != null) {
try {
InputStream input = donation.getFile1().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile1(), id);
numImages++;
redirectAttributes.addFlashAttribute("file1", "File 1: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file1", "File 1: Upload failed");
}
}
if (!donation.getFile2().getContentType().contains("application/octet-stream")
|| donation.getFile2() != null) {
try {
InputStream input = donation.getFile2().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile2(), id);
numImages++;
redirectAttributes.addFlashAttribute("file2", "File 2: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file2", "File 2: Upload failed");
}
}
if (!donation.getFile3().getContentType().contains("application/octet-stream")
|| donation.getFile3() != null) {
try {
InputStream input = donation.getFile3().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile3(), id);
numImages++;
redirectAttributes.addFlashAttribute("file3", "File 3: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file3", "File 3: Upload failed");
}
}
if (!donation.getFile4().getContentType().contains("application/octet-stream")
|| donation.getFile4() != null) {
try {
InputStream input = donation.getFile4().getInputStream();
ImageIO.read(input).toString();
saveAttachment(donation.getFile4(), id);
numImages++;
redirectAttributes.addFlashAttribute("file4", "File 4: Image uploaded");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("file4", "File 4: Upload failed");
}
}
donation.setNumImages(numImages);
donationService.saveOrUpdate(donation);
redirectAttributes.addFlashAttribute("role", currentRole);
String action = "updated";
if (created) {
action = "created";
emailDonorCreate(donation.getId(), userService.findById(donation.getDonor()));
} else {
emailDonorUpdate(donation.getId(), userService.findById(donation.getDonor()));
}
emailStaff(donation.getId(), userService.findById(donation.getDonor()), action);
// POST/REDIRECT/GET
return "redirect:/confirmation/" + donation.getId();
// POST/FORWARD/GET
// return "confirmation/confirm";
}
}
// show add donation form
@RequestMapping(value = "/donations/{id}/add", method = RequestMethod.GET)
public String showAddDonationForm(Model model, @PathVariable("id") int id,
final RedirectAttributes redirectAttributes) {
logger.debug("showAddDonationForm()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
Donation donation = new Donation();
User donor = userService.findById(id);
// set default value
donation.setDonor(donor.getId());
donation.setAddress(donor.getAddress());
donation.setCity(donor.getCity());
donation.setProvince(donor.getProvince());
donation.setPostalCode(donor.getPostalCode());
donation.setStatus("AWAITING APPROVAL");
donation.setNumImages(0);
donation.setReserved(false);
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("day", day);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
model.addAttribute("donationForm", donation);
model.addAttribute("noImage", true);
model.addAttribute("role", currentRole);
populateProvinces(model);
populateDonationTypes(model);
populateDonationStatuses(model);
return "donations/donateform";
}
}
// show update form
@RequestMapping(value = "/donations/{id}/update", method = RequestMethod.GET)
public String showUpdateDonationForm(@PathVariable("id") int id, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("showUpdateDonationForm() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<Donation> dons = donationService.findById(id);
int decrease = 1;
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (ctr != 0) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
Donation donation = dons.get(0);
images = attachmentService.findByDonation(id);
model.addAttribute("donationForm", donation);
Boolean noImage = false;
List<Integer> imageIds = new ArrayList<>();
for (int ctr = 0; ctr < images.size(); ctr++) {
Attachment attach = images.get(ctr);
if (attach.getImage() != null) {
imageIds.add(attach.getId());
}
}
if (imageIds.size() == 0) {
noImage = true;
} else {
model.addAttribute("imageIds", imageIds);
}
model.addAttribute("noImage", noImage);
model.addAttribute("role", currentRole);
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
List<ScheduledDate> dates = scheduledDateService.findAll();
model.addAttribute("allDonations", donationService.findAll());
model.addAttribute("dates", dates);
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("day", day);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
model.addAttribute("dateCount", donation.getScheduledDate().size());
populateProvinces(model);
populateDonationTypes(model);
populateDonationStatuses(model);
return "donations/donateform";
}
}
// decline donation
@RequestMapping(value = "/donations/{id}/decline", method = RequestMethod.GET)
public String declineDonation(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteDonation() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<Attachment> images = attachmentService.findByDonation(id);
User user = userService.findById(donationService.findById(id).get(0).getDonor());
for (int ctr = 0; ctr < images.size(); ctr++) {
attachmentService.delete(images.get(ctr).getId());
}
donationService.delete(id);
emailDonorDeclined(id, user);
emailStaff(id, user, "declined");
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Donation is deleted!");
if (listType.equals("user")) {
return "redirect:/donationsforuser";
} else {
return "redirect:/donations";
}
}
}
// delete donation
@RequestMapping(value = "/donations/{id}/delete", method = RequestMethod.GET)
public String deleteDonation(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteDonation() : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<Attachment> images = attachmentService.findByDonation(id);
User user = userService.findById(donationService.findById(id).get(0).getDonor());
for (int ctr = 0; ctr < images.size(); ctr++) {
attachmentService.delete(images.get(ctr).getId());
}
donationService.delete(id);
emailStaff(id, user, "deleted");
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Donation is deleted!");
if (listType.equals("user")) {
return "redirect:/donationsforuser";
} else {
return "redirect:/donations";
}
}
}
// approve donation
@RequestMapping(value = "/donations/{id}/approve", method = RequestMethod.GET)
public String approveDonation(@PathVariable("id") int id, Model model, HttpServletResponse response,
HttpServletRequest request, final RedirectAttributes redirectAttributes) {
logger.debug("approveDonation() id : {}", id);
Donation donation = donationService.findById(id).get(0);
if (donation.getType().equals("DROPOFF")) {
donationService.updateStatus(id, "AWAITING DROPOFF");
} else {
donationService.updateStatus(id, "AWAITING PICKUP");
}
User user = userService.findById(donation.getDonor());
emailDonorApproved(id, user);
emailStaff(id, user, "approved");
return "redirect:/donations/" + id;
}
// show donation
@RequestMapping(value = "/donations/{id}", method = RequestMethod.GET)
public String showDonation(@PathVariable("id") int id, Model model, HttpServletResponse response,
HttpServletRequest request, final RedirectAttributes redirectAttributes) {
logger.debug("showDonation() donation id: {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
List<Donation> dons = donationService.findById(id);
int decrease = 1;
if (dons.size() > 1) {
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (ctr != 0) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
}
Donation donation = dons.get(0);
List<Attachment> images = attachmentService.findByDonation(id);
if (donation == null) {
model.addAttribute("css", "danger");
model.addAttribute("msg", "Donation not found");
}
model.addAttribute("donation", donation);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(donation.getScheduledDate().get(0));
month = calendar.get(Calendar.MONTH);
year = calendar.get(Calendar.YEAR);
Boolean noImage = false;
List<Integer> imageIds = new ArrayList<>();
for (int ctr = 0; ctr < images.size(); ctr++) {
Attachment attach = images.get(ctr);
if (attach.getImage() != null) {
imageIds.add(attach.getId());
}
}
if (imageIds.size() == 0) {
noImage = true;
} else {
model.addAttribute("imageIds", imageIds);
}
List<ScheduledDate> dates = scheduledDateService.findAll();
model.addAttribute("allDonations", donationService.findAll());
model.addAttribute("dates", dates);
model.addAttribute("noImage", noImage);
model.addAttribute("role", currentRole);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("dateCount", donation.getScheduledDate().size());
return "donations/show";
}
}
// donation confirm page
@RequestMapping(value = "/confirmation/{id}", method = RequestMethod.GET)
public String donationConfirm(@PathVariable("id") int id, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("donationConfirm() id : {}", id);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else {
model.addAttribute("donId", id);
model.addAttribute("msg", "Donation ID " + id + " added successfully!");
return "confirmation/confirm";
}
}
// select donation date
@RequestMapping(value = "/donation/{donId}/choosedate/{datePos}", method = RequestMethod.POST)
public String chooseDonationDate(@PathVariable("donId") int donId, @PathVariable("datePos") int datePos,
Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("chooseDonationDate()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
List<ScheduledDate> dates = scheduledDateService.findByDonation(donId);
scheduledDateService.chooseDate(donId, dates.get(datePos).getId());
donationService.reserve(donId);
emailDonorDatePicked(donId, userService.findById(donationService.findById(donId).get(0).getDonor()));
return "redirect:/donations/" + donId;
}
}
// export donation + donor info to tax receipt
@RequestMapping(value = "/donations/{donId}/taxreceipt", method = RequestMethod.GET)
public String exportToTaxReceipt(@PathVariable("donId") int donId, Model model, HttpServletResponse response,
HttpServletRequest request, final RedirectAttributes redirectAttributes) {
logger.debug("exportToTaxReceipt() donation id : {}", donId);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
Donation donation = donationService.findById(donId).get(0);
if (donation.getCompletedDate() == null) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "Donation is incomplete. Cannot export.");
} else {
User user = userService.findById(donation.getDonor());
try {
InputStream in = UserController.class.getResourceAsStream("/excel/taxreceipt.xlsx");
Workbook workbook = WorkbookFactory.create(in);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(10);
Cell cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
cell.setCellValue(dateFormat.format(donation.getCompletedDate()));
row = sheet.getRow(16);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getFirstName() + " " + user.getLastName());
row = sheet.getRow(17);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getFirstName() + " " + user.getLastName());
row = sheet.getRow(18);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getAddress());
row = sheet.getRow(18);
cell = row.getCell(3);
if (cell == null)
{
cell = row.createCell(3);
}
cell.setCellValue(user.getCity());
row = sheet.getRow(19);
cell = row.getCell(3);
if (cell == null)
{
cell = row.createCell(3);
}
cell.setCellValue(user.getProvince());
row = sheet.getRow(20);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getPostalCode());
row = sheet.getRow(21);
cell = row.getCell(1);
if (cell == null)
{
cell = row.createCell(1);
}
cell.setCellValue(user.getPhone());
row = sheet.getRow(21);
cell = row.getCell(3);
if (cell == null)
{
cell = row.createCell(3);
}
cell.setCellValue(user.getEmail());
row = sheet.getRow(28);
cell = row.getCell(2);
if (cell == null)
{
cell = row.createCell(2);
}
cell.setCellValue(donation.getValue());
String home = System.getProperty("user.home");
String fileName = home + "/Downloads/taxreceipt_donationid" + donId + "_year"
+ today.get(Calendar.YEAR) + "_month" + today.get(Calendar.MONTH) + "_day"
+ today.get(Calendar.DAY_OF_MONTH) + "_hour" + today.get(Calendar.HOUR) + "_min"
+ today.get(Calendar.MINUTE) + "_sec" + today.get(Calendar.SECOND) + ".xlsx";
FileOutputStream out = new FileOutputStream(new File(fileName));
workbook.write(out);
out.close();
workbook.close();
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Donation exported to tax receipt form");
} catch (FileNotFoundException e) {
logger.debug("index() file not found exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "The tax receipt form could not be found.");
} catch (IOException e) {
logger.debug("index() io exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "An error occurred exporting the info. Please try again.");
} catch (EncryptedDocumentException e) {
logger.debug("index() encrypted document exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "An error occurred exporting the info. Please try again.");
} catch (InvalidFormatException e) {
logger.debug("index() invalid format exception : {}", e.getMessage());
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "An error occurred exporting the info. Please try again.");
}
}
return "redirect:/donations/" + donId;
}
}
// donation analytics menu
@RequestMapping(value = "/analytics", method = RequestMethod.GET)
public String analyticsMenu(Model model, final RedirectAttributes redirectAttributes) {
logger.debug("analyticsMenu()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return "donations/analytic_menu";
}
}
// donation analytics page
@RequestMapping(value = "/analytics/{analytic}", method = RequestMethod.GET)
public String donationAnalytics(@PathVariable("analytic") String analytic, Model model,
final RedirectAttributes redirectAttributes) {
logger.debug("donationAnalytics() analytic : {}", analytic);
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
switch (analytic) {
case "type":
analyticExport = donationService.findTypeCount();
break;
case "code":
analyticExport = donationService.findPostalCodeCount();
break;
case "meridian":
analyticExport = donationService.findMeridianCount();
}
model.addAttribute("analytics", analyticExport);
model.addAttribute("type", analytic.substring(0, 1).toUpperCase() + analytic.substring(1));
return "donations/analytic";
}
}
@RequestMapping(value = "/analytics/{type}/export", method = RequestMethod.POST)
public String exportAnalyticsToSpreadsheet(@PathVariable("type") String type, Model model, final RedirectAttributes redirectAttributes) {
logger.debug("exportAnalytics()");
today = new GregorianCalendar();
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("testsheet");
int rownum = 0;
for (Analytic analytic : analyticExport) {
Row row = sheet.createRow(rownum++);
if (rownum == 1) {
Cell cell = row.createCell(0);
cell.setCellValue(type.substring(0, 1).toUpperCase() + type.substring(1));
cell = row.createCell(1);
cell.setCellValue("Count");
row = sheet.createRow(rownum++);
createAnalyticList(analytic, row);
}
createAnalyticList(analytic, row);
}
String home = System.getProperty("user.home");
String fileName = home + "/Downloads/analytic_" + type + "_year" + today.get(Calendar.YEAR) + "_month"
+ today.get(Calendar.MONTH) + "_day" + today.get(Calendar.DAY_OF_MONTH) + "_hour"
+ today.get(Calendar.HOUR) + "_min" + today.get(Calendar.MINUTE) + "_sec"
+ today.get(Calendar.SECOND) + ".xlsx";
FileOutputStream out = new FileOutputStream(new File(fileName));
workbook.write(out);
out.close();
workbook.close();
} catch (FileNotFoundException e) {
logger.debug("index() file not found exception: {}", e.getMessage());
} catch (IOException e) {
logger.debug("index() io exception : {}", e.getMessage());
}
return "redirect:/analytics/" + type;
}
// day schedule page
@RequestMapping(value = "/schedule/{month}/{day}/{year}", method = RequestMethod.GET)
public String donationSchedule(@PathVariable("month") int month, @PathVariable("day") int day,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("donationSchedule()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getSchedule(model, month, day, year) + "schedule";
}
}
// printer friendly day schedule page
@RequestMapping(value = "/schedule/print/{month}/{day}/{year}", method = RequestMethod.GET)
public String printFriendlySchedule(@PathVariable("month") int month, @PathVariable("day") int day,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("printFriendlySchedule()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getSchedule(model, month, day, year) + "printschedule";
}
}
// process day schedule
private String getSchedule(Model model, int month, int day, int year) {
GregorianCalendar date = new GregorianCalendar(year, month, day);
List<Donation> dons = donationService.findByScheduledDate(date.getTime());
int previousId = 0;
int decrease = 0;
if (dons.size() > 1) {
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
}
Status status;
for (int ctr = 0; ctr < dons.size(); ctr++) {
status = new Status();
status.setId(dons.get(ctr).getId());
status.setStatus(dons.get(ctr).getStatus());
status.setDay(day);
status.setMonth(month);
status.setYear(year);
status.setType("day");
model.addAttribute("statusForm" + dons.get(ctr).getId(), status);
}
model.addAttribute("date", dayFormat.format(date.getTime()));
model.addAttribute("donations", dons);
model.addAttribute("month", month);
model.addAttribute("day", day);
model.addAttribute("year", year);
populateDonationStatuses(model);
return "calendar/";
}
// donation calendar
@RequestMapping(value = "/calendar/{month}/{year}/{sequence}", method = RequestMethod.GET)
public String calendar(@PathVariable("month") int month, @PathVariable("year") int year,
@PathVariable("sequence") String sequence, Model model, final RedirectAttributes redirectAttributes) {
logger.debug("calendar()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
if (!sequence.equals("recent")) {
if (sequence.equals("last")) {
if (month == 0) {
month = 11;
year--;
} else {
month--;
}
} else if (sequence.equals("next")) {
if (month == 11) {
month = 0;
year++;
} else {
month++;
}
} else {
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
}
}
if (today.get(Calendar.YEAR) == year && today.get(Calendar.MONTH) == month) {
int day = today.get(Calendar.DATE);
model.addAttribute("day", day);
}
GregorianCalendar first = new GregorianCalendar(year, month, 1);
int daysInMonth = first.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstOfMonth = first.get(Calendar.DAY_OF_WEEK);
GregorianCalendar last = new GregorianCalendar(year, month, daysInMonth);
int weeksInMonth = last.get(Calendar.WEEK_OF_MONTH);
List<Donation> donations = donationService.findByScheduledMonth(month + 1, year);
for (int ctr = 0; ctr < donations.size(); ctr++) {
User user = userService.findById(donations.get(ctr).getDonor());
donations.get(ctr).setDonorName(user.getFirstName() + " " + user.getLastName());
}
model.addAttribute("monthName", months[month]);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("daysInMonth", daysInMonth);
model.addAttribute("first", firstOfMonth);
model.addAttribute("weeksInMonth", weeksInMonth);
model.addAttribute("donations", donations);
this.month = month;
this.year = year;
return "calendar/calendar";
}
}
// week schedule page
@RequestMapping(value = "/calendar/weekof/{day}/{month}/{year}", method = RequestMethod.GET)
private String scheduleWeek(@PathVariable("day") int day, @PathVariable("month") int month,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("scheduleWeek()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getWeekSchedule(model, day, month, year) + "weekschedule";
}
}
// printer friendly week schedule page
@RequestMapping(value = "/weekof/print/{day}/{month}/{year}", method = RequestMethod.GET)
private String scheduleWeekPrint(@PathVariable("day") int day, @PathVariable("month") int month,
@PathVariable("year") int year, Model model, HttpServletResponse response, HttpServletRequest request,
final RedirectAttributes redirectAttributes) {
logger.debug("scheduleWeek()");
if (currentRole.equals("") || currentId == 0) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You must log in to access the website.");
return "redirect:/main";
} else if (!currentRole.equals("Staff")) {
redirectAttributes.addFlashAttribute("css", "danger");
redirectAttributes.addFlashAttribute("msg", "You do not have permission to access this page.");
return "redirect:/dashboard";
} else {
return getWeekSchedule(model, day, month, year) + "printweekschedule";
}
}
// process week schedule
private String getWeekSchedule(Model model, int day, int month, int year) {
logger.debug("getWeekSchedule()");
GregorianCalendar firstOfWeek = new GregorianCalendar(year, month, day);
int lastDayOfWeek = day;
switch (firstOfWeek.get(Calendar.DAY_OF_WEEK)) {
case 1:
lastDayOfWeek += 6;
break;
case 2:
lastDayOfWeek += 5;
break;
case 3:
lastDayOfWeek += 4;
break;
case 4:
lastDayOfWeek += 3;
break;
case 5:
lastDayOfWeek += 2;
break;
case 6:
lastDayOfWeek += 1;
}
List<Donation> dons = donationService.findByScheduledWeekOfMonth(day, lastDayOfWeek, month + 1, year);
int previousId = 0;
int decrease = 0;
if (dons.size() > 1) {
List<Integer> indexes = new ArrayList<>();
for (int ctr = 0; ctr < dons.size(); ctr++) {
if (previousId != dons.get(ctr).getId()) {
previousId = dons.get(ctr).getId();
decrease = 1;
} else if (previousId == dons.get(ctr).getId()) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
indexes.add(ctr);
decrease++;
}
}
for (int ctr = indexes.size() - 1; ctr >= 0; ctr--) {
int index = indexes.get(ctr);
dons.remove(index);
}
}
Status status;
for (int ctr = 0; ctr < dons.size(); ctr++) {
status = new Status();
status.setId(dons.get(ctr).getId());
status.setStatus(dons.get(ctr).getStatus());
status.setDay(day);
status.setMonth(month);
status.setYear(year);
status.setType("week");
model.addAttribute("statusForm" + dons.get(ctr).getId(), status);
}
model.addAttribute("week", months[month] + " " + day + " - " + lastDayOfWeek + ", " + year);
model.addAttribute("day", day);
model.addAttribute("month", month);
model.addAttribute("year", year);
model.addAttribute("donations", dons);
populateDonationStatuses(model);
return "calendar/";
}
// update donation status
@RequestMapping(value = "/statusupdate", method = RequestMethod.POST)
public String updateStatus(@ModelAttribute(STATUSFORM_PATTERN) @Validated Status status, BindingResult result,
Model model, final RedirectAttributes redirectAttributes, HttpServletResponse response,
HttpServletRequest request) {
logger.debug("updateStatus() status : {}", status);
populateDonationStatuses(model);
if (result.hasErrors()) {
model.addAttribute("error", status.getId());
if (status.getType().equals("week")) {
return getWeekSchedule(model, status.getDay(), status.getMonth(), status.getYear()) + "weekschedule";
} else {
return getSchedule(model, status.getMonth(), status.getDay(), status.getYear()) + "schedule";
}
} else {
donationService.updateStatus(status.getId(), status.getStatus());
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Status updated successfully!");
if (status.getType().equals("week")) {
return getWeekSchedule(model, status.getDay(), status.getMonth(), status.getYear()) + "weekschedule";
} else {
return getSchedule(model, status.getMonth(), status.getDay(), status.getYear()) + "schedule";
}
}
}
// display image
@RequestMapping(value = "/images/{id}", method = RequestMethod.GET)
private void displayImages(@PathVariable("id") int id, Model model, HttpServletResponse response,
HttpServletRequest request) {
logger.debug("displayImages() image id: {}", id);
try {
Attachment attach = attachmentService.findById(id);
byte[] image = attach.getBytes();
if (image != null) {
response.reset();
response.setContentType("image/png");
response.setContentLength(image.length);
response.getOutputStream().write(image);
response.getOutputStream().close();
}
} catch (IOException e) {
logger.debug("displayImages() IO Exception : {}", e.getCause());
}
}
// save attachment
public void saveAttachment(MultipartFile file, int id) {
logger.debug("saveAttachment() file : {}", file);
Attachment attach = new Attachment();
attach.setFile(file);
attach.setDonation(id);
attachmentService.saveOrUpdate(attach);
}
// delete attachment
@RequestMapping(value = "/images/{id}/delete", method = RequestMethod.POST)
public String deleteAttachment(@PathVariable("id") int id, final RedirectAttributes redirectAttributes) {
logger.debug("deleteAttachment() : {}", id);
int donId = attachmentService.findById(id).getDonation();
attachmentService.delete(id);
List<Donation> dons = donationService.findById(id);
int decrease = 1;
if (dons.size() > 1) {
for (int ctr = 0; ctr < dons.size(); ctr++) {
dons.get(ctr - decrease).getScheduledDate().add(dons.get(ctr).getScheduledDate().get(0));
dons.get(ctr - decrease).getMeridian().add(dons.get(ctr).getMeridian().get(0));
decrease++;
}
for (int ctr = dons.size() - 1; ctr >= 1; ctr--) {
dons.remove(ctr);
}
}
Donation donation = dons.get(0);
donation.decreaseNumImages(1);
donationService.saveOrUpdate(donation);
redirectAttributes.addFlashAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "Image is deleted!");
return "redirect:/donations/" + donId + "/update";
}
private void populateProvinces(Model model) {
Map<String, String> province = new LinkedHashMap<String, String>();
province.put("AB", "Alberta");
province.put("BC", "British Columbia");
province.put("MB", "Manitoba");
province.put("NB", "New Brunswick");
province.put("NL", "Newfoundland & Labrador");
province.put("NS", "Nova Scotia");
province.put("ON", "Ontario");
province.put("PE", "Prince Edward Island");
province.put("QE", "Quebec");
province.put("SA", "Saskatchewan");
province.put("NT", "Northwest Territories");
province.put("NU", "Nunavut");
province.put("YU", "Yukon");
model.addAttribute("provinceList", province);
}
private void populateRoles(Model model) {
Map<String, String> roles = new LinkedHashMap<String, String>();
roles.put("Donor", "Donor");
roles.put("Volunteer", "Volunteer");
roles.put("Staff", "Staff");
model.addAttribute("roleList", roles);
}
private void populateDonationTypes(Model model) {
Map<String, String> types = new LinkedHashMap<String, String>();
types.put("DROPOFF", "DROPOFF");
types.put("PICKUP", "PICKUP");
model.addAttribute("typeList", types);
}
private void populateDonationStatuses(Model model) {
Map<String, String> statuses = new LinkedHashMap<String, String>();
statuses.put("AWAITING DROPOFF", "AWAITING DROPOFF");
statuses.put("AWAITING PICKUP", "AWAITING PICKUP");
statuses.put("PICKUP COMPLETE", "PICKUP COMPLETE");
statuses.put("RESCHEDULED", "RESCHEDULED");
statuses.put("RECEIVED", "RECEIVED");
model.addAttribute("statusList", statuses);
}
private void populateMonths(Model model) {
Map<String, String> months = new LinkedHashMap<String, String>();
months.put("1", "January");
months.put("2", "February");
months.put("3", "March");
months.put("4", "April");
months.put("5", "May");
months.put("6", "June");
months.put("7", "July");
months.put("8", "August");
months.put("9", "September");
months.put("10", "October");
months.put("11", "November");
months.put("12", "December");
model.addAttribute("months", months);
}
@ExceptionHandler(EmptyResultDataAccessException.class)
public ModelAndView handleEmptyData(HttpServletRequest req, Exception ex) {
logger.debug("handleEmptyData()");
logger.error("Request: {}, error ", req.getRequestURL(), ex);
ModelAndView model = new ModelAndView();
model.setViewName("user/show");
model.addObject("msg", "user not found");
return model;
}
private void emailDonorCreate(Integer donId, User user) {
logger.debug("emailDonorCreate() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Submitted";
String text = "Hello " + user.getFirstName() + " " + user.getLastName()
+ ".\n\nYour donation has been submitted successfully and is now awaiting approval. "
+ "We will check our inbox as soon as possible in order to confirm your donation. "
+ "\n\nYour donation ID# is " + donId
+ ". Please refer to this number if you have any future questions or concerns."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "<EMAIL>";
email(subject, text, to);
}
private void emailDonorUpdate(Integer donId, User user) {
logger.debug("emailDonorUpdate() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Updated";
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + ".\n\nYour donation ID# " + donId
+ " has been updated. "
+ "If you have any questions or concerns involving these changes please contact us as soon as possible."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "<EMAIL>";
email(subject, text, to);
}
private void emailDonorApproved(Integer donId, User user) {
logger.debug("emailDonorDeclined() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Approved";
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + ".\n\nYour donation ID# " + donId
+ " has been approved."
+ "\n\nIf you have any further questions, details, or changes regarding your donation, please contact us as soon as possible."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "<EMAIL>";
email(subject, text, to);
}
private void emailDonorDeclined(Integer donId, User user) {
logger.debug("emailDonorDeclined() donation id : {}", donId);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Declined";
String text = "Hello " + user.getFirstName() + " " + user.getLastName()
+ ".\n\nThank you for your interest in supporting Habitat for Humanity through a donation to our ReStore. "
+ "We sincerely value the support of our community in our mission to build a better future with local families "
+ "by helping them to achieve affordable home ownership. While we are currently unable to schedule your donation at "
+ "this time, we sincerely appreciate that you thought of us.\n\nEvery donation that we schedule must meet a list of "
+ "requirements, including, for pick-ups, the resale value being high enough to offset the expense of sending our truck "
+ "and two staff members to complete the pick-up. Other reasons why we may choose to decline a donation are distance, "
+ "having too much stock of a similar product, not having enough storage space, and items not meeting our donation "
+ "guidelines and policies. To review our donation guidelines and policies, please visit our website at "
+ "habitatkingston.com. If you have questions or would like to speak to one of our team members, please call "
+ "613-548-8763.\n\nThank you for supporting Habitat for Humanity, and have a great day!"
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "<EMAIL>";
email(subject, text, to);
}
private void emailDonorDatePicked(Integer donId, User user) {
logger.debug("emailDonorDatePicked() donation id : {}", donId);
Donation donation = donationService.findById(donId).get(0);
String subject = "Donation ID# " + donId + " to Habitat for Humanity - Date Picked";
String text = "Hello " + user.getFirstName() + " " + user.getLastName() + ".\n\nA scheduled date of "
+ donation.getScheduledDate().get(0) + ": " + donation.getMeridian().get(0)
+ " has been chosen for your donation ID# " + donId + "."
+ "\n\nWe will contact you on the chosen date to confirm a time. If you have any questions or concerns please contact us as soon as possible."
+ "\n\nThank you for thinking of us, and we hope you enjoy the rest of your day."
+ "\n\nHabitat for Humanity Kingston ReStore";
String to = "<EMAIL>";
email(subject, text, to);
}
private void emailStaff(Integer donId, User user, String action) {
logger.debug("emailStaff() donation id : {}", donId);
String subject, text, to = "<EMAIL>";
if (!action.equals("deleted")) {
Donation donation = donationService.findById(donId).get(0);
subject = "Donation ID# " + donId + " " + action;
text = "Donation ID #" + donId + " description \"" + donation.getDescription() + ",\" submitted by "
+ user.getFirstName() + " " + user.getLastName() + " has been " + action + " at "
+ donation.getTacking() + ".";
String address;
if (donation.getType().equals("PICKUP")) {
address = donation.getAddress() + " " + donation.getCity() + ", " + donation.getProvince() + " " + donation.getPostalCode();
text += " Pickup address is " + address + ". ";
} else {
text += " Donation is to be dropped off at ReStore. ";
}
text += "Donor's phone number is " + user.getPhone() + ".";
} else {
String date = today.get(Calendar.DAY_OF_MONTH) + "/" + today.get(Calendar.MONTH) + "/" + today.get(Calendar.YEAR);
String time = today.get(Calendar.HOUR) + ":" + today.get(Calendar.MINUTE) + ":" + today.get(Calendar.SECOND);
subject = "Donation ID# " + donId + " " + action;
text = "Donation ID #" + donId + " submitted by " + user.getFirstName() + " " + user.getLastName() + " has been " + action + " on "
+ date + " at " + time + ". Donor's phone number is " + user.getPhone() + ".";
}
email(subject, text, to);
}
private void email(String subject, String text, String to) {
logger.debug("email()");
String from = "<EMAIL>";
String host = "smtp.gmail.com";
final String username = "<EMAIL>";
final String password = "<PASSWORD>";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
public void createUserList(User user, Row row) {
Cell cell = row.createCell(0);
cell.setCellValue(user.getId());
cell = row.createCell(1);
cell.setCellValue(user.getLoginName());
cell = row.createCell(2);
cell.setCellValue(user.getFirstName());
cell = row.createCell(3);
cell.setCellValue(user.getLastName());
cell = row.createCell(4);
cell.setCellValue(user.getEmail());
cell = row.createCell(5);
cell.setCellValue(user.getPhone());
cell = row.createCell(6);
cell.setCellValue(user.getAddress() + " " + user.getCity() + ", " + user.getProvince() + " " + user.getPostalCode());
cell = row.createCell(7);
cell.setCellValue(user.getRole());
cell = row.createCell(8);
if (user.isNotify()) {
cell.setCellValue("Yes");
} else {
cell.setCellValue("No");
}
}
public void createAnalyticList(Analytic analytic, Row row) {
Cell cell = row.createCell(0);
cell.setCellValue(analytic.getValue());
cell = row.createCell(1);
cell.setCellValue(analytic.getCount());
}
} | 78,355 | 0.670088 | 0.666408 | 2,186 | 33.92086 | 29.213894 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.184813 | false | false | 8 |
852fac1facff3305d4c44f50baac4576b14da650 | 15,109,694,964,180 | 4ccf82202d45f66cea245cade7ca0d057e2dffb7 | /src/main/java/com/steven/annotation/Name.java | c44937ce41003b3f62ce32d40a1f1979405bc95f | [] | no_license | gao715108023/spring-study | https://github.com/gao715108023/spring-study | 9367568aa181e06e89f2d0f30e828a340a9d6fdc | bef7afb01dd98265ab82760e090c4c67c6d7028c | refs/heads/master | 2016-09-08T01:38:00.226000 | 2014-09-23T06:29:48 | 2014-09-23T06:29:48 | 24,214,232 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.steven.annotation;
import java.lang.annotation.*;
/**
* @author gaochuanjun
* @since 14-9-19
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name {
public String originate();
public String community();
}
| UTF-8 | Java | 279 | java | Name.java | Java | [
{
"context": "n;\n\nimport java.lang.annotation.*;\n\n/**\n * @author gaochuanjun\n * @since 14-9-19\n */\n@Target(ElementType.METHOD)",
"end": 90,
"score": 0.9968992471694946,
"start": 79,
"tag": "USERNAME",
"value": "gaochuanjun"
}
] | null | [] | package com.steven.annotation;
import java.lang.annotation.*;
/**
* @author gaochuanjun
* @since 14-9-19
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name {
public String originate();
public String community();
}
| 279 | 0.724014 | 0.706093 | 16 | 16.4375 | 13.038255 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 8 |
528f807ad4a1e9970c7e4ba62ec507eb625881bf | 13,288,628,833,997 | a186a9983f7342699db220fd6a934fe54d79c299 | /src/main/Library/Structure/GraphNode.java | 167f8c2e0452da313894c371b688efc3331a3901 | [
"MIT"
] | permissive | RahulKumarParihar/DataStructures | https://github.com/RahulKumarParihar/DataStructures | e83bd46f94dd4433fedd4fc153a290f14119ac48 | 4cc65d027a984a4ebc22f3ade57aed3880ca0bcd | refs/heads/master | 2021-07-23T22:36:44.855000 | 2021-07-08T06:30:51 | 2021-07-08T06:30:51 | 205,975,951 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Structure;
import Enums.GraphRepresentation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GraphNode {
private int vertex;
private GraphRepresentation representation;
private int[][] matrix = null;
private List<Map<Integer, Integer>> list = null;
public int edges;
public int getVertex() {
return vertex;
}
public GraphRepresentation getRepresentation() {
return representation;
}
public GraphNode(int vertex, GraphRepresentation representation) {
this.vertex = vertex;
this.representation = representation;
}
public int[][] getMatrix() {
if(representation != GraphRepresentation.AdjacentMatrix){
throw new RuntimeException("Change Representation in Constructor");
}
if(vertex <= 0){
throw new RuntimeException("Node must be a positive integer.");
}
if(matrix == null){
matrix = new int[vertex][vertex];
}
return matrix;
}
public List<Map<Integer, Integer>> getList() {
if(representation != GraphRepresentation.AdjacentList){
throw new RuntimeException("Change Representation in Constructor");
}
if(vertex <= 0){
throw new RuntimeException("Node must be a positive integer.");
}
if(list == null){
list = new ArrayList<>(vertex);
for(int i = 0; i < vertex; i++){
list.add(new HashMap<>());
}
}
return list;
}
}
| UTF-8 | Java | 1,609 | java | GraphNode.java | Java | [] | null | [] | package Structure;
import Enums.GraphRepresentation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GraphNode {
private int vertex;
private GraphRepresentation representation;
private int[][] matrix = null;
private List<Map<Integer, Integer>> list = null;
public int edges;
public int getVertex() {
return vertex;
}
public GraphRepresentation getRepresentation() {
return representation;
}
public GraphNode(int vertex, GraphRepresentation representation) {
this.vertex = vertex;
this.representation = representation;
}
public int[][] getMatrix() {
if(representation != GraphRepresentation.AdjacentMatrix){
throw new RuntimeException("Change Representation in Constructor");
}
if(vertex <= 0){
throw new RuntimeException("Node must be a positive integer.");
}
if(matrix == null){
matrix = new int[vertex][vertex];
}
return matrix;
}
public List<Map<Integer, Integer>> getList() {
if(representation != GraphRepresentation.AdjacentList){
throw new RuntimeException("Change Representation in Constructor");
}
if(vertex <= 0){
throw new RuntimeException("Node must be a positive integer.");
}
if(list == null){
list = new ArrayList<>(vertex);
for(int i = 0; i < vertex; i++){
list.add(new HashMap<>());
}
}
return list;
}
}
| 1,609 | 0.60348 | 0.601616 | 59 | 26.271187 | 22.706551 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.491525 | false | false | 8 |
33ed77b5a608fcca9961e1ad0627bcc2a8a7c6c6 | 6,399,501,290,931 | f7c2367b1aabfa8be42af81e8df54ccbde376594 | /Estado/src/java/DAO/PeriodicidadeDAO.java | 5783f0dc22900135ce7c0bac62a5cc250c7e8b40 | [] | no_license | AlessandroRodrigo/gibizera-fef | https://github.com/AlessandroRodrigo/gibizera-fef | 940f8602a082d2e1924d6514ced51bfd76e35e1c | ded43ef48081eea82337261a8e40503ea905a803 | refs/heads/master | 2022-04-29T04:45:51.834000 | 2020-03-10T03:18:48 | 2020-03-10T03:18:48 | 245,030,174 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import Database.ConnectionFactory;
import Models.Periodicidade;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Aluno
*/
public class PeriodicidadeDAO implements GenericDAO {
private Connection Connection;
public PeriodicidadeDAO() throws Exception {
try {
this.Connection = ConnectionFactory.getConnection();
System.out.println("Conectado com Sucesso!");
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
@Override
public Boolean Cadastrar(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
Boolean bRetorno = false;
if (cPeriodicidade.getIdPeriodicidade() == 0 || cPeriodicidade.getIdPeriodicidade() == null) {
bRetorno = this.Inserir(cPeriodicidade);
} else {
bRetorno = this.Alterar(cPeriodicidade);
}
return bRetorno;
}
@Override
public Boolean Inserir(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
PreparedStatement Stmt = null;
//Prepara comando SQL
String strSQL = "Insert Into Periodicidade (descricaoPeriodicidade) Values (?);";
try {
Stmt = Connection.prepareStatement(strSQL);
try {
Stmt.setString(1, cPeriodicidade.getDescricaoPeriodicidade());
} catch (Exception ex) {
System.out.println("Problemas ao cadastrar Periodicidade! Erro:" + ex.getMessage());
ex.printStackTrace();
}
Stmt.execute();
return true;
} catch (SQLException ex) {
System.out.println("Problemas ao cadastrar Periodicidade! Erro:" + ex.getMessage());
ex.printStackTrace();
return false;
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
}
@Override
public Boolean Alterar(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
PreparedStatement Stmt = null;
/*PreparedStatement = prepara a intrução SQL*/
String strSQL = " Update Periodicidade set descricaoPeriodicidade = ? Where IdPeriodicidade = ?;";
try {
Stmt = Connection.prepareStatement(strSQL);
Stmt.setString(1, cPeriodicidade.getDescricaoPeriodicidade());
Stmt.setInt(2, cPeriodicidade.getIdPeriodicidade());
Stmt.executeUpdate();
return true;
} catch (SQLException ex) {
System.out.println("Problemas ao alterar Periodicidade! Erro:" + ex.getMessage());
ex.printStackTrace();
return false;
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
}
@Override
public Boolean Excluir(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
int idPeriodicidade = cPeriodicidade.getIdPeriodicidade();
PreparedStatement stmt = null;
String strSQL = "Delete From Periodicidade Where idPeriodicidade = ?";
try {
stmt = Connection.prepareStatement(strSQL);
stmt.setInt(1, idPeriodicidade);
stmt.execute();
return true;
} catch (Exception e) {
System.out.println("Problemas ao excluir Periodicidade! Erro: " + e.getMessage());
return false;
}
}
@Override
public Object Carregar(int Numero) {
PreparedStatement Stmt = null;
ResultSet rs = null;
Periodicidade cPeriodicidade = null;
String strSQL = "Select E.* From Periodicidade E Where E.IdPeriodicidade = ?;";
try {
Stmt = Connection.prepareStatement(strSQL);
Stmt.setInt(1, Numero);
rs = Stmt.executeQuery();
while (rs.next()) {
cPeriodicidade = new Periodicidade();
cPeriodicidade.setIdPeriodicidade(rs.getInt("IdPeriodicidade"));
cPeriodicidade.setDescricaoPeriodicidade(rs.getString("descricaoPeriodicidade"));
}
return cPeriodicidade;
} catch (SQLException ex) {
System.out.println("Problemas ao carregar Periodicidade! Erro: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt, rs);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
return cPeriodicidade;
}
@Override
public List<Object> Listar() {
List<Object> listaPeriodicidade = new ArrayList<>();
PreparedStatement Stmt = null;
ResultSet rs = null;
String strSQL = "Select E.* From Periodicidade E Order By E.descricaoPeriodicidade";
try {
Stmt = Connection.prepareStatement(strSQL);
rs = Stmt.executeQuery();
while (rs.next()) {
Periodicidade cPeriodicidade = new Periodicidade();
cPeriodicidade.setIdPeriodicidade(rs.getInt("IdPeriodicidade"));
cPeriodicidade.setDescricaoPeriodicidade(rs.getString("DescricaoPeriodicidade"));
listaPeriodicidade.add(cPeriodicidade);
}
} catch (SQLException ex) {
System.out.println("Problemas ao listar Periodicidade! Erro: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt, rs);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
return listaPeriodicidade;
}
}
| UTF-8 | Java | 7,017 | java | PeriodicidadeDAO.java | Java | [
{
"context": "st;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author Aluno\r\n */\r\npublic class PeriodicidadeDAO implements Gene",
"end": 476,
"score": 0.8586214184761047,
"start": 471,
"tag": "NAME",
"value": "Aluno"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import Database.ConnectionFactory;
import Models.Periodicidade;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Aluno
*/
public class PeriodicidadeDAO implements GenericDAO {
private Connection Connection;
public PeriodicidadeDAO() throws Exception {
try {
this.Connection = ConnectionFactory.getConnection();
System.out.println("Conectado com Sucesso!");
} catch (Exception ex) {
throw new Exception(ex.getMessage());
}
}
@Override
public Boolean Cadastrar(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
Boolean bRetorno = false;
if (cPeriodicidade.getIdPeriodicidade() == 0 || cPeriodicidade.getIdPeriodicidade() == null) {
bRetorno = this.Inserir(cPeriodicidade);
} else {
bRetorno = this.Alterar(cPeriodicidade);
}
return bRetorno;
}
@Override
public Boolean Inserir(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
PreparedStatement Stmt = null;
//Prepara comando SQL
String strSQL = "Insert Into Periodicidade (descricaoPeriodicidade) Values (?);";
try {
Stmt = Connection.prepareStatement(strSQL);
try {
Stmt.setString(1, cPeriodicidade.getDescricaoPeriodicidade());
} catch (Exception ex) {
System.out.println("Problemas ao cadastrar Periodicidade! Erro:" + ex.getMessage());
ex.printStackTrace();
}
Stmt.execute();
return true;
} catch (SQLException ex) {
System.out.println("Problemas ao cadastrar Periodicidade! Erro:" + ex.getMessage());
ex.printStackTrace();
return false;
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
}
@Override
public Boolean Alterar(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
PreparedStatement Stmt = null;
/*PreparedStatement = prepara a intrução SQL*/
String strSQL = " Update Periodicidade set descricaoPeriodicidade = ? Where IdPeriodicidade = ?;";
try {
Stmt = Connection.prepareStatement(strSQL);
Stmt.setString(1, cPeriodicidade.getDescricaoPeriodicidade());
Stmt.setInt(2, cPeriodicidade.getIdPeriodicidade());
Stmt.executeUpdate();
return true;
} catch (SQLException ex) {
System.out.println("Problemas ao alterar Periodicidade! Erro:" + ex.getMessage());
ex.printStackTrace();
return false;
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
}
@Override
public Boolean Excluir(Object objeto) {
Periodicidade cPeriodicidade = (Periodicidade) objeto;
int idPeriodicidade = cPeriodicidade.getIdPeriodicidade();
PreparedStatement stmt = null;
String strSQL = "Delete From Periodicidade Where idPeriodicidade = ?";
try {
stmt = Connection.prepareStatement(strSQL);
stmt.setInt(1, idPeriodicidade);
stmt.execute();
return true;
} catch (Exception e) {
System.out.println("Problemas ao excluir Periodicidade! Erro: " + e.getMessage());
return false;
}
}
@Override
public Object Carregar(int Numero) {
PreparedStatement Stmt = null;
ResultSet rs = null;
Periodicidade cPeriodicidade = null;
String strSQL = "Select E.* From Periodicidade E Where E.IdPeriodicidade = ?;";
try {
Stmt = Connection.prepareStatement(strSQL);
Stmt.setInt(1, Numero);
rs = Stmt.executeQuery();
while (rs.next()) {
cPeriodicidade = new Periodicidade();
cPeriodicidade.setIdPeriodicidade(rs.getInt("IdPeriodicidade"));
cPeriodicidade.setDescricaoPeriodicidade(rs.getString("descricaoPeriodicidade"));
}
return cPeriodicidade;
} catch (SQLException ex) {
System.out.println("Problemas ao carregar Periodicidade! Erro: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt, rs);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
return cPeriodicidade;
}
@Override
public List<Object> Listar() {
List<Object> listaPeriodicidade = new ArrayList<>();
PreparedStatement Stmt = null;
ResultSet rs = null;
String strSQL = "Select E.* From Periodicidade E Order By E.descricaoPeriodicidade";
try {
Stmt = Connection.prepareStatement(strSQL);
rs = Stmt.executeQuery();
while (rs.next()) {
Periodicidade cPeriodicidade = new Periodicidade();
cPeriodicidade.setIdPeriodicidade(rs.getInt("IdPeriodicidade"));
cPeriodicidade.setDescricaoPeriodicidade(rs.getString("DescricaoPeriodicidade"));
listaPeriodicidade.add(cPeriodicidade);
}
} catch (SQLException ex) {
System.out.println("Problemas ao listar Periodicidade! Erro: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
ConnectionFactory.CloseConnection(Connection, Stmt, rs);
} catch (Exception ex) {
System.out.println("Problemas ao fechar os parâmetros de conexão! Erro:" + ex.getMessage());
ex.printStackTrace();
}
}
return listaPeriodicidade;
}
}
| 7,017 | 0.573427 | 0.57257 | 209 | 31.526316 | 29.141472 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521531 | false | false | 8 |
4ad9d9791a5b8b16c71b81c383fcf921a47c155b | 21,217,138,462,503 | d146aa5fe4400a2927e499b635459246665e874e | /lib/src/main/java/es/diagram/utilidades/Strings.java | 4d1d11117ec6b8e92479a6588a00883557ff9b5b | [] | no_license | diagramsoftware/utilidades.android | https://github.com/diagramsoftware/utilidades.android | bbe42f9e662d0da306e8f6e3b4f5c418ac1251b8 | 5ce77c07dec5e5fb1936df2a1adb9c20d0de1527 | HEAD | 2017-04-27T13:41:47.762000 | 2017-02-20T17:59:49 | 2017-02-20T17:59:49 | 52,514,000 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package es.diagram.utilidades;
public class Strings {
public static final String EMPTY = "";
}
| UTF-8 | Java | 101 | java | Strings.java | Java | [] | null | [] | package es.diagram.utilidades;
public class Strings {
public static final String EMPTY = "";
}
| 101 | 0.712871 | 0.712871 | 6 | 15.833333 | 16.55714 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 8 |
0e69acae39a04b8bf2c84eee0f5dc9c0c58cfaa8 | 14,130,442,422,893 | aac102eefb37d267825337166e6bbdaa0d9e544a | /app/src/main/java/com/kedacom/touchdata/TouchDataActivity.java | 097d682992edaaf9a9e46a9904221e53901367d9 | [] | no_license | ScreenImageWork/TouchData | https://github.com/ScreenImageWork/TouchData | 690f4e6d07f72cb976a32bc2301b62b11162f077 | 1cb258dce7383c517be478ddea49fc4f2cf9d0d2 | refs/heads/master | 2020-03-25T06:37:31.336000 | 2018-08-04T09:08:02 | 2018-08-04T09:08:02 | 142,834,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kedacom.touchdata;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.kedacom.httpserver.utils.Network;
import com.kedacom.receiver.NetworkBroadcastReceiver;
import com.kedacom.service.BootService;
import com.kedacom.storagelibrary.model.MailboxInfo;
import com.kedacom.storagelibrary.model.StorageItem;
import com.kedacom.storagelibrary.model.WifiInfo;
import com.kedacom.storagelibrary.unity.StroageManager;
import com.kedacom.touchdata.filemanager.FileUtils;
import com.kedacom.touchdata.filemanager.OpenFileManager;
import com.kedacom.touchdata.mail.MailUtil;
import com.kedacom.touchdata.net.ConnectManager;
import com.kedacom.touchdata.net.SendHelper;
import com.kedacom.touchdata.net.SynFileManager;
import com.kedacom.touchdata.net.callback.NetCallback;
import com.kedacom.touchdata.net.entity.ApplyChairNtf;
import com.kedacom.touchdata.net.entity.CoordinateChangedMsg;
import com.kedacom.touchdata.net.entity.DeleteGraphMsg;
import com.kedacom.touchdata.net.entity.GraphCoordinateChangedMsg;
import com.kedacom.touchdata.net.utils.NetError;
import com.kedacom.touchdata.net.utils.NetUtil;
import com.kedacom.touchdata.whiteboard.BaseActivity;
import com.kedacom.touchdata.whiteboard.data.PageManager;
import com.kedacom.touchdata.whiteboard.graph.Graph;
import com.kedacom.touchdata.whiteboard.graph.Image;
import com.kedacom.touchdata.whiteboard.graph.ImageGraph;
import com.kedacom.touchdata.whiteboard.helper.IHelperHolder;
import com.kedacom.touchdata.whiteboard.page.IPage;
import com.kedacom.touchdata.whiteboard.page.Page;
import com.kedacom.touchdata.whiteboard.page.SubPage;
import com.kedacom.touchdata.whiteboard.utils.WhiteBoardUtils;
import com.kedacom.touchdata.whiteboard.view.IWhiteBoardStateChanagedListener;
import com.kedacom.touchdata.whiteboard.view.WhiteBoardView;
import com.kedacom.tplog.TPLog;
import com.kedacom.utils.ArithUtil;
import com.kedacom.utils.NetworkUtil;
import com.kedacom.utils.StorageMangerJarUtils;
import com.kedacom.utils.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zhanglei on 2016/9/22.
*/
public class TouchDataActivity extends BaseActivity implements IWhiteBoardStateChanagedListener, PageManager.ISavePageListener,MailUtil.OnSendMailListener,NetCallback,NetworkBroadcastReceiver.OnNetworkChangeListener {
private PageManager mPageManager;
private StroageManager mStroageManager;//U盘管理类
private WhiteBoardView mWb;
private IHelperHolder mHelperHolder;
private RelativeLayout bottomLayout;
private TextView wbNameTv;
private LinearLayout closeWbBtn;
private Button dragBtn;
private LinearLayout penBtn;
private ImageView subPenBtn;
private ImageView subPenIv;
private View penColorTag;
private LinearLayout eraseBtn;
private ImageView subEraseBtn;
private ImageView subEraseIv;
private Button undoBtn;
private Button redoBtn;
private Button moreBtn;
private Button createWbBtn;
private Button browseWbListBtn;
private Button menuBtn;
private RelativeLayout pageNumLayout;
private Button preSubPageBtn;
private Button nextSubPageBtn;
private LinearLayout selectSubPageBtn;
private TextView curSubPageNumTv;
private TextView maxSupPageNumTv;
private TextView subPageNumBiasLine;
private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "image7.jpg";
private SendHelper mSendHelper;
private ConnectManager mConnectManager;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
init();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touchdata);
initView();
initBtnClick();
initWbPage(savedInstanceState);
}
private void init(){
//检测服务是否启动,没有启动 执行启动
Intent intent = new Intent(this, BootService.class);
if(!Utils.isServiceRunning(this,"com.kedacom.service.BootService")){
TPLog.printKeyStatus("BootService 未启动");
startService(intent);
}else{
TPLog.printKeyStatus("BootService 已启动");
}
//初始化白板工具类
WhiteBoardUtils.init(this);
MailUtil.setOnSendMailListener(this);
//创建页面管理器
mPageManager = new PageManager();
SynFileManager.getInstance().setPageManager(mPageManager);
ConnectManager.getInstance().setCallback(this);
// ConnectManager.getInstance().start(NetUtil.IP,NetUtil.PORT);
mSendHelper = SendHelper.getInstance();
//初始化网络监听
NetworkBroadcastReceiver.registerOnNetworkChangeListener(this);
//初始化U盘管理类
mStroageManager = new StroageManager(this);
}
private void initView(){
bottomLayout = (RelativeLayout) findViewById(R.id.bottom);
wbNameTv = (TextView) findViewById(R.id.wbNameTv);
closeWbBtn = (LinearLayout) findViewById(R.id.closeWbBtn);
dragBtn = (Button) findViewById(R.id.dragBtn);
penBtn = (LinearLayout) findViewById(R.id.penBtn);
subPenBtn = (ImageView) findViewById(R.id.subPenBtn);
subPenIv = (ImageView) findViewById(R.id.subPenIv);
penColorTag = findViewById(R.id.colorTag);
eraseBtn = (LinearLayout) findViewById(R.id.eraseBtn);
subEraseBtn = (ImageView) findViewById(R.id.subEraseBtn);
subEraseIv = (ImageView) findViewById(R.id.subEraseIv);
undoBtn = (Button) findViewById(R.id.undoBtn);
redoBtn = (Button) findViewById(R.id.redoBtn);
moreBtn = (Button) findViewById(R.id.moreBtn);
createWbBtn = (Button)findViewById(R.id.createWbBtn);
browseWbListBtn = (Button)findViewById(R.id.browseWbListBtn);
menuBtn = (Button)findViewById(R.id.menuBtn);
preSubPageBtn = (Button) findViewById(R.id.preSubPageBtn);
nextSubPageBtn = (Button) findViewById(R.id.nextSubPageBtn);
selectSubPageBtn = (LinearLayout) findViewById(R.id.selectPageNumBtn);
curSubPageNumTv = (TextView) findViewById(R.id.curPageNumTv);
maxSupPageNumTv = (TextView) findViewById(R.id.maxPageNumTv);
subPageNumBiasLine = (TextView) findViewById(R.id.pageNumBiasLine);
pageNumLayout= (RelativeLayout)findViewById(R.id.pageNumLayout);
penBtn.setClickable(true);
eraseBtn.setClickable(true);
mWb = (WhiteBoardView) findViewById(R.id.mWhiteBoardView);
mWb.setIWhiteBoardStateChanagedListener(this);
}
private void initWbPage(Bundle savedInstanceState){
if(savedInstanceState==null) {
Page page = WhiteBoardUtils.createDefWbPage();
page.addSubPage(new SubPage());
mPageManager.addPage(page);
page.setBackGroundColor(getCurBackgroundColor());
}else{
restore(savedInstanceState);
}
mWb.setPageManager(mPageManager);
mHelperHolder = mWb.getHelperHolder();
setPageManager(mPageManager);
mPageManager.setISavePageListener(this);
mWb.setBackgroundColor(getCurBackgroundColor());
}
private void initBtnClick(){
//废弃
closeWbBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int count = mPageManager.getPageCount();
if(count>=1) {
int curPosintion = mPageManager.getSelectPageIndex();
mPageManager.removePage(curPosintion);
}else{
finish();
}
}
});
dragBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
resetSelectBtn(view.getId());
//开启拖动模式
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_DRAG);
}
});
subPenBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
resetSelectBtn(penBtn.getId());
if(mHelperHolder.getCurOpType() == WhiteBoardUtils.GRAPH_PEN) {
// subPenIv.setBackgroundResource(R.mipmap.triangle_select_icon);
// //弹出画笔选择框
// showSwitchColorDialog(subPenIv);
}else {
subPenIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
}
}
});
subPenIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
resetSelectBtn(penBtn.getId());
subPenIv.setBackgroundResource(R.mipmap.triangle_select_icon);
//弹出画笔选择框
showSwitchColorDialog(subPenIv);
}
});
subEraseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
resetSelectBtn(eraseBtn.getId());
if(mHelperHolder.getCurOpType() == WhiteBoardUtils.GRAPH_ERASE||mHelperHolder.getCurOpType() == WhiteBoardUtils.GRAPH_ERASE_AREA) {
//弹出擦除模式选择对话框
// showSwitchEraseDialog(subEraseIv);
// subEraseIv.setBackgroundResource(R.mipmap.triangle_select_icon);
}else{
subEraseIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE);
}
}
});
subEraseIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE);
resetSelectBtn(eraseBtn.getId());
subEraseIv.setBackgroundResource(R.mipmap.triangle_select_icon);
//弹出擦除模式选择对话框
showSwitchEraseDialog(subEraseIv);
}
});
undoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mHelperHolder.undo();
//发送撤销消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex() - 1;
mSendHelper.sendUndoMsg(pageId, subPageIndex);
}
});
redoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mHelperHolder.redo();
//发送恢复消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex() - 1;
mSendHelper.sendRedoMsg(pageId, subPageIndex);
}
});
moreBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
moreBtn.setBackgroundResource(R.mipmap.more_select_icon);
showMoreMenuDialog(moreBtn);
}
});
createWbBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int normalBg = WhiteBoardUtils.curBackground;
mWb.setBackgroundColor(normalBg);
Page page = WhiteBoardUtils.createDefWbPage();
page.setBackGroundColor(normalBg);
String name = page.getName();
setWbName(name);
mPageManager.addPage(page);
int count = mPageManager.getPageCount();
if (count >= 20) {
//toastMsg("白板数量已达上限!");
createWbBtn.setBackgroundResource(R.mipmap.create_wb_unable_icon);
createWbBtn.setClickable(false);
return;
}
//发送创建白板消息
mSendHelper.sendCreateNewPageMsg(page);
}
});
browseWbListBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view1) {
browseWbListBtn.setBackgroundResource(R.mipmap.browse_wb_select_icon);
showPageThumbnailDialog();
}
});
menuBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menuBtn.setBackgroundResource(R.mipmap.menu_select_icon);
menuBtn.setEnabled(false);
showMenuDialog(view);
}
});
preSubPageBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPageManager.previousSubPage();
//发送翻页消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex();
Image image = page.getCurSubPage().getImage();
mSendHelper.sendChangePageMsg(pageId,subPageIndex,image);
mSendHelper.requestImage(image,pageId,subPageIndex,((Page)page).getOwnerIndex());
}
});
nextSubPageBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPageManager.nextSubPage();
//发送翻页消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex();
Image image = page.getCurSubPage().getImage();
mSendHelper.sendChangePageMsg(pageId, subPageIndex, image);
mSendHelper.requestImage(image, pageId, subPageIndex, ((Page) page).getOwnerIndex());
}
});
selectSubPageBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isSelectSubPageBtn(true);
//弹出页码选择框
showPageNumDialog(mPageManager.getSelectPage().getSubPageCount(),selectSubPageBtn);
}
});
}
private void changeSubPageEnable(boolean isEnable){
selectSubPageBtn.setEnabled(isEnable);
nextSubPageBtn.setEnabled(isEnable);
preSubPageBtn.setEnabled(isEnable);
}
private void isSelectSubPageBtn(boolean isSelect){
int color = getResources().getColor(R.color.pagenum_normal_textcolor);
if(isSelect) {
color = getResources().getColor(R.color.pagenum_select_textcolor);
}
curSubPageNumTv.setTextColor(color);
subPageNumBiasLine.setTextColor(color);
maxSupPageNumTv.setTextColor(color);
}
private void resetSelectBtn(int btnId){
dragBtn.setBackgroundResource(R.mipmap.drag_normal_icon);
subPenBtn.setBackgroundResource(R.mipmap.pen_normal_icon);
subEraseBtn.setBackgroundResource(R.mipmap.erase_normal_icon);
switch(btnId){
case R.id.dragBtn:
dragBtn.setBackgroundResource(R.mipmap.drag_select_icon);
break;
case R.id.penBtn:
subPenBtn.setBackgroundResource(R.mipmap.pen_select_icon);
break;
case R.id.eraseBtn:
subEraseBtn.setBackgroundResource(R.mipmap.erase_select_icon);
break;
}
}
//重置所有的弹出框弹出标识
private void resetTriangleIv(){
subPenIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
subEraseIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
moreBtn.setBackgroundResource(R.mipmap.more_normal_icon);
browseWbListBtn.setBackgroundResource(R.mipmap.browse_wb_normal_icon);
menuBtn.setBackgroundResource(R.mipmap.menu_normal_icon);
isSelectSubPageBtn(false);
menuBtn.setEnabled(true);
}
@Override
public void onDCancelBtnEvent(DialogType dtype) {
resetTriangleIv();
if(needSaveProgressDialog&&curSavePage!=null&&dtype != DialogType.LOADFILE) {
curSaveProgress += curSavePage.getSubPageCount();
setCurProgress(curSaveProgress);
}else if(needSaveProgressDialog&&dtype == DialogType.LOADFILE){ //取消保存
//停止保存
saveQueue.clear();
if(curSavePage!=null){
((Page)curSavePage).stopSave();
}
curSavePage = null;
if(isExit){ //如果是退出保存的话,取消保存就直接退出应用
finish();
}
}else if(dtype == DialogType.LOADFILE){ //取消打开文件
int index = mPageManager.getSelectPageIndex();
mPageManager.removePage(index);
}
if(dtype == DialogType.FILEEXIST){
if(isCloseSave){
isCloseSave = false;
mPageManager.removePage(curSavePage);
}
if(isExit){
if(curSaveAllType == SAVEALL_ONEBYONE){
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
String msg = "\"" + curSavePage.getName() + "\""+" 是否保存?";
showIsSaveFileDilaog(msg);
}else{
finish();
}
}else if(curSaveAllType == SAVEALL_NOT_PROMPT){
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
onDSaveBtnEvent(saveDirName,true);
}else{
finish();
}
}
}
}
}
@Override
public void onDSureBtnEvent(DialogType dtype) {
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
if(curSaveAllType == SAVEALL_ONEBYONE){
String msg = "\"" + curSavePage.getName() + "\""+" 是否保存?";
showIsSaveFileDilaog(msg);
}
}else if(isExit){
finish();
}else if(isUnConnectServer&&dtype == DialogType.SURE){
showNetworkStateDialog(false,true);
}
}
@Override
public void onDOpenDirBtnEvent(String filePath) {
}
@Override
public void onDResetFileNameBtnEvent() {
// String aliasPath = FileUtils.getAliasPath(savePath);
//TPLog.printError("aliasPath-->"+aliasPath);
showSaveDialog();
}
@Override
public void onDReplaceFileBtnEvent() {
String localFilePath = savePath + File.separator + saveDirName;
FileUtils.deleteFile(localFilePath);//删掉之前的所有文件
onDSaveBtnEvent(saveDirName,isSaveAll);
}
private void initSaveAll(){
isExit = true;
setSaveDialogSaveAllBtnIsDisplay(false);
saveQueue.clear();
List<IPage> list = mPageManager.getPageList();
int count = list.size();
int subPageCount = 0; //统计所有子页个数
for(int i = 0;i<count;i++){
saveQueue.add(list.get(i));
subPageCount += list.get(i).getSubPageCount();
}
if(saveQueue.isEmpty())return;
curSavePage = saveQueue.remove(0);
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
savePageStart(subPageCount);
}
@Override
public void onDExitSaveBtnEvent() {//保存全部按钮
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
initSaveAll();
curSaveAllType = SAVEALL_NOT_PROMPT;
onDSaveBtnEvent(saveDirName, isSaveAll);
}
@Override
public void onDExitNotSaveBtnEvent() {
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
if(needSaveProgressDialog){//有保存进度对话框,关闭先
dismissDialog(DialogType.LOADFILE);
}
initSaveAll();
curSaveAllType = SAVEALL_ONEBYONE;
String msg = "\""+ curSavePage.getName() +"\"" + " 是否保存?";
showIsSaveFileDilaog(msg);
}
@Override
public void onDExitCancelBtnEvent() {
finish();
}
@Override
public void onDPenSizeBtnEvent(int size) {
mHelperHolder.setPaintStrokeWidth(size);
}
@Override
public void onDPenColorBtnEvent(int color) {
mHelperHolder.setPaintColor(color);
penColorTag.setBackgroundColor(color);
}
@Override
public void onDEraseBtnEvent() {
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE);
}
@Override
public void onDAreaEraseBtnEvent() {
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE_AREA);
}
@Override
public void onDClearScreenBtnEvent() {
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
resetSelectBtn(penBtn.getId());
mHelperHolder.clearScreen();
//发送清屏数据
mSendHelper.sendClearScreenMsg();
}
@Override
public float onDZoomOutBtnEvent() {
float curScale = mPageManager.getSelectPage().getCurScale();
//curScale = curScale + 0.1f; //java浮点运算就是坑
curScale = ArithUtil.add(curScale, 0.1f);
if(curScale>3.0f){
curScale = 3.0f;
}
mHelperHolder.scale(curScale);
// //发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(pageId, curScale * 100f);
return curScale;
}
@Override
public float onDZoomInBtnEvent() {
float curScale = mPageManager.getSelectPage().getCurScale();
if(curScale>3.0f){
curScale = 3.0f;
}
//curScale = curScale - 0.1f;
curScale = ArithUtil.sub(curScale,0.1f);
if(curScale<0.5f){
curScale = 0.5f;
}
mHelperHolder.scale(curScale);
// //发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(pageId, curScale * 100f);
return curScale;
}
@Override
public void onDRotateLeftBtnEvent() {
int curAngle = mPageManager.getSelectPage().getCurAngle();
curAngle = curAngle - 90;
mHelperHolder.rotate(curAngle, true);
//发送消息
long pageId = mPageManager.getSelectPage().getId();
//mSendHelper.sendRotateMsg((int)pageId,curAngle,true);
mSendHelper.sendLeftOrRightRotateMsg(true, pageId);
}
@Override
public void onDRotateRightBtnEvent() {
int curAngle = mPageManager.getSelectPage().getCurAngle();
curAngle = curAngle + 90;
mHelperHolder.rotate(curAngle, true);
//发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendLeftOrRightRotateMsg(false, pageId);
}
@Override
public void onDHeightSelfBtnEvent() {//需要进行图片居中计算
mHelperHolder.heightSelf();
IPage page = mPageManager.getSelectPage();
mSendHelper.sendScrollMsg(page.getOffsetX(),page.getOffsetY(),page.getId(),mPageManager.getCurPageSelectSubPageIndex(),true);
mSendHelper.sendScaleMsg(page.getId(),page.getCurScale());
}
@Override
public void onDWidthSelfBtnEvent() {
mHelperHolder.widthSelf();
IPage page = mPageManager.getSelectPage();
mSendHelper.sendScrollMsg(page.getOffsetX(),page.getOffsetY(),page.getId(),mPageManager.getCurPageSelectSubPageIndex(),true);
mSendHelper.sendScaleMsg(page.getId(), page.getCurScale() * 100f);
}
@Override
public void onDOneToOneBtnEvent() {
mHelperHolder.scale(1.0f);
//发送消息
long id = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(id, 1.0f * 100f);
}
@Override
public void onDCloseWbBtnEvent() {
onDCloseWbBtnEvent(mPageManager.getSelectPage());
}
@Override
public void onDCloseWbBtnEvent(IPage page) {
boolean isNeedSave = page.isNeedSave();
TPLog.printKeyStatus("关闭白板,是否需要保存:" + isNeedSave);
if(!isNeedSave) {
// if(mPageManager.getPageCount()==1){
// dismissDialog();
// }
mPageManager.removePage(page);
//发送关闭白板消息
mSendHelper.sendCloseWb(page.getId(),mPageManager.getSelectPage().getId());
}else{
dismissDialog();
isCloseSave = true;
curSavePage = page;
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
saveDirName = page.getName();
String msg = "\""+page.getName() + "\" 是否保存?";
showCloseSelectSaveWbDiloag(msg);
}
}
@Override
public void onDIsCloseWbSureBtnEvent(IPage page) {
}
@Override
public void onDCloseAllWbBtnEvent() {
}
@Override
public void onDSwitchDeviceSaveBtnEvent(String path) {
if(!new File(path).exists()){
showIsSureDialog("保存操作失败,外接存储设备已拔出!");
return;
}
if(!path.endsWith("/")){
path = path + File.separator;
}
TPLog.printKeyStatus("select storage device path:"+path);
setSaveDialogSaveAllBtnIsDisplay(true);
curSavePage = mPageManager.getSelectPage();
saveDirName = curSavePage.getName();
if(!path.contains(FileUtils.SDPATH)) {
savePath = path + FileUtils.USBFlashDriveSaveDir + FileUtils.getCurWhiteBoardSaveDir();
}else{
savePath = path + FileUtils.getCurWhiteBoardSaveDir();
}
FileUtils.checkDirExists(savePath);
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
showSaveDialog();
}
@Override
public void onDSwitchBackGroundColor(int color) {
mHelperHolder.setBackgroundColor(color);
mWb.setBackgroundColor(color);
mPageManager.getSelectPage().setBackGroundColor(color);
}
@Override
public void onDSelectSubPageNum(int pageNum) {
mPageManager.selectCurPageSubPage(pageNum);
//发送消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex();
mSendHelper.sendChangePageMsg(pageId, subPageIndex, page.getCurSubPage().getImage());
}
@Override
public void onDSelectPage(IPage page) {
mPageManager.selectPage(page.getId());
int subPageIndex = page.getCurSubPageIndex();
mSendHelper.sendChangePageMsg(page.getId(), subPageIndex, page.getCurSubPage().getImage());
}
@Override
public void onDMenuOpenFileBtnEvent() { //打开文件选择器
// String devices[] = {"本机文件"};
// FileEntity fe = FileUtils.findFiles(FileUtils.SDPATH);
// showSwitchFileDialog(devices,fe);
//showSwitchFileDialog();
int count = mPageManager.getPageCount();
if(count>=20){
toastMsg("当前白板页数量创建已达到上限,文件打开失败!");
}else{
startSwitchFileActivity();
}
}
//onDSwitchDeviceSaveBtnEvent
@Override
public void onDMenuSaveBtnEvent() {
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
//检查是否有U盘存在
//true
List<StorageItem> mStorageItems = mStroageManager.getStorageItems();
if(mStorageItems!=null&&!mStorageItems.isEmpty()) {
showSwitchSaveDeviceDialog(mStorageItems);
}else {
//false
//U盘不存在直接跳转到保存界面
setSaveDialogSaveAllBtnIsDisplay(true);
curSavePage = mPageManager.getSelectPage();
saveDirName = curSavePage.getName();
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
showSaveDialog();
}
}
@Override
public void onDMenuSendMailBtnEvent() {
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
if(!NetworkUtil.getNetworkState(this)){
showNetworkSettingDialog();
}else {
//sendMail = true;
showSendMailDialog();
}
}
@Override
public void onDMenuScanQRBtnEvent() {
if(NetworkUtil.getNetworkState(this)) {
TPLog.printKeyStatus("show qr code dialog and save current all page");
qRDownLoad = true;
showQRCodeDialog();
FileUtils.deleteFile(FileUtils.RUNNING_CACHE);
mPageManager.saveAllPage(FileUtils.RUNNING_CACHE);
}else{
TPLog.printKeyStatus(" qr code dialog display failed ,network unusable, network setting dialog showing");
showNetworkSettingDialog();
}
}
@Override
public void onDMenuChangeBgBtnEvent() {
showSwitchBackGroundDialog();
}
@Override
public void onDMenuExitBtnEvent() {
int count = mPageManager.getPageCount();
boolean needSave = false;
for(int i = 0;i<count;i++){
IPage page = mPageManager.getPage(i);
if(page.isNeedSave()){
needSave = true;
break;
}
}
showQuitIsSaveFileDialog();
}
//保存文件按钮触发事件 需要在此方法检查文件是否存在,进行后续处理
@Override
public void onDSaveBtnEvent(String dirName,boolean issa) {
isSaveAll = issa;
saveDirName = dirName;
final String curSavePath = savePath;
String filePath = curSavePath + File.separator + saveDirName;
TPLog.printKeyStatus("文件保存路径:"+filePath);
boolean isExists = FileUtils.checkFileExists(filePath);
if(isExists){//文件已经存在弹出文件存在对话框
if(needSaveProgressDialog){//有保存进度对话框,关闭先
dismissDialog(DialogType.LOADFILE);
}
String hintText = "\""+saveDirName+"\"文件已经存在,是否替换?";
showWhiteBoardNameDialog();
showFileExistDialog(hintText);
}else{
if(isSaveAll) {
//如果保存所有的类型不是逐个保存或者全部保存那么就是手动保存
if(curSaveAllType != SAVEALL_ONEBYONE&&curSaveAllType != SAVEALL_NOT_PROMPT){
savePageStart(curSavePage.getSubPageCount());
}
mPageManager.savePage(curSavePage,curSavePath,saveDirName);
}else{
mPageManager.saveSelectSubPage(curSavePage,curSavePath,saveDirName);
}
}
}
@Override
public void onDSaveDilaogCancelBtnEvent() {
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
saveDirName = curSavePage.getName();
savePath = FileUtils.SAVE_WRITEBOARD_DIR+FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
if(curSaveAllType == SAVEALL_ONEBYONE) {
String msg = "\""+curSavePage.getName() + "\""+" 是否保存?";
showIsSaveFileDilaog(msg);
}else{
onDSaveBtnEvent(saveDirName,true);
}
}else{
if(isCloseSave){
mPageManager.removePage(curSavePage);
isCloseSave = false;
}
}
}
@Override
public void onDSaveAllPageBtnEvent(String path, String dirName) {
}
@Override
public void onDIsSaveDialogSurBtnEvent() {
dismissDialog(DialogType.LOADFILE);
showSaveDialog();
}
@Override
public void onDIsSaveDialogCancelBtnEvent() {
if(curSaveAllType == SAVEALL_ONEBYONE&&!saveQueue.isEmpty()){
curSaveProgress += curSavePage.getSubPageCount();
IPage page = saveQueue.remove(0);
curSavePage = page;
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
saveDirName = page.getName();
String msg = "\""+page.getName() + "\" 是否保存?";
dismissDialog(DialogType.LOADFILE);
showIsSaveFileDilaog(msg);
}else if(!isExit&&isCloseSave){
mPageManager.removePage(curSavePage);
//发送关闭白板消息
mSendHelper.sendCloseWb(curSavePage.getId(),mPageManager.getSelectPage().getId());
isCloseSave = false;
}else{
finish();
}
}
@Override
public void onDCloseSelectSaveWbDiloagCancelBtnEvent() {
if(isCloseSave){
isCloseSave = false;
}
}
//发送邮件按钮事件
@Override
public void onDSendMailBtnEvent(String title, String[] mails) {
dismissDialog();
showIsSureDialog("邮件发送中......");
//showLoadDialog("正在发送邮件。。。");
sendMail = true;
mailTitle = title;
recMails = mails;
mailImageCacheDir = FileUtils.RUNNING_CACHE;
FileUtils.deleteFile(mailImageCacheDir);
mPageManager.saveAllPage(mailImageCacheDir);
}
@Override
public void onDSwitchFile(String filePath) {
TPLog.printKeyStatus("onDSwitchFile 选择文件--->"+filePath);
File file = new File(filePath);
Page page = WhiteBoardUtils.createDefWbPage();
String name = file.getName();
int index = name.indexOf(".");
if(index>0) {
name = name.substring(0, index);
}
page.setName(name);
SubPage subPage = new SubPage();
page.addSubPage(subPage);
page.setAnoymous(false);
mPageManager.addPage(page); //创建一个新的白板
mSendHelper.sendCreateNewPageMsg(page); //发送新建白板信息
//showLoadDialog("文件打开中...");
//showLoadFileDilaog(0,0,true);
//打开文档
OpenFileManager.openOrChangeFile(TouchDataActivity.this,page.getId()+"",filePath,false,new OpenFileListener());
}
@Override
public void onDToMailConfigSetting() {
StorageMangerJarUtils.toEmailSetting(this);
//toastMsg("去邮箱设置。。。。。。。。。。。。。");
}
@Override
public void onDilaogDismiss() {
resetTriangleIv();
}
@Override
public void onDRejectApplyChairman() {
}
@Override
public void onDAgreeApplyChairman(ApplyChairNtf acn) {
}
@Override
public void onScaleChanged(final float curScale) {
int tempScale = (int)(curScale*100f);
toastMsg(tempScale + "%");
runOnUiThread(new Runnable() {
@Override
public void run() {
setCurScale(curScale);
}
});
mHelperHolder.scale(curScale);
//发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(pageId, tempScale);
}
@Override
public void onScaleChangedFromGesture(float scaleFactor, float focusX, float focusY) {
final float curScale = mPageManager.getSelectPage().getCurScale();
final int tempScale = (int)(curScale*100f);
toastMsg(tempScale+"%");
runOnUiThread(new Runnable() {
@Override
public void run() {
setCurScale(curScale);
}
});
//发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendGestureZoomMsg(pageId, scaleFactor, (int) focusX, (int) focusY);
}
@Override
public void onUpdateScaleUI(final float curScale) {
mHelperHolder.updateGestureCurScale(curScale);
runOnUiThread(new Runnable() {
@Override
public void run() {
setCurScale(curScale);
}
});
}
@Override
public void onRotateChanged(int angle, boolean isFinish) {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendRotateMsg((int) page.getId(), angle, isFinish);
}
@Override
public void onUndo() {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendUndoMsg(page.getId(), page.getCurSubPageIndex() - 1);
}
@Override
public void onRedo() {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendRedoMsg(page.getId(), page.getCurSubPageIndex() - 1);
}
@Override
public void onUndoEnable(final boolean enable) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (enable) {
undoBtn.setBackgroundResource(R.drawable.undo_btn_style);
} else {
undoBtn.setBackgroundResource(R.mipmap.undo_unable_icon);
}
undoBtn.setEnabled(enable);
}
});
}
@Override
public void onRedoEnable(final boolean enable) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (enable) {
redoBtn.setBackgroundResource(R.drawable.redo_btn_style);
} else {
redoBtn.setBackgroundResource(R.mipmap.redo_unable_icon);
}
redoBtn.setEnabled(enable);
}
});
}
@Override
public void onGraphUpdate(Graph graph) {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendGraphMsg(graph, (int) page.getId(), page.getCurSubPageIndex() - 1);
}
@Override
public void onTranslateChanged(float ox, float oy, boolean isFinish) {
IPage page = mPageManager.getSelectPage();
TPLog.printError("onTranslateChanged---------------->ox=" + ox + ",oy=" + oy);
mSendHelper.sendScrollMsg(ox, oy, (int) page.getId(), page.getCurSubPageIndex() - 1, isFinish);
}
@Override
public void onCoordinateChanged() {
}
@Override
public void onPageChanged(final int pageIndex,final int curSubPageIndex,final int subPageNum, final boolean nextSubPageEnable, final boolean lastSubPageEnable) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(subPageNum>1){
pageNumLayout.setVisibility(View.VISIBLE);
}else{
pageNumLayout.setVisibility(View.GONE);
}
setSelectPageIndex(curSubPageIndex-1);
IPage page = mPageManager.getPage(pageIndex);
String name = page.getName();
mWb.setBackgroundColor(page.getBackGroundColor());
setWbName(name);
curSubPageNumTv.setText(curSubPageIndex+"");
maxSupPageNumTv.setText(subPageNum+"");
if(subPageNum<2) {
changeSubPageEnable(false);
}else{
TPLog.printError("lastSubPageEnable--->"+lastSubPageEnable+",nextSubPageEnable--->"+nextSubPageEnable);
if(!lastSubPageEnable){
selectSubPageBtn.setEnabled(true);
nextSubPageBtn.setEnabled(true);
preSubPageBtn.setEnabled(false);
}else if(!nextSubPageEnable){
preSubPageBtn.setEnabled(true);
selectSubPageBtn.setEnabled(true);
nextSubPageBtn.setEnabled(false);
}else{
changeSubPageEnable(true);
}
}
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
IPage page = mPageManager.getPage(pageIndex);
setCurScale(page.getCurScale());
}
});
}
@Override
public void cancelSelecImageTimer() {
}
@Override
public void onDelSelectImg(int imgId) {
}
@Override
public void onPaintDrawDown() {
}
@Override
public void onServerConnected() {
// toastMsg("onServerConnected");
}
@Override
public void onLoginServerSuccess() { //登录成功后反馈,一般为断线后登录
//toastMsg("onLoginServerSuccess");
// if(WhiteBoardUtils.isIntoMeeting&&WhiteBoardUtils.isAPPShowing){
if(isUnConnectServer) {
fullHorizontalScreenToastMsg("数据会议服务器连接成功!");
}
isUnConnectServer = false;
if(WhiteBoardUtils.isAPPShowing){
ConnectManager.getInstance().getSender().joinOrCreateMeeting("","",true);
}
dismissDialog(DialogType.NETWORKSTATE);
dismissDialog(DialogType.SURE);
}
@Override
public void onRecMeetingName(String meetingName) {
}
@Override
public void onServerDisconnected() {
TPLog.printKeyStatus("datameeting server disconnected");
if(!isUnConnectServer) {
isUnConnectServer = true;
if(!NetworkUtil.getNetworkState(this)) {
showNetworkStateDialog(true,false);
showNetworkSettingDialog();
}else{
showNetworkStateDialog(false,false);
showIsSureDialog("服务器异常,无法进行数据协作,正在重新连接......");
}
}
}
@Override
public void onServerConnectException(Exception e) {
//Toast.makeText(this,"onServerConnectException",Toast.LENGTH_SHORT).show();
}
@Override
public void onRecCreateMeeting(long resultCode) {
}
@Override
public void onRecJoinMeeting(long resultCode) {
TPLog.printError("receive join meeting result:" + resultCode);
if(resultCode== NetError.ESUCCESS) {
NetUtil.isJoinMeeting = true;
}
}
@Override
public void onRecServerCurBufferSzie(long size) {
Image image = mPageManager.getSelectPage().getCurSubPage().getImage();
SynFileManager.getInstance().sendImage(image);
}
@Override
public void onRecServerReqSyn(long synReqId) {
mSendHelper.sendSynData(mPageManager, synReqId);
}
@Override
public void onRecSynFailed() {
}
@Override
public void onRecSynData(long curPageId,List<Page> pageList) {
mPageManager.getPageList().clear();
mPageManager.setPageList(pageList);
mPageManager.selectPage(curPageId);
Image image = mPageManager.getSelectPage().getCurSubPage().getImage();
if(image!=null){
SynFileManager.getInstance().requestFileInfo(image);
}
}
@Override
public void onRecGraphData(Graph graph) {
if(graph==null)return;
mHelperHolder.requestDrawGraph(graph);
}
@Override
public void onRecImageData(SubPage subpage) {
mPageManager.getSelectPage().addSubPage(subpage);
}
@Override
public void onRecZoomData(float zoom) {
TPLog.printKeyStatus("receive zoom:"+zoom);
mHelperHolder.scale(zoom / 100f);
setCurScale(zoom / 100f);
}
@Override
public void onRecGestureZoomData(float scaleFactor, int focusX, int focusY) {
TPLog.printError("onRecGestureZoomData------->" + scaleFactor);
float zoom = mPageManager.getSelectPage().getCurScale();
zoom = zoom*scaleFactor;
mHelperHolder.postScale(scaleFactor, focusX, focusY);
setCurScale(zoom);
}
@Override
public void onRecScrollData(android.graphics.Point scrollData) {
TPLog.printKeyStatus("receive scroll:x:"+scrollData.x+",y:"+scrollData.y);
Page page = (Page)mPageManager.getSelectPage();
float ox = scrollData.x - page.getOffsetX();
float oy = scrollData.y - page.getOffsetY();
//为了兼容PC,因此接收到的偏移量,这边需要进行特殊处理
mHelperHolder.postTranslate(ox, oy);
}
@Override
public void onRecClearScreen() {
mHelperHolder.clearScreen();
}
@Override
public void onRecCreateWbData(Page page) {
mPageManager.addPage(page);
}
@Override
public void onRecDelWbData(long delWbId,long nextWbId) {
mPageManager.removePage(delWbId);
mPageManager.selectPage(nextWbId);
}
@Override
public void onRecDelAllWbData(long newTabId) {
}
@Override
public void onRecChangePage(long wbId, long subPageIndex) {
subPageIndex = subPageIndex +1;
TPLog.printKeyStatus("onRecChangePage---->wbId="+wbId+",subPageIndex="+subPageIndex);
IPage page = mPageManager.getSelectPage();
if(page.getId()!=wbId) {
mPageManager.selectPage(wbId);
}else {
mPageManager.selectCurPageSubPage((int)(subPageIndex));
}
Image image = mPageManager.getCurSelectSubPage().getImage();
if(image!=null&&!image.isDlSuccess()){
mSendHelper.requestImage(image,mPageManager.getSelectPage().getId(),mPageManager.getCurPageSelectSubPageIndex()-1,((Page)mPageManager.getSelectPage()).getOwnerIndex());
}
mPageManager.notifyPageChanged();
}
@Override
public void onRecServerReqChangePage(long wbId, long subPageIndex) { //服务器请求翻页,其实是请求图片
IPage page = mPageManager.getSelectPage();
Image image = mPageManager.getSelectPage().getCurSubPage().getImage();
mSendHelper.requestServerRecFlow();
// mSendHelper.requestImage(image,page.getId(),page.getCurSubPageIndex()-1,((Page)page).getOwnerIndex());
}
@Override
public void onRecImageDownloaded(long imageId) {
TPLog.printKeyStatus("图片下载完成 Id:"+imageId);
mPageManager.notifyPageChanged();
}
@Override
public void onRecRedoData(long wbId, long subPageIndex) {
mHelperHolder.redo();
}
@Override
public void onRecUndoData(long wbId, long subPageIndex) {
mHelperHolder.undo();
}
@Override
public void onRecLeftRotate() {
int angle = mPageManager.getSelectPage().getCurAngle();
angle = angle - 90;
mHelperHolder.rotate(angle,true);
}
@Override
public void onRecRightRotate() {
int angle = mPageManager.getSelectPage().getCurAngle();
angle = angle + 90;
mHelperHolder.rotate(angle,true);
}
@Override
public void onRecRotate(long angle, long isFinish) {
boolean boo = false;
if(isFinish==0){
boo = true;
}else{
boo = false;
}
mHelperHolder.rotate((int)angle,boo);
}
@Override
public void onRecInsertImg(ImageGraph img) {
}
@Override
public void onRecCoordinateChanged(CoordinateChangedMsg msg) {
}
@Override
public void onRecSelectGrpahCoordinateChanged(ArrayList<GraphCoordinateChangedMsg> list) {
}
@Override
public void onRecDeleteGraph(DeleteGraphMsg msg) {
}
@Override
public void onRecConfMemberListUpdate(int num) {
}
@Override
public void onRecServerConnectNumNtf(int num) {
}
@Override
public void onDToSettingNetwork() {
// toastMsg("打开网络设置!");
try {
StorageMangerJarUtils.toNetWorkSetting(this);
}catch(Exception e){
TPLog.printError("PackageUtils", "not found activity " + StorageMangerJarUtils.PACKAGE_SYSTEM_SETTINGS + "/" + StorageMangerJarUtils.APP_SYSTEM_SETTINGS);
//toastMsg("IMIX设置程序未安装,该功能无法使用!");
}
}
@Override
public void onDRlsDcsMnger() {
}
@Override
public void onDDataConfModeChange(int mode) {
}
@Override
public void onDToFileManager(String path) {
}
/**********************网络状态监听*****************************/
@Override
public void onNetworkUsable() {
TPLog.printKeyStatus("current network usable");
if(!WhiteBoardUtils.isAPPShowing){
return;
}
ConnectManager.getInstance().startReconnect();
//隐藏网络连接对话框
dismissDialog(DialogType.SETTINGNETWORK);
showNetworkStateDialog(false,true);
}
@Override
public void onNetworkUnusable() {
TPLog.printKeyStatus("current network unusable");
if(!WhiteBoardUtils.isAPPShowing){
TPLog.printKeyStatus("white board did not showing");
return;
}
ConnectManager.getInstance().stopReconnect();
//打开网络异常对话框
showNetworkSettingDialog();
showNetworkStateDialog(true, false);
}
/**********************保存白板************************/
@Override
public void savePageStart(int saveCount) {
TPLog.printKeyStatus("need save page count: "+saveCount);
if(saveCount>2){
if(!sendMail&&!qRDownLoad){//发送邮件和二维码下载保存白板时不需要进行进度显示
//showLoadFileDilaog(saveCount,0,false);
needSaveProgressDialog = true;
curSaveProgress = 0;
}
}
}
@Override
public void saveProgress(int progress) {
TPLog.printKeyStatus("current save page progress:"+progress);
if(sendMail||qRDownLoad){
return;
}
if(needSaveProgressDialog) {
curSaveProgress ++;
runOnUiThread(new Runnable() {
@Override
public void run() {
//loadFileDiloagShowAgain();
setCurProgress(curSaveProgress);
}
});
}
}
@Override
public void savePageSuccess(final String savePath) {
TPLog.printKeyStatus("save all page success!");
if(!sendMail&&!qRDownLoad) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (saveQueue.isEmpty() || curSaveAllType == SAVEALL_ONEBYONE) {
String locPath = FileUtils.getAliasPath(savePath,mStroageManager);
String strs[] = locPath.split("/");
String path = "";
for (int i = 0; i < strs.length; i++) {
if (i == (strs.length - 1)) break;
path = path + strs[i] + "/";
}
String msg = "已保存至:" + path;
TPLog.printKeyStatus("page save path:"+path);
dismissDialog(DialogType.LOADFILE);
dismissDialog();
showIsSureDialog(msg);
if(isCloseSave){
mPageManager.removePage(curSavePage);
//发送关闭白板消息
mSendHelper.sendCloseWb(curSavePage.getId(),mPageManager.getSelectPage().getId());
isCloseSave = false;
}
} else {
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
if (curSaveAllType == SAVEALL_NOT_PROMPT) {
onDSaveBtnEvent(saveDirName, isSaveAll);
}
}
}
});
}else if(sendMail){ //发送邮件
TPLog.printKeyStatus("send mail start...");
List<String> filePaths = new ArrayList<String>();
FileUtils.findAllChildFile(mailImageCacheDir,filePaths);
TPLog.printKeyStatus("add "+filePaths.size()+" files to mail");
String images[] = new String[filePaths.size()];
filePaths.toArray(images);
MailUtil.sendImageMail(recMails,mailTitle,images);
sendMail = false;
}else if(qRDownLoad){
// List<String> filePaths = new ArrayList<String>();
// FileUtils.findAllChildFile(FileUtils.RUNNING_CACHE,filePaths);
String title = FileUtils.getCurWhiteBoardSaveDir();
String subtitle = mPageManager.getPageCount()+"个白板,共"+mPageManager.getSubPageCount()+"页";
setQRCodeCacheFileDir(title,subtitle,FileUtils.RUNNING_CACHE);
qRDownLoad = false;
}
}
@Override
public void savePageFailed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
TPLog.printKeyStatus("save page failed");
String msg = "文件保存失败!";
dismissDialog(DialogType.LOADFILE);
dismissDialog();
showIsSureDialog(msg);
}
});
}
@Override
public void onPageCountChanged(int count) {
createWbBtn.setBackgroundResource(R.drawable.create_wb_btn_style);
createWbBtn.setClickable(true);
}
/************************邮件发送******************************/
@Override
public void onSendMailSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissLoadDialog();//现在可以不要,不过留着也不会报错 ,留着先
String msg = "邮件发送成功!";
TPLog.printKeyStatus("send mail success!");
showIsSureDialog(msg);
}
});
}
@Override
public void onSendMailFailed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissLoadDialog();
String msg = "邮件发送失败!";
showIsSureDialog(msg);
}
});
}
@Override
public void onSendMailUnknownHost() {//这个暂时不处理
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// dismissLoadDialog();
// String msg = "邮件发送失败!";
// showIsSureDialog(msg);
// }
// });
}
@Override
public void onConnectMailServerFailed() {
}
@Override
public void onSendMailAuthenticationFailed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissLoadDialog();
dismissDialog();
showToMailConfigSettingDialog();
}
});
}
/************************打开文件*****************************/
class OpenFileListener implements OpenFileManager.OnFileToImageListener{
private int totalCount;
@Override
public void onPageCount(final int count, final String checkCode) {
runOnUiThread(new Runnable() {
@Override
public void run() {
totalCount = count;
TPLog.printKeyStatus("开始打开文件,文件总页数:"+count+",checkCode:"+checkCode);
String pageId = mPageManager.getSelectPage().getId()+"";
if(!pageId.equals(checkCode))
return;
setProgressMax(count);
}
});
}
@Override
public void onProgress(final int progress, final String checkCode) {
TPLog.printKeyStatus("打开文件当前进度:"+progress+"/"+totalCount);
runOnUiThread(new Runnable() {
@Override
public void run() {
String pageId = mPageManager.getSelectPage().getId() + "";
if (!pageId.equals(checkCode))
return;
setCurProgress(progress);
}});
}
@Override
public void onFialed(String errorMsg,String path,final String checkCode) {
TPLog.printKeyStatus("文件打开失败!");
runOnUiThread(new Runnable() {
@Override
public void run() {
String pageId = mPageManager.getSelectPage().getId() + "";
if (!pageId.equals(checkCode))
return;
// if (!hasDialogShowing()) {
// showLoadFileDilaog(1, 0,true);
// }
showLoadFileFailedText();
}});
}
@Override
public void onComplete(List<String> files, String fileName, String checkCode) {
TPLog.printKeyStatus("打开文件成功,fileName="+fileName);
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissDialog();
}
});
String pageId = mPageManager.getSelectPage().getId()+"";
if(!pageId.equals(checkCode))
return;
IPage page = mPageManager.getSelectPage();
int count = files.size();
//1.发送文档打开完成命令
mSendHelper.sendOpenOfficeComplete(page.getId());
//2.发送文档总页数
mSendHelper.sendSubpageCountMsg(mPageManager.getSelectPage().getId(), count);
for(int i = 0;i<files.size();i++){
Image image = WhiteBoardUtils.createImage(files.get(i),true);
image.setSubpageIndex(i);
SubPage subPage = new SubPage(image);
subPage.setIndex(i);
page.addSubPage(subPage);
//3.发送文件列表
SynFileManager.getInstance().sendImageInfo(image);
//4.如果是第一张图的话,就发送文件信息和文件内容到服务器
if (i == 0) {
SynFileManager.getInstance().sendImage(image);
}
}
mPageManager.notifyPageChanged();
//新需求,打开文件完毕后,修改画笔颜色为红色
// if(mHelperHolder.getPaintColor() == WhiteBoardUtils.colors[0]) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onDPenColorBtnEvent(WhiteBoardUtils.colors[1]);
}
});
//}
//新需求打开文件默认宽度自适应 去掉了
// onDWidthSelfBtnEvent();
}
}
@Override
protected void onResume() {
super.onResume();
TPLog.printError("TouchDataActivity---------------->onResume");
ConnectManager.getInstance().setCallback(this);
WhiteBoardUtils.isAPPShowing = true;
ConnectManager.getInstance().getSender().joinOrCreateMeeting("", "", true); // 每次App启动都会执行一次加入会议操作
intent = new Intent();
intent.setAction("com.kedacom.touchdata");
intent.putExtra("isShow", true);
sendBroadcast(intent);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
TPLog.printError("TouchDataActivtiy ------------onStop--------------->");
//ConnectManager.getInstance().setCallback(null);
dismissWhiteBoardNameDialog();
WhiteBoardUtils.isAPPShowing = false;
NetUtil.isJoinMeeting = false;
mSendHelper.quitMeeting();
//finish();
intent.putExtra("isShow",false);
sendBroadcast(intent);
}
@Override
protected void onDestroy() {
TPLog.printError("TouchDataActivtiy -> onDestroy");
ConnectManager.getInstance().setCallback(null);
super.onDestroy();
NetworkBroadcastReceiver.unRegisterOnNetworkChangeListener(this);
//mHelperHolder.onDestory();
//WhiteBoardUtils.resetCurPageNum();
// android.os.Process.killProcess( android.os.Process.myPid());
mWb.destroy();
if(mHelperHolder!=null)
mHelperHolder.onDestory();
if(mPageManager!=null)
mPageManager.onDestroy();
WhiteBoardUtils.reset();
}
private void restore(Bundle saveState) {
if (saveState == null) {
return;
}
if (!saveState.containsKey("PAGE")) {
return;
}
//还原Page页
Parcelable parcelabe[] = saveState.getParcelableArray("PAGE");
if (parcelabe == null) {
return;
}
List<Page> pages = new ArrayList<Page>();
for (int i = 0; i < parcelabe.length; i++) {
pages.add((Page) parcelabe[i]);
}
int curPageIndex = saveState.getInt("SelectPageIndex");
mPageManager.setPageList(pages);
mPageManager.selectPage(curPageIndex);
Page page = (Page) mPageManager.getSelectPage();
//还原基础数据
mHelperHolder.translate(page.getOffsetX(), page.getOffsetY());
mHelperHolder.scale(page.getCurScale());
mHelperHolder.rotate(page.getCurAngle(), false);
//还原画板面板数据
int color = saveState.getInt("Color");
mHelperHolder.setPaintColor(color);
float width = saveState.getFloat("StrokeWidth");
TPLog.printError("2StrokeWidth------------->"+width);
mHelperHolder.setPaintStrokeWidth(width);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
/*
TPLog.printKeyStatus("onSaveInstanceState---->start save data");
List<IPage> list = mPageManager.getPageList();
if(list==null)return;
int count = list.size();
Page[] pages = new Page[count];
for (int i = 0; i < count; i++) {
IPage page = list.get(i);
pages[i] = (Page) page;
}
outState.putParcelableArray("PAGE", pages);
outState.putInt("SelectPageIndex", mPageManager.getSelectPageIndex());
outState.putInt("Color", mHelperHolder.getPaintColor());
outState.putFloat("StrokeWidth", mHelperHolder.getPaintStrokeWidth());
outState.setClassLoader(getClass().getClassLoader());
TPLog.printKeyStatus("onSaveInstanceState---->暂存数据完成!");
*/
super.onSaveInstanceState(outState);
}
private static final String ACTION_SWTICH_FILE_ACTIVITY = "com.kedacom.fileexplorer.FileRetriever";
private void startSwitchFileActivity(){
try {
Intent intent = new Intent(ACTION_SWTICH_FILE_ACTIVITY);
startActivityForResult(intent, 1);
}catch(Exception e){
toastMsg("文件管理未安装,该功能无法使用!");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String returnedData = data.getStringExtra("file_retriever_path");
if (returnedData!=null&&!returnedData.trim().isEmpty()) {
onDSwitchFile(returnedData);
}
}
break;
default:
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == 19){
Intent intent1 = new Intent();
intent1.setAction("android.intent.action.MAIN");
intent1.addCategory("android.intent.category.HOME");
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
System.out.println("keycode" + keyCode);
int pageCount = mPageManager.getPageCount();
int selectPageIndex = mPageManager.getSelectPageIndex();
if (keyCode == 21){ //向上翻页键
System.out.println("pageCount"+pageCount);
if (selectPageIndex < pageCount-1 ) {
prePage(selectPageIndex);
}else if (selectPageIndex == pageCount-1){
selectPageIndex = -1;
prePage(selectPageIndex);
}
}else if (keyCode == 22){ //向下翻页键
if (selectPageIndex > 0 ) {
nextPage(selectPageIndex);
}else if (selectPageIndex == 0){
selectPageIndex = pageCount + 1;
nextPage(selectPageIndex);
}
}else if (keyCode == 20){
if(!hasDialogShowing()){
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
resetSelectBtn(penBtn.getId());
subPenIv.setBackgroundResource(R.mipmap.triangle_select_icon);
//弹出画笔选择框
showSwitchColorDialog(subPenIv);
}
}
return true;
}
private void nextPage(int selectPageIndex) {
selectPageIndex = selectPageIndex - 1;
mPageManager.selectPage(selectPageIndex);
Page page = (Page) mPageManager.getSelectPage();
long id = page.getId();
System.out.println("subPageIndex" + selectPageIndex);
mSendHelper.sendChangePageMsg(id, selectPageIndex, page.getCurSubPage().getImage());
}
private void prePage(int selectPageIndex) {
selectPageIndex = selectPageIndex + 1;
mPageManager.selectPage(selectPageIndex);
Page page = (Page) mPageManager.getSelectPage();
long id = page.getId();
System.out.println("subPageIndex" + selectPageIndex);
mSendHelper.sendChangePageMsg(id, selectPageIndex, page.getCurSubPage().getImage());
}
} | UTF-8 | Java | 69,507 | java | TouchDataActivity.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by zhanglei on 2016/9/22.\n */\npublic class TouchDataActivity ",
"end": 2552,
"score": 0.9994292259216309,
"start": 2544,
"tag": "USERNAME",
"value": "zhanglei"
}
] | null | [] | package com.kedacom.touchdata;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.kedacom.httpserver.utils.Network;
import com.kedacom.receiver.NetworkBroadcastReceiver;
import com.kedacom.service.BootService;
import com.kedacom.storagelibrary.model.MailboxInfo;
import com.kedacom.storagelibrary.model.StorageItem;
import com.kedacom.storagelibrary.model.WifiInfo;
import com.kedacom.storagelibrary.unity.StroageManager;
import com.kedacom.touchdata.filemanager.FileUtils;
import com.kedacom.touchdata.filemanager.OpenFileManager;
import com.kedacom.touchdata.mail.MailUtil;
import com.kedacom.touchdata.net.ConnectManager;
import com.kedacom.touchdata.net.SendHelper;
import com.kedacom.touchdata.net.SynFileManager;
import com.kedacom.touchdata.net.callback.NetCallback;
import com.kedacom.touchdata.net.entity.ApplyChairNtf;
import com.kedacom.touchdata.net.entity.CoordinateChangedMsg;
import com.kedacom.touchdata.net.entity.DeleteGraphMsg;
import com.kedacom.touchdata.net.entity.GraphCoordinateChangedMsg;
import com.kedacom.touchdata.net.utils.NetError;
import com.kedacom.touchdata.net.utils.NetUtil;
import com.kedacom.touchdata.whiteboard.BaseActivity;
import com.kedacom.touchdata.whiteboard.data.PageManager;
import com.kedacom.touchdata.whiteboard.graph.Graph;
import com.kedacom.touchdata.whiteboard.graph.Image;
import com.kedacom.touchdata.whiteboard.graph.ImageGraph;
import com.kedacom.touchdata.whiteboard.helper.IHelperHolder;
import com.kedacom.touchdata.whiteboard.page.IPage;
import com.kedacom.touchdata.whiteboard.page.Page;
import com.kedacom.touchdata.whiteboard.page.SubPage;
import com.kedacom.touchdata.whiteboard.utils.WhiteBoardUtils;
import com.kedacom.touchdata.whiteboard.view.IWhiteBoardStateChanagedListener;
import com.kedacom.touchdata.whiteboard.view.WhiteBoardView;
import com.kedacom.tplog.TPLog;
import com.kedacom.utils.ArithUtil;
import com.kedacom.utils.NetworkUtil;
import com.kedacom.utils.StorageMangerJarUtils;
import com.kedacom.utils.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zhanglei on 2016/9/22.
*/
public class TouchDataActivity extends BaseActivity implements IWhiteBoardStateChanagedListener, PageManager.ISavePageListener,MailUtil.OnSendMailListener,NetCallback,NetworkBroadcastReceiver.OnNetworkChangeListener {
private PageManager mPageManager;
private StroageManager mStroageManager;//U盘管理类
private WhiteBoardView mWb;
private IHelperHolder mHelperHolder;
private RelativeLayout bottomLayout;
private TextView wbNameTv;
private LinearLayout closeWbBtn;
private Button dragBtn;
private LinearLayout penBtn;
private ImageView subPenBtn;
private ImageView subPenIv;
private View penColorTag;
private LinearLayout eraseBtn;
private ImageView subEraseBtn;
private ImageView subEraseIv;
private Button undoBtn;
private Button redoBtn;
private Button moreBtn;
private Button createWbBtn;
private Button browseWbListBtn;
private Button menuBtn;
private RelativeLayout pageNumLayout;
private Button preSubPageBtn;
private Button nextSubPageBtn;
private LinearLayout selectSubPageBtn;
private TextView curSubPageNumTv;
private TextView maxSupPageNumTv;
private TextView subPageNumBiasLine;
private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "image7.jpg";
private SendHelper mSendHelper;
private ConnectManager mConnectManager;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
init();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touchdata);
initView();
initBtnClick();
initWbPage(savedInstanceState);
}
private void init(){
//检测服务是否启动,没有启动 执行启动
Intent intent = new Intent(this, BootService.class);
if(!Utils.isServiceRunning(this,"com.kedacom.service.BootService")){
TPLog.printKeyStatus("BootService 未启动");
startService(intent);
}else{
TPLog.printKeyStatus("BootService 已启动");
}
//初始化白板工具类
WhiteBoardUtils.init(this);
MailUtil.setOnSendMailListener(this);
//创建页面管理器
mPageManager = new PageManager();
SynFileManager.getInstance().setPageManager(mPageManager);
ConnectManager.getInstance().setCallback(this);
// ConnectManager.getInstance().start(NetUtil.IP,NetUtil.PORT);
mSendHelper = SendHelper.getInstance();
//初始化网络监听
NetworkBroadcastReceiver.registerOnNetworkChangeListener(this);
//初始化U盘管理类
mStroageManager = new StroageManager(this);
}
private void initView(){
bottomLayout = (RelativeLayout) findViewById(R.id.bottom);
wbNameTv = (TextView) findViewById(R.id.wbNameTv);
closeWbBtn = (LinearLayout) findViewById(R.id.closeWbBtn);
dragBtn = (Button) findViewById(R.id.dragBtn);
penBtn = (LinearLayout) findViewById(R.id.penBtn);
subPenBtn = (ImageView) findViewById(R.id.subPenBtn);
subPenIv = (ImageView) findViewById(R.id.subPenIv);
penColorTag = findViewById(R.id.colorTag);
eraseBtn = (LinearLayout) findViewById(R.id.eraseBtn);
subEraseBtn = (ImageView) findViewById(R.id.subEraseBtn);
subEraseIv = (ImageView) findViewById(R.id.subEraseIv);
undoBtn = (Button) findViewById(R.id.undoBtn);
redoBtn = (Button) findViewById(R.id.redoBtn);
moreBtn = (Button) findViewById(R.id.moreBtn);
createWbBtn = (Button)findViewById(R.id.createWbBtn);
browseWbListBtn = (Button)findViewById(R.id.browseWbListBtn);
menuBtn = (Button)findViewById(R.id.menuBtn);
preSubPageBtn = (Button) findViewById(R.id.preSubPageBtn);
nextSubPageBtn = (Button) findViewById(R.id.nextSubPageBtn);
selectSubPageBtn = (LinearLayout) findViewById(R.id.selectPageNumBtn);
curSubPageNumTv = (TextView) findViewById(R.id.curPageNumTv);
maxSupPageNumTv = (TextView) findViewById(R.id.maxPageNumTv);
subPageNumBiasLine = (TextView) findViewById(R.id.pageNumBiasLine);
pageNumLayout= (RelativeLayout)findViewById(R.id.pageNumLayout);
penBtn.setClickable(true);
eraseBtn.setClickable(true);
mWb = (WhiteBoardView) findViewById(R.id.mWhiteBoardView);
mWb.setIWhiteBoardStateChanagedListener(this);
}
private void initWbPage(Bundle savedInstanceState){
if(savedInstanceState==null) {
Page page = WhiteBoardUtils.createDefWbPage();
page.addSubPage(new SubPage());
mPageManager.addPage(page);
page.setBackGroundColor(getCurBackgroundColor());
}else{
restore(savedInstanceState);
}
mWb.setPageManager(mPageManager);
mHelperHolder = mWb.getHelperHolder();
setPageManager(mPageManager);
mPageManager.setISavePageListener(this);
mWb.setBackgroundColor(getCurBackgroundColor());
}
private void initBtnClick(){
//废弃
closeWbBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int count = mPageManager.getPageCount();
if(count>=1) {
int curPosintion = mPageManager.getSelectPageIndex();
mPageManager.removePage(curPosintion);
}else{
finish();
}
}
});
dragBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
resetSelectBtn(view.getId());
//开启拖动模式
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_DRAG);
}
});
subPenBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
resetSelectBtn(penBtn.getId());
if(mHelperHolder.getCurOpType() == WhiteBoardUtils.GRAPH_PEN) {
// subPenIv.setBackgroundResource(R.mipmap.triangle_select_icon);
// //弹出画笔选择框
// showSwitchColorDialog(subPenIv);
}else {
subPenIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
}
}
});
subPenIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
resetSelectBtn(penBtn.getId());
subPenIv.setBackgroundResource(R.mipmap.triangle_select_icon);
//弹出画笔选择框
showSwitchColorDialog(subPenIv);
}
});
subEraseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
resetSelectBtn(eraseBtn.getId());
if(mHelperHolder.getCurOpType() == WhiteBoardUtils.GRAPH_ERASE||mHelperHolder.getCurOpType() == WhiteBoardUtils.GRAPH_ERASE_AREA) {
//弹出擦除模式选择对话框
// showSwitchEraseDialog(subEraseIv);
// subEraseIv.setBackgroundResource(R.mipmap.triangle_select_icon);
}else{
subEraseIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE);
}
}
});
subEraseIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(hasDialogShowing()){
dismissDialog();
return;
}
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE);
resetSelectBtn(eraseBtn.getId());
subEraseIv.setBackgroundResource(R.mipmap.triangle_select_icon);
//弹出擦除模式选择对话框
showSwitchEraseDialog(subEraseIv);
}
});
undoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mHelperHolder.undo();
//发送撤销消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex() - 1;
mSendHelper.sendUndoMsg(pageId, subPageIndex);
}
});
redoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mHelperHolder.redo();
//发送恢复消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex() - 1;
mSendHelper.sendRedoMsg(pageId, subPageIndex);
}
});
moreBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
moreBtn.setBackgroundResource(R.mipmap.more_select_icon);
showMoreMenuDialog(moreBtn);
}
});
createWbBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int normalBg = WhiteBoardUtils.curBackground;
mWb.setBackgroundColor(normalBg);
Page page = WhiteBoardUtils.createDefWbPage();
page.setBackGroundColor(normalBg);
String name = page.getName();
setWbName(name);
mPageManager.addPage(page);
int count = mPageManager.getPageCount();
if (count >= 20) {
//toastMsg("白板数量已达上限!");
createWbBtn.setBackgroundResource(R.mipmap.create_wb_unable_icon);
createWbBtn.setClickable(false);
return;
}
//发送创建白板消息
mSendHelper.sendCreateNewPageMsg(page);
}
});
browseWbListBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view1) {
browseWbListBtn.setBackgroundResource(R.mipmap.browse_wb_select_icon);
showPageThumbnailDialog();
}
});
menuBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
menuBtn.setBackgroundResource(R.mipmap.menu_select_icon);
menuBtn.setEnabled(false);
showMenuDialog(view);
}
});
preSubPageBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPageManager.previousSubPage();
//发送翻页消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex();
Image image = page.getCurSubPage().getImage();
mSendHelper.sendChangePageMsg(pageId,subPageIndex,image);
mSendHelper.requestImage(image,pageId,subPageIndex,((Page)page).getOwnerIndex());
}
});
nextSubPageBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPageManager.nextSubPage();
//发送翻页消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex();
Image image = page.getCurSubPage().getImage();
mSendHelper.sendChangePageMsg(pageId, subPageIndex, image);
mSendHelper.requestImage(image, pageId, subPageIndex, ((Page) page).getOwnerIndex());
}
});
selectSubPageBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isSelectSubPageBtn(true);
//弹出页码选择框
showPageNumDialog(mPageManager.getSelectPage().getSubPageCount(),selectSubPageBtn);
}
});
}
private void changeSubPageEnable(boolean isEnable){
selectSubPageBtn.setEnabled(isEnable);
nextSubPageBtn.setEnabled(isEnable);
preSubPageBtn.setEnabled(isEnable);
}
private void isSelectSubPageBtn(boolean isSelect){
int color = getResources().getColor(R.color.pagenum_normal_textcolor);
if(isSelect) {
color = getResources().getColor(R.color.pagenum_select_textcolor);
}
curSubPageNumTv.setTextColor(color);
subPageNumBiasLine.setTextColor(color);
maxSupPageNumTv.setTextColor(color);
}
private void resetSelectBtn(int btnId){
dragBtn.setBackgroundResource(R.mipmap.drag_normal_icon);
subPenBtn.setBackgroundResource(R.mipmap.pen_normal_icon);
subEraseBtn.setBackgroundResource(R.mipmap.erase_normal_icon);
switch(btnId){
case R.id.dragBtn:
dragBtn.setBackgroundResource(R.mipmap.drag_select_icon);
break;
case R.id.penBtn:
subPenBtn.setBackgroundResource(R.mipmap.pen_select_icon);
break;
case R.id.eraseBtn:
subEraseBtn.setBackgroundResource(R.mipmap.erase_select_icon);
break;
}
}
//重置所有的弹出框弹出标识
private void resetTriangleIv(){
subPenIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
subEraseIv.setBackgroundResource(R.mipmap.triangle_normal_icon);
moreBtn.setBackgroundResource(R.mipmap.more_normal_icon);
browseWbListBtn.setBackgroundResource(R.mipmap.browse_wb_normal_icon);
menuBtn.setBackgroundResource(R.mipmap.menu_normal_icon);
isSelectSubPageBtn(false);
menuBtn.setEnabled(true);
}
@Override
public void onDCancelBtnEvent(DialogType dtype) {
resetTriangleIv();
if(needSaveProgressDialog&&curSavePage!=null&&dtype != DialogType.LOADFILE) {
curSaveProgress += curSavePage.getSubPageCount();
setCurProgress(curSaveProgress);
}else if(needSaveProgressDialog&&dtype == DialogType.LOADFILE){ //取消保存
//停止保存
saveQueue.clear();
if(curSavePage!=null){
((Page)curSavePage).stopSave();
}
curSavePage = null;
if(isExit){ //如果是退出保存的话,取消保存就直接退出应用
finish();
}
}else if(dtype == DialogType.LOADFILE){ //取消打开文件
int index = mPageManager.getSelectPageIndex();
mPageManager.removePage(index);
}
if(dtype == DialogType.FILEEXIST){
if(isCloseSave){
isCloseSave = false;
mPageManager.removePage(curSavePage);
}
if(isExit){
if(curSaveAllType == SAVEALL_ONEBYONE){
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
String msg = "\"" + curSavePage.getName() + "\""+" 是否保存?";
showIsSaveFileDilaog(msg);
}else{
finish();
}
}else if(curSaveAllType == SAVEALL_NOT_PROMPT){
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
onDSaveBtnEvent(saveDirName,true);
}else{
finish();
}
}
}
}
}
@Override
public void onDSureBtnEvent(DialogType dtype) {
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
if(curSaveAllType == SAVEALL_ONEBYONE){
String msg = "\"" + curSavePage.getName() + "\""+" 是否保存?";
showIsSaveFileDilaog(msg);
}
}else if(isExit){
finish();
}else if(isUnConnectServer&&dtype == DialogType.SURE){
showNetworkStateDialog(false,true);
}
}
@Override
public void onDOpenDirBtnEvent(String filePath) {
}
@Override
public void onDResetFileNameBtnEvent() {
// String aliasPath = FileUtils.getAliasPath(savePath);
//TPLog.printError("aliasPath-->"+aliasPath);
showSaveDialog();
}
@Override
public void onDReplaceFileBtnEvent() {
String localFilePath = savePath + File.separator + saveDirName;
FileUtils.deleteFile(localFilePath);//删掉之前的所有文件
onDSaveBtnEvent(saveDirName,isSaveAll);
}
private void initSaveAll(){
isExit = true;
setSaveDialogSaveAllBtnIsDisplay(false);
saveQueue.clear();
List<IPage> list = mPageManager.getPageList();
int count = list.size();
int subPageCount = 0; //统计所有子页个数
for(int i = 0;i<count;i++){
saveQueue.add(list.get(i));
subPageCount += list.get(i).getSubPageCount();
}
if(saveQueue.isEmpty())return;
curSavePage = saveQueue.remove(0);
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
savePageStart(subPageCount);
}
@Override
public void onDExitSaveBtnEvent() {//保存全部按钮
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
initSaveAll();
curSaveAllType = SAVEALL_NOT_PROMPT;
onDSaveBtnEvent(saveDirName, isSaveAll);
}
@Override
public void onDExitNotSaveBtnEvent() {
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
if(needSaveProgressDialog){//有保存进度对话框,关闭先
dismissDialog(DialogType.LOADFILE);
}
initSaveAll();
curSaveAllType = SAVEALL_ONEBYONE;
String msg = "\""+ curSavePage.getName() +"\"" + " 是否保存?";
showIsSaveFileDilaog(msg);
}
@Override
public void onDExitCancelBtnEvent() {
finish();
}
@Override
public void onDPenSizeBtnEvent(int size) {
mHelperHolder.setPaintStrokeWidth(size);
}
@Override
public void onDPenColorBtnEvent(int color) {
mHelperHolder.setPaintColor(color);
penColorTag.setBackgroundColor(color);
}
@Override
public void onDEraseBtnEvent() {
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE);
}
@Override
public void onDAreaEraseBtnEvent() {
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_ERASE_AREA);
}
@Override
public void onDClearScreenBtnEvent() {
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
resetSelectBtn(penBtn.getId());
mHelperHolder.clearScreen();
//发送清屏数据
mSendHelper.sendClearScreenMsg();
}
@Override
public float onDZoomOutBtnEvent() {
float curScale = mPageManager.getSelectPage().getCurScale();
//curScale = curScale + 0.1f; //java浮点运算就是坑
curScale = ArithUtil.add(curScale, 0.1f);
if(curScale>3.0f){
curScale = 3.0f;
}
mHelperHolder.scale(curScale);
// //发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(pageId, curScale * 100f);
return curScale;
}
@Override
public float onDZoomInBtnEvent() {
float curScale = mPageManager.getSelectPage().getCurScale();
if(curScale>3.0f){
curScale = 3.0f;
}
//curScale = curScale - 0.1f;
curScale = ArithUtil.sub(curScale,0.1f);
if(curScale<0.5f){
curScale = 0.5f;
}
mHelperHolder.scale(curScale);
// //发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(pageId, curScale * 100f);
return curScale;
}
@Override
public void onDRotateLeftBtnEvent() {
int curAngle = mPageManager.getSelectPage().getCurAngle();
curAngle = curAngle - 90;
mHelperHolder.rotate(curAngle, true);
//发送消息
long pageId = mPageManager.getSelectPage().getId();
//mSendHelper.sendRotateMsg((int)pageId,curAngle,true);
mSendHelper.sendLeftOrRightRotateMsg(true, pageId);
}
@Override
public void onDRotateRightBtnEvent() {
int curAngle = mPageManager.getSelectPage().getCurAngle();
curAngle = curAngle + 90;
mHelperHolder.rotate(curAngle, true);
//发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendLeftOrRightRotateMsg(false, pageId);
}
@Override
public void onDHeightSelfBtnEvent() {//需要进行图片居中计算
mHelperHolder.heightSelf();
IPage page = mPageManager.getSelectPage();
mSendHelper.sendScrollMsg(page.getOffsetX(),page.getOffsetY(),page.getId(),mPageManager.getCurPageSelectSubPageIndex(),true);
mSendHelper.sendScaleMsg(page.getId(),page.getCurScale());
}
@Override
public void onDWidthSelfBtnEvent() {
mHelperHolder.widthSelf();
IPage page = mPageManager.getSelectPage();
mSendHelper.sendScrollMsg(page.getOffsetX(),page.getOffsetY(),page.getId(),mPageManager.getCurPageSelectSubPageIndex(),true);
mSendHelper.sendScaleMsg(page.getId(), page.getCurScale() * 100f);
}
@Override
public void onDOneToOneBtnEvent() {
mHelperHolder.scale(1.0f);
//发送消息
long id = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(id, 1.0f * 100f);
}
@Override
public void onDCloseWbBtnEvent() {
onDCloseWbBtnEvent(mPageManager.getSelectPage());
}
@Override
public void onDCloseWbBtnEvent(IPage page) {
boolean isNeedSave = page.isNeedSave();
TPLog.printKeyStatus("关闭白板,是否需要保存:" + isNeedSave);
if(!isNeedSave) {
// if(mPageManager.getPageCount()==1){
// dismissDialog();
// }
mPageManager.removePage(page);
//发送关闭白板消息
mSendHelper.sendCloseWb(page.getId(),mPageManager.getSelectPage().getId());
}else{
dismissDialog();
isCloseSave = true;
curSavePage = page;
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
saveDirName = page.getName();
String msg = "\""+page.getName() + "\" 是否保存?";
showCloseSelectSaveWbDiloag(msg);
}
}
@Override
public void onDIsCloseWbSureBtnEvent(IPage page) {
}
@Override
public void onDCloseAllWbBtnEvent() {
}
@Override
public void onDSwitchDeviceSaveBtnEvent(String path) {
if(!new File(path).exists()){
showIsSureDialog("保存操作失败,外接存储设备已拔出!");
return;
}
if(!path.endsWith("/")){
path = path + File.separator;
}
TPLog.printKeyStatus("select storage device path:"+path);
setSaveDialogSaveAllBtnIsDisplay(true);
curSavePage = mPageManager.getSelectPage();
saveDirName = curSavePage.getName();
if(!path.contains(FileUtils.SDPATH)) {
savePath = path + FileUtils.USBFlashDriveSaveDir + FileUtils.getCurWhiteBoardSaveDir();
}else{
savePath = path + FileUtils.getCurWhiteBoardSaveDir();
}
FileUtils.checkDirExists(savePath);
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
showSaveDialog();
}
@Override
public void onDSwitchBackGroundColor(int color) {
mHelperHolder.setBackgroundColor(color);
mWb.setBackgroundColor(color);
mPageManager.getSelectPage().setBackGroundColor(color);
}
@Override
public void onDSelectSubPageNum(int pageNum) {
mPageManager.selectCurPageSubPage(pageNum);
//发送消息
IPage page = mPageManager.getSelectPage();
long pageId = page.getId();
int subPageIndex = page.getCurSubPageIndex();
mSendHelper.sendChangePageMsg(pageId, subPageIndex, page.getCurSubPage().getImage());
}
@Override
public void onDSelectPage(IPage page) {
mPageManager.selectPage(page.getId());
int subPageIndex = page.getCurSubPageIndex();
mSendHelper.sendChangePageMsg(page.getId(), subPageIndex, page.getCurSubPage().getImage());
}
@Override
public void onDMenuOpenFileBtnEvent() { //打开文件选择器
// String devices[] = {"本机文件"};
// FileEntity fe = FileUtils.findFiles(FileUtils.SDPATH);
// showSwitchFileDialog(devices,fe);
//showSwitchFileDialog();
int count = mPageManager.getPageCount();
if(count>=20){
toastMsg("当前白板页数量创建已达到上限,文件打开失败!");
}else{
startSwitchFileActivity();
}
}
//onDSwitchDeviceSaveBtnEvent
@Override
public void onDMenuSaveBtnEvent() {
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
//检查是否有U盘存在
//true
List<StorageItem> mStorageItems = mStroageManager.getStorageItems();
if(mStorageItems!=null&&!mStorageItems.isEmpty()) {
showSwitchSaveDeviceDialog(mStorageItems);
}else {
//false
//U盘不存在直接跳转到保存界面
setSaveDialogSaveAllBtnIsDisplay(true);
curSavePage = mPageManager.getSelectPage();
saveDirName = curSavePage.getName();
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
showSaveDialog();
}
}
@Override
public void onDMenuSendMailBtnEvent() {
if(sendMail){
toastMsg("设备繁忙,请稍后再试!");
return;
}
if(!NetworkUtil.getNetworkState(this)){
showNetworkSettingDialog();
}else {
//sendMail = true;
showSendMailDialog();
}
}
@Override
public void onDMenuScanQRBtnEvent() {
if(NetworkUtil.getNetworkState(this)) {
TPLog.printKeyStatus("show qr code dialog and save current all page");
qRDownLoad = true;
showQRCodeDialog();
FileUtils.deleteFile(FileUtils.RUNNING_CACHE);
mPageManager.saveAllPage(FileUtils.RUNNING_CACHE);
}else{
TPLog.printKeyStatus(" qr code dialog display failed ,network unusable, network setting dialog showing");
showNetworkSettingDialog();
}
}
@Override
public void onDMenuChangeBgBtnEvent() {
showSwitchBackGroundDialog();
}
@Override
public void onDMenuExitBtnEvent() {
int count = mPageManager.getPageCount();
boolean needSave = false;
for(int i = 0;i<count;i++){
IPage page = mPageManager.getPage(i);
if(page.isNeedSave()){
needSave = true;
break;
}
}
showQuitIsSaveFileDialog();
}
//保存文件按钮触发事件 需要在此方法检查文件是否存在,进行后续处理
@Override
public void onDSaveBtnEvent(String dirName,boolean issa) {
isSaveAll = issa;
saveDirName = dirName;
final String curSavePath = savePath;
String filePath = curSavePath + File.separator + saveDirName;
TPLog.printKeyStatus("文件保存路径:"+filePath);
boolean isExists = FileUtils.checkFileExists(filePath);
if(isExists){//文件已经存在弹出文件存在对话框
if(needSaveProgressDialog){//有保存进度对话框,关闭先
dismissDialog(DialogType.LOADFILE);
}
String hintText = "\""+saveDirName+"\"文件已经存在,是否替换?";
showWhiteBoardNameDialog();
showFileExistDialog(hintText);
}else{
if(isSaveAll) {
//如果保存所有的类型不是逐个保存或者全部保存那么就是手动保存
if(curSaveAllType != SAVEALL_ONEBYONE&&curSaveAllType != SAVEALL_NOT_PROMPT){
savePageStart(curSavePage.getSubPageCount());
}
mPageManager.savePage(curSavePage,curSavePath,saveDirName);
}else{
mPageManager.saveSelectSubPage(curSavePage,curSavePath,saveDirName);
}
}
}
@Override
public void onDSaveDilaogCancelBtnEvent() {
if(!saveQueue.isEmpty()){
curSavePage = saveQueue.remove(0);
saveDirName = curSavePage.getName();
savePath = FileUtils.SAVE_WRITEBOARD_DIR+FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
if(curSaveAllType == SAVEALL_ONEBYONE) {
String msg = "\""+curSavePage.getName() + "\""+" 是否保存?";
showIsSaveFileDilaog(msg);
}else{
onDSaveBtnEvent(saveDirName,true);
}
}else{
if(isCloseSave){
mPageManager.removePage(curSavePage);
isCloseSave = false;
}
}
}
@Override
public void onDSaveAllPageBtnEvent(String path, String dirName) {
}
@Override
public void onDIsSaveDialogSurBtnEvent() {
dismissDialog(DialogType.LOADFILE);
showSaveDialog();
}
@Override
public void onDIsSaveDialogCancelBtnEvent() {
if(curSaveAllType == SAVEALL_ONEBYONE&&!saveQueue.isEmpty()){
curSaveProgress += curSavePage.getSubPageCount();
IPage page = saveQueue.remove(0);
curSavePage = page;
savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
saveDirName = page.getName();
String msg = "\""+page.getName() + "\" 是否保存?";
dismissDialog(DialogType.LOADFILE);
showIsSaveFileDilaog(msg);
}else if(!isExit&&isCloseSave){
mPageManager.removePage(curSavePage);
//发送关闭白板消息
mSendHelper.sendCloseWb(curSavePage.getId(),mPageManager.getSelectPage().getId());
isCloseSave = false;
}else{
finish();
}
}
@Override
public void onDCloseSelectSaveWbDiloagCancelBtnEvent() {
if(isCloseSave){
isCloseSave = false;
}
}
//发送邮件按钮事件
@Override
public void onDSendMailBtnEvent(String title, String[] mails) {
dismissDialog();
showIsSureDialog("邮件发送中......");
//showLoadDialog("正在发送邮件。。。");
sendMail = true;
mailTitle = title;
recMails = mails;
mailImageCacheDir = FileUtils.RUNNING_CACHE;
FileUtils.deleteFile(mailImageCacheDir);
mPageManager.saveAllPage(mailImageCacheDir);
}
@Override
public void onDSwitchFile(String filePath) {
TPLog.printKeyStatus("onDSwitchFile 选择文件--->"+filePath);
File file = new File(filePath);
Page page = WhiteBoardUtils.createDefWbPage();
String name = file.getName();
int index = name.indexOf(".");
if(index>0) {
name = name.substring(0, index);
}
page.setName(name);
SubPage subPage = new SubPage();
page.addSubPage(subPage);
page.setAnoymous(false);
mPageManager.addPage(page); //创建一个新的白板
mSendHelper.sendCreateNewPageMsg(page); //发送新建白板信息
//showLoadDialog("文件打开中...");
//showLoadFileDilaog(0,0,true);
//打开文档
OpenFileManager.openOrChangeFile(TouchDataActivity.this,page.getId()+"",filePath,false,new OpenFileListener());
}
@Override
public void onDToMailConfigSetting() {
StorageMangerJarUtils.toEmailSetting(this);
//toastMsg("去邮箱设置。。。。。。。。。。。。。");
}
@Override
public void onDilaogDismiss() {
resetTriangleIv();
}
@Override
public void onDRejectApplyChairman() {
}
@Override
public void onDAgreeApplyChairman(ApplyChairNtf acn) {
}
@Override
public void onScaleChanged(final float curScale) {
int tempScale = (int)(curScale*100f);
toastMsg(tempScale + "%");
runOnUiThread(new Runnable() {
@Override
public void run() {
setCurScale(curScale);
}
});
mHelperHolder.scale(curScale);
//发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendScaleMsg(pageId, tempScale);
}
@Override
public void onScaleChangedFromGesture(float scaleFactor, float focusX, float focusY) {
final float curScale = mPageManager.getSelectPage().getCurScale();
final int tempScale = (int)(curScale*100f);
toastMsg(tempScale+"%");
runOnUiThread(new Runnable() {
@Override
public void run() {
setCurScale(curScale);
}
});
//发送消息
long pageId = mPageManager.getSelectPage().getId();
mSendHelper.sendGestureZoomMsg(pageId, scaleFactor, (int) focusX, (int) focusY);
}
@Override
public void onUpdateScaleUI(final float curScale) {
mHelperHolder.updateGestureCurScale(curScale);
runOnUiThread(new Runnable() {
@Override
public void run() {
setCurScale(curScale);
}
});
}
@Override
public void onRotateChanged(int angle, boolean isFinish) {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendRotateMsg((int) page.getId(), angle, isFinish);
}
@Override
public void onUndo() {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendUndoMsg(page.getId(), page.getCurSubPageIndex() - 1);
}
@Override
public void onRedo() {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendRedoMsg(page.getId(), page.getCurSubPageIndex() - 1);
}
@Override
public void onUndoEnable(final boolean enable) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (enable) {
undoBtn.setBackgroundResource(R.drawable.undo_btn_style);
} else {
undoBtn.setBackgroundResource(R.mipmap.undo_unable_icon);
}
undoBtn.setEnabled(enable);
}
});
}
@Override
public void onRedoEnable(final boolean enable) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (enable) {
redoBtn.setBackgroundResource(R.drawable.redo_btn_style);
} else {
redoBtn.setBackgroundResource(R.mipmap.redo_unable_icon);
}
redoBtn.setEnabled(enable);
}
});
}
@Override
public void onGraphUpdate(Graph graph) {
IPage page = mPageManager.getSelectPage();
mSendHelper.sendGraphMsg(graph, (int) page.getId(), page.getCurSubPageIndex() - 1);
}
@Override
public void onTranslateChanged(float ox, float oy, boolean isFinish) {
IPage page = mPageManager.getSelectPage();
TPLog.printError("onTranslateChanged---------------->ox=" + ox + ",oy=" + oy);
mSendHelper.sendScrollMsg(ox, oy, (int) page.getId(), page.getCurSubPageIndex() - 1, isFinish);
}
@Override
public void onCoordinateChanged() {
}
@Override
public void onPageChanged(final int pageIndex,final int curSubPageIndex,final int subPageNum, final boolean nextSubPageEnable, final boolean lastSubPageEnable) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(subPageNum>1){
pageNumLayout.setVisibility(View.VISIBLE);
}else{
pageNumLayout.setVisibility(View.GONE);
}
setSelectPageIndex(curSubPageIndex-1);
IPage page = mPageManager.getPage(pageIndex);
String name = page.getName();
mWb.setBackgroundColor(page.getBackGroundColor());
setWbName(name);
curSubPageNumTv.setText(curSubPageIndex+"");
maxSupPageNumTv.setText(subPageNum+"");
if(subPageNum<2) {
changeSubPageEnable(false);
}else{
TPLog.printError("lastSubPageEnable--->"+lastSubPageEnable+",nextSubPageEnable--->"+nextSubPageEnable);
if(!lastSubPageEnable){
selectSubPageBtn.setEnabled(true);
nextSubPageBtn.setEnabled(true);
preSubPageBtn.setEnabled(false);
}else if(!nextSubPageEnable){
preSubPageBtn.setEnabled(true);
selectSubPageBtn.setEnabled(true);
nextSubPageBtn.setEnabled(false);
}else{
changeSubPageEnable(true);
}
}
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
IPage page = mPageManager.getPage(pageIndex);
setCurScale(page.getCurScale());
}
});
}
@Override
public void cancelSelecImageTimer() {
}
@Override
public void onDelSelectImg(int imgId) {
}
@Override
public void onPaintDrawDown() {
}
@Override
public void onServerConnected() {
// toastMsg("onServerConnected");
}
@Override
public void onLoginServerSuccess() { //登录成功后反馈,一般为断线后登录
//toastMsg("onLoginServerSuccess");
// if(WhiteBoardUtils.isIntoMeeting&&WhiteBoardUtils.isAPPShowing){
if(isUnConnectServer) {
fullHorizontalScreenToastMsg("数据会议服务器连接成功!");
}
isUnConnectServer = false;
if(WhiteBoardUtils.isAPPShowing){
ConnectManager.getInstance().getSender().joinOrCreateMeeting("","",true);
}
dismissDialog(DialogType.NETWORKSTATE);
dismissDialog(DialogType.SURE);
}
@Override
public void onRecMeetingName(String meetingName) {
}
@Override
public void onServerDisconnected() {
TPLog.printKeyStatus("datameeting server disconnected");
if(!isUnConnectServer) {
isUnConnectServer = true;
if(!NetworkUtil.getNetworkState(this)) {
showNetworkStateDialog(true,false);
showNetworkSettingDialog();
}else{
showNetworkStateDialog(false,false);
showIsSureDialog("服务器异常,无法进行数据协作,正在重新连接......");
}
}
}
@Override
public void onServerConnectException(Exception e) {
//Toast.makeText(this,"onServerConnectException",Toast.LENGTH_SHORT).show();
}
@Override
public void onRecCreateMeeting(long resultCode) {
}
@Override
public void onRecJoinMeeting(long resultCode) {
TPLog.printError("receive join meeting result:" + resultCode);
if(resultCode== NetError.ESUCCESS) {
NetUtil.isJoinMeeting = true;
}
}
@Override
public void onRecServerCurBufferSzie(long size) {
Image image = mPageManager.getSelectPage().getCurSubPage().getImage();
SynFileManager.getInstance().sendImage(image);
}
@Override
public void onRecServerReqSyn(long synReqId) {
mSendHelper.sendSynData(mPageManager, synReqId);
}
@Override
public void onRecSynFailed() {
}
@Override
public void onRecSynData(long curPageId,List<Page> pageList) {
mPageManager.getPageList().clear();
mPageManager.setPageList(pageList);
mPageManager.selectPage(curPageId);
Image image = mPageManager.getSelectPage().getCurSubPage().getImage();
if(image!=null){
SynFileManager.getInstance().requestFileInfo(image);
}
}
@Override
public void onRecGraphData(Graph graph) {
if(graph==null)return;
mHelperHolder.requestDrawGraph(graph);
}
@Override
public void onRecImageData(SubPage subpage) {
mPageManager.getSelectPage().addSubPage(subpage);
}
@Override
public void onRecZoomData(float zoom) {
TPLog.printKeyStatus("receive zoom:"+zoom);
mHelperHolder.scale(zoom / 100f);
setCurScale(zoom / 100f);
}
@Override
public void onRecGestureZoomData(float scaleFactor, int focusX, int focusY) {
TPLog.printError("onRecGestureZoomData------->" + scaleFactor);
float zoom = mPageManager.getSelectPage().getCurScale();
zoom = zoom*scaleFactor;
mHelperHolder.postScale(scaleFactor, focusX, focusY);
setCurScale(zoom);
}
@Override
public void onRecScrollData(android.graphics.Point scrollData) {
TPLog.printKeyStatus("receive scroll:x:"+scrollData.x+",y:"+scrollData.y);
Page page = (Page)mPageManager.getSelectPage();
float ox = scrollData.x - page.getOffsetX();
float oy = scrollData.y - page.getOffsetY();
//为了兼容PC,因此接收到的偏移量,这边需要进行特殊处理
mHelperHolder.postTranslate(ox, oy);
}
@Override
public void onRecClearScreen() {
mHelperHolder.clearScreen();
}
@Override
public void onRecCreateWbData(Page page) {
mPageManager.addPage(page);
}
@Override
public void onRecDelWbData(long delWbId,long nextWbId) {
mPageManager.removePage(delWbId);
mPageManager.selectPage(nextWbId);
}
@Override
public void onRecDelAllWbData(long newTabId) {
}
@Override
public void onRecChangePage(long wbId, long subPageIndex) {
subPageIndex = subPageIndex +1;
TPLog.printKeyStatus("onRecChangePage---->wbId="+wbId+",subPageIndex="+subPageIndex);
IPage page = mPageManager.getSelectPage();
if(page.getId()!=wbId) {
mPageManager.selectPage(wbId);
}else {
mPageManager.selectCurPageSubPage((int)(subPageIndex));
}
Image image = mPageManager.getCurSelectSubPage().getImage();
if(image!=null&&!image.isDlSuccess()){
mSendHelper.requestImage(image,mPageManager.getSelectPage().getId(),mPageManager.getCurPageSelectSubPageIndex()-1,((Page)mPageManager.getSelectPage()).getOwnerIndex());
}
mPageManager.notifyPageChanged();
}
@Override
public void onRecServerReqChangePage(long wbId, long subPageIndex) { //服务器请求翻页,其实是请求图片
IPage page = mPageManager.getSelectPage();
Image image = mPageManager.getSelectPage().getCurSubPage().getImage();
mSendHelper.requestServerRecFlow();
// mSendHelper.requestImage(image,page.getId(),page.getCurSubPageIndex()-1,((Page)page).getOwnerIndex());
}
@Override
public void onRecImageDownloaded(long imageId) {
TPLog.printKeyStatus("图片下载完成 Id:"+imageId);
mPageManager.notifyPageChanged();
}
@Override
public void onRecRedoData(long wbId, long subPageIndex) {
mHelperHolder.redo();
}
@Override
public void onRecUndoData(long wbId, long subPageIndex) {
mHelperHolder.undo();
}
@Override
public void onRecLeftRotate() {
int angle = mPageManager.getSelectPage().getCurAngle();
angle = angle - 90;
mHelperHolder.rotate(angle,true);
}
@Override
public void onRecRightRotate() {
int angle = mPageManager.getSelectPage().getCurAngle();
angle = angle + 90;
mHelperHolder.rotate(angle,true);
}
@Override
public void onRecRotate(long angle, long isFinish) {
boolean boo = false;
if(isFinish==0){
boo = true;
}else{
boo = false;
}
mHelperHolder.rotate((int)angle,boo);
}
@Override
public void onRecInsertImg(ImageGraph img) {
}
@Override
public void onRecCoordinateChanged(CoordinateChangedMsg msg) {
}
@Override
public void onRecSelectGrpahCoordinateChanged(ArrayList<GraphCoordinateChangedMsg> list) {
}
@Override
public void onRecDeleteGraph(DeleteGraphMsg msg) {
}
@Override
public void onRecConfMemberListUpdate(int num) {
}
@Override
public void onRecServerConnectNumNtf(int num) {
}
@Override
public void onDToSettingNetwork() {
// toastMsg("打开网络设置!");
try {
StorageMangerJarUtils.toNetWorkSetting(this);
}catch(Exception e){
TPLog.printError("PackageUtils", "not found activity " + StorageMangerJarUtils.PACKAGE_SYSTEM_SETTINGS + "/" + StorageMangerJarUtils.APP_SYSTEM_SETTINGS);
//toastMsg("IMIX设置程序未安装,该功能无法使用!");
}
}
@Override
public void onDRlsDcsMnger() {
}
@Override
public void onDDataConfModeChange(int mode) {
}
@Override
public void onDToFileManager(String path) {
}
/**********************网络状态监听*****************************/
@Override
public void onNetworkUsable() {
TPLog.printKeyStatus("current network usable");
if(!WhiteBoardUtils.isAPPShowing){
return;
}
ConnectManager.getInstance().startReconnect();
//隐藏网络连接对话框
dismissDialog(DialogType.SETTINGNETWORK);
showNetworkStateDialog(false,true);
}
@Override
public void onNetworkUnusable() {
TPLog.printKeyStatus("current network unusable");
if(!WhiteBoardUtils.isAPPShowing){
TPLog.printKeyStatus("white board did not showing");
return;
}
ConnectManager.getInstance().stopReconnect();
//打开网络异常对话框
showNetworkSettingDialog();
showNetworkStateDialog(true, false);
}
/**********************保存白板************************/
@Override
public void savePageStart(int saveCount) {
TPLog.printKeyStatus("need save page count: "+saveCount);
if(saveCount>2){
if(!sendMail&&!qRDownLoad){//发送邮件和二维码下载保存白板时不需要进行进度显示
//showLoadFileDilaog(saveCount,0,false);
needSaveProgressDialog = true;
curSaveProgress = 0;
}
}
}
@Override
public void saveProgress(int progress) {
TPLog.printKeyStatus("current save page progress:"+progress);
if(sendMail||qRDownLoad){
return;
}
if(needSaveProgressDialog) {
curSaveProgress ++;
runOnUiThread(new Runnable() {
@Override
public void run() {
//loadFileDiloagShowAgain();
setCurProgress(curSaveProgress);
}
});
}
}
@Override
public void savePageSuccess(final String savePath) {
TPLog.printKeyStatus("save all page success!");
if(!sendMail&&!qRDownLoad) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (saveQueue.isEmpty() || curSaveAllType == SAVEALL_ONEBYONE) {
String locPath = FileUtils.getAliasPath(savePath,mStroageManager);
String strs[] = locPath.split("/");
String path = "";
for (int i = 0; i < strs.length; i++) {
if (i == (strs.length - 1)) break;
path = path + strs[i] + "/";
}
String msg = "已保存至:" + path;
TPLog.printKeyStatus("page save path:"+path);
dismissDialog(DialogType.LOADFILE);
dismissDialog();
showIsSureDialog(msg);
if(isCloseSave){
mPageManager.removePage(curSavePage);
//发送关闭白板消息
mSendHelper.sendCloseWb(curSavePage.getId(),mPageManager.getSelectPage().getId());
isCloseSave = false;
}
} else {
curSavePage = saveQueue.remove(0);
TouchDataActivity.this.savePath = FileUtils.SAVE_WRITEBOARD_DIR + FileUtils.getCurWhiteBoardSaveDir();
FileUtils.checkDirExists(savePath);
saveDirName = curSavePage.getName();
aliasSavePath = FileUtils.getAliasPath(savePath,mStroageManager);
isSaveAll = true;
if (curSaveAllType == SAVEALL_NOT_PROMPT) {
onDSaveBtnEvent(saveDirName, isSaveAll);
}
}
}
});
}else if(sendMail){ //发送邮件
TPLog.printKeyStatus("send mail start...");
List<String> filePaths = new ArrayList<String>();
FileUtils.findAllChildFile(mailImageCacheDir,filePaths);
TPLog.printKeyStatus("add "+filePaths.size()+" files to mail");
String images[] = new String[filePaths.size()];
filePaths.toArray(images);
MailUtil.sendImageMail(recMails,mailTitle,images);
sendMail = false;
}else if(qRDownLoad){
// List<String> filePaths = new ArrayList<String>();
// FileUtils.findAllChildFile(FileUtils.RUNNING_CACHE,filePaths);
String title = FileUtils.getCurWhiteBoardSaveDir();
String subtitle = mPageManager.getPageCount()+"个白板,共"+mPageManager.getSubPageCount()+"页";
setQRCodeCacheFileDir(title,subtitle,FileUtils.RUNNING_CACHE);
qRDownLoad = false;
}
}
@Override
public void savePageFailed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
TPLog.printKeyStatus("save page failed");
String msg = "文件保存失败!";
dismissDialog(DialogType.LOADFILE);
dismissDialog();
showIsSureDialog(msg);
}
});
}
@Override
public void onPageCountChanged(int count) {
createWbBtn.setBackgroundResource(R.drawable.create_wb_btn_style);
createWbBtn.setClickable(true);
}
/************************邮件发送******************************/
@Override
public void onSendMailSuccess() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissLoadDialog();//现在可以不要,不过留着也不会报错 ,留着先
String msg = "邮件发送成功!";
TPLog.printKeyStatus("send mail success!");
showIsSureDialog(msg);
}
});
}
@Override
public void onSendMailFailed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissLoadDialog();
String msg = "邮件发送失败!";
showIsSureDialog(msg);
}
});
}
@Override
public void onSendMailUnknownHost() {//这个暂时不处理
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// dismissLoadDialog();
// String msg = "邮件发送失败!";
// showIsSureDialog(msg);
// }
// });
}
@Override
public void onConnectMailServerFailed() {
}
@Override
public void onSendMailAuthenticationFailed() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissLoadDialog();
dismissDialog();
showToMailConfigSettingDialog();
}
});
}
/************************打开文件*****************************/
class OpenFileListener implements OpenFileManager.OnFileToImageListener{
private int totalCount;
@Override
public void onPageCount(final int count, final String checkCode) {
runOnUiThread(new Runnable() {
@Override
public void run() {
totalCount = count;
TPLog.printKeyStatus("开始打开文件,文件总页数:"+count+",checkCode:"+checkCode);
String pageId = mPageManager.getSelectPage().getId()+"";
if(!pageId.equals(checkCode))
return;
setProgressMax(count);
}
});
}
@Override
public void onProgress(final int progress, final String checkCode) {
TPLog.printKeyStatus("打开文件当前进度:"+progress+"/"+totalCount);
runOnUiThread(new Runnable() {
@Override
public void run() {
String pageId = mPageManager.getSelectPage().getId() + "";
if (!pageId.equals(checkCode))
return;
setCurProgress(progress);
}});
}
@Override
public void onFialed(String errorMsg,String path,final String checkCode) {
TPLog.printKeyStatus("文件打开失败!");
runOnUiThread(new Runnable() {
@Override
public void run() {
String pageId = mPageManager.getSelectPage().getId() + "";
if (!pageId.equals(checkCode))
return;
// if (!hasDialogShowing()) {
// showLoadFileDilaog(1, 0,true);
// }
showLoadFileFailedText();
}});
}
@Override
public void onComplete(List<String> files, String fileName, String checkCode) {
TPLog.printKeyStatus("打开文件成功,fileName="+fileName);
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissDialog();
}
});
String pageId = mPageManager.getSelectPage().getId()+"";
if(!pageId.equals(checkCode))
return;
IPage page = mPageManager.getSelectPage();
int count = files.size();
//1.发送文档打开完成命令
mSendHelper.sendOpenOfficeComplete(page.getId());
//2.发送文档总页数
mSendHelper.sendSubpageCountMsg(mPageManager.getSelectPage().getId(), count);
for(int i = 0;i<files.size();i++){
Image image = WhiteBoardUtils.createImage(files.get(i),true);
image.setSubpageIndex(i);
SubPage subPage = new SubPage(image);
subPage.setIndex(i);
page.addSubPage(subPage);
//3.发送文件列表
SynFileManager.getInstance().sendImageInfo(image);
//4.如果是第一张图的话,就发送文件信息和文件内容到服务器
if (i == 0) {
SynFileManager.getInstance().sendImage(image);
}
}
mPageManager.notifyPageChanged();
//新需求,打开文件完毕后,修改画笔颜色为红色
// if(mHelperHolder.getPaintColor() == WhiteBoardUtils.colors[0]) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onDPenColorBtnEvent(WhiteBoardUtils.colors[1]);
}
});
//}
//新需求打开文件默认宽度自适应 去掉了
// onDWidthSelfBtnEvent();
}
}
@Override
protected void onResume() {
super.onResume();
TPLog.printError("TouchDataActivity---------------->onResume");
ConnectManager.getInstance().setCallback(this);
WhiteBoardUtils.isAPPShowing = true;
ConnectManager.getInstance().getSender().joinOrCreateMeeting("", "", true); // 每次App启动都会执行一次加入会议操作
intent = new Intent();
intent.setAction("com.kedacom.touchdata");
intent.putExtra("isShow", true);
sendBroadcast(intent);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
TPLog.printError("TouchDataActivtiy ------------onStop--------------->");
//ConnectManager.getInstance().setCallback(null);
dismissWhiteBoardNameDialog();
WhiteBoardUtils.isAPPShowing = false;
NetUtil.isJoinMeeting = false;
mSendHelper.quitMeeting();
//finish();
intent.putExtra("isShow",false);
sendBroadcast(intent);
}
@Override
protected void onDestroy() {
TPLog.printError("TouchDataActivtiy -> onDestroy");
ConnectManager.getInstance().setCallback(null);
super.onDestroy();
NetworkBroadcastReceiver.unRegisterOnNetworkChangeListener(this);
//mHelperHolder.onDestory();
//WhiteBoardUtils.resetCurPageNum();
// android.os.Process.killProcess( android.os.Process.myPid());
mWb.destroy();
if(mHelperHolder!=null)
mHelperHolder.onDestory();
if(mPageManager!=null)
mPageManager.onDestroy();
WhiteBoardUtils.reset();
}
private void restore(Bundle saveState) {
if (saveState == null) {
return;
}
if (!saveState.containsKey("PAGE")) {
return;
}
//还原Page页
Parcelable parcelabe[] = saveState.getParcelableArray("PAGE");
if (parcelabe == null) {
return;
}
List<Page> pages = new ArrayList<Page>();
for (int i = 0; i < parcelabe.length; i++) {
pages.add((Page) parcelabe[i]);
}
int curPageIndex = saveState.getInt("SelectPageIndex");
mPageManager.setPageList(pages);
mPageManager.selectPage(curPageIndex);
Page page = (Page) mPageManager.getSelectPage();
//还原基础数据
mHelperHolder.translate(page.getOffsetX(), page.getOffsetY());
mHelperHolder.scale(page.getCurScale());
mHelperHolder.rotate(page.getCurAngle(), false);
//还原画板面板数据
int color = saveState.getInt("Color");
mHelperHolder.setPaintColor(color);
float width = saveState.getFloat("StrokeWidth");
TPLog.printError("2StrokeWidth------------->"+width);
mHelperHolder.setPaintStrokeWidth(width);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
/*
TPLog.printKeyStatus("onSaveInstanceState---->start save data");
List<IPage> list = mPageManager.getPageList();
if(list==null)return;
int count = list.size();
Page[] pages = new Page[count];
for (int i = 0; i < count; i++) {
IPage page = list.get(i);
pages[i] = (Page) page;
}
outState.putParcelableArray("PAGE", pages);
outState.putInt("SelectPageIndex", mPageManager.getSelectPageIndex());
outState.putInt("Color", mHelperHolder.getPaintColor());
outState.putFloat("StrokeWidth", mHelperHolder.getPaintStrokeWidth());
outState.setClassLoader(getClass().getClassLoader());
TPLog.printKeyStatus("onSaveInstanceState---->暂存数据完成!");
*/
super.onSaveInstanceState(outState);
}
private static final String ACTION_SWTICH_FILE_ACTIVITY = "com.kedacom.fileexplorer.FileRetriever";
private void startSwitchFileActivity(){
try {
Intent intent = new Intent(ACTION_SWTICH_FILE_ACTIVITY);
startActivityForResult(intent, 1);
}catch(Exception e){
toastMsg("文件管理未安装,该功能无法使用!");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String returnedData = data.getStringExtra("file_retriever_path");
if (returnedData!=null&&!returnedData.trim().isEmpty()) {
onDSwitchFile(returnedData);
}
}
break;
default:
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == 19){
Intent intent1 = new Intent();
intent1.setAction("android.intent.action.MAIN");
intent1.addCategory("android.intent.category.HOME");
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
System.out.println("keycode" + keyCode);
int pageCount = mPageManager.getPageCount();
int selectPageIndex = mPageManager.getSelectPageIndex();
if (keyCode == 21){ //向上翻页键
System.out.println("pageCount"+pageCount);
if (selectPageIndex < pageCount-1 ) {
prePage(selectPageIndex);
}else if (selectPageIndex == pageCount-1){
selectPageIndex = -1;
prePage(selectPageIndex);
}
}else if (keyCode == 22){ //向下翻页键
if (selectPageIndex > 0 ) {
nextPage(selectPageIndex);
}else if (selectPageIndex == 0){
selectPageIndex = pageCount + 1;
nextPage(selectPageIndex);
}
}else if (keyCode == 20){
if(!hasDialogShowing()){
mHelperHolder.setOpType(WhiteBoardUtils.GRAPH_PEN);
resetSelectBtn(penBtn.getId());
subPenIv.setBackgroundResource(R.mipmap.triangle_select_icon);
//弹出画笔选择框
showSwitchColorDialog(subPenIv);
}
}
return true;
}
private void nextPage(int selectPageIndex) {
selectPageIndex = selectPageIndex - 1;
mPageManager.selectPage(selectPageIndex);
Page page = (Page) mPageManager.getSelectPage();
long id = page.getId();
System.out.println("subPageIndex" + selectPageIndex);
mSendHelper.sendChangePageMsg(id, selectPageIndex, page.getCurSubPage().getImage());
}
private void prePage(int selectPageIndex) {
selectPageIndex = selectPageIndex + 1;
mPageManager.selectPage(selectPageIndex);
Page page = (Page) mPageManager.getSelectPage();
long id = page.getId();
System.out.println("subPageIndex" + selectPageIndex);
mSendHelper.sendChangePageMsg(id, selectPageIndex, page.getCurSubPage().getImage());
}
} | 69,507 | 0.593583 | 0.591519 | 1,998 | 32.707706 | 25.947908 | 217 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53954 | false | false | 8 |
f15432a754c2a87a90d1d06fc6b99cc809ca2db9 | 14,130,442,427,105 | 3316aa0905855ed3cf1f743d7af0935930489e06 | /CucumberFirstTest/src/main/java/tests/ParentTest.java | f93dfa8860ee10586a06c49ae3c7b2ffc8a7c65f | [] | no_license | javiergerard1986/CucumberTest | https://github.com/javiergerard1986/CucumberTest | b428879a887298ea501c85930f7352b5476fc657 | 654abec9dd44ae7ac997f56232c0ed4093de60d9 | refs/heads/master | 2016-09-22T21:44:17.162000 | 2016-05-31T19:15:53 | 2016-05-31T19:18:17 | 60,036,520 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tests;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class ParentTest {
//-------------------------------
//ATTRIBUTES
//-------------------------------
protected WebDriver driver;
protected ProfilesIni profile;
//-------------------------------
//VOIDS AND FUNCTIONS
//-------------------------------
/**
* Method to initialize test
*/
protected void initializeTest(){
profile = new ProfilesIni();
FirefoxProfile fprofile = profile.getProfile("Collapse Profile");
driver = new FirefoxDriver(fprofile);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://store.demoqa.com/");
}
/**
* Method to complete the execution of test
*/
protected void completeTest(){
this.driver.close();
}
/**
* Function to verify the result of the test
* @param text - (String) text to check that is appearing in page
* @return
*/
protected boolean checkResult(String text){
try{
this.waitSeconds(driver, 5);
WebElement bodyTag = driver.findElement(By.tagName("body"));
if (bodyTag.getText().contains(text)){
return true;
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return false;
}
/**
* Method to wait requested seconds
* @param (driver) - WebDriver
* @param (seconds) - This is the quantity of seconds to wait
*/
protected void waitSeconds(WebDriver driver, int seconds){
synchronized(driver){
try {
driver.wait(seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | UTF-8 | Java | 2,083 | java | ParentTest.java | Java | [] | null | [] | package tests;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class ParentTest {
//-------------------------------
//ATTRIBUTES
//-------------------------------
protected WebDriver driver;
protected ProfilesIni profile;
//-------------------------------
//VOIDS AND FUNCTIONS
//-------------------------------
/**
* Method to initialize test
*/
protected void initializeTest(){
profile = new ProfilesIni();
FirefoxProfile fprofile = profile.getProfile("Collapse Profile");
driver = new FirefoxDriver(fprofile);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://store.demoqa.com/");
}
/**
* Method to complete the execution of test
*/
protected void completeTest(){
this.driver.close();
}
/**
* Function to verify the result of the test
* @param text - (String) text to check that is appearing in page
* @return
*/
protected boolean checkResult(String text){
try{
this.waitSeconds(driver, 5);
WebElement bodyTag = driver.findElement(By.tagName("body"));
if (bodyTag.getText().contains(text)){
return true;
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
return false;
}
/**
* Method to wait requested seconds
* @param (driver) - WebDriver
* @param (seconds) - This is the quantity of seconds to wait
*/
protected void waitSeconds(WebDriver driver, int seconds){
synchronized(driver){
try {
driver.wait(seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | 2,083 | 0.570811 | 0.567451 | 98 | 19.275511 | 19.348459 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.591837 | false | false | 8 |
c585b5094f8eb07b100e017f03b350843b6c3dec | 12,309,376,327,836 | f1661f05c96cd3461a2f3c067ab6339a93c0c603 | /game_server/src/main/java/ru/atom/gameserver/service/GameRepository.java | dfb276494bb990fb6a2e3a59655057b0b7b8dd7a | [
"MIT"
] | permissive | profile4me/atom | https://github.com/profile4me/atom | 55f30dcef58e27d99b851ff76087b27778b4d505 | db4f656b6bd3dc56e57a4b07199ab38dae507d15 | refs/heads/master | 2021-08-30T10:21:01.969000 | 2017-12-14T21:46:05 | 2017-12-14T21:46:05 | 105,032,130 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.atom.gameserver.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.atom.gameserver.component.ConnectionHandler;
import ru.atom.gameserver.gsession.GameSession;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class GameRepository {
private final Map<Long, GameSession> games = new ConcurrentHashMap<>();
@Autowired
private ConnectionHandler connectionHandler;
public Long createGame(int playersNum) {
Long gameId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
games.put(gameId, new GameSession(gameId, connectionHandler));
return gameId;
}
public GameSession getGameById(Long id) {
return games.get(id);
}
}
| UTF-8 | Java | 840 | java | GameRepository.java | Java | [] | null | [] | package ru.atom.gameserver.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.atom.gameserver.component.ConnectionHandler;
import ru.atom.gameserver.gsession.GameSession;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class GameRepository {
private final Map<Long, GameSession> games = new ConcurrentHashMap<>();
@Autowired
private ConnectionHandler connectionHandler;
public Long createGame(int playersNum) {
Long gameId = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
games.put(gameId, new GameSession(gameId, connectionHandler));
return gameId;
}
public GameSession getGameById(Long id) {
return games.get(id);
}
}
| 840 | 0.752381 | 0.752381 | 30 | 27 | 25.476788 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566667 | false | false | 8 |
e750913e2004941666301523892309acf524e101 | 25,769,868,585 | 881c759f53d37e322f38b3e2e64006cb7905fd5b | /src/elemental/json/JsonNumber.java | 1611e96e9ae5d25d23304749fb2b1607ddac3113 | [] | no_license | kellegous/perfboard | https://github.com/kellegous/perfboard | d0fd36c8625fe14931b29d4d1df79c55fa2a9e62 | 7a56232c6521fae6332e3751f8152e1f72516ec4 | refs/heads/master | 2016-09-07T19:00:40.048000 | 2010-03-04T04:38:56 | 2010-03-04T04:38:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package elemental.json;
import java.io.IOException;
import java.io.Writer;
public abstract class JsonNumber implements JsonValue {
private static class JsonInteger extends JsonNumber {
private final long value;
public JsonInteger(long value) {
this.value = value;
}
@Override
public long getInteger() {
return value;
}
@Override
public double getDecimal() {
return value;
}
@Override
public void write(Writer writer) throws IOException {
writer.write(Long.toString(value));
}
@Override
public boolean isNull() {
return false;
}
}
private static class JsonDecimal extends JsonNumber {
private final double value;
public JsonDecimal(double value) {
this.value = value;
}
@Override
public double getDecimal() {
return value;
}
@Override
public long getInteger() {
return (long) value;
}
@Override
public void write(Writer writer) throws IOException {
writer.write(Double.toString(value));
}
@Override
public boolean isNull() {
return false;
}
}
private JsonNumber() {
}
public abstract long getInteger();
public abstract double getDecimal();
public static JsonNumber create(long value) {
return new JsonInteger(value);
}
public static JsonNumber create(int value) {
return new JsonInteger(value);
}
public static JsonNumber create(double value) {
return new JsonDecimal(value);
}
@Override
public JsonArray asArray() {
return null;
}
@Override
public JsonBoolean asBoolean() {
return null;
}
@Override
public JsonNumber asNumber() {
return this;
}
@Override
public JsonObject asObject() {
return null;
}
@Override
public JsonString asString() {
return null;
}
@Override
public boolean isArray() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isBoolean() {
return false;
}
@Override
public boolean isNumber() {
return true;
}
@Override
public boolean isObject() {
return false;
}
@Override
public boolean isString() {
return false;
}
}
| UTF-8 | Java | 2,216 | java | JsonNumber.java | Java | [] | null | [] | package elemental.json;
import java.io.IOException;
import java.io.Writer;
public abstract class JsonNumber implements JsonValue {
private static class JsonInteger extends JsonNumber {
private final long value;
public JsonInteger(long value) {
this.value = value;
}
@Override
public long getInteger() {
return value;
}
@Override
public double getDecimal() {
return value;
}
@Override
public void write(Writer writer) throws IOException {
writer.write(Long.toString(value));
}
@Override
public boolean isNull() {
return false;
}
}
private static class JsonDecimal extends JsonNumber {
private final double value;
public JsonDecimal(double value) {
this.value = value;
}
@Override
public double getDecimal() {
return value;
}
@Override
public long getInteger() {
return (long) value;
}
@Override
public void write(Writer writer) throws IOException {
writer.write(Double.toString(value));
}
@Override
public boolean isNull() {
return false;
}
}
private JsonNumber() {
}
public abstract long getInteger();
public abstract double getDecimal();
public static JsonNumber create(long value) {
return new JsonInteger(value);
}
public static JsonNumber create(int value) {
return new JsonInteger(value);
}
public static JsonNumber create(double value) {
return new JsonDecimal(value);
}
@Override
public JsonArray asArray() {
return null;
}
@Override
public JsonBoolean asBoolean() {
return null;
}
@Override
public JsonNumber asNumber() {
return this;
}
@Override
public JsonObject asObject() {
return null;
}
@Override
public JsonString asString() {
return null;
}
@Override
public boolean isArray() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isBoolean() {
return false;
}
@Override
public boolean isNumber() {
return true;
}
@Override
public boolean isObject() {
return false;
}
@Override
public boolean isString() {
return false;
}
}
| 2,216 | 0.643953 | 0.643953 | 132 | 15.787879 | 15.492927 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 8 |
a277b6a035990f0d0c985f0250b4aef0dfee41cd | 29,935,922,116,244 | 159b44084cdc4458a9f470efa2091ac608002ba4 | /app/src/main/java/com/example/a60440/collegestudent/activity/SignupActivity.java | 4100cb0913001ffdce2738fc1c44dbeb20ba64cb | [] | no_license | coda1997/CollegeStudent | https://github.com/coda1997/CollegeStudent | 73d609b0f744f4c5c58cfadfee21525ed3e51995 | 4304a4676669c2c696b2e7513422eafef6e8d7d3 | refs/heads/master | 2020-06-14T10:38:58.765000 | 2017-05-25T13:03:10 | 2017-05-25T13:03:10 | 73,898,819 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.a60440.collegestudent.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.example.a60440.collegestudent.Manifest;
import com.example.a60440.collegestudent.R;
import com.example.a60440.collegestudent.bean.User;
import com.example.a60440.collegestudent.requestServes.RegisterServes;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
* Created by 60440 on 2017/2/7.
*/
public class SignupActivity extends Activity {
@Bind(R.id.editText3)
EditText registerName;
@Bind(R.id.editText5)
EditText registerpwd;
@Bind(R.id.editText4)
EditText registerCheckpwd;
@OnClick(R.id.button5)
void registerResetOnClick(){
registerName.setText("");
registerpwd.setText("");
registerCheckpwd.setText("");
}
@OnClick(R.id.button4)
void registerSubmitOnclick(){
String pwd = registerpwd.getText().toString();
String confirm = registerCheckpwd.getText().toString();
int nameLength = registerName.getText().toString().length();
int pwdLength = pwd.length();
if(nameLength<7){
Toast.makeText(this, "用户名过短,应有8-11位用户名", Toast.LENGTH_SHORT).show();
return;
}else if(nameLength>12){
Toast.makeText(this, "用户名过长,应有8-11位用户名", Toast.LENGTH_SHORT).show();
return;
}else if(pwdLength<5&&pwdLength>19){
Toast.makeText(this, "密码格式不正确,应为6-18位字母或数字", Toast.LENGTH_SHORT).show();
return;
}
if(pwd.equals(confirm)){
InitSignup(registerName.getText().toString(),registerpwd.getText().toString());
Log.i("signup == ",registerName.getText().toString()+" "+registerpwd.getText().toString());
}else {
Toast.makeText(this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
registerpwd.setText("");
registerCheckpwd.setText("");
}
}
@Bind(R.id.toolbar)
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_main);
ButterKnife.bind(this);
toolbar.setTitle("账号注册");
}
private void InitSignup(final String username, final String userpwd) {
Retrofit retorfit = new Retrofit.Builder()
.baseUrl(getResources().getString(R.string.baseURL))
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
RegisterServes requestServes = retorfit.create(RegisterServes.class);
Call<String> call = requestServes.getString(username.toString(),userpwd.toString());
call.enqueue(new Callback<String>(){
@Override
public void onFailure(Call<String> call, Throwable throwable) {
Log.e("===","fail");
}
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.e("==","return:"+response.body().toString());
Toast.makeText(SignupActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
if(response.body().toString().equals("ture")){
User user = new User();
user.setUsername(username);
user.setPassword(userpwd);
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
}
}
});
}
}
| UTF-8 | Java | 4,104 | java | SignupActivity.java | Java | [
{
"context": "alars.ScalarsConverterFactory;\n\n/**\n * Created by 60440 on 2017/2/7.\n */\n\npublic class SignupActivity ext",
"end": 814,
"score": 0.9993259310722351,
"start": 809,
"tag": "USERNAME",
"value": "60440"
},
{
"context": " new User();\n user.setUserna... | null | [] | package com.example.a60440.collegestudent.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.example.a60440.collegestudent.Manifest;
import com.example.a60440.collegestudent.R;
import com.example.a60440.collegestudent.bean.User;
import com.example.a60440.collegestudent.requestServes.RegisterServes;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
* Created by 60440 on 2017/2/7.
*/
public class SignupActivity extends Activity {
@Bind(R.id.editText3)
EditText registerName;
@Bind(R.id.editText5)
EditText registerpwd;
@Bind(R.id.editText4)
EditText registerCheckpwd;
@OnClick(R.id.button5)
void registerResetOnClick(){
registerName.setText("");
registerpwd.setText("");
registerCheckpwd.setText("");
}
@OnClick(R.id.button4)
void registerSubmitOnclick(){
String pwd = registerpwd.getText().toString();
String confirm = registerCheckpwd.getText().toString();
int nameLength = registerName.getText().toString().length();
int pwdLength = pwd.length();
if(nameLength<7){
Toast.makeText(this, "用户名过短,应有8-11位用户名", Toast.LENGTH_SHORT).show();
return;
}else if(nameLength>12){
Toast.makeText(this, "用户名过长,应有8-11位用户名", Toast.LENGTH_SHORT).show();
return;
}else if(pwdLength<5&&pwdLength>19){
Toast.makeText(this, "密码格式不正确,应为6-18位字母或数字", Toast.LENGTH_SHORT).show();
return;
}
if(pwd.equals(confirm)){
InitSignup(registerName.getText().toString(),registerpwd.getText().toString());
Log.i("signup == ",registerName.getText().toString()+" "+registerpwd.getText().toString());
}else {
Toast.makeText(this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
registerpwd.setText("");
registerCheckpwd.setText("");
}
}
@Bind(R.id.toolbar)
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_main);
ButterKnife.bind(this);
toolbar.setTitle("账号注册");
}
private void InitSignup(final String username, final String userpwd) {
Retrofit retorfit = new Retrofit.Builder()
.baseUrl(getResources().getString(R.string.baseURL))
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
RegisterServes requestServes = retorfit.create(RegisterServes.class);
Call<String> call = requestServes.getString(username.toString(),userpwd.toString());
call.enqueue(new Callback<String>(){
@Override
public void onFailure(Call<String> call, Throwable throwable) {
Log.e("===","fail");
}
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.e("==","return:"+response.body().toString());
Toast.makeText(SignupActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
if(response.body().toString().equals("ture")){
User user = new User();
user.setUsername(username);
user.setPassword(<PASSWORD>);
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
}
}
});
}
}
| 4,107 | 0.640351 | 0.624561 | 110 | 35.272728 | 25.430086 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.709091 | false | false | 7 |
5846941e3e2a18a1f3f81cc574855b08882845f4 | 34,918,084,131,448 | 1d73232ed967213d44af9d75f4bd965ef342c0c3 | /PAD/assignment5/AverageLinkage.java | f1baef9dc325ae9cc686bc580cc62aa7c58c156e | [] | no_license | sirkibsirkib/old_B_CS_code | https://github.com/sirkibsirkib/old_B_CS_code | 8e95ac5345ef83f8ef17da34ec4ae0632a7885a6 | bbaed7bdde2c803e788423cf5e84007bf883720f | refs/heads/master | 2021-05-07T22:43:55.487000 | 2017-10-17T14:52:46 | 2017-10-17T14:52:46 | 107,283,289 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package assignment5;
public class AverageLinkage implements ClusterMethod{
private DistanceMeasure d;
AverageLinkage(DistanceMeasure d){
this.d = d;
}
public double CalculateDistance(Cluster a, Cluster b) {
double sumDistance = 0;
for(int i = 0; i < a.numberOfUnits(); i++){
for(int j = i; j < b.numberOfUnits(); j++){
sumDistance += d.calculateDistance(a.getUnit(i), b.getUnit(j));
}
}
return sumDistance / (a.numberOfUnits()*b.numberOfUnits());
}
public String getName(){
return "AverageLinkage";
}
}
| UTF-8 | Java | 539 | java | AverageLinkage.java | Java | [] | null | [] | package assignment5;
public class AverageLinkage implements ClusterMethod{
private DistanceMeasure d;
AverageLinkage(DistanceMeasure d){
this.d = d;
}
public double CalculateDistance(Cluster a, Cluster b) {
double sumDistance = 0;
for(int i = 0; i < a.numberOfUnits(); i++){
for(int j = i; j < b.numberOfUnits(); j++){
sumDistance += d.calculateDistance(a.getUnit(i), b.getUnit(j));
}
}
return sumDistance / (a.numberOfUnits()*b.numberOfUnits());
}
public String getName(){
return "AverageLinkage";
}
}
| 539 | 0.680891 | 0.675325 | 23 | 22.434782 | 22.076597 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.956522 | false | false | 7 |
6acf50409fb5e651266a29408473710745249a90 | 8,761,733,313,243 | 66dc358018967b4396dddcf02e973a137afa5429 | /src/main/java/net/canarymod/tasks/TaskOwner.java | 35c40d7cf731c199bb60afaf417c85084066dc9d | [] | no_license | Hidendra/CanaryLib | https://github.com/Hidendra/CanaryLib | 795d752503d3d1317c63554bcd75076d5e334295 | 7210931c821cf34410a892e345c76e73a71bfd7d | refs/heads/master | 2021-01-17T06:35:16.508000 | 2013-08-18T18:06:04 | 2013-08-18T18:06:29 | 12,199,302 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.canarymod.tasks;
/**
* Interface for defining a {@link ServerTask} owner
* <p>
* Has no other use outside of the {@link ServerTask}
*
* @author Jason (darkdiplomat)
*/
public interface TaskOwner {}
| UTF-8 | Java | 218 | java | TaskOwner.java | Java | [
{
"context": "e outside of the {@link ServerTask}\n * \n * @author Jason (darkdiplomat)\n */\npublic interface TaskOwner {}\n",
"end": 168,
"score": 0.9913640022277832,
"start": 163,
"tag": "NAME",
"value": "Jason"
},
{
"context": "e of the {@link ServerTask}\n * \n * @author Jason (... | null | [] | package net.canarymod.tasks;
/**
* Interface for defining a {@link ServerTask} owner
* <p>
* Has no other use outside of the {@link ServerTask}
*
* @author Jason (darkdiplomat)
*/
public interface TaskOwner {}
| 218 | 0.692661 | 0.692661 | 10 | 20.799999 | 19.584688 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 7 |
a9f75867cdd7550e03037fdc803ab4e71ff360ed | 4,415,226,448,710 | a55177f2372b52a9d0e18006de13ce93de770bd9 | /YoGiOh!M4-/src/eg/edu/guc/yugioh/cards/spells/MonsterReborn.java | 060f600c12d065bdce0cf85650932656c617ca32 | [] | no_license | AmrEzzatIbrahim/YuGiOhGame | https://github.com/AmrEzzatIbrahim/YuGiOhGame | 980c3aacaa1918fd1e38b3792c6c164e68a6d339 | ad3017047319a53af0b869480bafd0b0161a3fb2 | refs/heads/master | 2020-04-27T12:39:11.693000 | 2019-04-26T13:42:29 | 2019-04-26T13:42:29 | 174,339,157 | 1 | 0 | null | false | 2019-04-26T13:40:56 | 2019-03-07T12:22:07 | 2019-04-25T21:21:10 | 2019-04-26T13:40:56 | 14,474 | 0 | 0 | 0 | Java | false | false | package eg.edu.guc.yugioh.cards.spells;
import java.io.IOException;
import eg.edu.guc.yugioh.board.Board;
import eg.edu.guc.yugioh.board.player.Player;
import eg.edu.guc.yugioh.cards.Card;
import eg.edu.guc.yugioh.cards.MonsterCard;
public class MonsterReborn extends SpellCard {
public MonsterReborn(String name, String description){
super(name, description);
}
public void action(MonsterCard monster){
MonsterCard max = new MonsterCard("","",0,0,0);
boolean flag = false;
boolean monsterfound=false;
if(!getBoard().getActivePlayer().getField().getGraveyard().isEmpty())
for (int i = 0; i < getBoard().getActivePlayer().getField()
.getGraveyard().size(); i++) {
if (getBoard().getActivePlayer().getField().getGraveyard().get(i) instanceof MonsterCard) {
monsterfound=true;
if (((MonsterCard) (getBoard().getActivePlayer().getField()
.getGraveyard().get(i))).getAttackPoints() > max
.getAttackPoints()) {
max = (MonsterCard) getBoard().getActivePlayer().getField()
.getGraveyard().get(i);
}
}
}
if(!getBoard().getOpponentPlayer().getField().getGraveyard().isEmpty())
for (int i = 0; i < getBoard().getOpponentPlayer().getField()
.getGraveyard().size(); i++) {
if (getBoard().getOpponentPlayer().getField().getGraveyard().get(i) instanceof MonsterCard) {
monsterfound=true;
if (((MonsterCard) (getBoard().getOpponentPlayer().getField()
.getGraveyard().get(i))).getAttackPoints() > max
.getAttackPoints()) {
max = (MonsterCard) getBoard().getOpponentPlayer().getField()
.getGraveyard().get(i);
flag = true;
}
}
}
if(monsterfound){
getBoard().getActivePlayer().getField().addMonsterToField(max, max.getMode(), false);
getBoard().getActivePlayer().getField().setSummoned(false);
if (!flag) {
getBoard()
.getActivePlayer()
.getField()
.getGraveyard()
.remove(getBoard().getActivePlayer().getField()
.getGraveyard().indexOf(max));
} else {
getBoard()
.getOpponentPlayer()
.getField()
.getGraveyard()
.remove(getBoard().getOpponentPlayer().getField()
.getGraveyard().indexOf(max));
}
}
}
}
| UTF-8 | Java | 2,293 | java | MonsterReborn.java | Java | [] | null | [] | package eg.edu.guc.yugioh.cards.spells;
import java.io.IOException;
import eg.edu.guc.yugioh.board.Board;
import eg.edu.guc.yugioh.board.player.Player;
import eg.edu.guc.yugioh.cards.Card;
import eg.edu.guc.yugioh.cards.MonsterCard;
public class MonsterReborn extends SpellCard {
public MonsterReborn(String name, String description){
super(name, description);
}
public void action(MonsterCard monster){
MonsterCard max = new MonsterCard("","",0,0,0);
boolean flag = false;
boolean monsterfound=false;
if(!getBoard().getActivePlayer().getField().getGraveyard().isEmpty())
for (int i = 0; i < getBoard().getActivePlayer().getField()
.getGraveyard().size(); i++) {
if (getBoard().getActivePlayer().getField().getGraveyard().get(i) instanceof MonsterCard) {
monsterfound=true;
if (((MonsterCard) (getBoard().getActivePlayer().getField()
.getGraveyard().get(i))).getAttackPoints() > max
.getAttackPoints()) {
max = (MonsterCard) getBoard().getActivePlayer().getField()
.getGraveyard().get(i);
}
}
}
if(!getBoard().getOpponentPlayer().getField().getGraveyard().isEmpty())
for (int i = 0; i < getBoard().getOpponentPlayer().getField()
.getGraveyard().size(); i++) {
if (getBoard().getOpponentPlayer().getField().getGraveyard().get(i) instanceof MonsterCard) {
monsterfound=true;
if (((MonsterCard) (getBoard().getOpponentPlayer().getField()
.getGraveyard().get(i))).getAttackPoints() > max
.getAttackPoints()) {
max = (MonsterCard) getBoard().getOpponentPlayer().getField()
.getGraveyard().get(i);
flag = true;
}
}
}
if(monsterfound){
getBoard().getActivePlayer().getField().addMonsterToField(max, max.getMode(), false);
getBoard().getActivePlayer().getField().setSummoned(false);
if (!flag) {
getBoard()
.getActivePlayer()
.getField()
.getGraveyard()
.remove(getBoard().getActivePlayer().getField()
.getGraveyard().indexOf(max));
} else {
getBoard()
.getOpponentPlayer()
.getField()
.getGraveyard()
.remove(getBoard().getOpponentPlayer().getField()
.getGraveyard().indexOf(max));
}
}
}
}
| 2,293 | 0.636284 | 0.634104 | 75 | 28.573334 | 25.499372 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.16 | false | false | 7 |
5d429db1b695d0fd2230c8bd3687450decde4d37 | 17,325,898,137,233 | 70fa7137dfbd8130403aae0fd7a993d9cd6c6aeb | /src/java/beans/psdi/webclient/beans/repfacility/CreateWorkorderBean.java | 0bf3a6da25a96b5736953fde772e4a84d11576ca | [
"MIT"
] | permissive | shoukaiseki/sksweb | https://github.com/shoukaiseki/sksweb | 65fc26e8d45640d5b3dd55a2c2a545113891b658 | 0f3f37da21296634f9480780e3e615711fb76c1b | refs/heads/master | 2023-01-13T15:03:30.369000 | 2022-12-30T10:56:13 | 2022-12-30T10:56:13 | 120,575,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* */ package psdi.webclient.beans.repfacility;
/* */
/* */ import java.rmi.RemoteException;
/* */ import psdi.mbo.MboRemote;
/* */ import psdi.mbo.MboSetRemote;
/* */ import psdi.util.MXException;
/* */ import psdi.webclient.system.beans.DataBean;
/* */ import psdi.webclient.system.controller.AppInstance;
/* */ import psdi.webclient.system.controller.PageInstance;
/* */ import psdi.webclient.system.session.WebClientSession;
/* */
/* */ public class CreateWorkorderBean extends DataBean
/* */ {
/* */ protected void initialize()
/* */ throws MXException, RemoteException
/* */ {
/* 38 */ super.initialize();
/* */
/* 40 */ MboSetRemote mboSet = super.getMboSet();
/* 41 */ DataBean appBean = this.app.getAppBean();
/* */
/* 43 */ MboRemote woRemoteMbo = null;
/* 44 */ if ((appBean != null) && ((appBean instanceof FollowUpWithRepairFacilities)))
/* */ {
/* 46 */ woRemoteMbo = ((FollowUpWithRepairFacilities)appBean).createFollowUp(mboSet);
/* */ }
/* */
/* 53 */ if (woRemoteMbo != null)
/* */ {
/* 55 */ String workorderID = woRemoteMbo.getString("workorderid");
/* */
/* 58 */ int mboSetSize = mboSet.getSize();
/* 59 */ for (int i = 0; i < mboSetSize; i++)
/* */ {
/* 61 */ mboSet.moveTo(i);
/* 62 */ if (!workorderID.equals(mboSet.getString("workorderid")))
/* */ continue;
/* 64 */ moveTo(i);
/* 65 */ break;
/* */ }
/* */ }
/* */ }
/* */
/* */ public synchronized int execute()
/* */ throws MXException, RemoteException
/* */ {
/* 74 */ MboRemote newMbo = getMbo();
/* */
/* 76 */ DataBean appBean = this.app.getAppBean();
/* */
/* 78 */ if ((appBean != null) && ((appBean instanceof FollowUpWithRepairFacilities)))
/* */ {
/* 80 */ FollowUpWithRepairFacilities followUpWithRepairFacilities = (FollowUpWithRepairFacilities)appBean;
/* */
/* 82 */ if (!followUpWithRepairFacilities.canSaveFollowUp(newMbo))
/* 83 */ return 1;
/* 84 */ followUpWithRepairFacilities.beforeFollowUpSave(newMbo);
/* 85 */ super.execute();
/* 86 */ followUpWithRepairFacilities.afterFollowUpSave(newMbo);
/* */ }
/* */ else {
/* 89 */ super.execute();
/* */ }
/* 91 */ PageInstance thisDialog = this.clientSession.getCurrentApp().getCurrentPage();
/* 92 */ this.clientSession.getCurrentApp().popPage(thisDialog);
/* */
/* 94 */ return 1;
/* */ }
/* */ }
/* Location: D:\maxapp\MAXIMO.ear\maximouiweb.war\WEB-INF\classes\
* Qualified Name: psdi.webclient.beans.repfacility.CreateWorkorderBean
* JD-Core Version: 0.6.0
*/ | UTF-8 | Java | 2,788 | java | CreateWorkorderBean.java | Java | [] | null | [] | /* */ package psdi.webclient.beans.repfacility;
/* */
/* */ import java.rmi.RemoteException;
/* */ import psdi.mbo.MboRemote;
/* */ import psdi.mbo.MboSetRemote;
/* */ import psdi.util.MXException;
/* */ import psdi.webclient.system.beans.DataBean;
/* */ import psdi.webclient.system.controller.AppInstance;
/* */ import psdi.webclient.system.controller.PageInstance;
/* */ import psdi.webclient.system.session.WebClientSession;
/* */
/* */ public class CreateWorkorderBean extends DataBean
/* */ {
/* */ protected void initialize()
/* */ throws MXException, RemoteException
/* */ {
/* 38 */ super.initialize();
/* */
/* 40 */ MboSetRemote mboSet = super.getMboSet();
/* 41 */ DataBean appBean = this.app.getAppBean();
/* */
/* 43 */ MboRemote woRemoteMbo = null;
/* 44 */ if ((appBean != null) && ((appBean instanceof FollowUpWithRepairFacilities)))
/* */ {
/* 46 */ woRemoteMbo = ((FollowUpWithRepairFacilities)appBean).createFollowUp(mboSet);
/* */ }
/* */
/* 53 */ if (woRemoteMbo != null)
/* */ {
/* 55 */ String workorderID = woRemoteMbo.getString("workorderid");
/* */
/* 58 */ int mboSetSize = mboSet.getSize();
/* 59 */ for (int i = 0; i < mboSetSize; i++)
/* */ {
/* 61 */ mboSet.moveTo(i);
/* 62 */ if (!workorderID.equals(mboSet.getString("workorderid")))
/* */ continue;
/* 64 */ moveTo(i);
/* 65 */ break;
/* */ }
/* */ }
/* */ }
/* */
/* */ public synchronized int execute()
/* */ throws MXException, RemoteException
/* */ {
/* 74 */ MboRemote newMbo = getMbo();
/* */
/* 76 */ DataBean appBean = this.app.getAppBean();
/* */
/* 78 */ if ((appBean != null) && ((appBean instanceof FollowUpWithRepairFacilities)))
/* */ {
/* 80 */ FollowUpWithRepairFacilities followUpWithRepairFacilities = (FollowUpWithRepairFacilities)appBean;
/* */
/* 82 */ if (!followUpWithRepairFacilities.canSaveFollowUp(newMbo))
/* 83 */ return 1;
/* 84 */ followUpWithRepairFacilities.beforeFollowUpSave(newMbo);
/* 85 */ super.execute();
/* 86 */ followUpWithRepairFacilities.afterFollowUpSave(newMbo);
/* */ }
/* */ else {
/* 89 */ super.execute();
/* */ }
/* 91 */ PageInstance thisDialog = this.clientSession.getCurrentApp().getCurrentPage();
/* 92 */ this.clientSession.getCurrentApp().popPage(thisDialog);
/* */
/* 94 */ return 1;
/* */ }
/* */ }
/* Location: D:\maxapp\MAXIMO.ear\maximouiweb.war\WEB-INF\classes\
* Qualified Name: psdi.webclient.beans.repfacility.CreateWorkorderBean
* JD-Core Version: 0.6.0
*/ | 2,788 | 0.568149 | 0.546628 | 74 | 36.68919 | 26.675694 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.472973 | false | false | 7 |
0468a8f88ce66b435c457df0c46125aa4267cd8f | 18,700,287,669,592 | 7a1f3ac53f3b46271083f9ed48cbf6a32420f625 | /Client/src/main/java/org/naturalcli/parameters/HexadecimalParamType.java | 367e2daac793d4ae5a0778efb77c972a4a77d56d | [] | no_license | xt0fer/YouAreEllMVC | https://github.com/xt0fer/YouAreEllMVC | 9387b70c1837dda6ca704b9b884c150963cd7002 | 431bc938e0570980f0724b8482c8ce3e68b76d39 | refs/heads/master | 2020-04-18T15:08:23.962000 | 2019-03-15T15:40:58 | 2019-03-15T15:40:58 | 167,605,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* HexadecimalParamType.java
*
* Copyright (C) 2008 Ferran Busquets
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.naturalcli.parameters;
import org.naturalcli.IParameterType;
/**
* The class implements an hexadecimal number parameter type.
*
* @see Integer#valueOf(String, int)
* @author Ferran Busquets
*
*/
public class HexadecimalParamType implements IParameterType {
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#getParameterTypeName()
*/
@Override
public String getParameterTypeName() {
return "hexadecimal";
}
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#validateParameter(java.lang.String)
*/
@Override
public boolean validateParameter(String value) {
try {
Integer.parseInt(value, 16);
return true;
} catch (NumberFormatException e)
{
return false;
}
}
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#validationMessage(java.lang.String)
*/
@Override
public String validationMessage(String value) {
return this.validateParameter(value) ? null : "Bad hexadecimal.";
}
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#convertParameterValue(java.lang.String)
*/
@Override
public Object convertParameterValue(String strRepresentation) {
return Integer.parseInt(strRepresentation, 16);
}
}
| UTF-8 | Java | 1,971 | java | HexadecimalParamType.java | Java | [
{
"context": "xadecimalParamType.java\r\n *\r\n * Copyright (C) 2008 Ferran Busquets\r\n *\r\n * Licensed under the Apache License, Versio",
"end": 76,
"score": 0.9998703002929688,
"start": 61,
"tag": "NAME",
"value": "Ferran Busquets"
},
{
"context": "\r\n * @see Integer#valueOf(Str... | null | [] | /*
* HexadecimalParamType.java
*
* Copyright (C) 2008 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.naturalcli.parameters;
import org.naturalcli.IParameterType;
/**
* The class implements an hexadecimal number parameter type.
*
* @see Integer#valueOf(String, int)
* @author <NAME>
*
*/
public class HexadecimalParamType implements IParameterType {
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#getParameterTypeName()
*/
@Override
public String getParameterTypeName() {
return "hexadecimal";
}
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#validateParameter(java.lang.String)
*/
@Override
public boolean validateParameter(String value) {
try {
Integer.parseInt(value, 16);
return true;
} catch (NumberFormatException e)
{
return false;
}
}
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#validationMessage(java.lang.String)
*/
@Override
public String validationMessage(String value) {
return this.validateParameter(value) ? null : "Bad hexadecimal.";
}
/* (non-Javadoc)
* @see org.naturalcli.paramtypes.IParameterType#convertParameterValue(java.lang.String)
*/
@Override
public Object convertParameterValue(String strRepresentation) {
return Integer.parseInt(strRepresentation, 16);
}
}
| 1,953 | 0.700152 | 0.694064 | 70 | 26.157143 | 27.016205 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 7 |
58b3157245d5d0338dd1c38f85bc8a5bbac0306c | 36,704,790,538,010 | 3da540036872524a99a9b0befa875e08271debfd | /MPChartExample/src/com/xxmassdeveloper/mpchartexample/notimportant/ContentItem.java | 5baaeb8baebc2f18141e5dc0e4d22e2fbb626f02 | [
"Apache-2.0"
] | permissive | wangfengye/MPAndroidChart | https://github.com/wangfengye/MPAndroidChart | 398e0eaaebdd50f5f0be7d4ec5bf04a971f3d358 | 5868929015d1679260ac0b1dbf8cb62e6e0ff5a0 | refs/heads/master | 2020-03-22T08:54:45.307000 | 2018-07-05T10:35:57 | 2018-07-05T10:35:57 | 139,800,055 | 0 | 0 | Apache-2.0 | true | 2018-07-05T05:43:31 | 2018-07-05T05:43:31 | 2018-07-05T05:26:07 | 2018-07-04T14:28:24 | 20,984 | 0 | 0 | 0 | null | false | null | package com.xxmassdeveloper.mpchartexample.notimportant;
/**
* Created by Philipp Jahoda on 07/12/15.
*/
public class ContentItem {
String name;
String desc;
boolean isNew = false;
public ContentItem(String n, String d) {
name = n;
desc = d;
}
public static ContentItem createNew(String n, String d){
ContentItem contentItem = new ContentItem(n,d);
contentItem.isNew = true;
return contentItem;
}
}
| UTF-8 | Java | 472 | java | ContentItem.java | Java | [
{
"context": "er.mpchartexample.notimportant;\n\n/**\n * Created by Philipp Jahoda on 07/12/15.\n */\npublic class ContentItem {\n\n ",
"end": 90,
"score": 0.9998313188552856,
"start": 76,
"tag": "NAME",
"value": "Philipp Jahoda"
}
] | null | [] | package com.xxmassdeveloper.mpchartexample.notimportant;
/**
* Created by <NAME> on 07/12/15.
*/
public class ContentItem {
String name;
String desc;
boolean isNew = false;
public ContentItem(String n, String d) {
name = n;
desc = d;
}
public static ContentItem createNew(String n, String d){
ContentItem contentItem = new ContentItem(n,d);
contentItem.isNew = true;
return contentItem;
}
}
| 464 | 0.639831 | 0.627119 | 21 | 21.476191 | 19.543892 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 7 |
ea135934bccf38fc91fe600df6ee35e3a9955fe9 | 38,852,274,181,734 | 29e22899a4a307f944aede8a57cd746d5b6d8f2b | /leetcode/src/main/java/com/zfwhub/algorithm/leetcode/dp/RegularExpressionMatching.java | 291690c1cd409a9f345b82aab310ce665ccecfad | [] | no_license | markliu2013/algorithm | https://github.com/markliu2013/algorithm | 5a507ace10552007f767ffbcb97ec726eda151f7 | 7ad90a55992dc11aded376138ae7f84ff6d27bf4 | refs/heads/master | 2021-08-18T05:31:18.942000 | 2021-06-08T07:36:21 | 2021-06-08T07:36:21 | 132,756,025 | 5 | 1 | null | false | 2019-04-22T06:03:06 | 2018-05-09T12:48:59 | 2019-03-28T16:20:14 | 2019-04-22T06:03:05 | 1,050 | 0 | 0 | 0 | Java | false | false | package com.zfwhub.algorithm.leetcode.dp;
import java.util.*;
// https://leetcode.com/problems/regular-expression-matching/
public class RegularExpressionMatching {
static final Character ASTERISK_CHAR = '*';
static final Character POINT_CHAR = '.';
static final String ASTERISK_STRING = "*";
public static boolean solution1(String s, String p) {
if (p.length() == 0) {
if (s.length() == 0) {
return true;
} else {
return false;
}
}
List<CharPattern> patterns = new ArrayList<>();
for (int i = 0; i < p.length()-1; i++) {
CharPattern pattern = new CharPattern(p.charAt(i+1) == ASTERISK_CHAR, p.charAt(i));
patterns.add(pattern);
if (p.charAt(i+1) == ASTERISK_CHAR) {
i++;
}
}
if (p.charAt(p.length()-1) != ASTERISK_CHAR) {
patterns.add(new CharPattern(false, p.charAt(p.length()-1)));
}
return dp(s, patterns);
}
private static boolean dp(String s, List<CharPattern> patterns) {
if (s.length() == 0 && patterns.size() == 0) {
return true;
}
if (s.length() == 0) {
for (int i = 0; i < patterns.size(); i++) {
CharPattern pattern = patterns.get(i);
if (!pattern.isAsterisk) {
return false;
}
}
return true;
}
if (patterns.size() == 0) {
return false;
}
CharPattern lastPattern = patterns.get(patterns.size()-1);
List<CharPattern> subPatterns = patterns.subList(0, patterns.size()-1);
if (!lastPattern.isAsterisk) {
if (lastPattern.matches(s.charAt(s.length()-1))) {
return dp(s.substring(0, s.length()-1), subPatterns);
} else {
return false;
}
} else {
if (lastPattern.matches(s.charAt(s.length()-1))) {
// 是星号,且匹配上了,可以匹配多个,需要对string的最后匹配几个进行轮询
int count = 0;
if (lastPattern.isPoint()) {
count = s.length();
} else {
count = lastPattern.checkLastCount(s);
}
for (int i = 0; i <= count; i++) {
if (dp(s.substring(0, s.length()-i), subPatterns)) {
return true;
}
}
return false;
} else {
return dp(s, subPatterns);
}
}
}
private static class CharPattern {
public boolean isAsterisk;
public Character character;
public int checkLastCount(String s) {
int count = 0;
for (int i = s.length()-1; i >= 0; i--) {
if (matches(s.charAt(i))) {
count++;
} else {
break;
}
}
return count;
}
public CharPattern(boolean isAsterisk, Character character) {
this.isAsterisk = isAsterisk;
this.character = character;
}
public boolean isPoint() {
return character == POINT_CHAR;
}
public boolean matches(Character c) {
if (character == '.') {
return true;
}
return character == c;
}
@Override
public String toString() {
return character + (isAsterisk ? ASTERISK_STRING : "");
}
}
public static boolean solution2(String s, String p) {
if (p.length() == 0) {
return s.length() == 0;
}
if (s.length() == 0) {
int currentIndex = p.length()-1;
while (currentIndex >= 0) {
if (p.charAt(currentIndex) == ASTERISK_CHAR) {
currentIndex -= 2;
} else {
return false;
}
}
return true;
}
if (p.charAt(p.length()-1) == ASTERISK_CHAR) {
int currentIndex = s.length()-1;
if (solution2(s, p.substring(0, p.length()-2))) {
return true;
}
while ( currentIndex >= 0 && (s.charAt(currentIndex) == p.charAt(p.length()-2) || p.charAt(p.length()-2) == POINT_CHAR) ) {
if (solution2(s.substring(0, currentIndex), p.substring(0, p.length()-2))) {
return true;
} else {
currentIndex--;
}
}
return false;
} else {
if (s.charAt(s.length()-1) == p.charAt(p.length()-1) || p.charAt(p.length()-1) == POINT_CHAR) {
return solution2(s.substring(0, s.length()-1), p.substring(0, p.length()-1));
} else {
return false;
}
}
}
public static void main(String[] args) {
String s = "mississippi";
String p = "mis*is*ip*.";
System.out.println(solution2(s, p));
}
}
| UTF-8 | Java | 5,283 | java | RegularExpressionMatching.java | Java | [] | null | [] | package com.zfwhub.algorithm.leetcode.dp;
import java.util.*;
// https://leetcode.com/problems/regular-expression-matching/
public class RegularExpressionMatching {
static final Character ASTERISK_CHAR = '*';
static final Character POINT_CHAR = '.';
static final String ASTERISK_STRING = "*";
public static boolean solution1(String s, String p) {
if (p.length() == 0) {
if (s.length() == 0) {
return true;
} else {
return false;
}
}
List<CharPattern> patterns = new ArrayList<>();
for (int i = 0; i < p.length()-1; i++) {
CharPattern pattern = new CharPattern(p.charAt(i+1) == ASTERISK_CHAR, p.charAt(i));
patterns.add(pattern);
if (p.charAt(i+1) == ASTERISK_CHAR) {
i++;
}
}
if (p.charAt(p.length()-1) != ASTERISK_CHAR) {
patterns.add(new CharPattern(false, p.charAt(p.length()-1)));
}
return dp(s, patterns);
}
private static boolean dp(String s, List<CharPattern> patterns) {
if (s.length() == 0 && patterns.size() == 0) {
return true;
}
if (s.length() == 0) {
for (int i = 0; i < patterns.size(); i++) {
CharPattern pattern = patterns.get(i);
if (!pattern.isAsterisk) {
return false;
}
}
return true;
}
if (patterns.size() == 0) {
return false;
}
CharPattern lastPattern = patterns.get(patterns.size()-1);
List<CharPattern> subPatterns = patterns.subList(0, patterns.size()-1);
if (!lastPattern.isAsterisk) {
if (lastPattern.matches(s.charAt(s.length()-1))) {
return dp(s.substring(0, s.length()-1), subPatterns);
} else {
return false;
}
} else {
if (lastPattern.matches(s.charAt(s.length()-1))) {
// 是星号,且匹配上了,可以匹配多个,需要对string的最后匹配几个进行轮询
int count = 0;
if (lastPattern.isPoint()) {
count = s.length();
} else {
count = lastPattern.checkLastCount(s);
}
for (int i = 0; i <= count; i++) {
if (dp(s.substring(0, s.length()-i), subPatterns)) {
return true;
}
}
return false;
} else {
return dp(s, subPatterns);
}
}
}
private static class CharPattern {
public boolean isAsterisk;
public Character character;
public int checkLastCount(String s) {
int count = 0;
for (int i = s.length()-1; i >= 0; i--) {
if (matches(s.charAt(i))) {
count++;
} else {
break;
}
}
return count;
}
public CharPattern(boolean isAsterisk, Character character) {
this.isAsterisk = isAsterisk;
this.character = character;
}
public boolean isPoint() {
return character == POINT_CHAR;
}
public boolean matches(Character c) {
if (character == '.') {
return true;
}
return character == c;
}
@Override
public String toString() {
return character + (isAsterisk ? ASTERISK_STRING : "");
}
}
public static boolean solution2(String s, String p) {
if (p.length() == 0) {
return s.length() == 0;
}
if (s.length() == 0) {
int currentIndex = p.length()-1;
while (currentIndex >= 0) {
if (p.charAt(currentIndex) == ASTERISK_CHAR) {
currentIndex -= 2;
} else {
return false;
}
}
return true;
}
if (p.charAt(p.length()-1) == ASTERISK_CHAR) {
int currentIndex = s.length()-1;
if (solution2(s, p.substring(0, p.length()-2))) {
return true;
}
while ( currentIndex >= 0 && (s.charAt(currentIndex) == p.charAt(p.length()-2) || p.charAt(p.length()-2) == POINT_CHAR) ) {
if (solution2(s.substring(0, currentIndex), p.substring(0, p.length()-2))) {
return true;
} else {
currentIndex--;
}
}
return false;
} else {
if (s.charAt(s.length()-1) == p.charAt(p.length()-1) || p.charAt(p.length()-1) == POINT_CHAR) {
return solution2(s.substring(0, s.length()-1), p.substring(0, p.length()-1));
} else {
return false;
}
}
}
public static void main(String[] args) {
String s = "mississippi";
String p = "mis*is*ip*.";
System.out.println(solution2(s, p));
}
}
| 5,283 | 0.448765 | 0.43823 | 161 | 31.428572 | 23.028666 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.552795 | false | false | 7 |
aef004291ec492ba5a40bf4dda151d61a5087070 | 35,072,702,991,562 | 69c00032e21079eb41b86c2085d38b8ba3e6e5cb | /Development_library/05Coding/安卓/andr_b/src/cn/suanzi/baomi/shop/adapter/CampaignFreeAdapter.java | 152db9f3890d960d63c3d8e908e2bf80e7036c33 | [] | no_license | qiaobenlaing/coupon | https://github.com/qiaobenlaing/coupon | 476b90ac9c8a9bb56f4c481c3e0303adc9575133 | 32a53667f0c496cda0d7df71651e07f0138001d3 | refs/heads/master | 2023-01-20T03:40:42.118000 | 2020-11-20T00:59:29 | 2020-11-20T01:13:28 | 312,522,162 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.suanzi.baomi.shop.adapter;
import java.util.List;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.suanzi.baomi.base.Util;
import cn.suanzi.baomi.base.adapter.CommenViewHolder;
import cn.suanzi.baomi.base.adapter.CommonListViewAdapter;
import cn.suanzi.baomi.base.pojo.PromotionPrice;
import cn.suanzi.baomi.base.utils.DialogUtils;
import cn.suanzi.baomi.shop.R;
/**
* 活动规格
* @author wensi.yu
*
*/
public class CampaignFreeAdapter extends CommonListViewAdapter<PromotionPrice>{
private final static String TAG = "CampaignFreeAdapter";
private List<PromotionPrice> mData;
public CampaignFreeAdapter(Activity activity, List<PromotionPrice> datas) {
super(activity, datas);
this.mData = datas;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final CommenViewHolder holder = CommenViewHolder.get(mActivity , convertView , parent, R.layout.item_campaign_free, position);
final PromotionPrice item = (PromotionPrice) getItem(position);
TextView tvCampaignFree = holder.getView(R.id.tv_camapginfree_title);
EditText etCampaignFreeType = holder.getView(R.id.et_camapignfree_type);
EditText etCampaignFreeMoney = holder.getView(R.id.et_camapignfree_money);
LinearLayout lyCampignFree = holder.getView(R.id.ly_campaign_free);
if(!Util.isEmpty(item.getDes())){
etCampaignFreeType.setText(item.getDes());
}
if(!Util.isEmpty(item.getPrice()+"")){
if (item.getPrice() == 0.0) {
etCampaignFreeMoney.setText("");
} else {
etCampaignFreeMoney.setText(item.getPrice()+"");
}
}
if(item.getId() != 0){
tvCampaignFree.setText("规格"+item.getId());
}
etCampaignFreeType.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
item.setDes(s.toString());
}
});
etCampaignFreeMoney.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
String priceStr = s.toString();
if(Util.isEmpty(priceStr)){
priceStr = "0";
}
item.setPrice(Double.parseDouble(priceStr));
}
});
lyCampignFree.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final int promotionCode = item.getId();
Log.d(TAG, "promotionCode == "+promotionCode);
DialogUtils.showDialog(mActivity, mActivity.getString(R.string.cue),mActivity.getString(R.string.campaign_isdelete), mActivity.getString(R.string.ok), mActivity.getString(R.string.no), new DialogUtils().new OnResultListener() {
@Override
public void onOK() {
for (int i = 0; i < mData.size(); i++) {
PromotionPrice promotionPrice = mData.get(i);
Log.d(TAG,"promotionPrice == " +promotionPrice.getId());
if (i == position) {
mData.remove(promotionPrice);
notifyDataSetChanged();
}
}
}
@Override
public void onCancel(){
}
});
}
});
return holder.getConvertView();
}
}
| UTF-8 | Java | 3,723 | java | CampaignFreeAdapter.java | Java | [
{
"context": "rt cn.suanzi.baomi.shop.R;\n\n/**\n * 活动规格\n * @author wensi.yu\n *\n */\npublic class CampaignFreeAdapter extends C",
"end": 684,
"score": 0.9429724812507629,
"start": 676,
"tag": "NAME",
"value": "wensi.yu"
}
] | null | [] | package cn.suanzi.baomi.shop.adapter;
import java.util.List;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.suanzi.baomi.base.Util;
import cn.suanzi.baomi.base.adapter.CommenViewHolder;
import cn.suanzi.baomi.base.adapter.CommonListViewAdapter;
import cn.suanzi.baomi.base.pojo.PromotionPrice;
import cn.suanzi.baomi.base.utils.DialogUtils;
import cn.suanzi.baomi.shop.R;
/**
* 活动规格
* @author wensi.yu
*
*/
public class CampaignFreeAdapter extends CommonListViewAdapter<PromotionPrice>{
private final static String TAG = "CampaignFreeAdapter";
private List<PromotionPrice> mData;
public CampaignFreeAdapter(Activity activity, List<PromotionPrice> datas) {
super(activity, datas);
this.mData = datas;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final CommenViewHolder holder = CommenViewHolder.get(mActivity , convertView , parent, R.layout.item_campaign_free, position);
final PromotionPrice item = (PromotionPrice) getItem(position);
TextView tvCampaignFree = holder.getView(R.id.tv_camapginfree_title);
EditText etCampaignFreeType = holder.getView(R.id.et_camapignfree_type);
EditText etCampaignFreeMoney = holder.getView(R.id.et_camapignfree_money);
LinearLayout lyCampignFree = holder.getView(R.id.ly_campaign_free);
if(!Util.isEmpty(item.getDes())){
etCampaignFreeType.setText(item.getDes());
}
if(!Util.isEmpty(item.getPrice()+"")){
if (item.getPrice() == 0.0) {
etCampaignFreeMoney.setText("");
} else {
etCampaignFreeMoney.setText(item.getPrice()+"");
}
}
if(item.getId() != 0){
tvCampaignFree.setText("规格"+item.getId());
}
etCampaignFreeType.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
item.setDes(s.toString());
}
});
etCampaignFreeMoney.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
String priceStr = s.toString();
if(Util.isEmpty(priceStr)){
priceStr = "0";
}
item.setPrice(Double.parseDouble(priceStr));
}
});
lyCampignFree.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final int promotionCode = item.getId();
Log.d(TAG, "promotionCode == "+promotionCode);
DialogUtils.showDialog(mActivity, mActivity.getString(R.string.cue),mActivity.getString(R.string.campaign_isdelete), mActivity.getString(R.string.ok), mActivity.getString(R.string.no), new DialogUtils().new OnResultListener() {
@Override
public void onOK() {
for (int i = 0; i < mData.size(); i++) {
PromotionPrice promotionPrice = mData.get(i);
Log.d(TAG,"promotionPrice == " +promotionPrice.getId());
if (i == position) {
mData.remove(promotionPrice);
notifyDataSetChanged();
}
}
}
@Override
public void onCancel(){
}
});
}
});
return holder.getConvertView();
}
}
| 3,723 | 0.704392 | 0.703045 | 128 | 27.992188 | 31.288101 | 231 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.054688 | false | false | 7 |
3744d392ce908a25429b1fc9ccd56c69d550a1b9 | 38,208,029,085,818 | 913605148f7dd05de7e6458bd1931f0183f4f2bc | /src/main/java/clone/obj/Children.java | 2ab4c8a4d36ec75d7129cc70ff81b74324f91c07 | [] | no_license | kaibing/test | https://github.com/kaibing/test | 846fea998435887ef42cad531f7ca7cba7422afe | f4fb58f7fe3184821bd7a82250e93c2d654acc01 | refs/heads/master | 2018-11-11T09:55:18.586000 | 2018-10-31T03:23:15 | 2018-10-31T03:23:15 | 142,723,491 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clone.obj;
public class Children implements Cloneable{
private int id;
private Wife wife;
public Children() {
}
public Children(int id, Wife wife) {
this.id = id;
this.wife = wife;
}
@Override
public String toString() {
return "Children{" +
"id=" + id +
", wife=" + wife +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
@Override
public Object clone() throws CloneNotSupportedException {
Children children = (Children) super.clone();
children.wife = (Wife) children.getWife().clone();
return children;
}
}
| UTF-8 | Java | 861 | java | Children.java | Java | [] | null | [] | package clone.obj;
public class Children implements Cloneable{
private int id;
private Wife wife;
public Children() {
}
public Children(int id, Wife wife) {
this.id = id;
this.wife = wife;
}
@Override
public String toString() {
return "Children{" +
"id=" + id +
", wife=" + wife +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
@Override
public Object clone() throws CloneNotSupportedException {
Children children = (Children) super.clone();
children.wife = (Wife) children.getWife().clone();
return children;
}
}
| 861 | 0.522648 | 0.522648 | 45 | 18.133333 | 16.194101 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 7 |
2409007cd6fe94534bda516f7dac411f486274c9 | 10,325,101,409,034 | 1afa251a2caebded5ca83f227cb7158c9e6c049f | /tesler-core/src/main/java/io/tesler/core/util/InstrumentationAwareReflectionUtils.java | 489aed560a3bc04f4b5abfe6fb48845d15d92fa7 | [
"Apache-2.0"
] | permissive | tesler-platform/tesler | https://github.com/tesler-platform/tesler | 7c6951305c504a297d7213202667fcee320cd8e8 | 24e903c2b7dd01021bc3106bd2b5e4fb9b24ce4b | refs/heads/master | 2023-06-07T15:48:02.607000 | 2023-05-24T15:13:09 | 2023-05-24T15:13:09 | 224,087,872 | 25 | 19 | Apache-2.0 | false | 2023-05-24T15:13:10 | 2019-11-26T02:48:30 | 2023-05-01T14:09:38 | 2023-05-24T15:13:09 | 87,100 | 14 | 12 | 13 | Java | false | false | /*-
* #%L
* IO Tesler - Core
* %%
* Copyright (C) 2018 - 2021 Tesler Contributors
* %%
* 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.
* #L%
*/
package io.tesler.core.util;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.reflect.FieldUtils;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
@UtilityClass
public final class InstrumentationAwareReflectionUtils {
/**
* Gets all non synthetic fields of the given class and its parents (if any).
* Frameworks like jacoco add synthetic fields for internal usage.
* This method can be used instead of FieldUtils.getAllFieldsList to avoid clashes with such fields
*
* @param cls the {@link Class} to query
* @return an array of Fields (possibly empty).
* @throws IllegalArgumentException if the class is {@code null}
*/
public static List<Field> getAllNonSyntheticFieldsList(final Class<?> cls) {
return FieldUtils.getAllFieldsList(cls)
.stream()
.filter(field -> !field.isSynthetic())
.collect(Collectors.toList());
}
}
| UTF-8 | Java | 1,584 | java | InstrumentationAwareReflectionUtils.java | Java | [] | null | [] | /*-
* #%L
* IO Tesler - Core
* %%
* Copyright (C) 2018 - 2021 Tesler Contributors
* %%
* 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.
* #L%
*/
package io.tesler.core.util;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.reflect.FieldUtils;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
@UtilityClass
public final class InstrumentationAwareReflectionUtils {
/**
* Gets all non synthetic fields of the given class and its parents (if any).
* Frameworks like jacoco add synthetic fields for internal usage.
* This method can be used instead of FieldUtils.getAllFieldsList to avoid clashes with such fields
*
* @param cls the {@link Class} to query
* @return an array of Fields (possibly empty).
* @throws IllegalArgumentException if the class is {@code null}
*/
public static List<Field> getAllNonSyntheticFieldsList(final Class<?> cls) {
return FieldUtils.getAllFieldsList(cls)
.stream()
.filter(field -> !field.isSynthetic())
.collect(Collectors.toList());
}
}
| 1,584 | 0.734848 | 0.726641 | 48 | 32 | 28.282799 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.770833 | false | false | 7 |
a9da747a3897591baa921643db57acc5f2760209 | 14,534,169,355,776 | 6a8dc88bc2cbb908f9f1970622a6a5a4f3b1c475 | /core/src/acavailhez/html/internal/HtmlEngine.java | 56780b27cb805b981fd347fdb27e922cfbb8e0a9 | [
"Apache-2.0"
] | permissive | acavailhez/html-renderer | https://github.com/acavailhez/html-renderer | 41eccc3ca819c2dd4809a0c3e428af96956b0793 | a4e13973fe922d67c8d4886ce934bf6402bf1503 | refs/heads/master | 2021-01-18T21:23:24.238000 | 2016-09-06T23:55:28 | 2016-09-06T23:55:28 | 36,955,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package acavailhez.html.internal;
import acavailhez.html.utils.HtmlUtils;
import java.util.Map;
import java.util.Set;
// Everything heavy is coded in java for performances
public class HtmlEngine {
public static void openTag(StringBuilder html, String tagName, Map attrs) {
html.append("<");
html.append(tagName);
if (attrs != null) {
Set<Object> keyObjects = attrs.keySet();
for (Object keyO : keyObjects) {
String key = keyO.toString();
Object value = attrs.get(key);
if (value != null) {
String escaped = HtmlUtils.escapeHtmlAttribute(value);
html.append(" ");
html.append(key);
html.append("=\"");
html.append(escaped);
html.append("\"");
}
}
}
html.append(">");
}
public static void closeTag(StringBuilder html, String tagName) {
html.append("</");
html.append(tagName);
html.append(">");
}
}
| UTF-8 | Java | 1,103 | java | HtmlEngine.java | Java | [] | null | [] | package acavailhez.html.internal;
import acavailhez.html.utils.HtmlUtils;
import java.util.Map;
import java.util.Set;
// Everything heavy is coded in java for performances
public class HtmlEngine {
public static void openTag(StringBuilder html, String tagName, Map attrs) {
html.append("<");
html.append(tagName);
if (attrs != null) {
Set<Object> keyObjects = attrs.keySet();
for (Object keyO : keyObjects) {
String key = keyO.toString();
Object value = attrs.get(key);
if (value != null) {
String escaped = HtmlUtils.escapeHtmlAttribute(value);
html.append(" ");
html.append(key);
html.append("=\"");
html.append(escaped);
html.append("\"");
}
}
}
html.append(">");
}
public static void closeTag(StringBuilder html, String tagName) {
html.append("</");
html.append(tagName);
html.append(">");
}
}
| 1,103 | 0.520399 | 0.520399 | 37 | 28.81081 | 20.638245 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594595 | false | false | 7 |
26ab8d4e7a6966760555101479d5540172e47af0 | 27,943,057,231,705 | a06d5c89698eab0d371bfce453e721bb203921cc | /MetalliumUtils/src/com/metallium/utils/main/stuff/StuffProblems.java | 37fc572414ddbdbf1dc1c3e94edda64567ff1a96 | [] | no_license | rubenesc/MetalCity | https://github.com/rubenesc/MetalCity | 011e27c6b3a5b9bf1e2662d74dc71b27c72a3413 | 2db92eb6f4d27f25a38ff04ab2318ab3accce03a | refs/heads/master | 2016-09-10T22:13:39.181000 | 2012-04-11T05:40:02 | 2012-04-11T05:40:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.metallium.utils.main.stuff;
/**
*
* @author Ruben
*/
public class StuffProblems {
private static void painterTest() {
System.out.println("*** painterTest ***");
}
public StuffProblems() {
}
public static void main(String[] args) {
StuffProblems sp = new StuffProblems();
sp.mathPow();
String s = "-150";
System.out.println(s + ": atoi --> " + atoi(s));
//Given US denomination coins, what is the algorithm to make change for any amount?
getChangeTest();
System.out.println("");
System.out.println("--> " + 346 % 25);
System.out.println("--> " + 346 / 25);
System.out.println("--> " + 13 * 25);
System.out.println("--> " + (325+21));
painterTest();
}
private static void getChangeTest() {
System.out.println("*** getChangeTest ***");
double money = 3.46;
int[] coins = {25,10,5,1};
int[] change = getNumber(coins, money);
System.out.println("money: " + money);
System.out.print("coins: ");
printArray(change);
}
private static int[] getNumber(int[] coinDenominations, double totalAmountInDollars) {
int numberOfEachCoin[] = new int[coinDenominations.length];
int totalAmountInCents = (int) (totalAmountInDollars * 100);
for (int i = 0; i < coinDenominations.length; i++) {
int denomination = coinDenominations[i];
numberOfEachCoin[i] = totalAmountInCents / denomination;
totalAmountInCents = totalAmountInCents % denomination;
}
return numberOfEachCoin;
}
public static int atoi(String s) {
if (s == null) {
return 0;
}
int anwser = 0;
int sign = 1;
int i = 0;
int tens = 0;
char base = '0';
int length = s.length();
if (s.charAt(0) == '-') {
sign = -1;
i = 1;
}
for (; i < length; i++) {
char c = s.charAt(length - i);
anwser += (c - base) * tens;
if (tens == 0) {
tens = 1;
}
tens = tens * 10;
}
return anwser * sign;
}
private void mathPow() {
//a^b
long x = 3;
int b = 10;
for (int i = 1; i <= b; i++) {
System.out.println(x + "^" + i + " --> x: " + Math.pow(x, i));
}
}
private static void printArray(int[] data) {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + ",");
}
System.out.println("");
}
}
| UTF-8 | Java | 2,798 | java | StuffProblems.java | Java | [
{
"context": "com.metallium.utils.main.stuff;\n\n/**\n *\n * @author Ruben\n */\npublic class StuffProblems {\n\n private sta",
"end": 164,
"score": 0.999299168586731,
"start": 159,
"tag": "NAME",
"value": "Ruben"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.metallium.utils.main.stuff;
/**
*
* @author Ruben
*/
public class StuffProblems {
private static void painterTest() {
System.out.println("*** painterTest ***");
}
public StuffProblems() {
}
public static void main(String[] args) {
StuffProblems sp = new StuffProblems();
sp.mathPow();
String s = "-150";
System.out.println(s + ": atoi --> " + atoi(s));
//Given US denomination coins, what is the algorithm to make change for any amount?
getChangeTest();
System.out.println("");
System.out.println("--> " + 346 % 25);
System.out.println("--> " + 346 / 25);
System.out.println("--> " + 13 * 25);
System.out.println("--> " + (325+21));
painterTest();
}
private static void getChangeTest() {
System.out.println("*** getChangeTest ***");
double money = 3.46;
int[] coins = {25,10,5,1};
int[] change = getNumber(coins, money);
System.out.println("money: " + money);
System.out.print("coins: ");
printArray(change);
}
private static int[] getNumber(int[] coinDenominations, double totalAmountInDollars) {
int numberOfEachCoin[] = new int[coinDenominations.length];
int totalAmountInCents = (int) (totalAmountInDollars * 100);
for (int i = 0; i < coinDenominations.length; i++) {
int denomination = coinDenominations[i];
numberOfEachCoin[i] = totalAmountInCents / denomination;
totalAmountInCents = totalAmountInCents % denomination;
}
return numberOfEachCoin;
}
public static int atoi(String s) {
if (s == null) {
return 0;
}
int anwser = 0;
int sign = 1;
int i = 0;
int tens = 0;
char base = '0';
int length = s.length();
if (s.charAt(0) == '-') {
sign = -1;
i = 1;
}
for (; i < length; i++) {
char c = s.charAt(length - i);
anwser += (c - base) * tens;
if (tens == 0) {
tens = 1;
}
tens = tens * 10;
}
return anwser * sign;
}
private void mathPow() {
//a^b
long x = 3;
int b = 10;
for (int i = 1; i <= b; i++) {
System.out.println(x + "^" + i + " --> x: " + Math.pow(x, i));
}
}
private static void printArray(int[] data) {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + ",");
}
System.out.println("");
}
}
| 2,798 | 0.495711 | 0.476769 | 112 | 23.982143 | 21.746504 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 7 |
d522ee3a2d2c965526557dd3d6e013b8ad39d1d0 | 21,835,613,737,331 | c7edb107b2c1fb1313fe9a75ac1fd6d32f7d78c4 | /Java/Valid_Triangles.java | 8b0cc2cccff5f510fcaf5463eefaa9b21e7f8847 | [] | no_license | Dharan21/CodeChef | https://github.com/Dharan21/CodeChef | d729a99026eb7a190f76fa2e84fe1fb19126824c | 8c5a0dcc761d35d39a8db96c555e9fc05541933a | refs/heads/master | 2021-07-08T10:41:24.315000 | 2020-11-07T13:41:40 | 2020-11-07T13:41:40 | 207,360,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Valid_Triangles {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()){
int t = sc.nextInt();
for(int i=0;i<t;i++){
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if((a+b+c) == 180) System.out.println("YES");
else System.out.println("NO");
}
}
}
}
| UTF-8 | Java | 500 | java | Valid_Triangles.java | Java | [] | null | [] | import java.util.Scanner;
public class Valid_Triangles {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()){
int t = sc.nextInt();
for(int i=0;i<t;i++){
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if((a+b+c) == 180) System.out.println("YES");
else System.out.println("NO");
}
}
}
}
| 500 | 0.458 | 0.45 | 17 | 28.411764 | 16.9013 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 7 |
8a8477efad7f6fc6d8708e2f7ba01c3506626353 | 1,511,828,539,542 | 7220e7aaeba403350dffb1d21fe00bf50f098c82 | /app/src/main/java/com/capri4physio/util/Utils.java | 871bb9ac2380d5072a2b63777568bcd3ffe7965b | [] | no_license | vishwakarmasunil68/Capri4Physio | https://github.com/vishwakarmasunil68/Capri4Physio | 78f13e49e060054b36c732bb0840d9db7d1e511b | b8ab12c5974390361cebcd75eb7eae8f9f9333f2 | refs/heads/master | 2021-01-01T18:52:48.914000 | 2017-11-25T14:22:22 | 2017-11-25T14:22:26 | 98,457,961 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.capri4physio.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.capri4physio.R;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
/**
* Jobswolf utility class to define reusable methods
*
* @author prabhunathy
* @version 1.0
* @since 12/22/15.
*/
public class Utils {
public static boolean hideSpinnerKeyboard(Context context) {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
/**
* Get current time
*
* @return
*/
public static String getCurrentDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
public static String getCurrentDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
public static String getDateMonth() {
SimpleDateFormat df = new SimpleDateFormat("MMMM, yyyy", Locale.ENGLISH);
Calendar c = Calendar.getInstance();
String formattedDate = df.format(c.getTime());
return formattedDate;
}
/**
* Get storage directory base path
*
* @return
*/
public static String getStorageDirectory() {
String sdCardPath = "";
Boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (isSDPresent) {
sdCardPath = Environment.getExternalStorageDirectory().toString();
} else {
sdCardPath = Environment.getRootDirectory().toString();
}
return sdCardPath;
}
/**
* Video path to record a video in device storage
*
* @return String video file path
* @throws IOException
*/
private String videoPath() throws IOException {
String timeStamp = String.valueOf(System.currentTimeMillis());
String fileName = "VID_" + timeStamp + "_";
File storageDir = new File(Utils.getStorageDirectory(), "Capri4Physio");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
//File file = File.createTempFile(fileName, ".mp4", storageDir);
//return file;
fileName = storageDir.getPath() + "/" + fileName + ".mp4";
AppLog.e("Jobswolf", "Jobswolf video path :" + fileName);
return fileName;
}
/**
* Check internet connection
*
* @param context
* @return
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
/**
* Display alert message dialog
*
* @param context
* @param msg
*/
public static void showMessage(Context context, String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(msg);
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, null);
builder.create();
builder.show();
}
/**
* Display alert message dialog with error title
*
* @param context
* @param titile
* @param msg
*/
public static void showError(Context context, String titile, String msg) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
if (titile != null && !titile.equals(""))
alert.setTitle(titile);
alert.setMessage(msg);
alert.setPositiveButton(android.R.string.ok, null);
alert.create();
alert.show();
}
public static void showErrordemo(Context context, String titile, String msg) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
if (titile != null && !titile.equals(""))
alert.setTitle(titile);
alert.setMessage(msg);
alert.setPositiveButton(android.R.string.ok, null);
alert.create();
alert.show();
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (; ; ) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static String getEncodedUrl(String url) {
String imageUrl = url;
String filenames[] = imageUrl.split("/");
String filename = filenames[filenames.length - 1];
String newfilename = "";
try {
newfilename = URLEncoder.encode(filename, "Utf-8");
newfilename = newfilename.replace("+", "%20");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
imageUrl = imageUrl.replace(filename, newfilename);
return imageUrl;
}
public static int getCurrentHour() {
Calendar c = Calendar.getInstance();
int curHours = c.get(Calendar.HOUR_OF_DAY);
return curHours;
}
public static String replaceExtraChar(String str_todecode) {
String message = "";
message = str_todecode.replace("%A0", "");
return message;
}
public static String getToneSpinnerData(Context context, int position) {
if (position == 0) {
return "";
} else {
String arr[] = context.getResources().getStringArray(R.array.head_tone_of_the_motor);
return arr[position];
}
}
public static String getPowerSpinnerData(Context context, int position) {
if (position == 0) {
return "";
} else {
String arr[] = context.getResources().getStringArray(R.array.head_power_of_the_motor);
return arr[position];
}
}
public static String getEdittextData(EditText editText) {
return editText.getText().toString();
}
}
| UTF-8 | Java | 8,132 | java | Utils.java | Java | [
{
"context": "y class to define reusable methods\n *\n * @author prabhunathy\n * @version 1.0\n * @since 12/22/15.\n */\npublic cl",
"end": 928,
"score": 0.9912989139556885,
"start": 917,
"tag": "USERNAME",
"value": "prabhunathy"
}
] | null | [] | package com.capri4physio.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.capri4physio.R;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
/**
* Jobswolf utility class to define reusable methods
*
* @author prabhunathy
* @version 1.0
* @since 12/22/15.
*/
public class Utils {
public static boolean hideSpinnerKeyboard(Context context) {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
/**
* Get current time
*
* @return
*/
public static String getCurrentDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
public static String getCurrentDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
public static String getDateMonth() {
SimpleDateFormat df = new SimpleDateFormat("MMMM, yyyy", Locale.ENGLISH);
Calendar c = Calendar.getInstance();
String formattedDate = df.format(c.getTime());
return formattedDate;
}
/**
* Get storage directory base path
*
* @return
*/
public static String getStorageDirectory() {
String sdCardPath = "";
Boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (isSDPresent) {
sdCardPath = Environment.getExternalStorageDirectory().toString();
} else {
sdCardPath = Environment.getRootDirectory().toString();
}
return sdCardPath;
}
/**
* Video path to record a video in device storage
*
* @return String video file path
* @throws IOException
*/
private String videoPath() throws IOException {
String timeStamp = String.valueOf(System.currentTimeMillis());
String fileName = "VID_" + timeStamp + "_";
File storageDir = new File(Utils.getStorageDirectory(), "Capri4Physio");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
//File file = File.createTempFile(fileName, ".mp4", storageDir);
//return file;
fileName = storageDir.getPath() + "/" + fileName + ".mp4";
AppLog.e("Jobswolf", "Jobswolf video path :" + fileName);
return fileName;
}
/**
* Check internet connection
*
* @param context
* @return
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
/**
* Display alert message dialog
*
* @param context
* @param msg
*/
public static void showMessage(Context context, String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(msg);
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, null);
builder.create();
builder.show();
}
/**
* Display alert message dialog with error title
*
* @param context
* @param titile
* @param msg
*/
public static void showError(Context context, String titile, String msg) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
if (titile != null && !titile.equals(""))
alert.setTitle(titile);
alert.setMessage(msg);
alert.setPositiveButton(android.R.string.ok, null);
alert.create();
alert.show();
}
public static void showErrordemo(Context context, String titile, String msg) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
if (titile != null && !titile.equals(""))
alert.setTitle(titile);
alert.setMessage(msg);
alert.setPositiveButton(android.R.string.ok, null);
alert.create();
alert.show();
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (; ; ) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static String getEncodedUrl(String url) {
String imageUrl = url;
String filenames[] = imageUrl.split("/");
String filename = filenames[filenames.length - 1];
String newfilename = "";
try {
newfilename = URLEncoder.encode(filename, "Utf-8");
newfilename = newfilename.replace("+", "%20");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
imageUrl = imageUrl.replace(filename, newfilename);
return imageUrl;
}
public static int getCurrentHour() {
Calendar c = Calendar.getInstance();
int curHours = c.get(Calendar.HOUR_OF_DAY);
return curHours;
}
public static String replaceExtraChar(String str_todecode) {
String message = "";
message = str_todecode.replace("%A0", "");
return message;
}
public static String getToneSpinnerData(Context context, int position) {
if (position == 0) {
return "";
} else {
String arr[] = context.getResources().getStringArray(R.array.head_tone_of_the_motor);
return arr[position];
}
}
public static String getPowerSpinnerData(Context context, int position) {
if (position == 0) {
return "";
} else {
String arr[] = context.getResources().getStringArray(R.array.head_power_of_the_motor);
return arr[position];
}
}
public static String getEdittextData(EditText editText) {
return editText.getText().toString();
}
}
| 8,132 | 0.631825 | 0.626168 | 262 | 30.038168 | 26.460226 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622137 | false | false | 7 |
be25ec262e8465657619e3e6ec43f9047b3e353c | 20,572,893,369,639 | 5156fa686289d4d151c49a32bc40ea902f4e93c5 | /src/ep1/usp/access/db/RestaurantCommentDao.java | 6fae2a5190d339f3e0107f87f3c901135d32afa5 | [] | no_license | tassotirap/ep1_movel | https://github.com/tassotirap/ep1_movel | 4a31b1a94a69f1a400b77fdaecf056d27e4be88e | ccd0679e4f45626a19a2bfe5177b09dc5f013831 | refs/heads/master | 2021-01-01T19:42:12.311000 | 2012-05-08T00:12:49 | 2012-05-08T00:12:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ep1.usp.access.db;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import ep1.usp.lib.DateAndTime;
import ep1.usp.restaurant.MessageDto;
public class RestaurantCommentDao extends BaseDao<MessageDto>
{
public RestaurantCommentDao(Context ctx)
{
super(ctx);
TABLE_NAME = "RESTAURANT_COMMENTS";
COLUMNS = new String[] { "idRestaurant", "comment", "date", "status" };
}
@Override
public ArrayList<MessageDto> getAll()
{
ArrayList<MessageDto> msg = new ArrayList<MessageDto>();
Cursor c = getWritableDatabase().query(TABLE_NAME, COLUMNS, null, null, null, null, null);
while (c.moveToNext())
{
try
{
msg.add(new MessageDto(c.getInt(0), c.getString(1), DateAndTime.ParseToDate(c.getString(2)), c.getInt(3)));
}
catch (Exception e)
{
e.printStackTrace();
}
}
c.close();
close();
return msg;
}
@Override
public void set(MessageDto msg)
{
try
{
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMNS[0], msg.getRestaurantId());
contentValues.put(COLUMNS[1], msg.getMessage());
contentValues.put(COLUMNS[2], DateAndTime.ParseToString(msg.getDate()));
contentValues.put(COLUMNS[3], msg.getStaus());
getWritableDatabase().insertOrThrow(TABLE_NAME, null, contentValues);
}
catch (Exception e)
{
e.getMessage();
}
}
}
| UTF-8 | Java | 1,419 | java | RestaurantCommentDao.java | Java | [] | null | [] | package ep1.usp.access.db;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import ep1.usp.lib.DateAndTime;
import ep1.usp.restaurant.MessageDto;
public class RestaurantCommentDao extends BaseDao<MessageDto>
{
public RestaurantCommentDao(Context ctx)
{
super(ctx);
TABLE_NAME = "RESTAURANT_COMMENTS";
COLUMNS = new String[] { "idRestaurant", "comment", "date", "status" };
}
@Override
public ArrayList<MessageDto> getAll()
{
ArrayList<MessageDto> msg = new ArrayList<MessageDto>();
Cursor c = getWritableDatabase().query(TABLE_NAME, COLUMNS, null, null, null, null, null);
while (c.moveToNext())
{
try
{
msg.add(new MessageDto(c.getInt(0), c.getString(1), DateAndTime.ParseToDate(c.getString(2)), c.getInt(3)));
}
catch (Exception e)
{
e.printStackTrace();
}
}
c.close();
close();
return msg;
}
@Override
public void set(MessageDto msg)
{
try
{
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMNS[0], msg.getRestaurantId());
contentValues.put(COLUMNS[1], msg.getMessage());
contentValues.put(COLUMNS[2], DateAndTime.ParseToString(msg.getDate()));
contentValues.put(COLUMNS[3], msg.getStaus());
getWritableDatabase().insertOrThrow(TABLE_NAME, null, contentValues);
}
catch (Exception e)
{
e.getMessage();
}
}
}
| 1,419 | 0.700493 | 0.692741 | 64 | 21.171875 | 25.678028 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.09375 | false | false | 7 |
31b4ecce1cf5a29d0f2695b512bf13d8a4739ae5 | 28,467,043,246,017 | 6455ce956ab9beef0977dceced2e1a316329b039 | /app/src/main/java/es/esy/practikality/healr/CollabActivity.java | ebb53e58ae51fbce8109452998d838cb780f235a | [] | no_license | laxyapahuja/healr | https://github.com/laxyapahuja/healr | 33606b90ef1b08d39ca005f49c1662e7aec7a55b | fff7415e431c443b377664c82f08f944efe8134c | refs/heads/master | 2021-07-01T08:52:05.859000 | 2019-08-21T22:37:19 | 2019-08-21T22:37:19 | 203,531,592 | 0 | 1 | null | false | 2021-06-28T06:32:35 | 2019-08-21T07:34:28 | 2019-08-21T22:37:52 | 2021-06-28T06:32:35 | 15,437 | 0 | 1 | 1 | Java | false | false | package es.esy.practikality.healr;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class CollabActivity extends AppCompatActivity {
Button send;
EditText name, location, msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collab);
send = findViewById(R.id.send);
name = findViewById(R.id.name);
location = findViewById(R.id.location);
msg = findViewById(R.id.msg);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name_str = name.getText().toString();
String location_str = location.getText().toString();
String msg_str = msg.getText().toString();
Intent sendemail = new Intent(Intent.ACTION_SEND);
sendemail.putExtra(Intent.EXTRA_EMAIL, new String[]{"ribhavsharma2003@gmail.com"});
sendemail.putExtra(Intent.EXTRA_SUBJECT, "Collab Invite From " + name_str + ", "+location_str);
sendemail.putExtra(Intent.EXTRA_TEXT, msg_str);
sendemail.setType("message/rfc822");
startActivity(Intent.createChooser(sendemail, "Sent."));
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.action_pickup:
startActivity(new Intent(getApplicationContext(), MediActivity.class));
break;
case R.id.action_collab:
Toast.makeText(CollabActivity.this, "Already on Collab", Toast.LENGTH_SHORT).show();
break;
case R.id.action_profile:
startActivity(new Intent(getApplicationContext(), MenuActivity.class));
break;
case R.id.action_remind:
startActivity(new Intent(getApplicationContext(), RemindActivity.class));
break;
}
return true;
}
});
}
});
}
}
| UTF-8 | Java | 2,993 | java | CollabActivity.java | Java | [
{
"context": "demail.putExtra(Intent.EXTRA_EMAIL, new String[]{\"ribhavsharma2003@gmail.com\"});\n sendemail.putExtra(Intent.EXT",
"end": 1341,
"score": 0.9999048113822937,
"start": 1315,
"tag": "EMAIL",
"value": "ribhavsharma2003@gmail.com"
}
] | null | [] | package es.esy.practikality.healr;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class CollabActivity extends AppCompatActivity {
Button send;
EditText name, location, msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collab);
send = findViewById(R.id.send);
name = findViewById(R.id.name);
location = findViewById(R.id.location);
msg = findViewById(R.id.msg);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name_str = name.getText().toString();
String location_str = location.getText().toString();
String msg_str = msg.getText().toString();
Intent sendemail = new Intent(Intent.ACTION_SEND);
sendemail.putExtra(Intent.EXTRA_EMAIL, new String[]{"<EMAIL>"});
sendemail.putExtra(Intent.EXTRA_SUBJECT, "Collab Invite From " + name_str + ", "+location_str);
sendemail.putExtra(Intent.EXTRA_TEXT, msg_str);
sendemail.setType("message/rfc822");
startActivity(Intent.createChooser(sendemail, "Sent."));
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.action_pickup:
startActivity(new Intent(getApplicationContext(), MediActivity.class));
break;
case R.id.action_collab:
Toast.makeText(CollabActivity.this, "Already on Collab", Toast.LENGTH_SHORT).show();
break;
case R.id.action_profile:
startActivity(new Intent(getApplicationContext(), MenuActivity.class));
break;
case R.id.action_remind:
startActivity(new Intent(getApplicationContext(), RemindActivity.class));
break;
}
return true;
}
});
}
});
}
}
| 2,974 | 0.581022 | 0.578684 | 68 | 42.970589 | 31.57902 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.779412 | false | false | 7 |
c11bb70e856e65cde5ce7baf2eec1252197daab4 | 5,832,565,639,172 | 1b8899e74fba4c8cf2f1554a75e8d44249e37d7a | /Chapter Thirteen (Type Information)/ExerciseTwelve.java | 973367ec8f4ffd397e2069154aa3a07a302d32f1 | [] | no_license | fengxueem/Thinking-in-Java-Exercises | https://github.com/fengxueem/Thinking-in-Java-Exercises | 25a5c16ca34f8ea5aa0304d785d1c37bb9bec310 | 1b3d6d10883773a42937afd05bdeeabbf3571c4e | refs/heads/master | 2020-09-26T18:16:29.007000 | 2017-05-07T13:41:32 | 2017-05-07T13:41:32 | 66,377,081 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import net.mindview.util.*;
import generics.coffee.*;
public class ExerciseTwelve {
public static void main(String[] args){
// counter dealing with every type derived from Coffee
TypeCounter typeCounter = new TypeCounter(Coffee.class);
// generate 10 different types and count
for (Coffee coffee : new CoffeeGenerator(10)) {
System.out.println("counting: " + coffee.getClass().getSimpleName());
typeCounter.count(coffee);
}
// show the results
System.out.println("Counted Types:");
System.out.println(typeCounter);
}
} | UTF-8 | Java | 576 | java | ExerciseTwelve.java | Java | [] | null | [] | import net.mindview.util.*;
import generics.coffee.*;
public class ExerciseTwelve {
public static void main(String[] args){
// counter dealing with every type derived from Coffee
TypeCounter typeCounter = new TypeCounter(Coffee.class);
// generate 10 different types and count
for (Coffee coffee : new CoffeeGenerator(10)) {
System.out.println("counting: " + coffee.getClass().getSimpleName());
typeCounter.count(coffee);
}
// show the results
System.out.println("Counted Types:");
System.out.println(typeCounter);
}
} | 576 | 0.6875 | 0.680556 | 20 | 27.85 | 22.714037 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.