blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
7b5c65c0cd009fd57868b8dc40f82777ece4286f
|
Java
|
edward-shen/wisdom
|
/app/src/main/java/tk/easthigh/witsmobile/tools/MailAdapter.java
|
UTF-8
| 707
| 2.234375
| 2
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
package tk.easthigh.witsmobile.tools;
import tk.easthigh.witsmobile.MainActivity;
/**
* Created by Edward on 7/15/2015.
*/
public class MailAdapter extends RecyclerAdapter {
@Override
public void setActivitiesList() {
super.setActivitiesList();
SecurePreferences sPrefs = MainActivity.preferences;
for (int i = 0; i < Integer.valueOf(sPrefs.getString("mail.size")); i++){
ActivitiesList.add(sPrefs.getString("mail" + Integer.toString(i) + ".title"));
ActivitiesSubList.add(sPrefs.getString("mail" + Integer.toString(i) + ".sender"));
ActivitiesSubList2.add(sPrefs.getString("mail" + Integer.toString(i) + ".date"));
}
}
}
| true
|
4faa77dba79b5f6d980c6e1699215290c2b06ef0
|
Java
|
aspose-slides/Aspose.Slides-for-Java
|
/Examples/src/main/java/com/aspose/slides/examples/slides/hyperlinks/MutableHyperlink.java
|
UTF-8
| 1,388
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
package com.aspose.slides.examples.slides.hyperlinks;
import com.aspose.slides.*;
import com.aspose.slides.examples.RunExamples;
public class MutableHyperlink
{
public static void main(String[] args)
{
//ExStart:MutableHyperlink
// The path to the documents directory.
String dataDir = RunExamples.getDataDir_Slides_Presentations_Hyperlink();
Presentation presentation = new Presentation();
try
{
IAutoShape shape1 = presentation.getSlides().get_Item(0).getShapes().addAutoShape(ShapeType.Rectangle, 100, 100, 600, 50, false);
shape1.addTextFrame("Aspose: File Format APIs");
shape1.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0).getPortionFormat().setHyperlinkClick(new Hyperlink("https://www.aspose.com/"));
shape1.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0).getPortionFormat().getHyperlinkClick().setTooltip("More than 70% Fortune 100 companies trust Aspose APIs");
shape1.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0).getPortionFormat().setFontHeight(32);
presentation.save(dataDir + "presentation-out.pptx", SaveFormat.Pptx);
}
finally
{
if (presentation != null) presentation.dispose();
}
//ExEnd:MutableHyperlink
}
}
| true
|
63a23f8d67a2aa8dd4817eafa9efa2a3aa65c5cf
|
Java
|
FS-Rocha/PG3-1
|
/Testes/Teste1/tests/verao_2017_2018/Group.java
|
ISO-8859-1
| 752
| 3.03125
| 3
|
[] |
no_license
|
package testes.test1;
import java.util.Scanner;
/**
* Created by msousa on 4/23/2018.
*/
public class Group extends QueryCollection implements Query {
public Group( String title ) {
super( title );
}
public String getHeader() {
return "[" + getPoints()+"] " + title;
}
public static void main(String[] args) throws QueryException{
Group g1 = new Group("Object Oriented");
g1.append(new IntQuest ("Quantas visibilidades podem ter os campos", 1, 4))
.append(new IntQuest ("Qual o nmero de parmetros do mtodo toString", 2, 0));
System.out.println( g1.getHeader() );
Scanner in = new Scanner(System.in);
System.out.println("-> " + g1.ask(in,"")); }
}
| true
|
7074a6abaf88fe7b4ad61ad9ad5823914d1b7f32
|
Java
|
yanglr/jopenreg
|
/JOpenReg/src/maple/MapleEngine.java
|
UTF-8
| 3,044
| 2.734375
| 3
|
[] |
no_license
|
package maple;
import table.CustomTable;
import com.maplesoft.externalcall.MapleException;
import com.maplesoft.openmaple.Engine;
import com.maplesoft.openmaple.EngineCallBacksDefault;
public class MapleEngine {
private Engine engine;
private boolean isCalculated;
private String lastMethod;
/**
* opens a connection to Maple
*/
public MapleEngine() {
isCalculated = false;
String a[];
a = new String[1];
a[0] = "java";
try {
engine = new Engine( a, new EngineCallBacksDefault(), null, null );
} catch (MapleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void executeExp(String exp) {
try {
engine.evaluate(exp);
} catch (MapleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String doReggression(CustomTable table, Methods methods) {
lastMethod = methods.toString();
String x = table.getVectorStrings()[0];
String y = table.getVectorStrings()[1];
String regressionCurve = "<html>\n<body>\n";
try {
engine.evaluate("with(CurveFitting):");
engine.evaluate("xVector:=Vector(["+ x + "]):");
engine.evaluate("yVector:=Vector(["+ y + "]):");
switch(methods) {
case LEASTSQUARES:
engine.evaluate("R:=LeastSquares(xVector,yVector,x):");
regressionCurve += engine.evaluate("eval(R):").toString();
break;
case SPLINE:
engine.evaluate("R:=Spline(xVector,yVector,x,degree=1):");
String[] parts;
parts = engine.evaluate("eval(R):").toString().split("\\(");
parts = parts[1].split(",");
for (int i = 0; i < parts.length; i++) {
regressionCurve += parts[i];
if(i%2 != 0) {
regressionCurve += "<br>\n";
} else {
regressionCurve += " : ";
}
}
regressionCurve = regressionCurve.replace(" < ", "<");
regressionCurve = regressionCurve.replace(") :", " sonst");
}
} catch (MapleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isCalculated = true;
regressionCurve += "</body></html>";
return regressionCurve;
}
public String doEval(CustomTable table, Methods methods, double value) {
String calculatedValue = null;
if(!isCalculated || (lastMethod != methods.toString())) {
doReggression(table, methods);
}
try {
calculatedValue = engine.evaluate("eval(R,x=" + value + "):").toString();
} catch (MapleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return calculatedValue;
}
public CustomTable getCalculatedTable(CustomTable table, Methods methods) {
Double[][] rowData;
Object[] columnNames = {"X", "Y"};
for (int i = 0; i < table.getTable().getTableValues()[0].length; i++) {
rowData[0][i] = table.getTable().getTableValues()[0][i];
rowData[1][i] = Double.parseDouble(doEval(table, methods, table.getTable().getTableValues()[0][i]));
}
return new CustomTable(rowData, columnNames);
}
}
| true
|
efc24ba90f85edec2b2fbf95e2db0027763da530
|
Java
|
sbarakad/QAProject
|
/src/main/java/com/library/businessModels/Cover.java
|
UTF-8
| 811
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
package com.library.businessModels;
import java.sql.Blob;
import org.springframework.web.multipart.MultipartFile;
public class Cover {
private int itemID;
private Blob coverBlob;
private String fileExtension;
private MultipartFile coverImage;
public MultipartFile getCoverImage() {
return coverImage;
}
public void setCoverImage(MultipartFile coverImage) {
this.coverImage = coverImage;
}
public int getItemID() {
return itemID;
}
public void setItemID(int itemID) {
this.itemID = itemID;
}
public Blob getCoverBlob() {
return coverBlob;
}
public void setCoverBlob(Blob coverBlob) {
this.coverBlob = coverBlob;
}
public String getFileExtension() {
return fileExtension;
}
public void setFileExtension(String fileExtension) {
this.fileExtension = fileExtension;
}
}
| true
|
797a768ad2e0ba8ce3d1832ac228f4c6ff0f5296
|
Java
|
ySodias/atvs-generation-java
|
/modulo_2/semana_3/24.03/minhaLojaDeGames/src/main/java/com/minhaLojaDeGames/minhaLojaDeGames/Services/ProductService.java
|
UTF-8
| 1,436
| 2.234375
| 2
|
[] |
no_license
|
package com.minhaLojaDeGames.minhaLojaDeGames.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.minhaLojaDeGames.minhaLojaDeGames.Models.ProductModels;
import com.minhaLojaDeGames.minhaLojaDeGames.Repositories.ProductRepository;
@Service
public class ProductService {
@Autowired
private ProductRepository repositoryProduct;
public ResponseEntity<List<ProductModels>>findAllProduct(){
return ResponseEntity.ok(repositoryProduct.findAll());
}
public ResponseEntity<ProductModels>findAllByProduct(Long id){
return repositoryProduct.findById(id)
.map(resp -> ResponseEntity.ok(resp))
.orElse(ResponseEntity.notFound().build());
}
public ResponseEntity<List<ProductModels>>findByDescricaoProduct(String name){
return ResponseEntity.ok(repositoryProduct.findByNameContainingIgnoreCase(name));
}
public ResponseEntity<ProductModels>postNewProduct(ProductModels product){
return ResponseEntity.status(HttpStatus.CREATED).body(repositoryProduct.save(product));
}
public ResponseEntity<ProductModels>putNewProduct(ProductModels product){
return ResponseEntity.status(HttpStatus.CREATED).body(repositoryProduct.save(product));
}
public void deleteProduct(Long id) {
repositoryProduct.deleteById(id);
}
}
| true
|
0c3d84c323aadf497ae7ed5927681caebf826b0b
|
Java
|
murtaza-webonise/Java-Framework
|
/WizardFramework/src/main/java/com/webo/beans/Employee.java
|
UTF-8
| 835
| 2.875
| 3
|
[] |
no_license
|
package com.webo.beans;
import com.webo.annotations.Autoinit;
public class Employee {
private String name;
private long mbNo;
@Autoinit(state = "MH", city = "Mumbai", pinCode = "452011")
private Address add;
public Employee() {
name="Murtaza";
mbNo=12345678;
System.out.println(name+" "+mbNo);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getMbNo() {
return mbNo;
}
public void setMbNo(long mbNo) {
this.mbNo = mbNo;
}
public Address getAddress() {
return add;
}
public void setAddress(Address add) {
this.add = add;
System.out.println("Address is initialised");
System.out.println("City: " + add.getCity());
System.out.println("State: " + add.getState());
System.out.println("Pincode: " + add.getPinCode());
}
}
| true
|
9a483236f64809ab4d658ae462094e4448b074c7
|
Java
|
sheaye/Algorithm-Exercise
|
/src/leetcode/tree/Exercise39.java
|
UTF-8
| 1,475
| 3.90625
| 4
|
[] |
no_license
|
package leetcode.tree;
import common.TreeNode;
/**
* Given a binary tree, determine if it is height-balanced.
* For this problem, a height-balanced binary tree is defined as a binary tree in which
* the depth of the two subtrees of every node never differ by more than 1.
*/
public class Exercise39 {
public static void main(String[] args) {
Exercise39 exe = new Exercise39();
System.out.println(exe.isBalanced(TreeNode.createTreeNode("1,2")));
}
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return isBalanced(root.left) && isBalanced(root.right) && (Math.abs(depth(root.left) - depth(root.right)) <= 1);
}
private int depth(TreeNode tree) {
if (tree == null) {
return 0;
}
return Math.max(depth(tree.left), depth(tree.right)) + 1;
}
public boolean isBalanced2(TreeNode root) {
if (root == null) {
return true;
}
return getHeight(root) != -1;
}
private int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int left = getHeight(root.left);
if (left < 0) {
return -1;
}
int right = getHeight(root.right);
if (right < 0) {
return -1;
}
if (Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
}
| true
|
4ea74d8c8a445da8fbd2f33d455741459f57f878
|
Java
|
PavanDhumwad/Core-Java
|
/src/Java8/PredefinedFI/Consumer/TwoArgConsumer.java
|
UTF-8
| 607
| 3.6875
| 4
|
[] |
no_license
|
package Java8.PredefinedFI.Consumer;
import java.util.function.BiConsumer;
class Employee
{
double salary;
String name;
Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
}
public class TwoArgConsumer
{
public static void main(String[] args) {
BiConsumer<Employee, Double> c = (emp, salary)->emp.salary = emp.salary+ 0.05 * emp.salary;
Employee e1 = new Employee("Raj", 1000);
System.out.println(e1.name+" "+e1.salary);
c.accept(e1,e1.salary);
System.out.println(e1.name+" "+e1.salary);
}
}
| true
|
96b5010cc09527a89513e3fc325f9bde018da987
|
Java
|
sanidhyaRsharma/CPUStats
|
/app/src/main/java/com/example/cpustats/stats.java
|
UTF-8
| 4,951
| 2.484375
| 2
|
[] |
no_license
|
package com.example.cpustats;
import android.app.ActivityManager;
import android.content.Context;
import android.net.TrafficStats;
import android.os.SystemClock;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Locale;
import static android.content.Context.ACTIVITY_SERVICE;
public class stats
{
private Context context;
long prevRxByteCount = 0;
long prevTxByteCount = 0;
long time;
private String statistics = "%s\t%s\n%s\t%s";
private String dSpeed = "\u2193 %.02f %s";
private String uSpeed = "\u2191 %.02f %s";
private String cpu = "CPU %.02f";
private String ram = "RAM %d M";
stats(Context context)
{
this.context = context;
time = SystemClock.elapsedRealtime();
}
String getStats()
{
String R,C,D,U;
R = RAMusage();
C = CPUusage();
U = UploadDataUsage();
D = DownloadDataUsage();
time = SystemClock.elapsedRealtime();
return String.format(Locale.getDefault(),statistics,C,R,D,U);
}
private String RAMusage()
{
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
long totalMem = mi.totalMem / 1048576L;
float percent = availableMegs/totalMem*100;
// Log.i("RAM Usage", Long.toString(availableMegs));
// Log.i("Total RAM", Long.toString(totalMem));
// Log.i("Percent", Float.toString((float) availableMegs / totalMem * 100) + " %");
return String.format(Locale.getDefault(),ram, availableMegs);
}
private String CPUusage()
{
try
{
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" +"); // Split on one or more spaces
long idle1 = Long.parseLong(toks[4]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try
{
Thread.sleep(360);
}
catch (Exception e) {}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" +");
long idle2 = Long.parseLong(toks[4]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
float percent = (float) (cpu2 - cpu1)*100 / ((cpu2 + idle2) - (cpu1 + idle1));
return String.format(Locale.getDefault(), cpu, percent);
}
catch (IOException ex)
{
ex.printStackTrace();
}
return "";
}
private String DownloadDataUsage()
{
int level = 1;
long curRxByteCount = TrafficStats.getTotalRxBytes();
long downloadedData = curRxByteCount - prevRxByteCount;
prevRxByteCount = curRxByteCount;
float speed = (float)downloadedData*1000/(SystemClock.elapsedRealtime()-time);
while(speed>1024)
{
speed/=1024;
level++;
}
String l ="";
switch(level)
{
case 1:
l = "B/s";
break;
case 2:
l = "KB/s";
break;
case 3:
l = "MB/s";
break;
case 4:
l = "GB/s";
break;
case 5:
l = "TB/s";
break;
default:
l = "b/s";
}
return String.format(Locale.getDefault(), dSpeed, speed, l);
}
private String UploadDataUsage()
{
int level = 1;
long curTxByteCount = TrafficStats.getTotalTxBytes();
long uploadedData = curTxByteCount - prevTxByteCount;
prevTxByteCount = curTxByteCount;
float speed = (float)uploadedData*1000/(SystemClock.elapsedRealtime()-time);
while(speed>1024)
{
speed/=1024;
level++;
}
String l ="";
switch(level)
{
case 1:
l = "B/s";
break;
case 2:
l = "KB/s";
break;
case 3:
l = "MB/s";
break;
case 4:
l = "GB/s";
break;
case 5:
l = "TB/s";
break;
default:
l = "b/s";
}
return String.format(Locale.getDefault(),uSpeed, speed, l);
}
}
| true
|
8f2ea563b05ef6c1b6af0f0b8934736992fe36ed
|
Java
|
qwer9412/design-pattern-study
|
/visitor/src/SizeCalculateVisitor.java
|
UTF-8
| 404
| 2.921875
| 3
|
[] |
no_license
|
import java.util.List;
public class SizeCalculateVisitor implements Visitor {
private int size = 0;
public int getSize() {
return this.size;
}
@Override
public void visit(File file) {
size += file.getSize();
}
@Override
public void visit(Directory directory) {
List<Element> elements = directory.getList();
for (Element element : elements) {
element.accept(this);
}
}
}
| true
|
783218035fe0861267587f42381cacf235c776d7
|
Java
|
mkt-Do/codingBat_Java
|
/String-1/without2.java
|
UTF-8
| 245
| 2.71875
| 3
|
[] |
no_license
|
public String without2(String str) {
if (str.length() == 2) {
return "";
}
if (str.length() < 2) {
return str;
}
String tail = str.substring(str.length() - 2);
return str.startsWith(tail)
? str.substring(2)
: str;
}
| true
|
00e82df2cf5bcd95e72ac2b0bf59013bcf1eaeb2
|
Java
|
brennangw/fss
|
/FIX/src/web/InitializeParties.java
|
UTF-8
| 598
| 2
| 2
|
[] |
no_license
|
package web;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import main.StartParties;
import quickfix.SessionNotFound;
public class InitializeParties implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//Notification that the servlet context is about to be shut down.
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
StartParties.main();
} catch (SessionNotFound e) {
System.out.println("No session to send test message");
e.printStackTrace();
}
}
}
| true
|
5fdd50b05d0bd13417ac981712439e9ca78acd9c
|
Java
|
wyliebenjamin2019/Assignment-04-Spaced
|
/main.java
|
UTF-8
| 865
| 3.3125
| 3
|
[] |
no_license
|
public class Spaced{
public static void main(String[] args){
int x1 = 5;
int y1 = 2;
int z1 = -5;
int x2 = 4;
int y2 = 9;
int z2 = 2;
int x3 = -3;
int y3 = 2;
int z3 = 6;
double d1 = Math.sqrt(Math.pow((double) ((x2-x1)), 2)+Math.pow((double) ((y2-y1)), 2)+Math.pow((double) ((z2-z1)), 2));
double d2 = Math.sqrt(Math.pow((double) ((x3-x1)), 2)+Math.pow((double) ((y3-y1)), 2)+Math.pow((double) ((z3-z1)), 2));
double d3 = Math.sqrt(Math.pow((double) ((x3-x2)), 2)+Math.pow((double) ((y3-y2)), 2)+Math.pow((double) ((z3-z2)), 2));
double da = Math.max(d1,d2);
double db = Math.max(da,d3);
double dz = Math.min(d1,d2);
double dx = Math.min(dz,d3);
System.out.print("Longest distance: "+db+"\nShortest distance: "+dx);
}
}
| true
|
21830fd299b2fffd41fb9895316d6433712a198d
|
Java
|
moutainhigh/goddess-java
|
/modules/task/task-api/src/main/java/com/bjike/goddess/task/to/AcceptTO.java
|
UTF-8
| 3,243
| 2.125
| 2
|
[] |
no_license
|
package com.bjike.goddess.task.to;
import com.bjike.goddess.common.api.bo.BaseBO;
import com.bjike.goddess.common.api.entity.ADD;
import com.bjike.goddess.common.api.entity.EDIT;
import com.bjike.goddess.common.api.to.BaseTO;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* 问题受理对象传输
*
* @Author: [liguiqin]
* @Date: [2017-09-20 11:46]
* @Description: [ ]
* @Version: [1.0.0]
* @Copy: [com.bjike]
*/
public class AcceptTO extends BaseTO{
/**
* 问题id
*/
@NotBlank(message = "问题id不能为空", groups = {ADD.class, EDIT.class})
private String problemId;
/**
* 问题受理所属部门
*/
@NotBlank(message = "问题受理所属部门不能为空", groups = {ADD.class, EDIT.class})
private String acceptDepartment;
/**
* 问题跟进处理计划完成时间
*/
@NotBlank(message = "问题跟进处理计划完成时间不能为空", groups = {ADD.class, EDIT.class})
private String planFinishTime;
/**
* 问题跟进处理实际完成时间
*/
@NotBlank(message = "问题跟进处理实际完成时间不能为空", groups = {ADD.class, EDIT.class})
private String finishTime;
/**
* 问题处理结果
*/
@NotBlank(message = "问题处理结果不能为空", groups = {ADD.class, EDIT.class})
private String result;
/**
* 是否闭环
*/
@NotNull(message = "是否闭环不能为空", groups = {ADD.class, EDIT.class})
private Boolean closedLoop;
/**
* 是否需要协调
*/
@NotNull(message = "是否需要协调不能为空", groups = {ADD.class, EDIT.class})
private Boolean needGive;
/**
* 协调结果
*/
@NotBlank(message = "协调结果不能为空", groups = {ADD.class, EDIT.class})
private String giveResult;
public String getProblemId() {
return problemId;
}
public void setProblemId(String problemId) {
this.problemId = problemId;
}
public String getAcceptDepartment() {
return acceptDepartment;
}
public void setAcceptDepartment(String acceptDepartment) {
this.acceptDepartment = acceptDepartment;
}
public String getPlanFinishTime() {
return planFinishTime;
}
public void setPlanFinishTime(String planFinishTime) {
this.planFinishTime = planFinishTime;
}
public String getFinishTime() {
return finishTime;
}
public void setFinishTime(String finishTime) {
this.finishTime = finishTime;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Boolean getClosedLoop() {
return closedLoop;
}
public void setClosedLoop(Boolean closedLoop) {
this.closedLoop = closedLoop;
}
public Boolean getNeedGive() {
return needGive;
}
public void setNeedGive(Boolean needGive) {
this.needGive = needGive;
}
public String getGiveResult() {
return giveResult;
}
public void setGiveResult(String giveResult) {
this.giveResult = giveResult;
}
}
| true
|
6268f7758e52eb9d043c2ef95fb002263aec2c8c
|
Java
|
pankajwankhede/Concurrency-Practice
|
/src/cyclicBarrierTest/CyclicBarrierTest1.java
|
UTF-8
| 1,595
| 3.40625
| 3
|
[] |
no_license
|
package cyclicBarrierTest;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* CyclicBarrier简单尝试
* @author Caonuan
*
*/
public class CyclicBarrierTest1 {
static class Worker implements Callable<String>{
CyclicBarrier barrier ;
public Worker(CyclicBarrier barrier) {
super();
this.barrier = barrier;
}
@Override
public String call() throws Exception {
try {
Thread.sleep((long) (Math.random()*10000));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
System.out.println("当前等待线程数量:"+barrier.getNumberWaiting());
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
return "success";
}
}
public static void main(String[] args) {
ExecutorService executors = Executors.newFixedThreadPool(4);
CyclicBarrier barrier = new CyclicBarrier(4);
Future<String> f =executors.submit(new Worker(barrier));
executors.submit(new Worker(barrier));
executors.submit(new Worker(barrier));
executors.submit(new Worker(barrier));
try {
System.out.println(f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("全部运行完成");
executors.shutdown();
}
}
| true
|
018348a6d507363a30226e854482b555fefe5fb5
|
Java
|
nachocastineira/NumerosComplejos
|
/src/ar/edu/unlam/progbasica2/Complejo.java
|
UTF-8
| 1,177
| 3.5
| 4
|
[] |
no_license
|
package ar.edu.unlam.progbasica2;
public class Complejo { // Se crea la clase
private Double real; // Creo los atributos privados
private Double imaginario;
public Complejo (Double real, Double imaginario) //CONSTRUCTOR DE LA CLASE, PARA SUMAR REAL CON IMAGINARIO
{
this.imaginario = imaginario; //INICIALIZO LAS VARIABLES Y LAS IGUALO (variable global con variable local)
this.real = real;
}
public Complejo (Double numeroReal) //SEGUNDO CONTRUCTOR, PARA SUMAR SOLO LOS REALES
{
this.real = numeroReal;
this.imaginario = 0.0; // INICIALIZO EN 0 PARA QUE NO SEA NULL Y SE PUEDA SUMAR CON OTRO
}
public Complejo Suma(Complejo z)
{
this.real = this.real + z.getReal();
this.imaginario = this.imaginario + z.getImaginario();
return this;
}
public Double getReal() { //DEVUELVO o TRAIGO PARTE REAL
return real;
}
public void setReal(Double real) { // LE ASIGNO UN VALOR A LA PARTE REAL
this.real = real;
}
public Double getImaginario() { //DEVUELVO o TRAIGO PARTE IMAGINARIA
return imaginario;
}
public void setImaginario(Double imaginario) { // LE ASIGNO UN VALOR A LA PARTE IMAGINARIA
this.imaginario = imaginario;
}
}
| true
|
bbb73d1a3d2ddca3e8aa8fdeaabea5e34fe7786b
|
Java
|
358Tcyf/giisdemo
|
/app/src/main/java/simple/project/giisdemo/helper/utils/ActivityUtil.java
|
UTF-8
| 643
| 2.015625
| 2
|
[] |
no_license
|
package simple.project.giisdemo.helper.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import simple.project.giisdemo.activity.MainActivity;
/**
* @author Created by ys
* @date at 2019/1/23 17:03
* @describe
*/
public class ActivityUtil {
public static void toMainActivity(Activity mActivity, int flag) {
Intent intent = new Intent(mActivity, MainActivity.class);
intent.putExtra("flag", flag);
mActivity.startActivity(intent);
mActivity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
mActivity.finish();
}
}
| true
|
7e6422592be03f68d087f5407c1f5279c8232a30
|
Java
|
andrehora/jss-code-examples
|
/code-examples/org.springframework.web.servlet.ModelAndView.setViewName9.java
|
UTF-8
| 690
| 2.234375
| 2
|
[] |
no_license
|
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws IOException {
if (modelAndView != null) {
if (modelAndView.getModel().containsKey("currentTabWrapped")) {
final Object tabObject = modelAndView.getModelMap().get("currentTabWrapped");
if (tabObject instanceof ProposalTabWrapper) {
ProposalTabWrapper currentTabWrapped = (ProposalTabWrapper) tabObject;
if (!currentTabWrapped.getCanAccess()) {
modelAndView.setViewName(ErrorText.ACCESS_DENIED.flashAndReturnView(request));
}
}
}
}
}
| true
|
88d2f27763d5be5dd13dd91950110add9a106357
|
Java
|
paulofausto31/Vendas
|
/vendas/src/main/java/vendas/telas/UtilitarioTabContainer.java
|
UTF-8
| 1,033
| 2.015625
| 2
|
[] |
no_license
|
package vendas.telas;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import venda.util.Global;
public class UtilitarioTabContainer extends TabActivity {
@Override
public void onCreate(Bundle e){
super.onCreate(e);
setContentView(R.layout.tabcontainer);
this.setTitle(Global.tituloAplicacao);
TabHost host = getTabHost();
TabHost.TabSpec sec;
//... Pedidos Enviados
sec = host.
newTabSpec("Enviados").
setIndicator("Enviados").
setContent(new Intent(this,UtilitarioPedido.class))
;
host.addTab(sec);
//... Pedidos Pendentees de Envio
sec = host.
newTabSpec("Pendentes").
setIndicator("Pendentes").
setContent(new Intent(this,UtilitarioPedidoPendente.class))
;
host.addTab(sec);
//======
host.setCurrentTabByTag("Enviados");
}
}
| true
|
984d5e869759c9c7c2b45a4490191e04bf04f706
|
Java
|
Alba-Sula/SecondProblem
|
/src/SchedulesModel.java
|
UTF-8
| 1,606
| 2.640625
| 3
|
[] |
no_license
|
import java.util.Date;
public class SchedulesModel{
public String SchName;
public String SchDescription;
public Date SchStart;
public int IsRepeat;
public long RepetitionInMinutes;
public int Duration;
public SchedulesModel(String SchName, String SchDescription, Date SchStart,int IsRepeat,long RepetitionInMinutes, int Duration ){
this.SchName = SchName;
this.SchDescription = SchDescription;
this.SchStart = SchStart;
this.IsRepeat = IsRepeat;
this.RepetitionInMinutes = RepetitionInMinutes;
this.Duration = Duration;
}
public SchedulesModel() {
}
public int getDuration() {
return Duration;
}
public void setDuration(int duration) {
Duration = duration;
}
public String getSchName() {
return SchName;
}
public void setSchName(String schName) {
SchName = schName;
}
public String getSchDescription() {
return SchDescription;
}
public void setSchDescription(String schDescription) {
SchDescription = schDescription;
}
public Date getSchStart() {
return SchStart;
}
public void setSchStart(Date schStart) {
SchStart = schStart;
}
public int isRepeat() {
return IsRepeat;
}
public void setRepeat(int repeat) {
IsRepeat = repeat;
}
public long getRepetitionInMinutes() {
return RepetitionInMinutes;
}
public void setRepetitionInMinutes(long repetitionInMinutes) {
RepetitionInMinutes = repetitionInMinutes;
}
}
| true
|
c3d584f8301fb777e683423e257064bc94cd59f0
|
Java
|
NickBondarenko/JNPM
|
/jnpm/src/main/java/org/orienteer/jnpm/dm/VersionInfo.java
|
UTF-8
| 6,557
| 1.84375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.orienteer.jnpm.dm;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.apache.commons.compress.utils.IOUtils;
import org.orienteer.jnpm.ILogger;
import org.orienteer.jnpm.JNPMService;
import org.orienteer.jnpm.traversal.ITraversalRule;
import org.orienteer.jnpm.traversal.TraverseDirection;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.vdurmont.semver4j.Requirement;
import com.vdurmont.semver4j.Semver;
import com.vdurmont.semver4j.Semver.SemverType;
import com.vdurmont.semver4j.SemverException;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
/**
* Data class to store information about particular package version
*/
@Data
@JsonNaming
@ToString(onlyExplicitlyIncluded = true, callSuper = true)
public class VersionInfo extends AbstractArtifactInfo implements Comparable<VersionInfo>{
@JsonIgnore
private Semver version;
@ToString.Include private String versionAsString;
private String main;
private Map<String, String> scripts;
private Map<String, String> gitHooks;
private Map<String, String> dependencies;
private Map<String, String> optionalDependencies;
private Map<String, String> devDependencies;
private Map<String, String> peerDependencies;
private List<String> bundleDependencies;
private String gitHead;
private String nodeVersion;
private String npmVersion;
private DistributionInfo dist;
private HumanInfo npmUser;
private String unpkg;
private String jsdelivr;
private String module;
private String types;
private boolean sideEffects = false;
/*
* public Single<TraversalContext> traverse(TraverseDirection direction, boolean
* doForThis, ITraversalRule rule, ITraversalVisitor visitor) { TraversalContext
* ctx = new TraversalContext(null, direction, visitor); return traverse(ctx,
* doForThis, rule) .toSingleDefault(ctx); }
*
* public Single<TraversalContext> traverse(TraverseDirection direction, boolean
* doForThis, ITraversalRule rule, Function<VersionInfo, Completable>
* visitCompletableFunction) { TraversalContext ctx = new TraversalContext(null,
* direction, visitCompletableFunction); return traverse(ctx, doForThis, rule)
* .toSingleDefault(ctx); }
*
* private Completable traverse(TraversalContext ctx, boolean doForThis,
* ITraversalRule rule) { return Completable.defer(() -> {
* log.info("Package: "+getName()+"@"+getVersionAsString()); List<Completable>
* setToDo = new ArrayList<>(); if(doForThis)
* setToDo.add(ctx.visitCompletable(this));
*
* Map<String, String> toDownload = getNextDependencies(rule);
* log.info("To Download:"+toDownload);
*
* if(!toDownload.isEmpty()) { //Need to download first and then go deeper
* Flowable<VersionInfo> cachedDependencies =
* Observable.fromIterable(toDownload.entrySet()) .flatMapMaybe(e->
* JNPMService.instance().getRxService() .bestMatch(e.getKey(), e.getValue()))
* .doOnError(e ->
* log.error("Error during handing "+getName()+"@"+getVersionAsString()
* +" ToDownload: "+toDownload, e)) .filter(v -> !ctx.alreadyTraversed(v))
* .doOnNext(v -> ctx.markTraversed(v)) .cache()
* .toFlowable(BackpressureStrategy.BUFFER); switch (ctx.getDirection()) { case
* WIDER: // Download tarballs first
* setToDo.add(cachedDependencies.flatMapCompletable(ctx.
* getVisitCompletableFunction())); // Go to dependencies
* setToDo.add(cachedDependencies.flatMapCompletable(v -> v.traverse(ctx, false,
* ITraversalRule.DEPENDENCIES))); break; case DEEPER: // Go to dependencies
* right away setToDo.add(cachedDependencies.flatMapCompletable(v ->
* v.traverse(ctx, true, ITraversalRule.DEPENDENCIES))); break; } } return
* Completable.concat(setToDo); }); }
*/
public Completable download(ITraversalRule... rules) {
return JNPMService.instance().getRxService()
.traverse(TraverseDirection.WIDER, ITraversalRule.combine(rules), this)
.flatMapCompletable(t -> t.getVersion().downloadTarball());
}
public Completable downloadTarball() {
return Completable.defer(() ->{
File file = getLocalTarball();
if(file.exists()) return Completable.complete();
else {
return JNPMService.instance().getRxService()
.downloadFile(getDist().getTarball())
.map((r)->{
InputStream is = r.body().byteStream();
ILogger.getLogger().log("Trying create file on path: "+file.getAbsolutePath());
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
IOUtils.copy(is, fos);
is.close();
fos.close();
return file;
}).ignoreElement();
}
}).subscribeOn(Schedulers.io());
}
public Map<String, String> getNextDependencies(ITraversalRule rule) {
return rule.getNextDependencies(this);
}
public File getLocalTarball() {
return JNPMService.instance().getSettings().getDownloadDirectory().resolve(getDist().getTarballName()).toFile();
}
public String getVersionAsString() {
return version!=null?version.toString():versionAsString;
}
@JsonProperty("version")
public void setVersionAsString(String version) {
try {
this.version = new Semver(version, SemverType.NPM);
this.versionAsString = null;
} catch (SemverException e) {
this.version = null;
this.versionAsString = version;
}
}
public boolean isVersionValid() {
return version!=null && versionAsString ==null;
}
public boolean satisfies(String expression) {
return version!=null && version.satisfies(expression);
}
public boolean satisfies(Requirement requirement) {
return version!=null && version.satisfies(requirement);
}
public Observable<VersionInfo> getDependencies(ITraversalRule rule) {
Map<String, String> toDownload = rule.getNextDependencies(this);
return Observable.fromIterable(toDownload.entrySet())
.flatMapMaybe(e-> JNPMService.instance().getRxService()
.bestMatch(e.getKey(), e.getValue()));
}
@Override
public int compareTo(VersionInfo o) {
Semver version = getVersion();
Semver thatVersion = o.getVersion();
if(version!=null && thatVersion!=null) return version.compareTo(thatVersion);
else return getVersionAsString().compareTo(o.getVersionAsString());
}
@Override
public String toString() {
return "Version(\""+getName()+"@"+getVersionAsString()+"\")";
}
}
| true
|
43b2b7e60aa990a6e2f3699ca289fe9d586de683
|
Java
|
Karthikvenkatesan/junit-example
|
/src/test/java/HelloWorldTestCase.java
|
UTF-8
| 343
| 2.640625
| 3
|
[] |
no_license
|
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class HelloWorldTestCase
{
@Test
public final void test()
{
HelloWorld helloWorld = new HelloWorld();
String strTo = "Karthik";
String strAct = helloWorld.sayHello(strTo);
String strExp = "Hello Mr. " + strTo;
assertEquals(strExp, strAct);
}
}
| true
|
6a7ecee4193671b58ae56ac062aec6d5d203109e
|
Java
|
aaronamm/osgi-mvc
|
/framework/core/core-impl/src/main/java/com/funnic/mvc/core/impl/controllers/ControllerRepository.java
|
UTF-8
| 383
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package com.funnic.mvc.core.impl.controllers;
import com.funnic.mvc.core.api.exceptions.ControllerNotFoundException;
/**
* @author Per
*/
public interface ControllerRepository {
/**
* Retrieves a controller with the supplied name
*
* @param name The name of the controller
* @return
*/
ControllerInfo getController(String name) throws ControllerNotFoundException;
}
| true
|
c53531b659bca203edc95fdd541f78de4b2c1e6d
|
Java
|
loveq2016/futureN4J
|
/commons-collections/src/main/java/com/github/ittalks/commons/redis/queue/config/ConfigManager.java
|
UTF-8
| 620
| 2.21875
| 2
|
[] |
no_license
|
package com.github.ittalks.commons.redis.queue.config;
import java.util.Properties;
/**
* Created by 刘春龙 on 2017/3/3.
*/
public class ConfigManager {
private static Properties redisConn;
private static Properties redisQueue;
public void setRedisConn(Properties redisConn) {
ConfigManager.redisConn = redisConn;
}
public void setRedisQueue(Properties redisQueue) {
ConfigManager.redisQueue = redisQueue;
}
public static Properties getRedisConn() {
return redisConn;
}
public static Properties getRedisQueue() {
return redisQueue;
}
}
| true
|
bc91e589e3d7cb10c7003741c860644993dfd0d5
|
Java
|
LapTrinhWepT2/WebCaNhanVersion8
|
/src/dao/DeThiDAO.java
|
UTF-8
| 2,094
| 2.8125
| 3
|
[] |
no_license
|
package dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.mysql.jdbc.PreparedStatement;
import connect.DBConnect;
import model.DeThi;
import model.DeThi_CauHoi;
import model.KhoaHoc_DeThi;
public class DeThiDAO {
public ArrayList<DeThi> getListDeThi() throws SQLException{
Connection connection = DBConnect.getConnection();
String sql= "select * from dethi";
PreparedStatement ps;
ps = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs= ps.executeQuery();
ArrayList<DeThi> list = new ArrayList<>();
while (rs.next()){
DeThi dethi=new DeThi();
dethi.setMadethi(rs.getString("MaDeThi"));
dethi.setTendethi(rs.getString("TenDeThi"));
dethi.setThoigian(rs.getTime("ThoiGian"));
list.add(dethi);
}
return list;
}
public ArrayList<KhoaHoc_DeThi> getListDeThiWithKhoaHoc(String makhoahoc) throws SQLException{
Connection connection = DBConnect.getConnection();
String sql= "select * from khoahoc,dethi,khoahoc_dethi where khoahoc.MaKhoaHoc=khoahoc_dethi.MaKhoaHoc and khoahoc_dethi.MaDeThi=dethi.MaDeThi and khoahoc.MaKhoaHoc='"+makhoahoc+"'";
PreparedStatement ps;
ps = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs= ps.executeQuery();
ArrayList<KhoaHoc_DeThi> list = new ArrayList<>();
while (rs.next()){
KhoaHoc_DeThi khoahoc_dethi=new KhoaHoc_DeThi();
khoahoc_dethi.setMadethi(rs.getString("MaDeThi"));
khoahoc_dethi.setTendethi(rs.getString("TenDeThi"));
khoahoc_dethi.setThoigian(rs.getTime("ThoiGian"));
list.add( khoahoc_dethi);
}
return list;
}
public static void main(String[] args) throws SQLException{
DeThiDAO dethi=new DeThiDAO();
/*for(DeThi ds:dethi.getListDeThi())
System.out.println(ds.getMadethi()+'-'+ds.getTendethi());
System.out.println(dethi.getListDeThi());*/
//System.out.println(dao.getCauHoi("CH1").getNoidungcauhoi());
for(KhoaHoc_DeThi ds:dethi.getListDeThiWithKhoaHoc("KH01")){
System.out.println(ds.getMadethi()+"-"+ds.getTendethi());
}
}
}
| true
|
dbb3eb9bcaba482e5e561e4fdfb740470eb877bb
|
Java
|
bryant1410/MultiView
|
/adapters/src/main/java/io/apptik/multiview/adapters/WrapperAdapter.java
|
UTF-8
| 3,037
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2015 AppTik Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apptik.multiview.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.InvocationTargetException;
public class WrapperAdapter<A extends RecyclerView.Adapter, VG extends ViewGroup> extends RecyclerView.Adapter<WrapperAdapter.ViewHolder> {
A originalAdapter;
Class<VG> vgClass;
public WrapperAdapter(A originalAdapter, Class<VG> vgClass) {
this.originalAdapter = originalAdapter;
this.vgClass = vgClass;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
VG viewGroup = null;
try {
viewGroup = vgClass.getConstructor(Context.class).newInstance(parent.getContext());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
if(viewGroup==null) {
throw new IllegalStateException("viewGroup container was not initialized");
}
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT);
viewGroup.setLayoutParams(lp);
ViewHolder vh = new ViewHolder(originalAdapter.onCreateViewHolder(parent, viewType), viewGroup);
View childView = vh.originalVH.itemView;
ViewGroup.LayoutParams lpCh = childView.getLayoutParams();
lpCh.width = parent.getWidth();
lpCh.height = parent.getHeight();
viewGroup.addView(childView);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
originalAdapter.bindViewHolder(holder.originalVH, position);
}
@Override
public int getItemCount() {
return originalAdapter.getItemCount();
}
public class ViewHolder<VH extends RecyclerView.ViewHolder> extends RecyclerView.ViewHolder {
public final VH originalVH;
public final VG viewGroup;
public ViewHolder(VH originViewHolder, VG viewGroup) {
super(viewGroup);
originalVH = originViewHolder;
this.viewGroup = viewGroup;
}
}
}
| true
|
3aed137bb732ba82d0741ab3d412066ff22a80a5
|
Java
|
daskain/cft-desktop-app
|
/src/main/java/ru/cft/model/Rental.java
|
UTF-8
| 810
| 2.125
| 2
|
[] |
no_license
|
package ru.cft.model;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.extern.apachecommons.CommonsLog;
import javax.persistence.*;
import java.sql.Date;
import java.sql.Timestamp;
@Entity
@Table(name = "rentals")
@Data
public class Rental {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name = "passport")
private Client client;
@OneToOne
@JoinColumn(name = "vin_car")
private Car car;
@Column(name = "start_time_rental")
private Timestamp startTimeRental;
@Column(name = "contract")
private String contract;
@Getter(AccessLevel.NONE)
@Column(name = "active")
private Boolean active;
public Boolean isActive()
{
return active;
}
}
| true
|
0bff13ddff1296c93fcb18666527969ce6e18e8e
|
Java
|
noushunr/Pachoo
|
/app/src/main/java/com/highstreets/user/ui/place_order/PlaceOrderActivity.java
|
UTF-8
| 10,190
| 1.664063
| 2
|
[] |
no_license
|
package com.highstreets.user.ui.place_order;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.highstreets.user.R;
import com.highstreets.user.app_pref.SharedPrefs;
import com.highstreets.user.models.ProductResult;
import com.highstreets.user.models.Result;
import com.highstreets.user.models.Success;
import com.highstreets.user.ui.SplashActivity;
import com.highstreets.user.ui.address.add_address.model.PostResponse;
import com.highstreets.user.ui.base.BaseActivity;
import com.highstreets.user.ui.cart.model.CartData;
import com.highstreets.user.ui.main.HomeMainActivity;
import com.highstreets.user.ui.main.MoreCategoriesActivity;
import com.highstreets.user.ui.payment.RazorPayHelper;
import com.highstreets.user.ui.payment.stripe.StripeCheckoutActivity;
import com.highstreets.user.ui.place_order.model.FinalBalanceItem;
import com.highstreets.user.ui.place_order.model.payment.MakePaymentResponse;
import com.highstreets.user.ui.review_booking.adapter.ReviewBookingAdapter;
import com.highstreets.user.utils.CommonUtils;
import com.highstreets.user.utils.Constants;
import com.razorpay.PaymentData;
import com.razorpay.PaymentResultWithDataListener;
//import com.stripe.android.model.Card;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class PlaceOrderActivity extends BaseActivity implements PlaceOrderViewInterface, PaymentResultWithDataListener {
private static final String TAG = PlaceOrderActivity.class.getSimpleName();
private static int STRIPE_PAY_ACTIVITY_CODE = 123;
private String userId;
private String addressId;
private PlaceOrderPresenterInterface placeOrderPresenterInterface;
private String grandTotal;
@BindView(R.id.tvToolbarText)
TextView tvToolbarText;
@BindView(R.id.tvSubTotal)
TextView tvSubTotal;
@BindView(R.id.tvDeliveryCharge)
TextView tvDeliveryCharge;
@BindView(R.id.tvServiceCharge)
TextView tvServiceCharge;
@BindView(R.id.tvGrandTotal)
TextView tvGrandTotal;
@BindView(R.id.btnPlaceOrder)
Button btnPlaceOrder;
@BindView(R.id.rvOrderItems)
RecyclerView rvOrderItems;
double totalPrice;
public static Intent start(Context context){
return new Intent(context, PlaceOrderActivity.class);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tvToolbarText.setText(R.string.confirm_orders);
userId = SharedPrefs.getString(SharedPrefs.Keys.USER_ID, "");
addressId = String.valueOf(getIntent().getIntExtra(Constants.ADDRESS_ID,0));
rvOrderItems.setLayoutManager(new LinearLayoutManager(this));
rvOrderItems.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
placeOrderPresenterInterface = new PlaceOrderPresenter(this);
placeOrderPresenterInterface.getCartProducts(userId);
btnPlaceOrder.setEnabled(true);
clickHandles();
}
private void clickHandles() {
btnPlaceOrder.setOnClickListener(view -> {
placeOrderPresenterInterface.placeOrder("",addressId,"C");
// startActivityForResult(StripeCheckoutActivity.start(this), STRIPE_PAY_ACTIVITY_CODE);
// startActivity(new Intent(PlaceOrderActivity.this, StripeCheckoutActivity.class));
});
}
@Override
protected boolean setToolbar() {
return true;
}
@Override
public int setLayout() {
return R.layout.activity_place_order;
}
@Override
public void reloadPage() {
}
@Override
public void onResponseFailed(String message) {
}
@Override
public void onServerError(String message) {
}
@Override
public void dismissProgressIndicator() {
dismissProgress();
}
@Override
public void noInternet() {
}
@Override
public void showProgressIndicator() {
showProgress();
}
@Override
public void setFinalBalance(FinalBalanceItem finalBalanceItem) {
if (finalBalanceItem != null) {
this.grandTotal = finalBalanceItem.getGrandTotal();
String subTotal = getString(R.string.pound_symbol) + finalBalanceItem.getSubtotal();
String deliveryCharge = getString(R.string.pound_symbol) + finalBalanceItem.getDeliveryCharge();
String serviceCharge = getString(R.string.pound_symbol) + finalBalanceItem.getServiceCharge();
String grandTotal = getString(R.string.pound_symbol) + finalBalanceItem.getGrandTotal();
tvSubTotal.setText(subTotal);
tvDeliveryCharge.setText(deliveryCharge);
tvServiceCharge.setText(serviceCharge);
tvGrandTotal.setText(grandTotal);
btnPlaceOrder.setEnabled(true);
}
}
@Override
public void setPlaceOrderResponse(ProductResult postResponse) {
if (postResponse != null){
if (postResponse.getSuccess() == 0){
CommonUtils.showToast(this, postResponse.getMessage());
} else {
CommonUtils.showToast(this, "Successfully place the order");
SharedPrefs.setInt(SharedPrefs.Keys.CART_COUNT, 0);
// Intent toAllCategories = MoreCategoriesActivity.start(PlaceOrderActivity.this);
// SharedPrefs.setString(SharedPrefs.Keys.MERCHANT_ID, "16");
// toAllCategories.putExtra(Constants.MERCHANT_ID, "16");
// startActivity(toAllCategories);
Intent homeIntent = HomeMainActivity.start(this,false);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
// if (postResponse.getData()!=null){
// RazorPayHelper razorPayHelper = new RazorPayHelper(PlaceOrderActivity.this, totalPrice,postResponse.getData().getRazorpayOrderId(),"rzp_test_Wsk6F7p43i6gmz");
// razorPayHelper.startPayment();
// }
// CommonUtils.showToast(this, postResponse.getMessage());
// SharedPrefs.setString(SharedPrefs.Keys.CART_COUNT, "");
// Intent homeIntent = HomeMainActivity.start(this,false);
// homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(homeIntent);
// Intent toAllCategories = MoreCategoriesActivity.start(PlaceOrderActivity.this);
// SharedPrefs.setString(SharedPrefs.Keys.MERCHANT_ID, "16");
// toAllCategories.putExtra(Constants.MERCHANT_ID, "16");
// startActivity(toAllCategories);
}
}
}
@Override
public void setCartData(List<Success> cartData) {
rvOrderItems.setAdapter(new ReviewBookingAdapter(this, cartData));
totalPrice = 0;
for (int i=0;i<cartData.size();i++){
totalPrice=totalPrice+((Double.parseDouble(cartData.get(i).getSellingPrice()))*Integer.parseInt(cartData.get(i).getQuantity()));
}
tvGrandTotal.setText(getString(R.string.pound_symbol) + totalPrice);
// placeOrderPresenterInterface.getFinalBalance(userId, addressId);
}
@Override
public void paymentSuccess(ProductResult makePaymentResponse) {
CommonUtils.showToast(this, "Successfully place the order");
SharedPrefs.setInt(SharedPrefs.Keys.CART_COUNT, 0);
// Intent toAllCategories = MoreCategoriesActivity.start(PlaceOrderActivity.this);
// SharedPrefs.setString(SharedPrefs.Keys.MERCHANT_ID, "16");
// toAllCategories.putExtra(Constants.MERCHANT_ID, "16");
// startActivity(toAllCategories);
Intent homeIntent = HomeMainActivity.start(this,false);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
@Override
public void paymentError(ProductResult makePaymentResponse) {
CommonUtils.showToast(this, "Some problem with payment please try again");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == STRIPE_PAY_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
// String token = data.getStringExtra(Constants.WORLD_PAY_CARD_TOKEN);,
// Card cardDetails = (Card)data.getParcelableExtra(Constants.STRIPE_PAY_CARD);
// String card_number = cardDetails.getNumber();
// String exp_month = String.valueOf(cardDetails.getExpMonth());
// String exp_year = String.valueOf(cardDetails.getExpYear());
// String cvc = cardDetails.getCvc();
// Double total = Double.parseDouble(grandTotal);
// int totalValue = (int) (total * 100);
// Log.e(TAG, "onActivityResultToken: "+ token);
// Log.e(TAG, "onActivityResultCustomerId: "+ userId);
// Log.e(TAG, "onActivityResultAddressId: "+ addressId);
// Log.e(TAG, "onActivityResultAmount: "+ grandTotal);
// placeOrderPresenterInterface.makePayment(userId, addressId, String.valueOf(totalValue), card_number,exp_month,exp_year,cvc);
}
}
}
@Override
public void onPaymentSuccess(String s, PaymentData paymentData) {
if (paymentData!=null){
Log.d("Order_id", paymentData.getOrderId());
placeOrderPresenterInterface.makePayment("",paymentData.getOrderId(),"1");
}
}
@Override
public void onPaymentError(int i, String s, PaymentData paymentData) {
}
}
| true
|
4f30f3f71e4ee046123a7af058decd26624e68ed
|
Java
|
siddhantaws/LowLatency
|
/PROFILING/NIOMultiplexer/src/main/java/org/mk/training/plexer/impl/DumbBufferFactory.java
|
UTF-8
| 416
| 2.234375
| 2
|
[] |
no_license
|
package org.mk.training.plexer.impl;
import org.mk.training.plexer.BufferFactory;
import java.nio.ByteBuffer;
public class DumbBufferFactory implements BufferFactory {
private int capacity;
public DumbBufferFactory(int capacity) {
this.capacity = capacity;
}
public ByteBuffer newBuffer() {
return (ByteBuffer.allocate(capacity));
}
public void returnBuffer(ByteBuffer buffer) {
// do nothing
}
}
| true
|
f6dacfe27a407808d674e86eea5872a8c81b1c18
|
Java
|
realzoulou/omri-usb
|
/omriusb/src/main/java/org/omri/radio/impl/VisualDabSlideShowImpl.java
|
UTF-8
| 3,419
| 2.046875
| 2
|
[] |
no_license
|
package org.omri.radio.impl;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Calendar;
import org.omri.radioservice.metadata.VisualDabSlideShow;
import org.omri.radioservice.metadata.VisualType;
/**
* Copyright (C) 2018 IRT GmbH
*
* 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.
*
* @author Fabian Sattler, IRT GmbH
*/
public class VisualDabSlideShowImpl extends VisualImpl implements VisualDabSlideShow, Serializable {
private int mCatId = -1;
private String mContentName = "";
private int mContentType = -1;
private int mContentSubType = -1;
private URI mAltLocUri = null;
private Calendar mExpiryCal = null;
private int mSlsId = -1;
private Calendar mTriggerCal = null;
private String mCatText = "";
private URI mCatLink;
private URI mCatClickLink;
@Override
public VisualType getVisualType() {
return VisualType.METADATA_VISUAL_TYPE_DAB_SLS;
}
@Override
public boolean isCategorized() {
return mCatId >= 0 ? true : false;
}
@Override
public String getContentName() {
return mContentName;
}
void setContentName(String contName) {
this.mContentName = contName;
}
@Override
public int getContentType() {
return mContentType;
}
void setContentType(int contentType) {
mContentType = contentType;
}
@Override
public int getContentSubType() {
return mContentSubType;
}
void setContentSubType(int contentSubType) {
mContentSubType = contentSubType;
}
@Override
public URI getAlternativeLocationURL() {
return mAltLocUri;
}
void setAlternativeLocationURL(String altUrl) {
try {
mAltLocUri = URI.create(altUrl);
} catch(IllegalArgumentException illArg) {
illArg.printStackTrace();
}
}
@Override
public Calendar getExpiryTime() {
return mExpiryCal;
}
void setExpiryTime(Calendar cal) {
mExpiryCal = cal;
}
@Override
public int getSlideId() {
return mSlsId;
}
void setSlideId(int slideId) {
this.mSlsId = slideId;
}
@Override
public Calendar getTriggerTime() {
return mTriggerCal;
}
void setTriggerTime(String triggerTime) {
if(triggerTime == "NOW") {
mTriggerCal = null;
} else {
//TODO parse triggertime to calendar
}
}
@Override
public String getCategoryText() {
return mCatText;
}
void setCategoryText(String catText) {
this.mCatText = catText;
}
@Override
public int getCategoryId() {
return mCatId;
}
void setCategoryId(int catId) {
this.mCatId = catId;
}
@Override
public URI getLink() {
return mCatLink;
}
void setCategoryLink(String link) {
try {
this.mCatLink = new URI(link);
} catch (URISyntaxException e) {
this.mCatLink = null;
}
}
@Override
public URI getClickThroughUrl() {
return mCatClickLink;
}
void setCategoryClickThroughLink(String link) {
try {
this.mCatClickLink = new URI(link);
} catch (URISyntaxException e) {
this.mCatClickLink = null;
}
}
}
| true
|
0cf0e98df2d41e8b7364a820f238b1f54dbd3451
|
Java
|
radwasherif/ACM
|
/src/codeforces/div2/IlyaAndTicTacToeGame_754B.java
|
UTF-8
| 1,837
| 3.21875
| 3
|
[] |
no_license
|
package codeforces.div2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class IlyaAndTicTacToeGame_754B {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
char c [] [] = new char [4][4];
boolean yes = false;
for (int i = 0; i < 4; i++) {
String s = sc.nextLine();
if(s.contains("x.x") || s.contains("xx.") || s.contains(".xx"))
{
yes = true;
}
for (int j = 0; j < 4; j++) {
c[i][j] = s.charAt(j);
}
}
if(yes)
{
System.out.println("YES");
return;
}
for(int d =-1; d <= 4; d++) {
String s = "";
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(d <= 1 && (j - i) == d) {
// System.out.println(i + " " + j);
s += c[i][j];
} else if( d > 1 && (j + i) == d)
s+= c[i][j];
}
}
if(s.contains("x.x") || s.contains("xx.") || s.contains(".xx"))
{
System.out.println("YES");
return;
}
}
for(int j = 0; j < 4; j++) {
String s = "";
for(int i = 0; i < 4; i++) {
s += c[i][j];
}
if(s.contains("x.x") || s.contains("xx.") || s.contains(".xx"))
{
System.out.println("YES");
return;
}
}
System.out.println("NO");
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
| true
|
27c2825a850fe0f4a1094d1ecf77feb1d4ae5014
|
Java
|
jackplantin/AWeberTask
|
/src/test/java/pages/ProfilePage.java
|
UTF-8
| 1,321
| 2.53125
| 3
|
[] |
no_license
|
package pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import utils.CommonMethods;
public class ProfilePage extends CommonMethods {
//This input field takes in first name
@FindBy(xpath = "//input[@id = 'first_name']")
public WebElement firstNameField;
//This input field takes in first name
@FindBy(xpath = "//input[@id = 'last_name']")
public WebElement lastNameField;
//This input field takes in a description any # of characters
@FindBy(xpath = "//textarea[@id = 'description']")
public WebElement descriptionField;
//This is the button to save details
@FindBy(xpath = "//button[text() ='Save profile details']")
public WebElement saveProfileDetailsButton;
//This element shows that we have saved information successfully
@FindBy(xpath = "//span[contains(text(), 'success')]")
public WebElement successMessage;
public ProfilePage() {
PageFactory.initElements(driver, this);
}
public static void enterAllFields(String firstN, String lastN, String description) {
sendText(profilePage.firstNameField, firstN);
sendText(profilePage.lastNameField, lastN);
sendText(profilePage.descriptionField, description);
}
}
| true
|
0f068630c80cee585d2872972417cbdc24c81955
|
Java
|
tommasoVilla/Didattica_Mobile_Client_Android
|
/app/src/main/java/it/uniroma2/dicii/sdcc/didatticamobile/task/AddCourseTask.java
|
UTF-8
| 3,952
| 2.5625
| 3
|
[] |
no_license
|
package it.uniroma2.dicii.sdcc.didatticamobile.task;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import it.uniroma2.dicii.sdcc.didatticamobile.R;
import it.uniroma2.dicii.sdcc.didatticamobile.activity.CoursesActivity;
import it.uniroma2.dicii.sdcc.didatticamobile.activity.utility.InternetConnectionStatus;
import it.uniroma2.dicii.sdcc.didatticamobile.dao.CourseDao;
import it.uniroma2.dicii.sdcc.didatticamobile.dao.CourseDaoFactory;
import it.uniroma2.dicii.sdcc.didatticamobile.error.ErrorHandler;
import it.uniroma2.dicii.sdcc.didatticamobile.error.NoInternetConnectionException;
import it.uniroma2.dicii.sdcc.didatticamobile.model.Course;
/* An AddCourseTask is a task responsible to make the insert request to the server for a course.*/
public class AddCourseTask extends AsyncTask<Bundle, Void, Void> {
private Activity context;
/*
* This field is populated with the exception thrown inside doInBackground. If an exception occurs
* this field is not null and inside onPostExecute is called the ErrorHandler object to show the
* error to the user.
* */
private Exception thrownException;
public AddCourseTask(Activity activity){
this.context = activity;
}
/* During the execution a progress bar is shown and the other widgets are hidden.*/
@Override
protected void onPreExecute() {
context.findViewById(R.id.tvInsertCourseDescription).setVisibility(View.GONE);
context.findViewById(R.id.svDescription).setVisibility(View.GONE);
context.findViewById(R.id.btnConfirmAddCourse).setVisibility(View.GONE);
context.findViewById(R.id.pbAddCourse).setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Bundle ... bundle) {
try {
/* If the device is not connected to Internet an error is raised*/
InternetConnectionStatus internetConnectionStatus = new InternetConnectionStatus();
if (!internetConnectionStatus.isDeviceConnectedToInternet(context)) {
throw new NoInternetConnectionException();
}
/* The interaction with the persistence layer is delegated to an CourseDao object*/
CourseDaoFactory courseDaoFactory = CourseDaoFactory.getInstance();
CourseDao courseDao = courseDaoFactory.createCourseDao();
Course course = new Course(bundle[0]);
/* The request is embedded with an access token read from shared preferences*/
SharedPreferences sharedPreferences = context.getSharedPreferences("shared_preference", Context.MODE_PRIVATE);
String token = sharedPreferences.getString("token","defaultToken");
courseDao.add(course, token);
return null;
} catch (Exception e) {
thrownException = e;
return null;
}
}
@Override
protected void onPostExecute(Void v) {
if (thrownException != null) {
ErrorHandler errorHandler = new ErrorHandler(context);
errorHandler.show(thrownException);
/* After the execution, the visibility of the widgets is restored.*/
context.findViewById(R.id.tvInsertCourseDescription).setVisibility(View.VISIBLE);
context.findViewById(R.id.svDescription).setVisibility(View.VISIBLE);
context.findViewById(R.id.btnConfirmAddCourse).setVisibility(View.VISIBLE);
context.findViewById(R.id.pbAddCourse).setVisibility(View.GONE);
} else {
Toast.makeText(context, R.string.courseCreationConfirm_message, Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, CoursesActivity.class);
context.startActivity(intent);
}
}
}
| true
|
dbede52ab21b9193f04e564db5160db398e46c65
|
Java
|
olgt/Laboratorio_EDD_201612341_Proyecto2
|
/src/Screens/MainUsuario.java
|
UTF-8
| 3,610
| 2.421875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Screens;
/**
*
* @author Oscar
*/
public class MainUsuario extends javax.swing.JPanel {
/**
* Creates new form MainUsuario
*/
public MainUsuario() {
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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setBackground(new java.awt.Color(204, 255, 204));
setForeground(new java.awt.Color(51, 0, 51));
setPreferredSize(new java.awt.Dimension(734, 730));
jButton1.setText("Pedir Viaje");
jButton2.setText("Detalles de Cuenta");
jButton3.setText("Salir");
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(202, 202, 202)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(238, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(36, 36, 36)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(111, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
| true
|
857a8de6f46127606c6430ca6cd82d2631eb95e7
|
Java
|
jaimemorales52/appDockerizada
|
/appDockerizada/src/main/java/com/demo/docker/model/ConsulInstance.java
|
UTF-8
| 1,040
| 2
| 2
|
[] |
no_license
|
package com.demo.docker.model;
import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;
public class ConsulInstance {
private static Consul consul = Consul.builder().build(); // connect to localhost
// private static Consul consul = Consul.builder().withUrl("http://consul-service.softtoken-dev:8500").build(); // connect to
// Consul on
// private static Consul consul = Consul.builder().withUrl("http://consul:8500").build(); // connect to
private static KeyValueClient kvClient = consul.keyValueClient();
/**
* @return the consul
*/
public static Consul getConsul() {
return consul;
}
/**
* @param consul
* the consul to set
*/
public static void setConsul(Consul consul) {
ConsulInstance.consul = consul;
}
/**
* @return the kvClient
*/
public static KeyValueClient getKvClient() {
return kvClient;
}
/**
* @param kvClient
* the kvClient to set
*/
public static void setKvClient(KeyValueClient kvClient) {
ConsulInstance.kvClient = kvClient;
}
}
| true
|
4a3e308aa3f1fcd6ea0f936b8a4205518f9d6bfa
|
Java
|
rgavrysh/BetMonitor
|
/graphView/src/com/roman/graphview/MainActivity.java
|
UTF-8
| 3,189
| 2.59375
| 3
|
[] |
no_license
|
package com.roman.graphview;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
// The Intent is used to issue that an operation should
// be performed
Intent intent;
TextView betID;
// The object that allows me to manipulate the database
DBTools dbTools = new DBTools(this);
// Called when the Activity is first called
protected void onCreate(Bundle savedInstanceState) {
// Get saved data if there is any
super.onCreate(savedInstanceState);
// Designate that activity_main.xml is the interface used
setContentView(R.layout.activity_main);
// Gets all the data from the database and stores it
// in an ArrayList
ArrayList<HashMap<String, String>> betsList = dbTools.getAllBets();
// Check to make sure there are contacts to display
if(betsList.size()!=0) {
// Get the ListView and assign an event handler to it
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When an item is clicked get the TextView
// with a matching checkId
betID = (TextView) view.findViewById(R.id.betsIdEntryTextView);
// Convert that contactId into a String
String betIdValue = betID.getText().toString();
// Signals an intention to do something
// getApplication() returns the application that owns
// this activity
Intent theIndent = new Intent(getApplication(), EditBet.class);
// Put additional data in for EditContact to use
theIndent.putExtra("betId", betIdValue);
// Calls for EditContact
startActivity(theIndent);
}
});
// A list adapter is used bridge between a ListView and
// the ListViews data
// The SimpleAdapter connects the data in an ArrayList
// to the XML file
// First we pass in a Context to provide information needed
// about the application
// The ArrayList of data is next followed by the xml resource
// Then we have the names of the data in String format and
// their specific resource ids
ListAdapter adapter = new SimpleAdapter( MainActivity.this, betsList, R.layout.bets_entry, new String[] { "betsID","homeSide", "awaySide"}, new int[] {R.id.betsIdEntryTextView, R.id.homeSideEntryTextView, R.id.awaySideEntryTextView});
// setListAdapter provides the Cursor for the ListView
// The Cursor provides access to the database data
setListAdapter(adapter);
}
}
// When showAddContact is called with a click the Activity
// NewContact is called
public void showAddContact(View view) {
Intent theIntent = new Intent(getApplication(), NewBet.class);
startActivity(theIntent);
}
}
| true
|
2566f6dfc9573fb259d23810870d2c39f00a929a
|
Java
|
wangshengkui/Calligraphy
|
/src/com/jinke/smartpen/SimplePoint.java
|
UTF-8
| 866
| 2.21875
| 2
|
[] |
no_license
|
package com.jinke.smartpen;
import java.io.Serializable;
import android.R.integer;
public class SimplePoint implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public final float x;
public final float y;
public final double timestamp;
public final int force;
public final int ownerID;
public final int pageID;
public final int sectionID;
public final int BookID;
public final int color;
public final int angle;
public final int counter;
public SimplePoint(float x,float y,double timestamp,int force,int ownerID,int pageID,
int sectionID,int BookID,int color,int angle,int counter){
this.x=x;
this.y=y;
this.timestamp=timestamp;
this.force=force;
this.ownerID=ownerID;
this.pageID=pageID;
this.sectionID=sectionID;
this.BookID=BookID;
this.color=color;
this.angle=angle;
this.counter=counter;
}
}
| true
|
0cac9bfc951911dcd939db80ea813d1f0c151519
|
Java
|
waitforyouwtt/thread
|
/src/main/java/com/yidiandian/designmodel/zerenlian/Main.java
|
UTF-8
| 664
| 3
| 3
|
[] |
no_license
|
package com.yidiandian.designmodel.zerenlian;
/**
* @Author: 一点点
* @Date: 2019/4/30 14:37
* @Version 1.0
*/
public class Main {
public static void main(String[] args) {
//创建一个女子,发送自己的类型与请求
IWoman woman = new Woman(2,"我想出去购物..");
//创建责任链
ResponseHandler farther = new Father();
ResponseHandler husband = new Husband();
ResponseHandler son = new Son();
//设置下一责任人。
farther.setNext(husband);
husband.setNext(son);
//设置责任链入口,处理内容
farther.handleMessage(woman);
}
}
| true
|
2a62f5e4b0b648a4616b4fa688558832affad743
|
Java
|
lucifer7/hotswapdemo
|
/src/main/java/hotel/swap/demo/service/IndexService.java
|
UTF-8
| 268
| 1.609375
| 2
|
[] |
no_license
|
package hotel.swap.demo.service;
/**
* <B>系统名称:</B><BR>
* <B>模块名称:</B><BR>
* <B>中文类名:</B><BR>
* <B>概要说明:</B><BR>
*
* @author carl.yu
* @since 2016/6/16
*/
public interface IndexService {
public String hello();
}
| true
|
cc84bcc8c9a87995681b0d24f31179ac490c5484
|
Java
|
immortalcatz/MHFC
|
/src/main/java/mhfc/net/common/crafting/MHFCShapelessRecipe.java
|
UTF-8
| 320
| 1.890625
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
package mhfc.net.common.crafting;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.ShapelessRecipes;
public class MHFCShapelessRecipe extends ShapelessRecipes {
public MHFCShapelessRecipe(ItemStack output, List<ItemStack> inputList) {
super(output, inputList);
}
}
| true
|
fd87f0d8277c016cb3d8b6cd1d1ef158daf59acd
|
Java
|
KierenEinar/taobao
|
/taobao-account/src/main/java/taobao/account/listener/AccountRefundMessageListener.java
|
UTF-8
| 858
| 1.992188
| 2
|
[
"MIT"
] |
permissive
|
package taobao.account.listener;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import taobao.account.service.AccountService;
import taobao.core.constant.Constant;
import taobao.core.vo.OrderPayVo;
import taobao.rocketmq.annotation.RocketMQMessageListener;
import taobao.rocketmq.core.RocketMQListener;
@Service
@RocketMQMessageListener(consumerGroup = Constant.Producer.account_group, topic = Constant.Topic.order_update_failed_topic)
public class AccountRefundMessageListener implements RocketMQListener<String> {
@Autowired
AccountService accountService;
@Override
public void onMessage(String json) {
OrderPayVo orderPayVo = JSONObject.parseObject(json, OrderPayVo.class);
accountService.refund(orderPayVo);
}
}
| true
|
4fa29506553b41d03d961b2e8f57ea5d65464856
|
Java
|
RungeKutta2/LanzandoElCaberTheta
|
/src/clases/Podio.java
|
UTF-8
| 1,010
| 3.421875
| 3
|
[] |
no_license
|
package clases;
import java.util.Comparator;
import java.util.LinkedList;
public class Podio {
private LinkedList<Participante> participantes;
private Comparator<Participante> comparador;
public Podio(Comparator<Participante> comparador) {
this.comparador = comparador;
participantes = new LinkedList<Participante>();
}
public void add(Participante participante) {
boolean entro=false;
int i=0;
int len = participantes.size();
while (!entro && i<len) {
if(comparador.compare(participante, participantes.get(i)) > 0) {
entro=true;
participantes.add(i, participante);
}
i++;
}
if(participantes.size()>3) {
participantes.removeLast();
}
else if(participantes.size()<3 && !entro) {
participantes.add(participante);
}
}
@Override
public String toString() {
String res = "";
for (Participante participante : participantes) {
res+=participante.getNumero()+" ";
}
return res;
}
public Integer size() {
return participantes.size();
}
}
| true
|
cfd2a14864b8b2be2b388b5a364e150278f52912
|
Java
|
pushpendrapal2206/ParkingLotApp
|
/src/test/java/com/dkatalis/parkinglot/api/models/ParkingSlotTest.java
|
UTF-8
| 1,226
| 2.9375
| 3
|
[] |
no_license
|
package com.dkatalis.parkinglot.api.models;
import org.junit.Test;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ParkingSlotTest {
@Test
public void shouldConstructAndReturnParkingSlot() {
ParkingSlot parkingSlot = new ParkingSlot(1);
assertNotNull(parkingSlot);
assertEquals(1, parkingSlot.getSlotNumber());
assertTrue(parkingSlot.isFree());
}
@Test
public void shouldReturnTrueWhenEqualsIsCalled() {
ParkingSlot parkingSlot1 = new ParkingSlot(1);
ParkingSlot parkingSlot2 = new ParkingSlot(1);
assertEquals(parkingSlot1, parkingSlot2);
}
@Test
public void shouldReturnFalseWhenEqualsIsCalled() {
ParkingSlot parkingSlot1 = new ParkingSlot(1);
ParkingSlot parkingSlot2 = new ParkingSlot(2);
assertNotEquals(parkingSlot1, parkingSlot2);
}
@Test
public void shouldReturnHashForParkingSlot() {
ParkingSlot parkingSlot1 = new ParkingSlot(1);
assertEquals(Objects.hash(1), parkingSlot1.hashCode());
}
}
| true
|
73bab8f690f1357de853390a816e224c2120236e
|
Java
|
khidir000/maps-tracking
|
/app/src/main/java/edu/unt/transportation/bustrackingsystem/util/GeneralUtil.java
|
UTF-8
| 2,528
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package edu.unt.transportation.bustrackingsystem.util;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import java.util.Calendar;
import java.util.Locale;
/**
* Utility class consisting of all static methods. It can be used by any class just by calling the required static method.
* Created by Anurag Chitnis on 11/18/2016.
*/
public class GeneralUtil {
/**
* This method returns the day for TODAY. In firebase realtime database we have just one entry 'Monday' , which
* whose schedule is same for other days like Tuesday, Wednesday, Thursday. So, we are returning the string as 'Monday' even if
* the day is any of the above mentioned days.
* @return 'Monday' for Mon, Tue, Wed, Thu or 'Friday', 'Saturday' , 'Sunday' as applicable
*/
public static String getDayStringForToday() {
Calendar calendar = Calendar.getInstance();
String today = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US);
switch(today) {
case "Monday":
return "Monday";
case "Tuesday":
return "Monday";
case "Wednesday":
return "Monday";
case "Thursday":
return "Monday";
case "Friday":
return "Friday";
case "Saturday":
return "Saturday";
case "Sunday":
return "Sunday";
default:
return "Error";
}
}
public static void OpenFacebookPage(Context context){
String facebookPageID = "UNT-1118685708250263";
// URL
String facebookUrl = "https://www.facebook.com/" + facebookPageID;
String facebookUrlScheme = "fb://page/" + facebookPageID;
// try
//catch block for exception
try {
int versionCode = context.getPackageManager().getPackageInfo("com.facebook.katana", 0).versionCode;
if (versionCode >= 3002850) {
Uri uri = Uri.parse("fb://facewebmodal/f?href=" + facebookUrl);
context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
} else {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookUrlScheme)));
}
} catch (PackageManager.NameNotFoundException e) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookUrl)));
}
}
}
| true
|
c22f4c44a5e9488a54cb5521fae1b20f85c38d7b
|
Java
|
swift-lang/swift-t
|
/stc/code/src/exm/stc/common/util/ScopedUnionFind.java
|
UTF-8
| 5,270
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package exm.stc.common.util;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
/**
* Union-find data structure that supports scoping.
*
* The data-structure is structured as a tree. Every merge of two sets
* affects the current node and any descendants, but has no effect in the
* parent or other ancestors.
*
* Merging in a leaf node of the tree is straightforward: only local data
* structures need to be updated.
*
* Merging in a non-leaf node is more
*
* @param <T>
*/
public class ScopedUnionFind<T> {
/**
* Parent of the union find, null if this is root
*/
private final ScopedUnionFind<T> parent;
/**
* Internal mapping from member to canonical.
*
* We keep this up-to-date so every entry directly links an entry to its
* canonical.
*/
private final TwoWayMap<T, T> canonical;
/**
* Children that we might need to propagate changes to
*/
private final SetMultimap<Pair<T, Boolean>, UnionFindSubscriber<T>> subscribed;
private final Subscriber subscriber = new Subscriber();
private ScopedUnionFind(ScopedUnionFind<T> parent) {
this.parent = parent;
this.canonical = TwoWayMap.create();
this.subscribed = HashMultimap.create();
}
public static <T1> ScopedUnionFind<T1> createRoot() {
return new ScopedUnionFind<T1>(null);
}
public ScopedUnionFind<T> newScope() {
return new ScopedUnionFind<T>(this);
}
public T lookup(T x) {
ScopedUnionFind<T> curr = this;
while (curr != null) {
T canon = curr.canonical.get(x);
if (canon != null) {
return canon;
}
curr = curr.parent;
}
// x is on its own
return x;
}
/**
* Merge loser into winner.
* Note: if they are already in same set, no changes, even if loser
* is canonical
* @param winner
* @param loser
* @return unmodifiable collection of values that changed their canonical member
*/
public Set<T> merge(T winner, T loser) {
T winnerCanon = lookup(winner);
T loserCanon = lookup(loser);
// Already same set, do nothing
if (loserCanon.equals(winnerCanon)) {
return Collections.emptySet();
}
// Notify before change
notifyChanged(true, winnerCanon, loserCanon);
Set<T> affectedMembers = members(loserCanon);
for (T affectedMember: affectedMembers) {
canonical.put(affectedMember, winnerCanon);
}
subscribeToParentUpdates(winnerCanon);
subscribeToParentUpdates(loserCanon);
// Notify after change
notifyChanged(false, winnerCanon, loserCanon);
return Collections.unmodifiableSet(affectedMembers);
}
/**
* Find all member of set associated with canonical value, including
* the value itself
* @param val
* @return
*/
public Set<T> members(T canon) {
// Search up to find all members
Set<T> members = new HashSet<T>();
members.add(canon);
ScopedUnionFind<T> curr = this;
while (curr != null) {
members.addAll(curr.canonical.getByValue(canon));
curr = curr.parent;
}
return members;
}
/**
* Subscribe to canonical updates
* @param winnerCanon
*/
private void subscribeToParentUpdates(T x) {
if (parent != null) {
parent.subscribe(x, true, subscriber);
}
}
/**
* Subscribe to get notifications when a value x is merged into
* another.
* @param x
* @param before if true, notify before change applied
* @param subscriber
*/
public void subscribe(T x, boolean before, UnionFindSubscriber<T> subscriber) {
ScopedUnionFind<T> curr = this;
while (curr != null) {
curr.subscribed.put(Pair.create(x, before), subscriber);
curr = curr.parent;
}
}
private void notifyChanged(boolean before, T winnerCanon, T loserCanon) {
Pair<T, Boolean> key = Pair.create(loserCanon, before);
for (UnionFindSubscriber<T> subscriber: subscribed.get(key)) {
subscriber.notifyMerge(winnerCanon, loserCanon);
}
}
public Collection<Entry<T, T>> entries() {
return Collections.unmodifiableMap(canonical).entrySet();
}
/**
* Build a multimap with all set members
* @return
*/
public SetMultimap<T, T> sets() {
SetMultimap<T, T> result = HashMultimap.create();
ScopedUnionFind<T> curr = this;
while (curr != null) {
result.putAll(curr.canonical.inverse());
curr = curr.parent;
}
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
ScopedUnionFind<T> curr = this;
while (curr != null) {
if (sb.length() > 0) {
sb.append(" => \n");
}
sb.append(curr.canonical.toString());
curr = curr.parent;
}
return super.toString();
}
public Iterable<T> keys() {
return Collections.unmodifiableSet(canonical.keySet());
}
public static interface UnionFindSubscriber<T> {
public void notifyMerge(T winner, T loser);
}
private class Subscriber implements UnionFindSubscriber<T> {
@Override
public void notifyMerge(T winner, T loser) {
merge(winner, loser);
}
}
}
| true
|
5ee35aa25a271d2fbb9f51260a0e57dc404870a4
|
Java
|
savanrof/intern-project
|
/my-posts-rest-apis/src/main/java/com/nt/rookie/post/entity/Post.java
|
UTF-8
| 2,574
| 2.328125
| 2
|
[] |
no_license
|
package com.nt.rookie.post.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id")
@Table(name="posts")
public class Post {
@Id
@Column(name ="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "title", length = 50)
private String title;
@Column(name = "description")
private String description;
@Column(name = "content")
private String content;
@Column(name ="created_date")
private Date createdDate;
@ManyToOne
//@JsonBackReference
@JoinColumn(name = "author_id")
private Author author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Post(Integer id, String title, String description, String content, Date createdDate, Author author) {
super();
this.id = id;
this.title = title;
this.description = description;
this.content = content;
this.createdDate = createdDate;
this.author = author;
}
public Post() {
// super();
// TODO Auto-generated constructor stub
}
public Post(String string) {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Post [id=" + id + ", title=" + title + ", description=" + description + ", content=" + content
+ ", createdDate=" + createdDate + ", author=" + author + "]";
}
}
| true
|
aa1d08d9e6bdb938907cdf1bbb3142ecd7ec2b2e
|
Java
|
tutrunghieu/dsa-2017-java-tutorial
|
/dsa2017-project2-menuframe/src2-list-tree-graph/apps/ltg/modules/LtgModuleGraph.java
|
UTF-8
| 978
| 1.648438
| 2
|
[] |
no_license
|
package apps.ltg.modules;
import java.awt.event.ActionEvent;
public class LtgModuleGraph extends __Base_Module {
public Object actionNew(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
public Object actionOpen(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
public Object actionSave(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
public Object actionAddNode(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
public Object actionRemoveNode(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
public Object actionMoveNode(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
public Object actionAddLink(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
public Object actionRemoveLink(ActionEvent x) {
// TODO Auto-generated method stub
return null;
}
}
| true
|
ec1ae145a5a4fefb689f65d708aaba518264498d
|
Java
|
replimoc/compiler
|
/Compiler/src/compiler/lexer/TokenType.java
|
UTF-8
| 6,707
| 3.015625
| 3
|
[] |
no_license
|
package compiler.lexer;
/**
* This enum defines the basic types of tokens that can be handled by the lexer.
*
* @author Valentin Zickner
* @author Andreas Eberle
*
*/
public enum TokenType {
/* special tokens */
ERROR("error", OperationType.UNDEFINED),
EOF("EOF", OperationType.UNDEFINED),
IDENTIFIER("identifier", OperationType.UNDEFINED),
INTEGER("integer", OperationType.UNDEFINED),
/* key words */
ABSTRACT("abstract", OperationType.KEYWORD),
ASSERT("assert", OperationType.KEYWORD),
BOOLEAN("boolean", OperationType.KEYWORD),
BREAK("break", OperationType.KEYWORD),
BYTE("byte", OperationType.KEYWORD),
CASE("case", OperationType.KEYWORD),
CATCH("catch", OperationType.KEYWORD),
CHAR("char", OperationType.KEYWORD),
CLASS("class", OperationType.KEYWORD),
CONST("const", OperationType.KEYWORD),
CONTINUE("continue", OperationType.KEYWORD),
DEFAULT("default", OperationType.KEYWORD),
DOUBLE("double", OperationType.KEYWORD),
DO("do", OperationType.KEYWORD),
ELSE("else", OperationType.KEYWORD),
ENUM("enum", OperationType.KEYWORD),
EXTENDS("extends", OperationType.KEYWORD),
FALSE("false", OperationType.KEYWORD),
FINALLY("finally", OperationType.KEYWORD),
FINAL("final", OperationType.KEYWORD),
FLOAT("float", OperationType.KEYWORD),
FOR("for", OperationType.KEYWORD),
GOTO("goto", OperationType.KEYWORD),
IF("if", OperationType.KEYWORD),
IMPLEMENTS("implements", OperationType.KEYWORD),
IMPORT("import", OperationType.KEYWORD),
INSTANCEOF("instanceof", OperationType.KEYWORD),
INTERFACE("interface", OperationType.KEYWORD),
INT("int", OperationType.KEYWORD),
LONG("long", OperationType.KEYWORD),
NATIVE("native", OperationType.KEYWORD),
NEW("new", OperationType.KEYWORD),
NULL("null", OperationType.KEYWORD),
PACKAGE("package", OperationType.KEYWORD),
PRIVATE("private", OperationType.KEYWORD),
PROTECTED("protected", OperationType.KEYWORD),
PUBLIC("public", OperationType.KEYWORD),
RETURN("return", OperationType.KEYWORD),
SHORT("short", OperationType.KEYWORD),
STATIC("static", OperationType.KEYWORD),
STRICTFP("strictfp", OperationType.KEYWORD),
SUPER("super", OperationType.KEYWORD),
SWITCH("switch", OperationType.KEYWORD),
SYNCHRONIZED("synchronized", OperationType.KEYWORD),
THIS("this", OperationType.KEYWORD),
THROWS("throws", OperationType.KEYWORD),
THROW("throw", OperationType.KEYWORD),
TRANSIENT("transient", OperationType.KEYWORD),
TRUE("true", OperationType.KEYWORD),
TRY("try", OperationType.KEYWORD),
VOID("void", OperationType.KEYWORD),
VOLATILE("volatile", OperationType.KEYWORD),
WHILE("while", OperationType.KEYWORD),
/* operators */
/** Not equal: != */
NOTEQUAL("!=", OperationType.BINARY, 4, true),
/** Logical not: ! */
LOGICALNOT("!"),
/** Left parenthesis: ( */
LP("("),
/** Right parenthesis: ) */
RP(")"),
/** Multiply and assign: *= */
MULTIPLYASSIGN("*="),
/** Multiply: * */
MULTIPLY("*", OperationType.BINARY, 7, true),
/** Increment: ++ */
INCREMENT("++"),
/** Add and assign: += */
ADDASSIGN("+="),
/** Add: + */
ADD("+", OperationType.BINARY, 6, true),
/** Comma: , */
COMMA(","),
/** Subtract and assign: -= */
SUBTRACTASSIGN("-="),
/** Decrement: -- */
DECREMENT("--"),
/** Subtract: - */
SUBTRACT("-", OperationType.BINARY, 6, true),
/** Point: . */
POINT("."),
/** Divide and assign: /= */
DIVIDEASSIGN("/="),
/** Divide: / */
DIVIDE("/", OperationType.BINARY, 7, true),
/** Colon: : */
COLON(":"),
/** Semicolon: ; */
SEMICOLON(";"),
/** Left shift and assign: <<= */
LSASSIGN("<<="),
/** Left shift: << */
LS("<<"),
/** Less than or equal: <= */
LESSEQUAL("<=", OperationType.BINARY, 5, true),
/** Less than: < */
LESS("<", OperationType.BINARY, 5, true),
/** Equal: == */
EQUAL("==", OperationType.BINARY, 4, true),
/** Assign: = */
ASSIGN("=", OperationType.BINARY, 1, false),
/** Greater than or equal: >= */
GREATEREQUAL(">=", OperationType.BINARY, 5, true),
/** Right shift and assign: >>= */
RSASSIGN(">>="),
/** Right shift with zero fill and assign: >>>= */
RSZEROFILLASSIGN(">>>="),
/** Right shift with zero fill: >>> */
RSZEROFILL(">>>"),
/** Right shift: >> */
RS(">>"),
/** Greater than: > */
GREATER(">", OperationType.BINARY, 5, true),
/**
* Conditional: ?
* <p>
* condition ? true : false
*/
CONDITIONAL("?"),
/** Modulo and assign: %= */
MODULOASSIGN("%="),
/** Modulo: % */
MODULO("%", OperationType.BINARY, 7, true),
/** And and assign: &= */
ANDASSIGN("&="),
/** Logical and: && */
LOGICALAND("&&", OperationType.BINARY, 3, true),
/** And: & */
AND("&"),
/** Left square bracket: [ */
LSQUAREBRACKET("["),
/** Right square bracket: ] */
RSQUAREBRACKET("]"),
/** Exclusive or and assign: ^= */
EXCLUSIVEORASSIGN("^="),
/** Exclusive or: ^ */
EXCLUSIVEOR("^"),
/** Left curly bracket: { */
LCURLYBRACKET("{"),
/** Right curly bracket: } */
RCURLYBRACKET("}"),
/** Binary complement: ~ */
BINARYCOMPLEMENT("~"),
/** Inclusive or and assign: |= */
INCLUSIVEORASSIGN("|="),
/** Logical or: || */
LOGICALOR("||", OperationType.BINARY, 2, true),
/** Inclusive or: | */
INCLUSIVEOR("|");
private final String string;
private final OperationType operationType;
private final int precedence;
private final boolean leftAssociative;
/**
* Constructor. Sets the token specific string and the given keyword, it also specifies the precidence of an operator.
*
* @param string
* @param operationType
* @param precendence
*/
TokenType(String string, OperationType operationType, int precedence, boolean leftAssociative) {
this.string = string;
this.operationType = operationType;
this.precedence = precedence;
this.leftAssociative = leftAssociative;
}
/**
* Constructor. Sets the token specific string and the given keyword.
*
* @param string
* @param operationType
*/
TokenType(String string, OperationType operationType) {
this(string, operationType, -1, true);
}
/**
* Constructor. Sets the token specific string. Sets the keyword to false.
*
* @param string
*/
TokenType(String string) {
this(string, OperationType.UNDEFINED);
}
/**
* Returns the token specific string.
*
* @return
*/
public String getString() {
return string;
}
/**
* Return the type of an token.
*
* @return
*/
public OperationType getOperationType() {
return operationType;
}
/**
* Returns true if the token is a keyword. False otherwise.
*
* @return
*/
public boolean isKeyword() {
return operationType == OperationType.KEYWORD;
}
/**
* Returns the precedence of an token.
*
* @return
*/
public int getPrecedence() {
return precedence;
}
public boolean isLeftAssociative() {
return leftAssociative;
}
}
| true
|
013d3da82f92787b1c1782dc8ef2cbcc6acca957
|
Java
|
hmiguel/sigc
|
/src/main/java/lucene/Lucene.java
|
UTF-8
| 10,954
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package lucene;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopDocsCollector;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import data.DataReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
//import pt.uc.dei.ia.jena.TripleStoreReader;
import lucene.IndexBuilder;
import models.Article;
import models.Entity;
public class Lucene {
private static StandardAnalyzer analyzer;
private static File index;
public File getindexpath(){
return index;
}
public boolean CreateAutoCompleteIndexFromDic() {
File index = new File("C:/Users/hmiguel/workspace/index/autocomplete"); // index
if (index.isDirectory()) {
if (index.list().length > 0) {
// Index Directory must be empty!
return false;
}
}
try {
// INDEX WRITER CONFIG
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40,
analyzer);
// INDEX WRITER CONFIG
IndexWriter writer = new IndexWriter(FSDirectory.open(index), config);
// WORD DICIONARY READER
List<Entity> entities = data.DataReader.getEntities();
for (Entity entity : entities) {
IndexBuilder.addDocWords(writer, entity);
}
writer.close(); // Close Writer
} catch (Exception e) {
return false;
}
return true;
}
public static boolean CreateIndexFromData(File index) {
if (index.isDirectory()) {
if (index.list().length > 0) {
System.out.println("Index Directory must be empty!");
return false;
}
}
try {
// INDEX WRITER CONFIG
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40,
analyzer);
// INDEX WRITER CONFIG
IndexWriter w = new IndexWriter(FSDirectory.open(index), config);
// ARTICLES READER - SIGC READER
//List<Article> articles = TripleStoreReader.getArticles();
List<Article> articles = DataReader.getArticles();
// #ARTICLES
System.out.println("SIZE: " + articles.size());
// FOR EACH ARTICLE -> CREATE INDEX DOCUMENT
for (Article article : articles) {
IndexBuilder.addDoc(w, article);
}
w.close(); // Close Writer
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/* SUGESTED TERMS FUNCTION */
public JSONArray suggestTermsFor(String q) throws IOException, ParseException, JSONException {
File auto_index;
JSONArray array = new JSONArray();
if (System.getProperty("os.name").contains("Windows")){
auto_index = new File("C:/Users/hmiguel/workspace/index/autocomplete/");
}else{
auto_index = new File("/home/padsilva/Desktop/SIGC/index/autocomplete/"); //TODO
}
IndexReader autoCompleteReader = DirectoryReader.open(FSDirectory.open(auto_index)); // READ
IndexSearcher searcher = new IndexSearcher(autoCompleteReader);
Term t = new Term("entity", q);
SortField s = new SortField("count", SortField.Type.INT, true);
Sort sort = new Sort(s);
Query query = new PrefixQuery(t);
TopDocs docs = searcher.search(query, 5, sort);
for (ScoreDoc doc : docs.scoreDocs) {
String entity = autoCompleteReader.document(doc.doc).get("entity");
String type = autoCompleteReader.document(doc.doc).get("type");
/* filter types */
/*['money', 'percent', 'person', 'time', 'date', 'org', 'locals']*/
if(type.equals("org")) type = "Organization";
else if(type.equals("local")) type = "Local";
else if(type.equals("person")) type = "Person";
else if(type.equals("percent")) type = "Percent";
else if(type.equals("time")) type = "Time";
else if(type.equals("date")) type = "Date";
else if(type.equals("money")) type = "Money";
else type = "Unknow";
/* */
JSONObject item = new JSONObject();
item.put("entity", entity);
item.put("type", type);
array.put(item);
}
return array;
}
public JSONObject getArticle(String res) {
JSONObject results = new JSONObject();
// Create <Article> JsonArray
JSONArray data = new JSONArray();
try {
IndexReader reader = DirectoryReader.open(FSDirectory.open(index)); // READ
IndexSearcher searcher = new IndexSearcher(reader);
TermQuery query = new TermQuery(new Term("resource", res));
TopDocs topdocs = searcher.search(query, 1);
ScoreDoc[] hits = topdocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
JSONObject article = new JSONObject();
article.put("id", docId); // article Id
article.put("label", d.get("label")); // label
article.put("abstract", d.get("abstract")); // abstract
article.put("resource", d.get("resource")); // resource
article.put("description", d.get("description")); // description
article.put("pubdate", d.get("date")); // pub date
System.out.println(">>>" + d.get("description"));
// PRINT ALL FIELDS OF DOC
// d.getFields()
// TOPICS
JSONArray topics = new JSONArray();
IndexableField[] index_top = d.getFields("topic");
for (int j = 0; j < index_top.length; j++) {
topics.put(index_top[j].stringValue());
}
article.put("topics", topics);
// CATEGORIES
JSONArray cat = new JSONArray();
IndexableField[] index_cat = d.getFields("category");
for (int j = 0; j < index_cat.length; j++) {
cat.put(index_cat[j].stringValue());
}
article.put("categories", cat);
int index_d = data.length();
data.put(index_d, article); // Add Article to JsonArray
}
results.put("data", data); // Add JsonArray to Json Result
} catch (Exception e) {
return new JSONObject();
}
return results;
}
public JSONObject QuerySearch(String querystr, int page) {
JSONObject results = new JSONObject();
try {
// the "title" arg specifies the default field to use // when no
// field is explicitly specified in the query.
MultiFieldQueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_40,
new String[] {"label", "abstract"},
analyzer);
// SEARCH
int hitsPerPage = 9;
int pageOffset = 9;
IndexReader reader = DirectoryReader.open(FSDirectory.open(index)); // READ
IndexSearcher searcher = new IndexSearcher(reader);
// COLLECTOR
TopScoreDocCollector collector = TopScoreDocCollector.create(500,
true);
searcher.search(queryParser.parse(querystr), collector);
// SCORE DOCS
// TopDocs hits = collector.topDocs(maxReturn*page);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// BUILD RESPONSE
results.put("query", querystr); // Add Query to Json Result
results.put("hits", hits.length); // Add Hits to Json Result
// MEANING QUERY 1-WORD
if (querystr.split(" ").length < 2) {
results.put("mean", SpellCheck.Suggest(querystr)); // Add Mean
// to Json
// Result
} else {
results.put("mean", "");
}
// Create <Article> JsonArray
JSONArray data = new JSONArray();
// for each hit
for (int i = pageOffset * page; i < Math.min(hitsPerPage
* (page + 1), hits.length); i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
JSONObject article = new JSONObject();
article.put("id", docId); // article Id
article.put("label", d.get("label")); // label
article.put("abstract", d.get("abstract")); // abstract
article.put("resource", d.get("resource")); // resource
article.put("description", d.get("description")); // description
article.put("date", d.get("date")); // pub date
// PRINT ALL FIELDS OF DOC
// d.getFields()
// PEOPLE
JSONArray peo = new JSONArray();
IndexableField[] index_peo = d.getFields("person");
for (int j = 0; j < index_peo.length; j++) {
peo.put(index_peo[j].stringValue());
}
article.put("people", peo);
// ORGANIZATIONS
JSONArray org = new JSONArray();
IndexableField[] index_org = d.getFields("organization");
for (int j = 0; j < index_org.length; j++) {
org.put(index_org[j].stringValue());
}
article.put("organizations", org);
// LOCALS
JSONArray loc = new JSONArray();
IndexableField[] index_loc = d.getFields("local");
for (int j = 0; j < index_loc.length; j++) {
loc.put(index_loc[j].stringValue());
}
article.put("locals", loc);
// TOPICS
JSONArray topics = new JSONArray();
IndexableField[] index_top = d.getFields("topic");
for (int j = 0; j < index_top.length; j++) {
topics.put(index_top[j].stringValue());
}
article.put("topics", topics);
// CATEGORIES
JSONArray cat = new JSONArray();
IndexableField[] index_cat = d.getFields("category");
for (int j = 0; j < index_cat.length; j++) {
cat.put(index_cat[j].stringValue());
}
article.put("categories", cat);
int index_d = data.length();
data.put(index_d, article); // Add Article to JsonArray
}
results.put("data", data); // Add JsonArray to Json Result
reader.close();
} catch (Exception e) {
return new JSONObject();
}
return results;
}
public void init() {
// System.out.println("Lucene Starting...");
analyzer = new StandardAnalyzer(Version.LUCENE_40);
if (System.getProperty("os.name").contains("Windows")){
index = new File("C:/Users/hmiguel/workspace/index/");
}else{
index = new File("/home/padsilva/Desktop/SIGC/index/"); //TODO
}
}
public static void buildIndex() {
System.out.print("Creating Index...");
if (!CreateIndexFromData(index)) { // FIRST TIME
System.out.println("ERROR>>");
return;
} else {
System.out.println("OK");
}
}
public Lucene() {
init();
}
}
| true
|
e67d8a205fef0c02c47e3741831e733ad2c1aeb7
|
Java
|
WhiteSourceE/OppeInfo-SQLi-Flow-Simplified
|
/src/main/java/ee/hitsa/ois/web/dto/SubjectStudyPeriodSearchDto.java
|
UTF-8
| 3,567
| 1.914063
| 2
|
[] |
no_license
|
package ee.hitsa.ois.web.dto;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
public class SubjectStudyPeriodSearchDto {
private Long id;
private Long studentsNumber;
private Long hours;
private List<String> teachers;
private List<SubjectProgramResult> programs;
private AutocompleteResult subject;
private AutocompleteResult studyPeriod;
private Set<AutocompleteResult> midtermTasks;
private Boolean isPracticeSubject;
private Long moodleCourseId;
private Long subjectProgramId;
private String subjectProgramStatus;
private Integer subgroups;
private BigDecimal credits;
private String studentgroups;
private Boolean canEdit;
public Boolean getIsPracticeSubject() {
return isPracticeSubject;
}
public void setIsPracticeSubject(Boolean isPracticeSubject) {
this.isPracticeSubject = isPracticeSubject;
}
public Set<AutocompleteResult> getMidtermTasks() {
return midtermTasks;
}
public void setMidtermTasks(Set<AutocompleteResult> midtermTasks) {
this.midtermTasks = midtermTasks;
}
public Long getHours() {
return hours;
}
public void setHours(Long hours) {
this.hours = hours;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public AutocompleteResult getSubject() {
return subject;
}
public List<String> getTeachers() {
return teachers;
}
public void setTeachers(List<String> teachers) {
this.teachers = teachers;
}
public List<SubjectProgramResult> getPrograms() {
return programs;
}
public void setPrograms(List<SubjectProgramResult> programs) {
this.programs = programs;
}
public void setSubject(AutocompleteResult subject) {
this.subject = subject;
}
public AutocompleteResult getStudyPeriod() {
return studyPeriod;
}
public void setStudyPeriod(AutocompleteResult studyPeriod) {
this.studyPeriod = studyPeriod;
}
public Long getStudentsNumber() {
return studentsNumber;
}
public void setStudentsNumber(Long studentsNumber) {
this.studentsNumber = studentsNumber;
}
public Long getMoodleCourseId() {
return moodleCourseId;
}
public void setMoodleCourseId(Long moodleCourseId) {
this.moodleCourseId = moodleCourseId;
}
public Long getSubjectProgramId() {
return subjectProgramId;
}
public void setSubjectProgramId(Long subjectProgramId) {
this.subjectProgramId = subjectProgramId;
}
public String getSubjectProgramStatus() {
return subjectProgramStatus;
}
public void setSubjectProgramStatus(String subjectProgramStatus) {
this.subjectProgramStatus = subjectProgramStatus;
}
public Integer getSubgroups() {
return subgroups;
}
public void setSubgroups(Integer subgroups) {
this.subgroups = subgroups;
}
public BigDecimal getCredits() {
return credits;
}
public void setCredits(BigDecimal credits) {
this.credits = credits;
}
public Boolean getCanEdit() {
return canEdit;
}
public void setCanEdit(Boolean canEdit) {
this.canEdit = canEdit;
}
public String getStudentgroups() {
return studentgroups;
}
public void setStudentgroups(String studentgroups) {
this.studentgroups = studentgroups;
}
}
| true
|
9138eebfd68518923fc74331d8740988da49a4ba
|
Java
|
hyberbin/J-hibatis
|
/src/test/java/org/jplus/hibatis/PropertiesDaoTest.java
|
UTF-8
| 5,582
| 2.296875
| 2
|
[] |
no_license
|
/*
* Copyright 2015 www.hyberbin.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Email:hyberbin@qq.com
*/
package org.jplus.hibatis;
import org.jplus.contex.core.ObjectContext;
import org.jplus.hibatis.beans.Properties;
import org.jplus.hibatis.dao.PropertiesDao;
import org.jplus.hyb.database.config.ConfigCenter;
import org.jplus.hyb.database.config.DbConfig;
import org.jplus.hyb.database.config.SimpleConfigurator;
import org.jplus.hyb.database.sqlite.SqliteUtil;
import org.jplus.hyb.database.transaction.SimpleManager;
import org.jplus.hyb.log.LocalLogger;
import org.junit.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
*
* @author hyberbin
*/
public class PropertiesDaoTest {
private static PropertiesDao propertiesDao;
public PropertiesDaoTest() {
}
@BeforeClass
public static void setUpClass() {
SimpleConfigurator.addConfigurator(new DbConfig(DbConfig.DRIVER_SQLITE, "jdbc:sqlite:data.db", "", "", DbConfig.DEFAULT_CONFIG_NAME));
ConfigCenter.INSTANCE.setManager(new SimpleManager(DbConfig.DEFAULT_CONFIG_NAME));
LocalLogger.setLevel(LocalLogger.INFO);
HibatisInit.init();
propertiesDao = ObjectContext.CONTEXT.getResource(PropertiesDao.class);
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
tearDown();
SqliteUtil.setProperty("name", "hyb");
SqliteUtil.setProperty("age", "8");
}
@After
public void tearDown() {
SqliteUtil.clearProperties();
}
/**
* Test of getAllPropertis method, of class PropertiesDao.
*/
@Test
public void testGetAllPropertis() {
System.out.println("getAllPropertis");
List<Properties> result = propertiesDao.getAllPropertis();
assertEquals(result.size(), 2);
}
/**
* Test of getProperty method, of class PropertiesDao.
*/
@Test
public void testGetProperty() {
System.out.println("getProperty");
Map map = new HashMap();
map.put("key", "name");
Properties property = propertiesDao.getProperty(map);
assertEquals(property.getKey(), "name");
assertEquals(property.getValue(), "hyb");
}
/**
* Test of getPropertyByKey method, of class PropertiesDao.
*/
@Test
public void testGetPropertyByKey() {
System.out.println("getPropertyByKey");
String key = "name";
Properties property = propertiesDao.getPropertyByKey(key);
assertEquals(property.getKey(), "name");
assertEquals(property.getValue(), "hyb");
}
@Test
public void testSave(){
System.out.println("testSave");
Properties property = new Properties("site","http://www.hyberbin.com");
propertiesDao.save(property);
Properties site = propertiesDao.getPropertyByKey("site");
assertEquals(site.getKey(), "site");
assertEquals(site.getValue(), "http://www.hyberbin.com");
}
@Test
public void testSaveOrUpdate(){
System.out.println("testSaveOrUpdate");
Properties property = new Properties("site","http://www.hyberbin.com");
propertiesDao.save(property);
Properties update = new Properties("site","www.hyberbin.com");
propertiesDao.saveOrUpdate(update);
Properties site = propertiesDao.getPropertyByKey("site");
assertEquals(site.getKey(), "site");
assertEquals(site.getValue(), "www.hyberbin.com");
}
@Test
public void testGetByKey(){
System.out.println("testGetByKey");
Properties property =new Properties ("name",null);
propertiesDao.getByKey(property);
assertEquals(property.getKey(), "name");
assertEquals(property.getValue(), "hyb");
Properties property2 =new Properties (null,"hyb");
propertiesDao.getByKey(property2,"value");
assertEquals(property2.getKey(), "name");
assertEquals(property2.getValue(), "hyb");
}
@Test
public void testDeleteByKey(){
System.out.println("testDeleteByKey");
Properties property =new Properties ("name",null);
propertiesDao.deleteByKey(property);
List<Properties> allPropertis = propertiesDao.getAllPropertis();
assertEquals(allPropertis.size(), 1);
Properties property2 =new Properties (null,"8");
propertiesDao.deleteByKey(property2, "value");
List<Properties> allPropertis2 = propertiesDao.getAllPropertis();
assertEquals(allPropertis2.size(), 0);
}
@Test
public void testExecute(){
System.out.println("testExecute");
Integer count=propertiesDao.execute("delete from Properties where 1=2");
assertTrue(count==0);
Map map=new HashMap();
map.put("key",4);
Integer count2=propertiesDao.execute("delete from Properties where 1=$p.map.key",map);
assertTrue(count2==0);
}
}
| true
|
079ca642089de012d2c8280622b009c0129c4539
|
Java
|
miniPinocchio/MicrosoftClient
|
/app/src/main/java/com/microsoft/ui/activity/MainActivity.java
|
UTF-8
| 2,557
| 1.96875
| 2
|
[] |
no_license
|
package com.microsoft.ui.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.microsoft.base.BaseActivity;
import com.microsoft.bean.HostTab;
import com.microsoft.microsoftclient.R;
import com.microsoft.ui.fragment.MineFragment;
import com.microsoft.ui.fragment.TaskFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* 首页
*
* @author huiliu
*/
public class MainActivity extends BaseActivity {
@BindView(android.R.id.tabcontent)
FrameLayout mTabcontent;
@BindView(R.id.fl_main_content)
FrameLayout mFlMainContent;
@BindView(R.id.main_tabhost)
FragmentTabHost mMainTabhost;
private int[] mTitles = {R.string.earning, R.string.mine};
private int[] mImages = {
R.drawable.selector_task_img,
R.drawable.selector_mine_img
};
private List<HostTab> mTabs = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initView();
}
private void initView() {
LayoutInflater mInflater = LayoutInflater.from(this);
mMainTabhost.setup(this, getSupportFragmentManager(), R.id.fl_main_content);
mMainTabhost.getTabWidget().setDividerDrawable(null);
HostTab tabNome = new HostTab(mTitles[0], R.drawable.selector_task_img, TaskFragment.class);
HostTab tabAddress = new HostTab(mTitles[1], R.drawable.selector_mine_img, MineFragment.class);
mTabs.add(tabNome);
mTabs.add(tabAddress);
for (int i = 0; i < mTabs.size(); i++) {
View view = mInflater.inflate(R.layout.tab_item, null);
ImageView image = (ImageView) view.findViewById(R.id.image);
TextView title = (TextView) view.findViewById(R.id.title);
image.setImageResource(mImages[i]);
title.setText(mTitles[i]);
mMainTabhost.addTab(mMainTabhost.newTabSpec(getString(mTabs.get(i).getTitle())).setIndicator(view),
mTabs.get(i).getFragment(), null);
}
mMainTabhost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
mMainTabhost.setCurrentTab(0);
}
}
| true
|
c417174bb73725e18f25cb482e0793bb48bf12c4
|
Java
|
XLeanBiz/StartupData
|
/src/com/startupdata/client/topics/textTopics/EditTextIcon.java
|
UTF-8
| 955
| 1.898438
| 2
|
[] |
no_license
|
package com.startupdata.client.topics.textTopics;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.startupdata.client.MyCompanyPanel;
import com.startupdata.client.utilities.UseTracking;
public class EditTextIcon extends Anchor {
public EditTextIcon(final String topicID) {
this.setHTML("<a href=#><img src='"
+ GWT.getModuleBaseURL()
+ "startupstages/EditIcon.jpg' width='18px' height='18px' border=0></a>");
this.setSize("22px", "20px");
this.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
new UseTracking(
"com.startupdata.client.topics.edit.EditTextIcon");
MyCompanyPanel.vpStartupTopic.clear();
MyCompanyPanel.vpStartupTopic.add(new EditStartupDataTextTopic(
topicID));
}
});
}
}
| true
|
21c5f74602eaebe6d7c53c3c029da5e05097dadb
|
Java
|
sripadapavan/SimpleFlatMapper
|
/sfm/src/main/java/org/sfm/jdbc/impl/setter/FloatPreparedStatementIndexSetter.java
|
UTF-8
| 652
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
package org.sfm.jdbc.impl.setter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
public class FloatPreparedStatementIndexSetter implements PreparedStatementIndexSetter<Float> {
@Override
public void set(PreparedStatement target, Float value, int columnIndex) throws SQLException {
if (value != null) {
target.setFloat(columnIndex, value);
} else {
target.setNull(columnIndex, Types.FLOAT);
}
}
public void setFloat(PreparedStatement target, float value, int columnIndex) throws Exception {
target.setFloat(columnIndex, value);
}
}
| true
|
c07ca6b76f6e8b3f5ca952a411d0f30b311cdd66
|
Java
|
oleg-grigorijan/budgetgo
|
/src/main/java/com/godev/budgetgo/config/security/UserDetailsImpl.java
|
UTF-8
| 1,439
| 2.375
| 2
|
[] |
no_license
|
package com.godev.budgetgo.config.security;
import com.godev.budgetgo.domain.user.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.HashSet;
class UserDetailsImpl implements UserDetails {
private final String username;
private final String password;
private final Collection<GrantedAuthority> authorities = new HashSet<>();
UserDetailsImpl(User entity) {
username = entity.getLogin();
password = entity.getPasswordHash();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
if (entity.isAdmin()) authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| true
|
3ffd581c14a2cf95175151ec2ba191b62b0d9082
|
Java
|
Ybakman/BilSwap
|
/src/LastPanel.java
|
UTF-8
| 655
| 2.96875
| 3
|
[] |
no_license
|
/**
*@author: Yavuz Faruk Bakman
* @version: 24/12/2018
*/
import javax.swing.*;
import java.awt.*;
public class LastPanel extends JPanel
{
RequestPanel panel;
/**
* This constructor creates the last form of the make request panel by given user
* @param user
*/
public LastPanel(User user)
{
panel = new RequestPanel(user);
JLabel label = (new JLabel("COURSE YOU WANT TO OFFER COURSE YOU WANT TO TAKE"));
label.setFont(new Font("Serif", Font.PLAIN, 20));
label.setForeground(new Color(183,15,10));
add(label, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
}
| true
|
9bb83ae1f63e9093e4ac5b048407654eb0698388
|
Java
|
philosophicalintrovert/Beginner-Java-projects-lessons
|
/[First lesson] - Hello World/src/HelloWorld.java
|
UTF-8
| 262
| 3.078125
| 3
|
[] |
no_license
|
//This is a one-line comment.
/*
* This
* is
* a
* multi-line
* comment.
*/
public class HelloWorld {
public static void main(String[] args){ //Initiates the program
System.out.println("Hello World!"); //Prints out "Hello World!"
}
}
| true
|
e9c176705014e05d215ea4e45ed45c1080d76a75
|
Java
|
wasner/Td-POA
|
/TP5/src/politiquesEmprunt/AvantageStatut.java
|
UTF-8
| 987
| 2.53125
| 3
|
[] |
no_license
|
package politiquesEmprunt;
import emprunteurs.EmprunteurArgent;
import emprunteurs.EmprunteurBronze;
import emprunteurs.EmprunteurCarteLecture;
import emprunteurs.EmprunteurCarteMusique;
import emprunteurs.EmprunteurOr;
import emprunteurs.EmprunteurStandard;
public class AvantageStatut implements AvantageEmprunteur{
@Override
public int emprunter(EmprunteurArgent em) {
// TODO Auto-generated method stub
return 1;
}
@Override
public int emprunter(EmprunteurBronze em) {
// TODO Auto-generated method stub
return 2;
}
@Override
public int emprunter(EmprunteurCarteLecture em) {
// TODO Auto-generated method stub
return 3;
}
@Override
public int emprunter(EmprunteurCarteMusique em) {
// TODO Auto-generated method stub
return 4;
}
@Override
public int emprunter(EmprunteurOr em) {
// TODO Auto-generated method stub
return 5;
}
@Override
public int emprunter(EmprunteurStandard em) {
// TODO Auto-generated method stub
return 6;
}
}
| true
|
1480513d5bef77bc975c13f358c0a47e3dbdc885
|
Java
|
loloChan/rpc-demo
|
/src/main/java/cjy/rpc/demo/proxy/JDKInvocationHandler.java
|
UTF-8
| 1,662
| 2.765625
| 3
|
[] |
no_license
|
package cjy.rpc.demo.proxy;
import cjy.rpc.demo.netty.future.SyncWrite;
import cjy.rpc.demo.netty.msg.Request;
import cjy.rpc.demo.netty.msg.Response;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* 使用jdk动态代理生成服务接口的代理类
* 由代理类实现远程链接请求并获取结果
* 也就是说,在消费端,该类属于stub,用于网络连接调用。
* @author chenjianyuan
*/
public class JDKInvocationHandler implements InvocationHandler {
private Request request;
public JDKInvocationHandler(Request request) {
this.request = request;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
//toString、hashCode、equals方法不进行远程调用,无意义
if ("toString".equals(methodName) && parameterTypes.length == 0) {
return request.toString();
} else if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
return request.hashCode();
} else if ("equals".equals(methodName) && parameterTypes.length == 1) {
return request.equals(parameterTypes[0]);
}
//设置调用方法信息
request.setMethodName(methodName);
request.setParamTypes(parameterTypes);
request.setArgs(args);
//通过netty进行远程调用
SyncWrite syncWrite = SyncWrite.getInstance();
Response response = syncWrite.remoteInvoke(request, 1000);
return response;
}
}
| true
|
79b392c499112603e90326b62af79316a99f6d5b
|
Java
|
chenjunwei1993/yytx-app
|
/app/src/main/java/com/dyibing/myapp/bean/SubmitQuestionBean.java
|
UTF-8
| 468
| 2.09375
| 2
|
[] |
no_license
|
package com.dyibing.myapp.bean;
public class SubmitQuestionBean {
private int answerNum;
private String correctAnswer;
public int getAnswerNum() {
return answerNum;
}
public void setAnswerNum(int answerNum) {
this.answerNum = answerNum;
}
public String getCorrectAnswer() {
return correctAnswer;
}
public void setCorrectAnswer(String correctAnswer) {
this.correctAnswer = correctAnswer;
}
}
| true
|
9605a72b2a374a9309be006d4caf06dc3eb1e645
|
Java
|
Xmaoyh/TcTest
|
/app/src/main/java/com/example/maoyh/tctest/fragment/WuliuFragment.java
|
UTF-8
| 4,596
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.maoyh.tctest.fragment;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.example.maoyh.tctest.R;
import com.example.maoyh.tctest.until.AppUtils;
import com.example.maoyh.tctest.view.MyPopview;
/**
* Created by MAOYH on 2016/3/9.
*/
public class WuliuFragment extends Fragment {
private MapView mMapView;
private BaiduMap mBaiduMap;
// 有被点击过的marker
boolean checked;
// 已点过的marker
Marker previousMarker = null;
/**
* 需要传递参数时有利于解耦
*/
public static WuliuFragment newInstance() {
Bundle args = new Bundle();
WuliuFragment fragment = new WuliuFragment();
fragment.setArguments(args);
return fragment;
}
private Activity getMyActivity() {
Activity act = getActivity();
if (act == null) {
act = AppUtils.getActivity();
}
return act;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wuliu, null);
init(v);
return v;
}
private void init(final View v) {
mMapView = (MapView) v.findViewById(R.id.mbaidmap);
MapStatus ms = new MapStatus.Builder()
.target(new LatLng(30.2817240000, 119.9980410000)).zoom(8)
.build();
mBaiduMap = mMapView.getMap();
mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
for (int i = 0; i < 3; i++) {
addCar(new LatLng(30.2817240000 + Math.random(), 119.9980410000 + Math.random()), "notfull");
addCar(new LatLng(30.2817240000 + Math.random(), 119.9980410000 + Math.random()), "full");
}
mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
if (checked) {
switch ( previousMarker.getTitle()) {
case "t_full":
previousMarker.setIcon(BitmapDescriptorFactory
.fromResource(R.mipmap.car_full));
break;
case "t_notfull":
previousMarker.setIcon(BitmapDescriptorFactory
.fromResource(R.mipmap.car_notfull));
break;
}
checked = false;
}
marker.setIcon(BitmapDescriptorFactory
.fromResource(R.mipmap.car_set));
// 此marker已经点过,作为上一次点击的marker
checked = true;
previousMarker = marker;
showPopwindow(v);
return false;
}
});
}
private void showPopwindow(View parent) {
MyPopview myPopview = new MyPopview(getActivity());
myPopview.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
}
private void addCar(LatLng location, String state) {
// TODO Auto-generated method stub
switch (state) {
case "full":
OverlayOptions carfull = new MarkerOptions()
.title("t_full")
.position(location)
.icon(BitmapDescriptorFactory
.fromResource(R.mipmap.car_full));
mBaiduMap.addOverlay(carfull);
break;
case "notfull":
OverlayOptions carnotfull = new MarkerOptions()
.title("t_notfull")
.position(location)
.icon(BitmapDescriptorFactory
.fromResource(R.mipmap.car_notfull));
mBaiduMap.addOverlay(carnotfull);
break;
}
}
}
| true
|
26cba0a67188b50ec8ec53b287331f567519e6b4
|
Java
|
smith61/java-decompiler
|
/src/main/java/net/jsmith/java/byteforge/utils/IOUtils.java
|
UTF-8
| 1,314
| 2.890625
| 3
|
[] |
no_license
|
package net.jsmith.java.byteforge.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
public class IOUtils {
public static void safeClose( AutoCloseable c ) {
if( c != null ) {
try {
c.close( );
}
catch( Exception e ) { }
}
}
public static String readResourceAsString( String resourceName ) throws IOException{
return new String( IOUtils.readResource( resourceName ), Charset.forName( "UTF-8" ) );
}
public static byte[ ] readResource( String resourceName ) throws IOException {
InputStream is = null;
try {
is = IOUtils.class.getResourceAsStream( resourceName );
if( is == null ) {
throw new IOException( "Resource not found: " + resourceName );
}
return readFully( is );
}
finally {
IOUtils.safeClose( is );
}
}
public static byte[ ] readFully( InputStream is ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream( );
copyStream( is, baos );
return baos.toByteArray( );
}
public static void copyStream( InputStream is, OutputStream os ) throws IOException {
byte[ ] buffer = new byte[ 4096 ];
int read;
while( ( read = is.read( buffer ) ) >= 0 ) {
os.write( buffer, 0, read );
}
}
}
| true
|
d11409d8cdffb85e91fd72260c9b4b8cfd2b9798
|
Java
|
pingguosanjiantao/Elements-of-Programming-Interviews
|
/20-Parallel Computing/code/src/DeadLock.java
|
UTF-8
| 1,209
| 3.8125
| 4
|
[] |
no_license
|
/*
* 20.5
*/
public class DeadLock {
public static class Account {
private int balance;
private int id;
private static int globalId;
Account(int balance) {
this.balance = balance;
this.id = ++globalId;
}
// have a global ordering on locks and acquire them in that order
private boolean move(Account to, int amount) {
Account lock1 = id < to.id ? this : to;
Account lock2 = id < to.id ? to : this;
synchronized(lock1) {
synchronized(lock2) {
if (amount > balance) {
return false;
}
to.balance += amount;
this.balance -= amount;
System.out.println("returning true");
return true;
}
}
}
}
public static void transfer(final Account from, final Account to, final int amount) {
Thread transfer = new Thread(new Runnable() {
@Override
public void run() {
from.move(to, amount);
}
});
transfer.start();
}
}
| true
|
98b110e955f6f401a3e95e49e509d0604c9c2220
|
Java
|
christianfe/noleggio-veicoli-agensia
|
/src/main/java/it/univaq/disim/oop/bhertz/controller/MaintenanceController.java
|
UTF-8
| 8,435
| 2.078125
| 2
|
[] |
no_license
|
package it.univaq.disim.oop.bhertz.controller;
import java.net.URL;
import java.time.LocalDate;
import java.util.List;
import java.util.ResourceBundle;
import it.univaq.disim.oop.bhertz.business.BhertzBusinessFactory;
import it.univaq.disim.oop.bhertz.business.BusinessException;
import it.univaq.disim.oop.bhertz.business.ContractService;
import it.univaq.disim.oop.bhertz.business.MaintenanceService;
import it.univaq.disim.oop.bhertz.domain.AssistanceTicket;
import it.univaq.disim.oop.bhertz.domain.Contract;
import it.univaq.disim.oop.bhertz.domain.ContractState;
import it.univaq.disim.oop.bhertz.domain.TicketState;
import it.univaq.disim.oop.bhertz.domain.User;
import it.univaq.disim.oop.bhertz.domain.VeicleState;
import it.univaq.disim.oop.bhertz.view.ViewDispatcher;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
public class MaintenanceController extends ViewUtility implements Initializable, DataInitializable<User> {
@FXML
private Label titleLabel;
@FXML
private TableView<AssistanceTicket> maintenanceTable;
@FXML
private TableColumn<AssistanceTicket, String> userColumn;
@FXML
private TableColumn<AssistanceTicket, String> veicleColumn;
@FXML
private TableColumn<AssistanceTicket, String> stateColumn;
@FXML
private TableColumn<AssistanceTicket, MenuButton> actionColumn;
@FXML
private TableColumn<AssistanceTicket, String> substituteColumn;
private ViewDispatcher dispatcher;
private MaintenanceService maintenanceService;
private User user;
public MaintenanceController() {
dispatcher = ViewDispatcher.getInstance();
maintenanceService = BhertzBusinessFactory.getInstance().getMaintenanceService();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
userColumn.setCellValueFactory((CellDataFeatures<AssistanceTicket, String> param) -> {
return new SimpleStringProperty(param.getValue().getContract().getCustomer().getName());
});
veicleColumn.setCellValueFactory((CellDataFeatures<AssistanceTicket, String> param) -> {
return new SimpleStringProperty(param.getValue().getContract().getVeicle().getModel());
});
substituteColumn.setCellValueFactory((CellDataFeatures<AssistanceTicket, String> param) -> {
return new SimpleStringProperty(param.getValue().getSubstituteContract() == null ? "NO"
: param.getValue().getSubstituteContract().getVeicle().toString());
});
stateColumn.setCellValueFactory((CellDataFeatures<AssistanceTicket, String> param) -> {
String s = "";
switch (param.getValue().getState()) {
case REQUIRED:
s = "Richiesto";
break;
case WORKING:
s = "In Lavorazione";
break;
case READY:
s = "Pronto per il ritiro";
break;
case ENDED:
s = "Conclusa";
break;
}
return new SimpleStringProperty(s);
});
actionColumn.setStyle("-fx-alignment: CENTER;");
actionColumn.setCellValueFactory((CellDataFeatures<AssistanceTicket, MenuButton> param) -> {
MenuButton localMenuButton = new MenuButton("Menu");
MenuItem menuChangeStatus = new MenuItem();
MenuItem menuAppointment = new MenuItem("Fissa appuntamento ritiro");
MenuItem menuDetails = new MenuItem("Visualizza Dettagli");
MenuItem menuFixed = new MenuItem("Conferma veicolo aggiustato");
localMenuButton.getItems().add(menuDetails);
if (this.user.getRole() == 1) {
param.getValue().getContract().setAssistance(param.getValue());
switch (param.getValue().getState()) {
case REQUIRED:
if (param.getValue().getTimeStart() != null) {
menuAppointment.setText("Appuntamento: " + param.getValue().getStartDate() + " "
+ param.getValue().getTimeStart());
menuAppointment.setDisable(true);
menuChangeStatus.setText("Ritira Veicolo");
localMenuButton.getItems().add(menuChangeStatus);
}
localMenuButton.getItems().add(menuAppointment);
break;
case WORKING:
menuChangeStatus.setText("Seleziona Veicolo Sostitutivo");
if (param.getValue().getSubstituteContract() != null)
menuChangeStatus.setDisable(true);
localMenuButton.getItems().add(menuChangeStatus);
localMenuButton.getItems().add(menuFixed);
break;
case READY:
if (param.getValue().getEndDate() == null)
menuAppointment.setText("Fissa Appuntamento");
else {
menuAppointment.setText("Appuntamento: " + param.getValue().getEndDate() + " "
+ param.getValue().getTimeEnd());
menuAppointment.setDisable(true);
menuChangeStatus.setText("Riconsegna veicolo al cliente");
localMenuButton.getItems().add(menuChangeStatus);
}
localMenuButton.getItems().add(menuAppointment);
break;
case ENDED:
break;
}
} else if (this.user.getRole() == 2) {
userColumn.setVisible(false);
actionColumn.setVisible(false);
}
menuChangeStatus.setOnAction((ActionEvent event) -> {
switch (param.getValue().getState()) {
case REQUIRED:
dispatcher.renderView("maintenanceReturn",
new ObjectsCollector<User, AssistanceTicket>(user, param.getValue()));
break;
case WORKING:
dispatcher.renderView("maintenanceManagement",
new ObjectsCollector<User, AssistanceTicket>(user, param.getValue()));
break;
case READY:
AssistanceTicket t = param.getValue();
t.setState(TicketState.ENDED);
try {
maintenanceService.setTicket(t);
} catch (BusinessException e) {
dispatcher.renderError(e);
}
if (param.getValue().getSubstituteContract() == null) {
param.getValue().getContract().getVeicle().setState(VeicleState.BUSY);
dispatcher.renderView("changeContractState",
new ObjectsCollector<User, Contract>(user, param.getValue().getContract()));
} else
dispatcher.renderView("changeContractState", new ObjectsCollector<User, Contract>(user,
param.getValue().getSubstituteContract()));
break;
case ENDED:
}
});
menuFixed.setOnAction((ActionEvent event) -> {
AssistanceTicket t = param.getValue();
if (param.getValue().getSubstituteContract() != null) {
Contract c = t.getContract();
t.setState(TicketState.ENDED);
t.setEndDate(LocalDate.now());
t.setTimeEnd("");
c.setEndKm(t.getVeicleKm());
c.setState(ContractState.ENDED);
c.setEnd(t.getSubstituteContract().getStart());
try {
ContractService contractService = BhertzBusinessFactory.getInstance().getContractService();
contractService.setContract(c);
} catch (BusinessException e) {
dispatcher.renderError(e);
}
} else
t.setState(TicketState.READY);
try {
maintenanceService.setTicket(t);
} catch (BusinessException e) {
dispatcher.renderError(e);
}
dispatcher.renderView("maintenance", user);
});
menuAppointment.setOnAction((ActionEvent event) -> {
dispatcher.renderView("appointmentManager",
new ObjectsCollector<User, Contract>(user, param.getValue().getContract()));
});
menuDetails.setOnAction((ActionEvent event) -> {
dispatcher.renderView("maintenanceDetails",
new ObjectsCollector<User, AssistanceTicket>(this.user, param.getValue()));
});
return new SimpleObjectProperty<MenuButton>(localMenuButton);
});
}
@Override
public void initializeData(User user) {
this.user = user;
try {
List<AssistanceTicket> tickets = (user.getRole() == 2 ? maintenanceService.getTicketByUser(user)
: maintenanceService.getAllTickets());
ObservableList<AssistanceTicket> ticketsData = FXCollections.observableArrayList(tickets);
maintenanceTable.setItems(ticketsData);
} catch (BusinessException e) {
dispatcher.renderError(e);
}
}
}
| true
|
73128476cfd4d92a6e4fb783822ef288677a94c9
|
Java
|
UKHomeOffice/pttg-ip-api
|
/src/test/java/uk/gov/digital/ho/proving/income/validator/IncomeValidationServiceTest.java
|
UTF-8
| 8,969
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package uk.gov.digital.ho.proving.income.validator;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import uk.gov.digital.ho.proving.income.api.domain.CategoryCheck;
import uk.gov.digital.ho.proving.income.api.domain.CheckedIndividual;
import uk.gov.digital.ho.proving.income.validator.domain.IncomeValidationRequest;
import uk.gov.digital.ho.proving.income.validator.domain.IncomeValidationResult;
import uk.gov.digital.ho.proving.income.validator.domain.IncomeValidationStatus;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static uk.gov.digital.ho.proving.income.validator.domain.IncomeValidationStatus.CATB_NON_SALARIED_PASSED;
import static uk.gov.digital.ho.proving.income.validator.domain.IncomeValidationStatus.MONTHLY_SALARIED_PASSED;
@RunWith(MockitoJUnitRunner.class)
public class IncomeValidationServiceTest {
private IncomeValidationService incomeValidationService;
@Mock
private CatASalariedIncomeValidator catASalariedIncomeValidator;
@Mock
private CatBNonSalariedIncomeValidator catBNonSalariedIncomeValidator;
@Before
public void setUp() {
incomeValidationService = new IncomeValidationService(newArrayList(catASalariedIncomeValidator, catBNonSalariedIncomeValidator));
}
@Test
public void thatAllValidatorsAreCalled() {
IncomeValidationResult catAResult = getResult(MONTHLY_SALARIED_PASSED, "A");
IncomeValidationResult catBResult = getResult(CATB_NON_SALARIED_PASSED, "B");
when(catASalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catAResult);
when(catBNonSalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catBResult);
IncomeValidationRequest request = new IncomeValidationRequest(new ArrayList<>(), LocalDate.now(), 0);
incomeValidationService.validate(request);
verify(catASalariedIncomeValidator).validate(request);
verify(catBNonSalariedIncomeValidator).validate(request);
}
@Test
public void thatCategoryIsReturned() {
IncomeValidationResult catAResult = getResult(MONTHLY_SALARIED_PASSED, "A");
IncomeValidationResult catBResult = getResult(CATB_NON_SALARIED_PASSED, "B");
when(catASalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catAResult);
when(catBNonSalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catBResult);
IncomeValidationRequest request = new IncomeValidationRequest(new ArrayList<>(), LocalDate.now(), 0);
List<CategoryCheck> categoryChecks = incomeValidationService.validate(request);
assertThat(categoryChecks.size()).isEqualTo(2).withFailMessage("All validators should return a category check");
assertThat(categoryChecks.get(0).category()).isEqualTo("A").withFailMessage("The category A check should return category 'A'");
assertThat(categoryChecks.get(1).category()).isEqualTo("B").withFailMessage("The category B check should return category 'B'");
}
@Test
public void thatDatesAreReturned() {
final LocalDate assessmentStartDate = LocalDate.now().minusDays(2);
final LocalDate applicationRaisedDate = LocalDate.now().minusDays(1);
IncomeValidationResult catAResult = getResultWithStartDate(MONTHLY_SALARIED_PASSED, "A", assessmentStartDate);
IncomeValidationResult catBResult = getResultWithStartDate(CATB_NON_SALARIED_PASSED, "B", assessmentStartDate);
when(catASalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catAResult);
when(catBNonSalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catBResult);
IncomeValidationRequest request = new IncomeValidationRequest(new ArrayList<>(), applicationRaisedDate, 0);
List<CategoryCheck> categoryChecks = incomeValidationService.validate(request);
assertThat(categoryChecks.get(0).assessmentStartDate()).isEqualTo(assessmentStartDate)
.withFailMessage("The category A check should have correct assessment start date");
assertThat(categoryChecks.get(1).assessmentStartDate()).isEqualTo(assessmentStartDate)
.withFailMessage("The category B check should have correct assessment start date");
assertThat(categoryChecks.get(0).applicationRaisedDate()).isEqualTo(applicationRaisedDate)
.withFailMessage("The category A check should have correct application raised date");
assertThat(categoryChecks.get(1).applicationRaisedDate()).isEqualTo(applicationRaisedDate)
.withFailMessage("The category B check should have correct application raised date");
}
@Test
public void thatValidationResultsAreReturned() {
CheckedIndividual checkedIndividual = new CheckedIndividual("NINO", ImmutableList.of("Employer1", "Employer2"));
IncomeValidationResult catAResult = getResultWithIndividual(MONTHLY_SALARIED_PASSED, "A",checkedIndividual);
IncomeValidationResult catBResult = getResultWithIndividual(CATB_NON_SALARIED_PASSED, "B", checkedIndividual);
when(catASalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catAResult);
when(catBNonSalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catBResult);
IncomeValidationRequest request = new IncomeValidationRequest(new ArrayList<>(), LocalDate.now(), 0);
List<CategoryCheck> categoryChecks = incomeValidationService.validate(request);
assertThat(categoryChecks.get(0).failureReason()).isEqualTo(MONTHLY_SALARIED_PASSED)
.withFailMessage("The validation status should be as returned from the validator");
assertThat(categoryChecks.get(0).threshold()).isEqualTo(BigDecimal.TEN)
.withFailMessage("The threshold should be as returned from the validator");
assertThat(categoryChecks.get(0).individuals().get(0).employers()).contains("Employer1").contains("Employer2")
.withFailMessage("The employers should be as returned from the validator");
}
@Test
public void thatEmploymentCheckPassIsOverriddenByCategoryBNonSalariedCheck() {
IncomeValidationResult catAResult = getResult(MONTHLY_SALARIED_PASSED, "A");
IncomeValidationResult catBResult = getResult(CATB_NON_SALARIED_PASSED, "B");
when(catASalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catAResult);
when(catBNonSalariedIncomeValidator.validate(any(IncomeValidationRequest.class))).thenReturn(catBResult);
IncomeValidationRequest request = new IncomeValidationRequest(new ArrayList<>(), LocalDate.now(), 0);
List<CategoryCheck> categoryChecks = incomeValidationService.validate(request);
assertThat(categoryChecks.get(1).passed()).isTrue()
.withFailMessage("The category B check should fail if the employment check fails");
assertThat(categoryChecks.get(1).failureReason()).isEqualTo(CATB_NON_SALARIED_PASSED)
.withFailMessage("The category B check should indicate employment check failed");
}
private IncomeValidationResult getResult(IncomeValidationStatus status, String category) {
return IncomeValidationResult.builder()
.status(status)
.threshold(BigDecimal.TEN)
.individuals(new ArrayList<>())
.assessmentStartDate(LocalDate.now())
.category(category)
.calculationType("Calc type")
.build();
}
private IncomeValidationResult getResultWithStartDate(IncomeValidationStatus status, String category, LocalDate assessmentStartDate) {
return IncomeValidationResult.builder()
.status(status)
.threshold(BigDecimal.TEN)
.individuals(new ArrayList<>())
.assessmentStartDate(assessmentStartDate)
.category(category)
.calculationType("Calc type")
.build();
}
private IncomeValidationResult getResultWithIndividual(IncomeValidationStatus status, String category, CheckedIndividual checkedIndividual) {
return IncomeValidationResult.builder()
.status(status)
.threshold(BigDecimal.TEN)
.individuals(ImmutableList.of(checkedIndividual))
.assessmentStartDate(LocalDate.now())
.category(category)
.calculationType("Calc type")
.build();
}
}
| true
|
25bff9ec3adb3c8165ea5d64cda21b6c98cc95d2
|
Java
|
black-ant/case
|
/case Other Spring/case remote/server/src/main/java/com/gang/sping/remote/demo/service/TestService.java
|
UTF-8
| 317
| 1.703125
| 2
|
[] |
no_license
|
package com.gang.sping.remote.demo.service;
import org.springframework.stereotype.Service;
/**
* @Classname TestService
* @Description TODO
* @Date 2020/10/31 17:08
* @Created by zengzg
*/
@Service
public class TestService implements ITestService {
public String get() {
return "success";
}
}
| true
|
21c0eff5ae66261e04135dafbcdce6f4089e50c0
|
Java
|
kishangabani/N-Queen-Problem
|
/N_Queen_Project_Code/src/project/Queen.java
|
UTF-8
| 1,140
| 2.96875
| 3
|
[] |
no_license
|
package project;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
public class Queen extends JFrame {
private final Container mainContainer;
private final NQueen nq;
private final ButtonPanel bp;
protected static boolean solution;
Queen(int n) {
super("NQUEEN");
System.out.println("Solution " + solution);
if (solution) {
nq = new NQueen(n, true, this);
} else {
nq = new NQueen(n, false, this);
}
bp = new ButtonPanel(this);
setSize(500, 545);
mainContainer = getContentPane();
mainContainer.add(nq, BorderLayout.CENTER);
mainContainer.add(bp, BorderLayout.SOUTH);
this.setResizable(false);
}
public static void main(String arg[]) {
ncall(0);
}
public static void ncall(int n) {
System.out.println("Call " + solution);
Queen q = new Queen(n);
q.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
q.show();
}
// Image's link
//https://upload.wikimedia.org/wikipedia/commons/4/47/Chess_qdt45.svg
}
| true
|
18b111765dec01ac50ac31c9317056267e0cc12e
|
Java
|
aoke79/property
|
/src/com/sms/training/qualification/business/ITfQualPilotDocumentsBS.java
|
UTF-8
| 393
| 1.601563
| 2
|
[] |
no_license
|
package com.sms.training.qualification.business;
import java.util.List;
import com.sinoframe.business.IService;
import com.sms.training.qualification.bean.TfQualPilotDocuments;
public interface ITfQualPilotDocumentsBS extends IService{
int findDocumentsByDetailId(String detailsid, String userid);
List<TfQualPilotDocuments> findDocumentsByDetailId(String detailsid);
}
| true
|
e2dd698175c8ee110475eb0edb9fec70386b0dd0
|
Java
|
ven2day/online_stock_pro
|
/src/main/java/com/online/stock/services/impl/SystemVarService.java
|
UTF-8
| 1,645
| 2.171875
| 2
|
[] |
no_license
|
package com.online.stock.services.impl;
import com.online.stock.dto.SysGroup;
import com.online.stock.dto.request.SystemVarAddReq;
import com.online.stock.dto.response.SystemVarRes;
import com.online.stock.model.SysVar;
import com.online.stock.repository.SysVarRepository;
import com.online.stock.services.ISystemVarService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SystemVarService implements ISystemVarService {
@Autowired
private SysVarRepository sysVarRepository;
@Override
public List<SysVar> getListSysVar() {
List<SysVar> sysVarList = sysVarRepository.findAll();
return sysVarList;
}
@Override
public void addSysVar(SystemVarAddReq req) {
SysVar sysVar = new SysVar();
BeanUtils.copyProperties(req, sysVar);
sysVar.setGrname(req.getGrname().name());
sysVarRepository.save(sysVar);
}
@Override
public void updateSysVar(SystemVarAddReq req) {
SysVar sysVar = sysVarRepository.findFirstByGrnameAndVarname(req.getGrname().name(),
req.getVarname());
if (sysVar != null) {
BeanUtils.copyProperties(req, sysVar);
sysVarRepository.save(sysVar);
}
}
@Override
public void deleteSysVar(String sysGroup, String varName) {
SysVar sysVar = sysVarRepository.findFirstByGrnameAndVarname(sysGroup,
varName);
if (sysVar != null) {
sysVarRepository.delete(sysVar);
}
}
}
| true
|
58b783f993e6b0a217a64e59107501e94c92552f
|
Java
|
abhijeeth-accolite/assignments
|
/Assignment-22-01_(DesignPrinciples)/designPrinciples/src/main/java/com/abstractFactory/MammalFactory.java
|
UTF-8
| 145
| 2.453125
| 2
|
[] |
no_license
|
package com.abstractFactory;
public class MammalFactory extends AbstractFactory{
@Override
Animal getAnimal() {
return new Mammal();
}
}
| true
|
b8f679a8d119deef5707e5c08e8d5710fe1e3696
|
Java
|
souky/SVN
|
/shieldSystem_v1.0.0.5/src/main/java/com/jy/protocol/common/utils/GeneralProtocol.java
|
UTF-8
| 2,145
| 2.3125
| 2
|
[] |
no_license
|
package com.jy.protocol.common.utils;
import com.jy.moudles.device.entity.Device;
import com.jy.protocol.common.constant.DeviceVender;
import com.jy.protocol.jf.utils.IssuedSendUtils;
import org.apache.commons.lang3.StringUtils;
/**
* Create by wb
* TIME: 2018/1/29 10:24
* 发送协议通用接口,根据设备中的厂家选择调用对应的协议
**/
public class GeneralProtocol {
/**
* 发送屏蔽
* @param device
* @param operationType 控制模块
*/
public static void sendShieldCommand(Device device, String operationType){
////ip不为空,且状态在线
if(device != null && StringUtils.isNotBlank(device.getIp()) && device.getStatus() == 1){
if(DeviceVender.JF.equalsIgnoreCase(device.getVender())){
//0:未知、1:自动、2:手动-全部、3:手动---1G、4:手动---手机、5:手动---未选
if("1".equals(operationType) || "2".equals(operationType)){
IssuedSendUtils.shieldControllerBase(1, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
IssuedSendUtils.shieldControllerPhone(1, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
}else if("3".equals(operationType)){
IssuedSendUtils.shieldControllerBase(1, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
IssuedSendUtils.shieldControllerPhone(0, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
}else if("4".equals(operationType)){
IssuedSendUtils.shieldControllerBase(0, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
IssuedSendUtils.shieldControllerPhone(1, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
}else{
IssuedSendUtils.shieldControllerBase(0, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
IssuedSendUtils.shieldControllerPhone(0, device.getIp(), IssuedSendUtils.SHIELD_UDP_PORT);
}
}
if(DeviceVender.JY.equalsIgnoreCase(device.getVender())){
//
}
}
}
}
| true
|
d997e7db2aa09f24724d601edd31afe261e9bc8a
|
Java
|
usnistgov/fhir.emf
|
/gen/main/java/org/hl7/fhir/CompositionEvent.java
|
UTF-8
| 3,899
| 2.078125
| 2
|
[] |
no_license
|
/**
*/
package org.hl7.fhir;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Composition Event</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* A set of healthcare-related information that is assembled together into a single logical document that provides a single coherent statement of meaning, establishes its own context and that has clinical attestation with regard to who is making the statement. While a Composition defines the structure, it does not actually contain the content: rather the full content of a document is contained in a Bundle, of which the Composition is the first resource contained.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.hl7.fhir.CompositionEvent#getCode <em>Code</em>}</li>
* <li>{@link org.hl7.fhir.CompositionEvent#getPeriod <em>Period</em>}</li>
* <li>{@link org.hl7.fhir.CompositionEvent#getDetail <em>Detail</em>}</li>
* </ul>
*
* @see org.hl7.fhir.FhirPackage#getCompositionEvent()
* @model extendedMetaData="name='Composition.Event' kind='elementOnly'"
* @generated
*/
public interface CompositionEvent extends BackboneElement {
/**
* Returns the value of the '<em><b>Code</b></em>' containment reference list.
* The list contents are of type {@link org.hl7.fhir.CodeableConcept}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* This list of codes represents the main clinical acts, such as a colonoscopy or an appendectomy, being documented. In some cases, the event is inherent in the typeCode, such as a "History and Physical Report" in which the procedure being documented is necessarily a "History and Physical" act.
* <!-- end-model-doc -->
* @return the value of the '<em>Code</em>' containment reference list.
* @see org.hl7.fhir.FhirPackage#getCompositionEvent_Code()
* @model containment="true"
* extendedMetaData="kind='element' name='code' namespace='##targetNamespace'"
* @generated
*/
EList<CodeableConcept> getCode();
/**
* Returns the value of the '<em><b>Period</b></em>' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The period of time covered by the documentation. There is no assertion that the documentation is a complete representation for this period, only that it documents events during this time.
* <!-- end-model-doc -->
* @return the value of the '<em>Period</em>' containment reference.
* @see #setPeriod(Period)
* @see org.hl7.fhir.FhirPackage#getCompositionEvent_Period()
* @model containment="true"
* extendedMetaData="kind='element' name='period' namespace='##targetNamespace'"
* @generated
*/
Period getPeriod();
/**
* Sets the value of the '{@link org.hl7.fhir.CompositionEvent#getPeriod <em>Period</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Period</em>' containment reference.
* @see #getPeriod()
* @generated
*/
void setPeriod(Period value);
/**
* Returns the value of the '<em><b>Detail</b></em>' containment reference list.
* The list contents are of type {@link org.hl7.fhir.Reference}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The description and/or reference of the event(s) being documented. For example, this could be used to document such a colonoscopy or an appendectomy.
* <!-- end-model-doc -->
* @return the value of the '<em>Detail</em>' containment reference list.
* @see org.hl7.fhir.FhirPackage#getCompositionEvent_Detail()
* @model containment="true"
* extendedMetaData="kind='element' name='detail' namespace='##targetNamespace'"
* @generated
*/
EList<Reference> getDetail();
} // CompositionEvent
| true
|
58d320feca2866c593483369533f184573ed339a
|
Java
|
OpenNTF/org.openntf.domino
|
/domino/core/src/main/java/org/openntf/domino/nsfdata/structs/cd/BasicCDRecord.java
|
UTF-8
| 1,220
| 2.140625
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"ICU",
"MIT",
"BSD-2-Clause"
] |
permissive
|
/**
* Copyright © 2013-2021 The OpenNTF Domino API Team
*
* 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.openntf.domino.nsfdata.structs.cd;
import java.nio.ByteBuffer;
import org.openntf.domino.nsfdata.structs.SIG;
public class BasicCDRecord extends CDRecord {
private static final long serialVersionUID = 1L;
private SIG header_;
protected BasicCDRecord(final SIG header, final ByteBuffer data) {
header_ = header;
}
@Override
public SIG getHeader() {
return header_;
}
@Override
public String toString() {
return "[" + getClass().getSimpleName() + ": Signature=" + getHeader() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
| true
|
65d5bf3d4cd27fd51da345e2b2ede650252f2cf0
|
Java
|
SeyithanDilek/SpringCore-Examples
|
/src/value/JDBCConnection.java
|
UTF-8
| 974
| 2.71875
| 3
|
[] |
no_license
|
package value;
import java.sql.Connection;
import java.sql.DriverManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:resources/db.properties")
public class JDBCConnection {
@Value("${mysql.url}")
private String url;
@Value("${mysql.userName}")
private String userName;
@Value("${mysql.password}")
private String password;
@Value("${mysql.driver}")
private String driver;
public void features() {
System.out.println("SQL URL: "+url);
System.out.println("SQL User Name: "+userName);
System.out.println("SQL Password: "+password);
System.out.println("SQL Driver: "+driver);
}
public void getJDBCConnection() throws Exception {
Class.forName(driver);
Connection con=DriverManager.getConnection(url,userName,password);
System.out.println("connection sucesfful : " +con );
}
}
| true
|
83d311269ce7a0998b506eda5c22b11081d45225
|
Java
|
nithinkrishnapullivarthi/greet-share-meet
|
/backend/generated/open-api/src/main/java/com/seproject/meetgreetapp/StudentDetailResponseDTO.java
|
UTF-8
| 6,754
| 1.976563
| 2
|
[] |
no_license
|
package com.seproject.meetgreetapp;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.seproject.meetgreetapp.Interest;
import com.seproject.meetgreetapp.VolunteerInterest;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.openapitools.jackson.nullable.JsonNullable;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* StudentDetailResponseDTO
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2021-04-09T16:11:35.968987-05:00[America/Chicago]")
public class StudentDetailResponseDTO {
@JsonProperty("id")
private Integer id;
@JsonProperty("name")
private String name;
@JsonProperty("department")
private String department;
@JsonProperty("email")
private String email;
@JsonProperty("is_volunteer")
private Boolean isVolunteer;
@JsonProperty("contact")
private String contact;
@JsonProperty("interests")
@Valid
private List<Interest> interests = null;
@JsonProperty("volunteer_interests")
@Valid
private List<VolunteerInterest> volunteerInterests = null;
public StudentDetailResponseDTO id(Integer id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
*/
@ApiModelProperty(value = "")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public StudentDetailResponseDTO name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
*/
@ApiModelProperty(value = "")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public StudentDetailResponseDTO department(String department) {
this.department = department;
return this;
}
/**
* Get department
* @return department
*/
@ApiModelProperty(value = "")
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public StudentDetailResponseDTO email(String email) {
this.email = email;
return this;
}
/**
* Get email
* @return email
*/
@ApiModelProperty(value = "")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public StudentDetailResponseDTO isVolunteer(Boolean isVolunteer) {
this.isVolunteer = isVolunteer;
return this;
}
/**
* Get isVolunteer
* @return isVolunteer
*/
@ApiModelProperty(value = "")
public Boolean getIsVolunteer() {
return isVolunteer;
}
public void setIsVolunteer(Boolean isVolunteer) {
this.isVolunteer = isVolunteer;
}
public StudentDetailResponseDTO contact(String contact) {
this.contact = contact;
return this;
}
/**
* Get contact
* @return contact
*/
@ApiModelProperty(value = "")
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public StudentDetailResponseDTO interests(List<Interest> interests) {
this.interests = interests;
return this;
}
public StudentDetailResponseDTO addInterestsItem(Interest interestsItem) {
if (this.interests == null) {
this.interests = new ArrayList<>();
}
this.interests.add(interestsItem);
return this;
}
/**
* Get interests
* @return interests
*/
@ApiModelProperty(value = "")
@Valid
public List<Interest> getInterests() {
return interests;
}
public void setInterests(List<Interest> interests) {
this.interests = interests;
}
public StudentDetailResponseDTO volunteerInterests(List<VolunteerInterest> volunteerInterests) {
this.volunteerInterests = volunteerInterests;
return this;
}
public StudentDetailResponseDTO addVolunteerInterestsItem(VolunteerInterest volunteerInterestsItem) {
if (this.volunteerInterests == null) {
this.volunteerInterests = new ArrayList<>();
}
this.volunteerInterests.add(volunteerInterestsItem);
return this;
}
/**
* Get volunteerInterests
* @return volunteerInterests
*/
@ApiModelProperty(value = "")
@Valid
public List<VolunteerInterest> getVolunteerInterests() {
return volunteerInterests;
}
public void setVolunteerInterests(List<VolunteerInterest> volunteerInterests) {
this.volunteerInterests = volunteerInterests;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StudentDetailResponseDTO studentDetailResponseDTO = (StudentDetailResponseDTO) o;
return Objects.equals(this.id, studentDetailResponseDTO.id) &&
Objects.equals(this.name, studentDetailResponseDTO.name) &&
Objects.equals(this.department, studentDetailResponseDTO.department) &&
Objects.equals(this.email, studentDetailResponseDTO.email) &&
Objects.equals(this.isVolunteer, studentDetailResponseDTO.isVolunteer) &&
Objects.equals(this.contact, studentDetailResponseDTO.contact) &&
Objects.equals(this.interests, studentDetailResponseDTO.interests) &&
Objects.equals(this.volunteerInterests, studentDetailResponseDTO.volunteerInterests);
}
@Override
public int hashCode() {
return Objects.hash(id, name, department, email, isVolunteer, contact, interests, volunteerInterests);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class StudentDetailResponseDTO {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" department: ").append(toIndentedString(department)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" isVolunteer: ").append(toIndentedString(isVolunteer)).append("\n");
sb.append(" contact: ").append(toIndentedString(contact)).append("\n");
sb.append(" interests: ").append(toIndentedString(interests)).append("\n");
sb.append(" volunteerInterests: ").append(toIndentedString(volunteerInterests)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| true
|
f9b5416271dd068f31009cfe224abe988c81ce2f
|
Java
|
alish2001/MarKey
|
/src/supply/exige/markey/entries/MarkEntry.java
|
UTF-8
| 1,630
| 2.859375
| 3
|
[] |
no_license
|
package supply.exige.markey.entries;
public class MarkEntry {
private String name;
private double vouchers;
private double achieved, max;
private double weightFactor;
private Category category;
public MarkEntry(String name, String actualMark, double weightFactor, Category category) {
this.name = name;
String[] tokenizer = actualMark.split("/");
this.achieved = Double.parseDouble(tokenizer[0]);
this.max = Double.parseDouble(tokenizer[1]);
this.weightFactor = weightFactor;
this.category = category;
}
public void addVoucher() {
this.vouchers += 0.5;
}
public void setVouchers(double vouchers) {
this.vouchers = vouchers;
}
public double getVouchers() {
return vouchers;
}
public void setAchieved(double achieved) {
this.achieved = achieved;
}
public String getName() {
return name;
}
public String getActualMark() {
return achieved + "/" + max;
}
public double getAchieved() {
return achieved;
}
public double getMax() {
return max;
}
public double getPercentage() {
return achieved / max * 100;
}
public double getEScore() {
if (max - achieved == 0) return 0;
return (1 - ((achieved + vouchers) / max)) * weightFactor;
}
public double getWeightFactor() {
return weightFactor;
}
public void setWeightFactor(double weightFactor) {
this.weightFactor = weightFactor;
}
public Category getCategory() {
return category;
}
}
| true
|
a33ab496d4616cadd4ece688c108b5192d3b8395
|
Java
|
arminha/davesgame
|
/domain/src/test/java/arminha/davesgame/domain/BoardTest.java
|
UTF-8
| 2,370
| 2.921875
| 3
|
[] |
no_license
|
package arminha.davesgame.domain;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class BoardTest {
private Board board;
@Before
public void setup() {
board = new Board();
}
@Test
public void emptyBoardHasNoWinner() throws Exception {
assertFalse(board.hasWinner());
}
@Test
public void simpleHorizontalWinningBoard() throws Exception {
board.put(new Stone(0), 0, 0);
board.put(new Stone(1), 0, 1);
board.put(new Stone(2), 0, 2);
board.put(new Stone(3), 0, 3);
assertTrue(board.hasWinner());
}
@Test
public void horizontalFlatWinningBoard() throws Exception {
board.put(new Stone(8), 1, 0);
board.put(new Stone(9), 1, 1);
board.put(new Stone(10), 1, 2);
board.put(new Stone(12), 1, 3);
assertTrue(board.hasWinner());
}
@Test
public void simpleVerticalWinningBoard() throws Exception {
board.put(new Stone(0), 0, 0);
board.put(new Stone(1), 1, 0);
board.put(new Stone(2), 2, 0);
board.put(new Stone(3), 3, 0);
assertTrue(board.hasWinner());
}
@Test
public void simpleLeftDiagonalWinningBoard() throws Exception {
board.put(new Stone(0), 0, 0);
board.put(new Stone(1), 1, 1);
board.put(new Stone(2), 2, 2);
board.put(new Stone(3), 3, 3);
assertTrue(board.hasWinner());
}
@Test
public void simpleRightDiagonalWinningBoard() throws Exception {
board.put(new Stone(0), 0, 3);
board.put(new Stone(1), 1, 2);
board.put(new Stone(2), 2, 1);
board.put(new Stone(3), 3, 0);
assertTrue(board.hasWinner());
}
@Test(expected = IllegalArgumentException.class)
public void cannotPutSameSpotTwice() throws Exception {
board.put(new Stone(0), 0, 0);
board.put(new Stone(1), 0, 0);
}
@Test(expected = IllegalArgumentException.class)
public void cannotPutUsedStone() throws Exception {
board.put(new Stone(0), 0, 0);
board.put(new Stone(0), 0, 1);
}
@Test
public void isEmpty() throws Exception {
assertTrue(board.isEmpty(0, 0));
board.put(new Stone(0), 0, 0);
assertFalse(board.isEmpty(0, 0));
}
@Test
public void isUsed() throws Exception {
assertFalse(board.isUsed(new Stone(0)));
board.put(new Stone(0), 0, 0);
assertTrue(board.isUsed(new Stone(0)));
}
}
| true
|
265242a33dbaf9ffdeea51aaf29a0861998755c1
|
Java
|
hvy/battlecode2015
|
/teams/team1/common/Action.java
|
UTF-8
| 2,510
| 3.125
| 3
|
[] |
no_license
|
package team1.common;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.RobotController;
import battlecode.common.RobotInfo;
import battlecode.common.RobotType;
import battlecode.common.Team;
public class Action {
// This method will attack an enemy in sight, if there is one
public static void attackSomething(int myRange, Team enemyTeam, RobotController rc) throws GameActionException {
RobotInfo[] enemies = rc.senseNearbyRobots(myRange, enemyTeam);
int index = 0;
double lowestHealth = Double.MAX_VALUE;
for (int i = 0; i < enemies.length; i++) {
if (enemies[i].health < lowestHealth) {
lowestHealth = enemies[i].health;
index = i;
}
}
if (enemies.length > 0) {
rc.attackLocation(enemies[index].location);
}
}
// This method will attempt to move in Direction d (or as close to it as possible)
public static void tryMove(Direction d, RobotController rc) throws GameActionException {
int offsetIndex = 0;
int[] offsets = {0,1,-1,2,-2};
int dirint = Util.directionToInt(d);
boolean blocked = false;
while (offsetIndex < 5 && !rc.canMove(Util.directions[(dirint+offsets[offsetIndex]+8)%8])) {
offsetIndex++;
}
if (offsetIndex < 5) {
rc.move(Util.directions[(dirint+offsets[offsetIndex]+8)%8]);
}
}
// This method will attempt to spawn in the given direction (or as close to it as possible)
public static void trySpawn(Direction d, RobotType type, RobotController rc) throws GameActionException {
int offsetIndex = 0;
int[] offsets = {0,1,-1,2,-2,3,-3,4};
int dirint = Util.directionToInt(d);
boolean blocked = false;
while (offsetIndex < 8 && !rc.canSpawn(Util.directions[(dirint+offsets[offsetIndex]+8)%8], type)) {
offsetIndex++;
}
if (offsetIndex < 8) {
rc.spawn(Util.directions[(dirint+offsets[offsetIndex]+8)%8], type);
}
}
// This method will attempt to build in the given direction (or as close to it as possible)
public static void tryBuild(Direction d, RobotType type, RobotController rc) throws GameActionException {
int offsetIndex = 0;
int[] offsets = {0,1,-1,2,-2,3,-3,4};
int dirint = Util.directionToInt(d);
boolean blocked = false;
while (offsetIndex < 8 && !rc.canMove(Util.directions[(dirint+offsets[offsetIndex]+8)%8])) {
offsetIndex++;
}
if (offsetIndex < 8) {
rc.build(Util.directions[(dirint+offsets[offsetIndex]+8)%8], type);
}
}
}
| true
|
b442e0bd32fc6f85c08d408355371f0e1d16ba48
|
Java
|
Caaarlowsz/bukkit-kitpvp
|
/src/main/java/com/escapeg/kitpvp/handlers/SpawnHandler.java
|
UTF-8
| 1,896
| 2.53125
| 3
|
[] |
no_license
|
package com.escapeg.kitpvp.handlers;
import com.escapeg.kitpvp.KitPvP;
import com.escapeg.kitpvp.utilities.GameChat;
import com.google.inject.Inject;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashMap;
import java.util.Map;
public class SpawnHandler implements Listener {
private final KitPvP plugin;
private final Map<Player, BukkitTask> tasks = new HashMap<>();
@Inject
public SpawnHandler(KitPvP plugin) {
this.plugin = plugin;
}
public Map<Player, BukkitTask> getTasks() {
return this.tasks;
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
if (removeSpawnTask(player)) {
GameChat.sendInfo(player, "Komanda atšaukta dėl pajudėjimo iš vietos.");
}
}
@EventHandler
public void onPlayerDamageByPlayer(EntityDamageByEntityEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (removeSpawnTask(player)) {
GameChat.sendInfo(player, "Komanda atšaukta dėl padarytos žalos nuo kito žaidėjo.");
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
removeSpawnTask(player);
}
private boolean removeSpawnTask(Player player) {
if (tasks.containsKey(player)) {
BukkitTask spawnTask = tasks.get(player);
spawnTask.cancel();
tasks.remove(player);
return true;
}
return false;
}
}
| true
|
a07e94d4c8078025a2af30bf32a2325e0dad09db
|
Java
|
KkukYang/bitSpring
|
/SpringBootJpaEx2/src/main/java/com/example/demo/BoardController.java
|
UTF-8
| 2,127
| 2.21875
| 2
|
[] |
no_license
|
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class BoardController {
@Autowired
MycarDao dao;
@GetMapping({ "/", "/list" })
public ModelAndView list() {
System.out.println("list()");
ModelAndView mview = new ModelAndView();
mview.addObject("message", "messagemessage");
// Map<String, String> map = new HashMap<String, String>();
// map.put("asdf", "asdfasdf");
// map.put("qwer", "qwerqwer");
//
// mview.addObject("map", map);
// Iterable<MyCarDto> list = dao.getAllDatas();
// int totalCount =((Collection<?>) list).size();
List<MyCarDto> list = dao.getAllDatas();
int totalCount = list.size();
mview.addObject("list", list);
mview.addObject("totalCount", totalCount);
mview.setViewName("list");
return mview;
}
@GetMapping("/carform")
public String form() {
return "writeform";
}
@GetMapping("/updateform")
public ModelAndView gotoUpdateform(@RequestParam String num) {
System.out.println("gotoUpdateform()");
Long id = Long.parseLong(num);
MyCarDto dto = dao.getData(id);
ModelAndView mview = new ModelAndView();
mview.addObject("dto", dto);
mview.setViewName("updateform");
return mview;
}
@PostMapping("/update")
public String update(@ModelAttribute MyCarDto dto) {
System.out.println("update()");
dao.updateCar(dto);
return "redirect:list";
}
@GetMapping("/delete")
public String delete(@RequestParam String num) {
System.out.println("delete()");
Long id = Long.parseLong(num);
dao.deleteCar(id);
return "redirect:list";
}
@PostMapping("/read")
public String read(@ModelAttribute MyCarDto dto) {
System.out.println("read() -> insert");
dao.insertCar(dto);
return "redirect:list";
}
}
| true
|
6c472173789b1bb2a35d907e6de68999cd538f57
|
Java
|
tatashii/MusicalApp
|
/app/src/main/java/com/example/musicalapp/Angham.java
|
UTF-8
| 859
| 1.875
| 2
|
[] |
no_license
|
package com.example.musicalapp;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Angham extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_angham);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
button=findViewById(R.id.album_angham);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(Angham.this,Album_Angham.class);
startActivity(intent);
}
});
}
}
| true
|
fb5675ba94c37f64c0229a68a6a9690c9effd1dd
|
Java
|
yellow013/northstar
|
/northstar-common/src/main/java/tech/xuanwu/northstar/common/utils/OrderUtil.java
|
UTF-8
| 1,098
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package tech.xuanwu.northstar.common.utils;
import tech.xuanwu.northstar.common.model.OrderRequest.TradeOperation;
import xyz.redtorch.pb.CoreEnum.DirectionEnum;
import xyz.redtorch.pb.CoreEnum.OffsetFlagEnum;
import xyz.redtorch.pb.CoreEnum.PositionDirectionEnum;
public class OrderUtil {
public static DirectionEnum resolveDirection(TradeOperation opr) {
return opr.toString().charAt(0) == 'B' ? DirectionEnum.D_Buy : DirectionEnum.D_Sell;
}
public static boolean isOpenningOrder(TradeOperation opr) {
return opr.toString().charAt(1) == 'K';
}
public static boolean isClosingOrder(TradeOperation opr) {
return opr.toString().charAt(1) == 'P';
}
public static PositionDirectionEnum getClosingDirection(DirectionEnum dir) {
if(dir == DirectionEnum.D_Buy) {
return PositionDirectionEnum.PD_Short;
} else if(dir == DirectionEnum.D_Sell) {
return PositionDirectionEnum.PD_Long;
}
throw new IllegalArgumentException("无法确定[" + dir + "]的对应持仓方向");
}
public static OffsetFlagEnum resolveOffsetFlag(TradeOperation opr) {
return null;
}
}
| true
|
61a11ee56039caf00d8064e0c3fdf2b69c35d47f
|
Java
|
lisajoanno/BlackOut
|
/src/jeu/blackOut/utils/instructions/InstructionsImageText.java
|
UTF-8
| 556
| 2.140625
| 2
|
[] |
no_license
|
package jeu.blackOut.utils.instructions;
public abstract class InstructionsImageText {
// TODO: Ici Antoine - Mettre texte - Move dans Constants
public final static String INSTRU_TEXT_0 = "Voici un exemple d'utilisation. Nous partons de la grille ci-contre et nous choisissons de cliquer sur la case entourée de bleu.";
public final static String INSTRU_TEXT_1 = "Si nous cliquons sur cette case, elle et les 4 cases qui la touchent vont changer de couleur.";
public final static String INSTRU_TEXT_2 = "Voici le resultat du clic.";
}
| true
|
8782edc3e9fd59cf1187b01479251c7e5572039b
|
Java
|
chqu1012/RichClientFX
|
/de.dc.javafx.xcore.workbench.ide.lang/src-gen/de/dc/javafx/xcore/workbench/ide/Editable.java
|
UTF-8
| 1,086
| 1.6875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* generated by Xtext 2.17.0
*/
package de.dc.javafx.xcore.workbench.ide;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Editable</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link de.dc.javafx.xcore.workbench.ide.Editable#getMethodName <em>Method Name</em>}</li>
* </ul>
*
* @see de.dc.javafx.xcore.workbench.ide.IdePackage#getEditable()
* @model
* @generated
*/
public interface Editable extends EObject
{
/**
* Returns the value of the '<em><b>Method Name</b></em>' attribute list.
* The list contents are of type {@link java.lang.String}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Method Name</em>' attribute list.
* @see de.dc.javafx.xcore.workbench.ide.IdePackage#getEditable_MethodName()
* @model unique="false"
* @generated
*/
EList<String> getMethodName();
} // Editable
| true
|
6ea34d30a720a763556858c8209a7b2e64d39c88
|
Java
|
juanchoque/truextenddemo
|
/src/main/java/com/truextend/dev/recipes/services/AccountsService.java
|
UTF-8
| 417
| 1.585938
| 2
|
[] |
no_license
|
package com.truextend.dev.recipes.services;
import com.truextend.dev.recipes.model.Accounts;
import java.util.HashMap;
public interface AccountsService {
HashMap deteleAccounts(Accounts accounts);
HashMap getAllAccounts(Accounts accounts);
HashMap getAccountsById(Accounts accounts);
HashMap getAccountsByEmailAndPass(Accounts accounts);
HashMap saveOrUpdateAccounts(Accounts accounts);
}
| true
|
338da48ac2e736fdee1b68bd5abf03db01d5e8b1
|
Java
|
minjae9010/WorldHunts
|
/src/main/java/tk/mjsv/TimerHandler/warTimer.java
|
UTF-8
| 3,153
| 2.46875
| 2
|
[] |
no_license
|
package tk.mjsv.TimerHandler;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import tk.mjsv.CmdHandler.WarHandler;
import tk.mjsv.WorldHunter;
import tk.mjsv.YAML;
public class warTimer implements Runnable{
private static final int WarMaxTime = 2*60;
int warTime = WarMaxTime;
int TaskId;
String attackTeam;
String sheldTeam;
Chunk c;
int NoPlayerTime = 0;
public warTimer(String team,Chunk c){
this.attackTeam = team;
this.sheldTeam = YAML.getLandTeam(c);
this.c = c;
Bukkit.broadcast(Component.text("\n" + WorldHunter.index + attackTeam + "팀이 "+sheldTeam+"의 (" + YAML.getLandLoc(c) + ")에 점령 선포를 하였습니다.\n"));
}
@Override
public void run() {
if(Timer.setting.equals("전쟁")){
int sheldPlayer = 0;
int attackPlayer = 0;
for(Entity e:c.getEntities()){
if(e instanceof Player){
if(YAML.getPlayerTeam(e.getName()).equals(sheldTeam)) sheldPlayer += 1;
else if(YAML.getPlayerTeam(e.getName()).equals(attackTeam)) attackPlayer +=1;
}
}
if(attackPlayer-sheldPlayer>=3){
if(warTime==WarMaxTime){
Bukkit.broadcast(Component.text("\n"+ WorldHunter.index+attackTeam+"팀이 ("+YAML.getLandLoc(c)+") 지역을 점령하기 시작했습니다. (남은시간 : "+warTime/60+"분)\n"));
}else if(warTime/60<=5&warTime%60==0&warTime!=0){
Bukkit.broadcast(Component.text("\n"+ WorldHunter.index+attackTeam+"팀이 ("+YAML.getLandLoc(c)+") 지역을 점령중입니다. (남은시간 : "+warTime/60+"분)\n"));
}else if(warTime==0){
Bukkit.broadcast(Component.text("\n"+ WorldHunter.index+attackTeam+"팀이 ("+YAML.getLandLoc(c)+") 지역을 점령성공하셨습니다.\n"));
TaskId = WarHandler.TaskList.get(YAML.getLandLoc(c).toString());
WarHandler.pvpList.remove(YAML.getLandLoc(c).toString());
WarHandler.TaskList.remove(YAML.getLandLoc(c).toString());
YAML.subLandTeam(c);
YAML.setLandTeam(attackTeam,c);
Bukkit.getScheduler().cancelTask(TaskId);
}
warTime-=1;
}else{
if(warTime!=WarMaxTime)
Bukkit.broadcast(Component.text("\n"+ WorldHunter.index+attackTeam+"팀이 ("+YAML.getLandLoc(c)+") 지역을 점령실패하셨습니다.\n"));
if(NoPlayerTime==180)
Bukkit.broadcast(Component.text("\n"+WorldHunter.index+"("+YAML.getLandLoc(c)+") 지역을 점령하기 위한 플레이어 수가 부족합니다\n"));
NoPlayerTime++;
warTime=WarMaxTime;
}
}else {
TaskId = WarHandler.TaskList.get(YAML.getLandLoc(c).toString());
Bukkit.getScheduler().cancelTask(TaskId);
}
}
}
| true
|
89fcf6e7f5299edb5873d0f32f7d203067b1bbea
|
Java
|
guodongdong/iaat-source
|
/src/test/java/com/iaat/webapi/ApiAbstractTestCase.java
|
UTF-8
| 6,787
| 1.960938
| 2
|
[] |
no_license
|
package com.iaat.webapi;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;
import com.iaat.model.AccountBean;
import com.nokia.ads.common.util.Log;
import com.nokia.ads.common.util.StringUtils;
import com.nokia.ads.platform.backend.annotation.ApiPath;
import com.nokia.ads.platform.backend.annotation.Authorization;
import com.nokia.ads.platform.backend.core.auth.IAuthScope;
import com.nokia.ads.platform.backend.core.webapi.ApiMaps;
import com.nokia.ads.platform.backend.core.webapi.ApiMaps.ApiMethod;
import com.nokia.ads.platform.backend.core.webapi.ApiRequest;
import com.nokia.ads.platform.backend.core.webapi.ApiResponse;
import com.nokia.ads.platform.backend.core.webapi.ApiResult;
import com.nokia.ads.platform.backend.core.webapi.ApiService;
import com.nokia.ads.platform.backend.core.webapi.ApiUser;
import com.nokia.ads.platform.backend.core.webapi.json.gson.GsonHelper;
import com.nokia.ads.platform.backend.profile.AdNetwork;
import com.nokia.ads.platform.backend.profile.DataFormat;
import com.nokia.ads.platform.backend.util.Paging;
public abstract class ApiAbstractTestCase<T extends ApiService> {
protected Log log = Log.getLogger(ApiAbstractTestCase.class);
// private String contextPath = "/madmanager";
private String contextPath = "/";
protected ApiMethod apiMethod = null;
protected DataFormat dataFormat = null;
private Class<T> apiClass = null;
private ApiUser apiUser = null;
protected Map<String, Object> parameters;
@SuppressWarnings("unchecked")
protected ApiAbstractTestCase() {
this.apiClass = (Class<T>) ((ParameterizedType) this.getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
public void setUp(String requestURI) {
this.apiUser = new ApiUser("101");
AccountBean accountBean = new AccountBean();
accountBean.setId(101L);
// accountBean.setAccountType(AccountType.RESELLER);
// accountBean.setDeveloperType(DeveloperType.COMPANY);
/*
this.apiUser.setData(accountBean);
//1.KeywordApi
ApiMaps.Register(this.apiClass);
String ext = requestURI.substring(requestURI.lastIndexOf(".") + 1);
//2.JSON
dataFormat = DataFormat.JSON;
String apiAction =ext;
//3
*/
this.apiUser.setData(accountBean);
//1.KeywordApi
ApiMaps.Register(this.apiClass);
String ext = requestURI.substring(requestURI.lastIndexOf(".") + 1);
//2.JSON
dataFormat = DataFormat.valueOf(ext.toUpperCase());
String apiAction = requestURI.substring(contextPath.length(),
requestURI.lastIndexOf("."));
//3
apiMethod = ApiMaps.findApiMethod(apiAction);
this.parameters = new HashMap<String, Object>();
this.parameters.put("locale", "zh_CN");
this.parameters.put("network", AdNetwork.NOKIA);
this.parameters.put("params", new HashMap<String, Object>());
}
/**
* addParam(Here describes this method function with a few words)
*
* add paramter
*
* @param keyName
* @param value
*
* void
*/
@SuppressWarnings("unchecked")
protected void addParam(String keyName, Object value) {
if (null != this.parameters) {
if (this.parameters.containsKey("params")) {
Object mapOfObject = this.parameters.get("params");
if (mapOfObject instanceof Map) {
Map<String, Object> paramOfMap = (Map<String, Object>) mapOfObject;
paramOfMap.put(keyName, value);
this.parameters.put("params", paramOfMap);
}
}
}
}
// protected void testResonse(ApiRequest request) {
// if (null == request)
// throw new IllegalArgumentException("request is null");
// if (null != this.apiMethod) {
// try {
// ApiResult result = (ApiResult) this.apiMethod.getMethod()
// .invoke(null, request,this.apiUser);
// ApiResponse response = ApiResponse.getInstance(this.dataFormat,
// result);
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Writer writer=new OutputStreamWriter(outputStream, "UTF-8");
// response.write(writer);
//// response.write(outputStream, "UTF-8");
// String responseOfString = new String(
// outputStream.toByteArray(), "UTF-8");
// log.debug(responseOfString);
// System.out.println("responseOfString:\n"+responseOfString);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
protected void testResonse(ApiRequest request) {
if (null == request)
throw new IllegalArgumentException("request is null");
if (null != this.apiMethod) {
try {
/**添加验证****/
String paramKey = "";
boolean isCheck = false;
IAuthScope<ApiUser, ApiRequest> scope = null;
if (apiMethod.getAuth() != null) {
Authorization auth = apiMethod.getAuth();
paramKey = auth.paramKey();
scope = (IAuthScope<ApiUser, ApiRequest>) auth.value().newInstance();
isCheck = scope.checkScope(apiUser, request, paramKey);
}
ApiResult result = null;
try {
result = (ApiResult) this.apiMethod.getMethod()
.invoke(null, request,this.apiUser);
} catch (Exception e) {
e.printStackTrace();
}
ApiResponse response = ApiResponse.getInstance(this.dataFormat,
result);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer writer=new OutputStreamWriter(outputStream, "UTF-8");
log.debug("check:"+isCheck);
response.write(writer);
// response.write(outputStream, "UTF-8");
String responseOfString = new String(
outputStream.toByteArray(), "UTF-8");
log.error(responseOfString);
log.debug(responseOfString);
System.out.println("responseOfString:\n"+responseOfString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected ApiRequest createApiRequest() {
if (null == this.parameters)
throw new IllegalArgumentException("the paramters is null");
String json = GsonHelper.buildGson().toJson(this.parameters);
System.out.println("json:\n"+json);
ApiPath apiPath = new ApiPath()
{
@Override
public Class<? extends Annotation> annotationType()
{
return null;
}
@Override
public String value()
{
return null;
}
};
ApiRequest request = ApiRequest.getInstance(this.dataFormat, apiPath, json);
return request;
}
protected String getUrl(String url) {
if (!StringUtils.hasLength(url))
throw new IllegalArgumentException("url is blank");
return this.contextPath + url + ".json";
}
protected Paging getPaging() {
Paging paging = new Paging();
paging.setPageSize(7);
paging.setCurrentPage(2);
return paging;
}
protected Paging getNullPaging() {
Paging paging = new Paging();
paging.setPageSize(-1);
paging.setCurrentPage(0);
return paging;
}
}
| true
|
0f4fbb47482da96e07b8ee848ff8a5e0e795171f
|
Java
|
gaoruishan/APP_v1.0
|
/mobileTravel/src/main/java/com/cmcc/hyapps/andyou/adapter/TripDayDropdownAdapter.java
|
UTF-8
| 1,821
| 2.265625
| 2
|
[] |
no_license
|
package com.cmcc.hyapps.andyou.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.kuloud.android.widget.recyclerview.BaseHeaderAdapter;
import com.cmcc.hyapps.andyou.R;
import com.cmcc.hyapps.andyou.model.QHStrategy;
import com.cmcc.hyapps.andyou.model.Trip;
/**
* @author kuloud
*/
public class TripDayDropdownAdapter extends BaseHeaderAdapter<Object, QHStrategy> {
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView content;
public ViewHolder(View itemView) {
super(itemView);
content = (TextView) itemView.findViewById(R.id.content);
}
}
@Override
public ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_trip_dropdown, parent, false);
return new ViewHolder(v);
}
@Override
public void onBinderHeaderViewHolder(android.support.v7.widget.RecyclerView.ViewHolder holder) {
}
@Override
public android.support.v7.widget.RecyclerView.ViewHolder onCreateItemViewHolder(
ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_trip_dropdown, parent, false);
return new ViewHolder(v);
}
@Override
public void onBinderItemViewHolder(android.support.v7.widget.RecyclerView.ViewHolder holder,
int position) {
ViewHolder vh = (ViewHolder) holder;
vh.itemView.setTag(mDataItems.get(position));
vh.content.setText(mDataItems.get(position).title);
attachClickListener(vh, vh.itemView, position);
}
}
| true
|
e3f77d7950eda5ad3991c8f3c98daee002ae5a98
|
Java
|
knewjade/solution-finder
|
/src/test/java/core/field/MiddleFieldTest.java
|
UTF-8
| 46,444
| 2.75
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
package core.field;
import core.mino.Mino;
import core.mino.Piece;
import core.neighbor.OriginalPiece;
import core.srs.Rotate;
import lib.Randoms;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
class MiddleFieldTest {
private static final int FIELD_WIDTH = 10;
private static final int FIELD_HEIGHT = 12;
private ArrayList<OriginalPiece> createAllPieces(int fieldHeight) {
ArrayList<OriginalPiece> pieces = new ArrayList<>();
for (Piece piece : Piece.values()) {
for (Rotate rotate : Rotate.values()) {
Mino mino = new Mino(piece, rotate);
for (int y = -mino.getMinY(); y < fieldHeight - mino.getMaxY(); y++) {
for (int x = -mino.getMinX(); x < FIELD_WIDTH - mino.getMaxX(); x++) {
pieces.add(new OriginalPiece(mino, x, y, fieldHeight));
}
}
}
}
return pieces;
}
@Test
void testGetMaxFieldHeight() throws Exception {
Field field = FieldFactory.createMiddleField();
assertThat(field.getMaxFieldHeight()).isEqualTo(FIELD_HEIGHT);
}
@Test
void testPutAndRemoveBlock() throws Exception {
Field field = FieldFactory.createSmallField();
assertThat(field.isEmpty(0, 0)).isTrue();
field.setBlock(0, 0);
assertThat(field.isEmpty(0, 0)).isFalse();
field.removeBlock(0, 0);
assertThat(field.isEmpty(0, 0)).isTrue();
assertThat(field.isEmpty(9, 9)).isTrue();
field.setBlock(9, 9);
assertThat(field.isEmpty(9, 9)).isFalse();
field.removeBlock(9, 9);
assertThat(field.isEmpty(9, 9)).isTrue();
}
@Test
void testPutAndRemoveMino() throws Exception {
Field field = FieldFactory.createMiddleField();
field.put(new Mino(Piece.T, Rotate.Spawn), 1, 0);
assertThat(field.isEmpty(0, 0)).isFalse();
assertThat(field.isEmpty(1, 0)).isFalse();
assertThat(field.isEmpty(2, 0)).isFalse();
assertThat(field.isEmpty(1, 1)).isFalse();
field.put(new Mino(Piece.I, Rotate.Left), 4, 6);
assertThat(field.isEmpty(4, 5)).isFalse();
assertThat(field.isEmpty(4, 6)).isFalse();
assertThat(field.isEmpty(4, 7)).isFalse();
assertThat(field.isEmpty(4, 8)).isFalse();
field.put(new Mino(Piece.O, Rotate.Spawn), 8, 8);
assertThat(field.isEmpty(8, 8)).isFalse();
assertThat(field.isEmpty(8, 9)).isFalse();
assertThat(field.isEmpty(9, 8)).isFalse();
assertThat(field.isEmpty(9, 9)).isFalse();
field.remove(new Mino(Piece.T, Rotate.Spawn), 1, 0);
field.remove(new Mino(Piece.I, Rotate.Left), 4, 6);
field.remove(new Mino(Piece.O, Rotate.Spawn), 8, 8);
assertThat(field.isEmpty()).isTrue();
}
@Test
void testPutAndRemovePiece() throws Exception {
MiddleField field = FieldFactory.createMiddleField();
int maxFieldHeight = field.getMaxFieldHeight();
ArrayList<OriginalPiece> pieces = createAllPieces(maxFieldHeight);
for (OriginalPiece piece : pieces) {
// Initialize
Mino mino = piece.getMino();
int x = piece.getX();
int y = piece.getY();
// Expect
MiddleField expected = FieldFactory.createMiddleField();
expected.put(mino, x, y);
// Test
field.put(piece);
assertThat(field)
.as("%s (%d, %d)", mino, x, y)
.isEqualTo(expected);
field.remove(piece);
assertThat(field.isEmpty())
.as("%s (%d, %d)", mino, x, y)
.isTrue();
}
}
@Test
void testGetYOnHarddrop() throws Exception {
String marks = "" +
"X_________" +
"__________" +
"__________" +
"__________" +
"_________X" +
"____X_____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.getYOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 1, 10)).isEqualTo(6);
assertThat(field.getYOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 2, 10)).isEqualTo(0);
assertThat(field.getYOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 3, 10)).isEqualTo(1);
assertThat(field.getYOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 8, 10)).isEqualTo(2);
}
@Test
void testCanReachOnHarddrop() throws Exception {
String marks = "" +
"X_________" +
"__________" +
"__________" +
"__________" +
"__________" +
"_________X" +
"____X_____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.canReachOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 1, 4)).isFalse();
assertThat(field.canReachOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 2, 4)).isTrue();
assertThat(field.canReachOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 2, 3)).isTrue();
assertThat(field.canReachOnHarddrop(new Mino(Piece.T, Rotate.Spawn), 1, 1)).isFalse();
}
@Test
void testCanReachOnHarddrop2() throws Exception {
Randoms randoms = new Randoms();
MiddleField field = createRandomMiddleField(randoms);
String string = FieldView.toString(field);
ArrayList<OriginalPiece> pieces = createAllPieces(field.getMaxFieldHeight());
for (OriginalPiece piece : pieces) {
Mino mino = piece.getMino();
int x = piece.getX();
int y = piece.getY();
assertThat(field.canReachOnHarddrop(piece))
.as(string + piece.toString())
.isEqualTo(field.canPut(mino, x, y) && field.canReachOnHarddrop(mino, x, y));
}
}
@Test
void testExistAbove() throws Exception {
String marks = "" +
"_____X____" +
"__________" +
"__________" +
"__________" +
"___X______" +
"__________" +
"_______X__" +
"__________" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.existsAbove(0)).isTrue();
assertThat(field.existsAbove(6)).isTrue();
assertThat(field.existsAbove(7)).isTrue();
assertThat(field.existsAbove(8)).isFalse();
assertThat(field.existsAbove(9)).isFalse();
}
@Test
void testIsPerfect() throws Exception {
Field field = FieldFactory.createMiddleField();
assertThat(field.isEmpty(0, 0)).isTrue();
assertThat(field.isEmpty()).isTrue();
field.setBlock(7, 8);
assertThat(field.isEmpty(7, 8)).isFalse();
assertThat(field.isEmpty()).isFalse();
}
@Test
void testIsFilledInColumn() throws Exception {
String marks = "" +
"____X_____" +
"____X_____" +
"____X_____" +
"____X_____" +
"____X_____" +
"___XX_____" +
"__XXX_____" +
"X__XX_____" +
"__XXXX____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.isFilledInColumn(0, 4)).isFalse();
assertThat(field.isFilledInColumn(1, 4)).isFalse();
assertThat(field.isFilledInColumn(2, 4)).isFalse();
assertThat(field.isFilledInColumn(3, 4)).isTrue();
assertThat(field.isFilledInColumn(3, 6)).isFalse();
assertThat(field.isFilledInColumn(4, 4)).isTrue();
assertThat(field.isFilledInColumn(4, 6)).isTrue();
assertThat(field.isFilledInColumn(4, 9)).isTrue();
assertThat(field.isFilledInColumn(4, 10)).isFalse();
assertThat(field.isFilledInColumn(5, 7)).isFalse();
}
@Test
void testIsWallBetweenLeft() throws Exception {
String marks = "" +
"____X_____" +
"____X_____" +
"____X_____" +
"____X_____" +
"____X_____" +
"_X_XX_____" +
"_XXXX_____" +
"X_XXX_____" +
"_XXXXX____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.isWallBetweenLeft(1, 4)).isTrue();
assertThat(field.isWallBetweenLeft(1, 5)).isFalse();
assertThat(field.isWallBetweenLeft(2, 4)).isTrue();
assertThat(field.isWallBetweenLeft(2, 5)).isFalse();
assertThat(field.isWallBetweenLeft(3, 4)).isTrue();
assertThat(field.isWallBetweenLeft(3, 5)).isFalse();
assertThat(field.isWallBetweenLeft(4, 9)).isTrue();
assertThat(field.isWallBetweenLeft(4, 10)).isFalse();
assertThat(field.isWallBetweenLeft(5, 9)).isTrue();
assertThat(field.isWallBetweenLeft(5, 10)).isFalse();
assertThat(field.isWallBetweenLeft(6, 6)).isFalse();
}
@Test
void testCanPutMino() throws Exception {
String marks = "" +
"______X___" +
"___X______" +
"___XX_____" +
"___XX_____" +
"___XX_____" +
"__X_X_____" +
"X___X_____" +
"__X_XX____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.canPut(new Mino(Piece.T, Rotate.Spawn), 4, 7)).isTrue();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Spawn), 5, 6)).isTrue();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Right), 1, 1)).isTrue();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Reverse), 1, 3)).isTrue();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Left), 3, 1)).isTrue();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Spawn), 5, 7)).isFalse();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Spawn), 4, 6)).isFalse();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Right), 0, 1)).isFalse();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Reverse), 1, 1)).isFalse();
assertThat(field.canPut(new Mino(Piece.T, Rotate.Left), 1, 1)).isFalse();
}
@Test
void testCanPutMino2() throws Exception {
String marks = "" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X" +
"XXXXXXXX_X";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.canPut(new Mino(Piece.I, Rotate.Left), 8, 1)).isTrue();
assertThat(field.canPut(new Mino(Piece.I, Rotate.Left), 8, 11)).isTrue();
assertThat(field.canPut(new Mino(Piece.I, Rotate.Left), 8, 12)).isTrue();
assertThat(field.canPut(new Mino(Piece.I, Rotate.Left), 8, 13)).isTrue();
assertThat(field.canPut(new Mino(Piece.I, Rotate.Left), 8, 14)).isTrue();
}
@Test
void testCanPutPiece() {
Randoms randoms = new Randoms();
MiddleField field = createRandomMiddleField(randoms);
int maxFieldHeight = field.getMaxFieldHeight();
ArrayList<OriginalPiece> pieces = createAllPieces(maxFieldHeight);
for (OriginalPiece piece : pieces) {
Mino mino = piece.getMino();
int x = piece.getX();
int y = piece.getY();
assertThat(field.canPut(piece))
.as("%s (%d, %d)", mino, x, y)
.isEqualTo(field.canPut(mino, x, y));
}
}
private MiddleField createRandomMiddleField(Randoms randoms) {
Field randomField = randoms.field(FIELD_HEIGHT, 25);
return new MiddleField(randomField.getBoard(0), randomField.getBoard(1));
}
@Test
void testIsOnGround() throws Exception {
String marks = "" +
"X_________" +
"___X______" +
"___XX_____" +
"___XX_____" +
"__X_X_____" +
"X___X_____" +
"__X_XX____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Spawn), 1, 7)).isTrue();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Spawn), 5, 5)).isTrue();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Right), 8, 1)).isTrue();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Reverse), 1, 3)).isTrue();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Left), 1, 2)).isTrue();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Spawn), 1, 6)).isFalse();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Spawn), 6, 5)).isFalse();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Spawn), 8, 1)).isFalse();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Right), 8, 2)).isFalse();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Reverse), 7, 3)).isFalse();
assertThat(field.isOnGround(new Mino(Piece.T, Rotate.Left), 9, 2)).isFalse();
}
@Test
void testGetBlockCountBelowOnX() throws Exception {
String marks = "" +
"___XX_____" +
"___XX_____" +
"___XX_____" +
"____X_____" +
"___XX_____" +
"___XX_____" +
"___XX_____" +
"__X_X_____" +
"X___X_____" +
"__X_XX____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.getBlockCountBelowOnX(0, 1)).isEqualTo(0);
assertThat(field.getBlockCountBelowOnX(0, 2)).isEqualTo(1);
assertThat(field.getBlockCountBelowOnX(2, 4)).isEqualTo(2);
assertThat(field.getBlockCountBelowOnX(3, 4)).isEqualTo(1);
assertThat(field.getBlockCountBelowOnX(3, 6)).isEqualTo(3);
assertThat(field.getBlockCountBelowOnX(3, 9)).isEqualTo(5);
assertThat(field.getBlockCountBelowOnX(3, 10)).isEqualTo(6);
assertThat(field.getBlockCountBelowOnX(4, 6)).isEqualTo(6);
assertThat(field.getBlockCountBelowOnX(4, 9)).isEqualTo(9);
assertThat(field.getBlockCountBelowOnX(4, 10)).isEqualTo(10);
}
@Test
void testGetAllBlockCount() throws Exception {
String marks = "" +
"___XX_____" +
"___XX_____" +
"___XX_____" +
"___XX_____" +
"___XX_____" +
"__X_X_____" +
"X___X_____" +
"__X_XX____" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.getNumOfAllBlocks()).isEqualTo(17);
}
@Test
void testClearLine1() throws Exception {
String marks = "" +
"XXXXXXXX_X" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXX_XXXXXX" +
"XXXXXXXXXX" +
"X_XXXXXXXX" +
"XXXXXXXXXX" +
"XXXX_XXXXX" +
"XXXXXXXXXX";
Field field = FieldFactory.createMiddleField(marks);
int deleteLine = field.clearLine();
assertThat(deleteLine).isEqualTo(6);
assertThat(field.existsAbove(3)).isTrue();
assertThat(field.existsAbove(4)).isFalse();
assertThat(field.isEmpty(0, 0)).isFalse();
assertThat(field.isEmpty(4, 0)).isTrue();
assertThat(field.isEmpty(1, 1)).isTrue();
assertThat(field.isEmpty(3, 2)).isTrue();
assertThat(field.isEmpty(8, 3)).isTrue();
}
@Test
void testClearLine2() throws Exception {
String marks = "" +
"XXXXXXXXXX" +
"XXXXXXXX_X" +
"XXXXXXX_XX" +
"XXXXXX_XXX" +
"XXXXXXXXXX" +
"XXXXX_XXXX" +
"XXXX_XXXXX" +
"XXX_XXXXXX" +
"XX_XXXXXXX" +
"XXXXXXXXXX" +
"X_XXXXXXXX" +
"_XXXXXXXXX";
Field field = FieldFactory.createMiddleField(marks);
int deleteLine = field.clearLine();
assertThat(deleteLine).isEqualTo(3);
assertThat(field.existsAbove(8)).isTrue();
assertThat(field.existsAbove(9)).isFalse();
for (int index = 0; index < 9; index++)
assertThat(field.isEmpty(index, index)).isTrue();
}
@Test
void testClearLine3() throws Exception {
String marks = "" +
"XXXXXXXXXX" +
"XXXXX_XXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXXX_XXXXX" +
"XXX_XXXXXX" +
"XX_XXXXXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"X_XXXXXXXX" +
"_XXXXXXXXX";
Field field = FieldFactory.createMiddleField(marks);
int deleteLine = field.clearLine();
assertThat(deleteLine).isEqualTo(6);
assertThat(field.existsAbove(5)).isTrue();
assertThat(field.existsAbove(6)).isFalse();
for (int index = 0; index < 6; index++)
assertThat(field.isEmpty(index, index)).isTrue();
}
@Test
void testClearLineAndInsertBlackLine() throws Exception {
String marks = "" +
"XXXXXXXX_X" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXX_XXXXXX" +
"XXXXXXXXXX" +
"X_XXXXXXXX" +
"XXXXXXXXXX" +
"XXXX_XXXXX" +
"XXXXXXXXXX";
Field field = FieldFactory.createMiddleField(marks);
Field freeze = field.freeze(field.getMaxFieldHeight());
long deleteKey = field.clearLineReturnKey();
assertThat(Long.bitCount(deleteKey)).isEqualTo(6);
field.insertBlackLineWithKey(deleteKey);
for (int index = 0; index < freeze.getBoardCount(); index++)
assertThat(field.getBoard(index)).isEqualTo(freeze.getBoard(index));
}
@Test
void testClearLineAndInsertWhiteLine() throws Exception {
String marks = "" +
"XXXXXXXX_X" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXX_XXXXXX" +
"XXXXXXXXXX" +
"X_XXXXXXXX" +
"XXXXXXXXXX" +
"XXXX_XXXXX" +
"XXXXXXXXXX";
Field field = FieldFactory.createMiddleField(marks);
String expectedMarks = "" +
"XXXXXXXX_X" +
"__________" +
"__________" +
"__________" +
"XXX_XXXXXX" +
"__________" +
"X_XXXXXXXX" +
"__________" +
"XXXX_XXXXX" +
"__________";
Field expected = FieldFactory.createMiddleField(expectedMarks);
long deleteKey = field.clearLineReturnKey();
assertThat(Long.bitCount(deleteKey)).isEqualTo(6);
field.insertWhiteLineWithKey(deleteKey);
for (int index = 0; index < expected.getBoardCount(); index++)
assertThat(field.getBoard(index)).isEqualTo(expected.getBoard(index));
}
@Test
void testGetBoard() throws Exception {
String marks = "" +
"_________X" +
"_________X" +
"_________X" +
"X_________" +
"X_________" +
"X_________" +
"X_________" +
"X_________" +
"X_________" +
"";
MiddleField field = FieldFactory.createMiddleField(marks);
assertThat(field.getBoardCount()).isEqualTo(2);
assertThat(field.getBoard(0))
.isEqualTo(0x4010040100401L)
.isEqualTo(field.getXBoardLow());
assertThat(field.getBoard(1))
.isEqualTo(0x20080200L)
.isEqualTo(field.getXBoardHigh());
for (int index = 2; index < 100; index++)
assertThat(field.getBoard(index)).isEqualTo(0L);
}
@Test
void testFreeze() throws Exception {
String marks = "" +
"X_________" +
"X_________" +
"X_________" +
"X_________" +
"";
Field field = FieldFactory.createMiddleField(marks);
assertThat(field.getNumOfAllBlocks()).isEqualTo(4);
Field freeze = field.freeze(field.getMaxFieldHeight());
field.setBlock(9, 0);
assertThat(field.getNumOfAllBlocks()).isEqualTo(5);
assertThat(freeze.getNumOfAllBlocks()).isEqualTo(4);
}
@Test
void testEqual() throws Exception {
String marks = "XXXXXX____";
MiddleField field1 = FieldFactory.createMiddleField(marks);
MiddleField field2 = FieldFactory.createMiddleField(marks);
assertThat(field1.equals(field2)).isTrue();
MiddleField field3 = FieldFactory.createMiddleField(marks + "XXXXXX____");
assertThat(field1.equals(field3)).isFalse();
SmallField field4 = FieldFactory.createSmallField(marks);
assertThat(field1.equals(field4)).isTrue();
}
@Test
void testGetBlockCountOnY() {
String marks = "" +
"X__X__X___" +
"XXXXXXXXXX" +
"XXX_XXX__X" +
"__________" +
"X___XXX__X" +
"X__X___XX_" +
"X____X____" +
"X_________" +
"";
MiddleField field = FieldFactory.createMiddleField(marks);
assertThat(field.getBlockCountOnY(0)).isEqualTo(1);
assertThat(field.getBlockCountOnY(1)).isEqualTo(2);
assertThat(field.getBlockCountOnY(2)).isEqualTo(4);
assertThat(field.getBlockCountOnY(3)).isEqualTo(5);
assertThat(field.getBlockCountOnY(4)).isEqualTo(0);
assertThat(field.getBlockCountOnY(5)).isEqualTo(7);
assertThat(field.getBlockCountOnY(6)).isEqualTo(10);
assertThat(field.getBlockCountOnY(7)).isEqualTo(3);
}
@Test
void testCanMerge1() {
String marks1 = "" +
"X_X_X_X__X" +
"X__X____XX" +
"__________" +
"__________" +
"XXX_XXX__X" +
"X__X___XX_" +
"__________" +
"__________" +
"";
MiddleField field1 = FieldFactory.createMiddleField(marks1);
String marks2 = "" +
"__________" +
"__________" +
"X_XX_X_X_X" +
"XXXXXXXXXX" +
"__________" +
"__________" +
"X__X_X_X__" +
"XXX_XX___X" +
"";
MiddleField field2 = FieldFactory.createMiddleField(marks2);
assertThat(field1.canMerge(field2)).isTrue();
}
@Test
void testCanMerge2() {
String marks1 = "" +
"__XX_X_X__" +
"__________" +
"__________" +
"__XX_X_X__" +
"XXX_XXX__X" +
"X__X___XX_" +
"XXXXX_____" +
"XXXXX_____" +
"";
MiddleField field1 = FieldFactory.createMiddleField(marks1);
String marks2 = "" +
"__________" +
"__________" +
"X__X_X_X__" +
"XXXXXXXXXX" +
"__________" +
"__________" +
"__________" +
"__________" +
"";
MiddleField field2 = FieldFactory.createMiddleField(marks2);
assertThat(field1.canMerge(field2)).isFalse();
}
@Test
void testMerge1() {
String marks1 = "" +
"XXX_XXX__X" +
"X__X___XX_" +
"__________" +
"__________" +
"XXX_XXX__X" +
"X__X___XX_" +
"__________" +
"__________" +
"";
MiddleField field1 = FieldFactory.createMiddleField(marks1);
String marks2 = "" +
"__________" +
"__________" +
"X__X_X_X__" +
"XXX_XX___X" +
"__________" +
"__________" +
"X__X_X_X__" +
"XXX_XX___X" +
"";
MiddleField field2 = FieldFactory.createMiddleField(marks2);
String expectedMarks = "" +
"XXX_XXX__X" +
"X__X___XX_" +
"X__X_X_X__" +
"XXX_XX___X" +
"XXX_XXX__X" +
"X__X___XX_" +
"X__X_X_X__" +
"XXX_XX___X" +
"";
MiddleField fieldExpected = FieldFactory.createMiddleField(expectedMarks);
field1.merge(field2);
assertThat(field1).isEqualTo(fieldExpected);
assertThat(field2).isNotEqualTo(fieldExpected);
}
@Test
void testMerge2() {
String marks1 = "" +
"XXX_XXX__X" +
"X__X___XX_" +
"XXXXX_____" +
"XXXXX_____" +
"XXX_XXX__X" +
"X__X___XX_" +
"XXXXX_____" +
"XXXXX_____" +
"";
MiddleField field1 = FieldFactory.createMiddleField(marks1);
String marks2 = "" +
"__________" +
"__________" +
"X__X_X_X__" +
"XXX_XX___X" +
"__________" +
"__________" +
"X__X_X_X__" +
"XXX_XX___X" +
"";
MiddleField field2 = FieldFactory.createMiddleField(marks2);
String expectedMarks = "" +
"XXX_XXX__X" +
"X__X___XX_" +
"XXXXXX_X__" +
"XXXXXX___X" +
"XXX_XXX__X" +
"X__X___XX_" +
"XXXXXX_X__" +
"XXXXXX___X" +
"";
MiddleField fieldExpected = FieldFactory.createMiddleField(expectedMarks);
field1.merge(field2);
assertThat(field1).isEqualTo(fieldExpected);
assertThat(field2).isNotEqualTo(fieldExpected);
}
@Test
void testReduce() {
String marks1 = "" +
"XXXXXXXXX_" +
"__________" +
"__________" +
"XXXXXXXXX_" +
"XXXXXXXXX_" +
"__________" +
"__________" +
"XXXXXXXXX_" +
"";
MiddleField field1 = FieldFactory.createMiddleField(marks1);
String marks2 = "" +
"XXXXX_____" +
"_X___X____" +
"X__X_X_X__" +
"XXX_XX___X" +
"XXXXX_____" +
"_X___X____" +
"X__X_X_X__" +
"XXX_XX___X" +
"";
MiddleField field2 = FieldFactory.createMiddleField(marks2);
String expectedMarks = "" +
"_____XXXX_" +
"__________" +
"__________" +
"___X__XXX_" +
"_____XXXX_" +
"__________" +
"__________" +
"___X__XXX_" +
"";
MiddleField fieldExpected = FieldFactory.createMiddleField(expectedMarks);
field1.reduce(field2);
assertThat(field1).isEqualTo(fieldExpected);
assertThat(field2).isNotEqualTo(fieldExpected);
}
@Test
void testGetUpperYWith4Blocks() {
String marks = "" +
"__________" +
"_____X____" +
"____XXX___" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"";
MiddleField field = FieldFactory.createMiddleField(marks);
assertThat(field.getUpperYWith4Blocks()).isEqualTo(7);
}
@Test
void testGetUpperYWith4BlocksRandom() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
MiddleField field = FieldFactory.createMiddleField();
int maxY = -1;
while (field.getNumOfAllBlocks() != 4) {
int x = randoms.nextIntOpen(FIELD_WIDTH);
int y = randoms.nextIntOpen(0, FIELD_HEIGHT);
field.setBlock(x, y);
if (maxY < y)
maxY = y;
}
assertThat(field.getUpperYWith4Blocks()).isEqualTo(maxY);
}
}
@Test
void testGetLowerY() {
String marks = "" +
"__________" +
"_____X____" +
"____XXX___" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"";
MiddleField field = FieldFactory.createMiddleField(marks);
assertThat(field.getLowerY()).isEqualTo(8);
}
@Test
void testGetLowerYWithEmpty() {
MiddleField field = FieldFactory.createMiddleField();
assertThat(field.getLowerY()).isEqualTo(-1);
}
@Test
void testGetLowerYRandom() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
MiddleField field = FieldFactory.createMiddleField();
int minY = Integer.MAX_VALUE;
int numOfBlocks = randoms.nextIntOpen(1, FIELD_WIDTH * FIELD_HEIGHT);
for (int block = 0; block < numOfBlocks; block++) {
int x = randoms.nextIntOpen(FIELD_WIDTH);
int y = randoms.nextIntOpen(0, FIELD_HEIGHT);
field.setBlock(x, y);
if (y < minY)
minY = y;
}
assertThat(field.getLowerY()).isEqualTo(minY);
}
}
@Test
void testSlideLeft() {
String marks = "" +
"__________" +
"_____X____" +
"____XXX___" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"";
MiddleField field = FieldFactory.createMiddleField(marks);
field.slideLeft(3);
String expectedMarks = "" +
"__________" +
"__X_______" +
"_XXX______" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"__________" +
"";
MiddleField expectedField = FieldFactory.createMiddleField(expectedMarks);
assertThat(field).isEqualTo(expectedField);
}
@Test
void testSlideLeftRandom() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
int slide = randoms.nextIntOpen(10);
MiddleField field = FieldFactory.createMiddleField();
MiddleField expect = FieldFactory.createMiddleField();
int numOfBlocks = randoms.nextIntOpen(1, FIELD_WIDTH * FIELD_HEIGHT);
for (int block = 0; block < numOfBlocks; block++) {
int x = randoms.nextIntOpen(FIELD_WIDTH);
int y = randoms.nextIntOpen(0, FIELD_HEIGHT);
field.setBlock(x, y);
if (0 <= x - slide)
expect.setBlock(x - slide, y);
}
field.slideLeft(slide);
assertThat(field).isEqualTo(expect);
}
}
@Test
void fillLine() {
for (int y = 0; y < FIELD_HEIGHT; y++) {
MiddleField field = new MiddleField();
field.fillLine(y);
for (int x = 0; x < FIELD_WIDTH; x++)
assertThat(field.isEmpty(x, y)).isFalse();
field.clearLine();
assertThat(field.isEmpty()).isTrue();
}
}
@Test
void contains() {
Field parent = FieldFactory.createField("" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____"
);
Field child1 = FieldFactory.createField("" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____"
);
Field child2 = FieldFactory.createField("" +
"XXX_______" +
"XXX_______" +
"XXX_______" +
"XXX_______" +
"XXX_______" +
"XXX_______"
);
Field child3 = FieldFactory.createField("" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX_____" +
"XXXXX__X__"
);
Field child4 = FieldFactory.createField("" +
"__________" +
"__________" +
"__________" +
"__________"
);
Field child5 = FieldFactory.createField("" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX" +
"XXXXXXXXXX"
);
assertThat(parent)
.returns(true, p -> p.contains(child1))
.returns(true, p -> p.contains(child2))
.returns(false, p -> p.contains(child3))
.returns(true, p -> p.contains(child4))
.returns(false, p -> p.contains(child5));
}
@Test
void containsRandom() {
Randoms randoms = new Randoms();
for (int count = 0; count < 50000; count++) {
Field initField = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(4, 15));
{
Field field = initField.freeze(FIELD_HEIGHT);
for (int i = 0; i < 100; i++) {
int x = randoms.nextIntOpen(Randoms.FIELD_WIDTH);
int y = randoms.nextIntOpen(0, FIELD_HEIGHT);
field.removeBlock(x, y);
assertThat(initField.contains(field)).isTrue();
}
}
{
Field field = initField.freeze(FIELD_HEIGHT);
for (int i = 0; i < 100; i++) {
int x = randoms.nextIntOpen(Randoms.FIELD_WIDTH);
int y = randoms.nextIntOpen(0, FIELD_HEIGHT);
if (!field.isEmpty(x, y))
continue;
field.setBlock(x, y);
assertThat(initField.contains(field)).isFalse();
}
}
}
}
@Test
void slideDown() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = new MiddleField();
Field expected = new MiddleField();
for (int x = 0; x < FIELD_WIDTH; x++) {
if (randoms.nextBoolean())
field.setBlock(x, 0);
}
for (int y = 1; y < FIELD_HEIGHT; y++) {
for (int x = 0; x < FIELD_WIDTH; x++) {
if (randoms.nextBoolean()) {
field.setBlock(x, y);
expected.setBlock(x, y - 1);
}
}
}
field.slideDown();
assertThat(field).isEqualTo(expected);
}
}
@Test
void slideDownN() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = randoms.field(FIELD_HEIGHT, 20);
int slide = randoms.nextIntOpen(FIELD_HEIGHT + 1);
Field freeze = field.freeze();
for (int n = 0; n < slide; n++) {
freeze.slideDown();
}
field.slideDown(slide);
assertThat(field).isEqualTo(freeze);
}
}
@Test
void slideUpWithWhiteLine() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = randoms.field(FIELD_HEIGHT, 20);
Field freeze = field.freeze();
freeze.slideDown();
freeze.slideUpWithWhiteLine(1);
for (int x = 0; x < FIELD_WIDTH; x++) {
field.removeBlock(x, 0);
}
assertThat(field).isEqualTo(freeze);
}
}
@Test
void slideUpWithBlackLine() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = randoms.field(FIELD_HEIGHT, 20);
Field freeze = field.freeze();
freeze.slideDown();
freeze.slideUpWithBlackLine(1);
for (int x = 0; x < FIELD_WIDTH; x++) {
field.setBlock(x, 0);
}
assertThat(field).isEqualTo(freeze);
}
}
@Test
void slideUpWithWhiteLineN() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = randoms.field(FIELD_HEIGHT, 20);
int slide = randoms.nextIntOpen(FIELD_HEIGHT + 1);
Field freeze = field.freeze();
for (int n = 0; n < slide; n++) {
freeze.slideUpWithWhiteLine(1);
}
field.slideUpWithWhiteLine(slide);
assertThat(field).isEqualTo(freeze);
}
}
@Test
void slideUpWithBlackLineN() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = randoms.field(FIELD_HEIGHT, 20);
int slide = randoms.nextIntOpen(FIELD_HEIGHT + 1);
Field freeze = field.freeze();
for (int n = 0; n < slide; n++) {
freeze.slideUpWithBlackLine(1);
}
field.slideUpWithBlackLine(slide);
assertThat(field).isEqualTo(freeze);
}
}
@Test
void slideLeft() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = new MiddleField();
Field expected = new MiddleField();
int slide = randoms.nextIntClosed(0, 9);
for (int x = 0; x < slide; x++) {
for (int y = 0; y < FIELD_HEIGHT; y++) {
if (randoms.nextBoolean())
field.setBlock(x, y);
}
}
for (int x = slide; x < FIELD_WIDTH; x++) {
for (int y = 0; y < FIELD_HEIGHT; y++) {
if (randoms.nextBoolean()) {
field.setBlock(x, y);
expected.setBlock(x - slide, y);
}
}
}
field.slideLeft(slide);
assertThat(field).isEqualTo(expected);
}
}
@Test
void slideRight() {
Randoms randoms = new Randoms();
for (int count = 0; count < 100000; count++) {
Field field = new MiddleField();
Field expected = new MiddleField();
int slide = randoms.nextIntClosed(0, 9);
for (int x = 9; 9 - slide < x; x--) {
for (int y = 0; y < FIELD_HEIGHT; y++) {
if (randoms.nextBoolean())
field.setBlock(x, y);
}
}
for (int x = 9 - slide; 0 <= x; x--) {
for (int y = 0; y < FIELD_HEIGHT; y++) {
if (randoms.nextBoolean()) {
field.setBlock(x, y);
expected.setBlock(x + slide, y);
}
}
}
field.slideRight(slide);
assertThat(field).isEqualTo(expected);
}
}
@Test
void inverse() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
Field initField = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(4, 15));
Field field = initField.freeze(FIELD_HEIGHT);
field.inverse();
for (int y = 0; y < FIELD_HEIGHT; y++)
for (int x = 0; x < FIELD_WIDTH; x++)
assertThat(field.isEmpty(x, y)).isNotEqualTo(initField.isEmpty(x, y));
}
}
@Test
void mirror() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
Field initField = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(3, 10));
Field field = initField.freeze(FIELD_HEIGHT);
field.mirror();
for (int y = 0; y < FIELD_HEIGHT; y++)
for (int x = 0; x < FIELD_WIDTH; x++)
assertThat(field.isEmpty(x, y)).isEqualTo(initField.isEmpty(9 - x, y));
}
}
@Test
void getMinX() {
{
int minX = FieldFactory.createMiddleField().getMinX();
assertThat(minX).isEqualTo(-1);
}
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
Field initField = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(3, 10));
Field field = initField.freeze(FIELD_HEIGHT);
int minX = field.getMinX();
int expectedMinX = -1;
for (int x = 0; x < 10; x++) {
boolean isExists = false;
for (int y = 0; y < FIELD_HEIGHT; y++) {
if (!field.isEmpty(x, y)) {
isExists = true;
break;
}
}
if (isExists) {
expectedMinX = x;
break;
}
}
assertThat(minX).isEqualTo(expectedMinX);
}
}
@Test
void existsBlockCountOnY() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
Field initField = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(3, 10));
for (int y = 0; y < FIELD_HEIGHT; y++) {
boolean expected = false;
for (int x = 0; x < FIELD_WIDTH; x++) {
if (!initField.isEmpty(x, y)) {
expected = true;
}
}
assertThat(initField.existsBlockCountOnY(y)).isEqualTo(expected);
}
}
}
@Test
void deleteLine() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
// 適度にフィールドのラインが揃うようにランダムに地形を作る
Field field = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(3, 10));
int maxCount = randoms.nextIntOpen(0, FIELD_HEIGHT * 2);
for (int lineCount = 0; lineCount < maxCount; lineCount++) {
field.fillLine(randoms.nextIntClosed(0, FIELD_HEIGHT));
}
Field expected = field.freeze();
long deletedKey = expected.clearLineReturnKey();
field.deleteLineWithKey(deletedKey);
assertThat(field).isEqualTo(expected);
}
}
@Test
void mask() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
// 適度にフィールドのラインが揃うようにランダムに地形を作る
Field field1 = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(3, 10));
Field field2 = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(3, 10));
// 期待値
Field expected = FieldFactory.createField(field1.getMaxFieldHeight());
for (int y = 0; y < FIELD_HEIGHT; y++) {
for (int x = 0; x < FIELD_WIDTH; x++) {
if (!field1.isEmpty(x, y) && !field2.isEmpty(x, y)) {
expected.setBlock(x, y);
}
}
}
{
Field freeze = field1.freeze();
freeze.mask(field2);
assertThat(freeze).isEqualTo(expected);
}
{
Field freeze = field2.freeze();
freeze.mask(field1);
assertThat(freeze).isEqualTo(expected);
}
}
}
@Test
void getUsingKey() {
Randoms randoms = new Randoms();
for (int count = 0; count < 10000; count++) {
Field field = randoms.field(FIELD_HEIGHT, randoms.nextIntOpen(1, 10));
// 期待値
long expected = 0L;
for (int y = 0; y < FIELD_HEIGHT; y++) {
for (int x = 0; x < FIELD_WIDTH; x++) {
if (field.exists(x, y)) {
expected |= KeyOperators.getDeleteBitKey(y);
break;
}
}
}
assertThat(field.getUsingKey()).isEqualTo(expected);
}
}
}
| true
|
a8f2db898a76142920ed00f88da06562cc6560a4
|
Java
|
1jaywong1/IEC61131-based-PLC-with-HMI-Operator-Panel
|
/DDC_HMI/src/main/java/com/controllers/ElevatorController.java
|
UTF-8
| 3,563
| 2.453125
| 2
|
[] |
no_license
|
package com.controllers;
import com.panel.transaction.BufferManager;
import com.panel.transaction.MyIntegerProperty;
import com.panel.transaction.PropertyManager;
import com.panel.view.ViewManager;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.util.ArrayList;
public class ElevatorController {
@FXML
ArrayList<Button> buttons;
@FXML
ArrayList<Rectangle> cabinPosition;
@FXML
ArrayList<Rectangle> controls;
private Runnable backToStart;
private ViewManager vw;
@FXML
private void initialize(){
for(Rectangle r : controls) {
r.getStyleClass().add("controls");
}
for(Button button : buttons)
button.getStyleClass().add("buttonsInactive");
System.out.println("Initialize elevator");
}
@FXML
private void closeApp(){
Platform.exit();
}
@FXML
private void backToStart(){
backToStart.run();
}
public void setBackToStart(Runnable r){
backToStart = r;
}
private void recolorFloor(Rectangle floor, int value){
if(value == 0)
floor.setFill(Color.GREEN);
else
floor.setFill(Color.RED);
}
public void setViewManager(ViewManager vw){
this.vw = vw;
}
public void setActionsForFloorIndicator(){
for(Rectangle floor : cabinPosition){
String id = floor.getId();
MyIntegerProperty property = vw.getPropertyManager().getProperty(id);
if(property != null){
property.addValueListener(value -> {
recolorFloor(floor, value);
} );
}
}
}
public void setActionsControls(){
PropertyManager propertyManager = vw.getPropertyManager();
for(Rectangle r : controls){
String id = r.getId();
SimpleIntegerProperty property = propertyManager.getProperty(id);
if(property != null)
property.addListener((observableValue, oldValue, newValue) -> {
if((int)newValue == 1)
r.setFill(Color.BLUE);
else
r.setFill(Color.valueOf("#353634"));
});
}
}
public void setActionsCabinRequests() {
for (Button button : buttons) {
String id = button.getId();
button.setOnAction((value) -> {
button.getStyleClass().removeAll("buttonsInactive");
button.getStyleClass().add("buttonsActive");
BufferManager bufferManager = vw.getBufferManager();
try {
bufferManager.setParameter(id, 1);
}
catch(NullPointerException e){
System.out.println("Cannot find property! Check config!");
}
});
PropertyManager propertyManager = vw.getPropertyManager();
MyIntegerProperty property = propertyManager.getProperty(id);
if (property != null) {
property.addValueListener(newValue -> {
if (newValue == 0) {
button.getStyleClass().removeAll("buttonsActive");
button.getStyleClass().add("buttonsInactive");
}
});
}
}
}
}
| true
|
70d199ab1c7099e857274c5ea06f74a9492b1419
|
Java
|
wffirilat/BetterObsidian
|
/src/main/java/wffirilat/betterobsidian/Blocks/GenBlock.java
|
UTF-8
| 1,385
| 2.609375
| 3
|
[] |
no_license
|
package wffirilat.betterobsidian.Blocks;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import wffirilat.betterobsidian.lib.GrowingTree;
public class GenBlock extends ModBlock {
public GenBlock() {
super("genBlock");
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float faceX, float faceY, float faceZ) {
GrowingTree maze = new GrowingTree(10, 10, 10);
maze.generate();
for(int dx = 0; dx < maze.maze.length; dx++) {
for(int dy = 0; dy < maze.maze[dx].length; dy++) {
for(int dz = 0; dz < maze.maze[dx][dy].length; dz++) {
Block block = maze.maze[dx][dy][dz]? Blocks.stone : Blocks.water;
world.setBlock(x + dx * 2, y + dy * 2, z + dz * 2, block);
world.setBlock(x + dx * 2, y + dy * 2, z + dz * 2 + 1, block);
world.setBlock(x + dx * 2, y + dy * 2 + 1, z + dz * 2, block);
world.setBlock(x + dx * 2, y + dy * 2 + 1, z + dz * 2 + 1, block);
world.setBlock(x + dx * 2 + 1, y + dy * 2, z + dz * 2, block);
world.setBlock(x + dx * 2 + 1, y + dy * 2, z + dz * 2 + 1, block);
world.setBlock(x + dx * 2 + 1, y + dy * 2 + 1, z + dz * 2, block);
world.setBlock(x + dx * 2 + 1, y + dy * 2 + 1, z + dz * 2 + 1, block);
}
}
}
return true;
}
}
| true
|
83392125d7f97dbd4e3d6072f878fe819ad62588
|
Java
|
igor-zac/D-D
|
/src/com/warriors/items/equipments/offense/Weapon.java
|
UTF-8
| 387
| 2.515625
| 3
|
[] |
no_license
|
package com.warriors.items.equipments.offense;
public abstract class Weapon extends OffensiveEquipment{
// CONSTRUCTORS ===================================================================================================
/**
*
* @param name
* @param strength
*/
public Weapon(String name, int strength){
super("Weapon", name, strength);
}
}
| true
|
ab695c72a5e9560742fb858dc66605e6f5609305
|
Java
|
grazianiborcai/Agenda_WS
|
/src/br/com/mind5/dao/DaoStmtExecHelper.java
|
UTF-8
| 6,728
| 2.296875
| 2
|
[] |
no_license
|
package br.com.mind5.dao;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import br.com.mind5.common.DefaultValue;
import br.com.mind5.common.SystemLog;
import br.com.mind5.common.SystemMessage;
import br.com.mind5.info.InfoRecord;
public final class DaoStmtExecHelper<T extends InfoRecord> implements DaoStmtExec<T> {
private List<DaoStmt<T>> sqlStmts;
private List<T> resultset;
private Class<?> stmtClass;
public DaoStmtExecHelper(List<DaoStmtExecOption<T>> options, Class<? extends DaoStmt<T>> classOfStmt, Class<T> classOfT) {
checkArgument(options, classOfStmt, classOfT);
clear();
List<DaoStmtExecOption<T>> copyOptions = makeClone(options);
sqlStmts = buildStmt(copyOptions, classOfStmt, classOfT);
}
private List<DaoStmt<T>> buildStmt(List<DaoStmtExecOption<T>> options, Class<? extends DaoStmt<T>> classOfStmt, Class<T> classOfT) {
List<DaoStmt<T>> results = new ArrayList<>();
for (DaoStmtExecOption<T> eachOption : options) {
DaoStmt<T> sqlStatement = getNewInstanceOfStmt(eachOption, classOfStmt, classOfT);
results.add(sqlStatement);
}
checkBuild(results);
return results;
}
private DaoStmt<T> getNewInstanceOfStmt(DaoStmtExecOption<T> option, Class<? extends DaoStmt<T>> classOfStmt, Class<T> classOfT) {
try {
Constructor<? extends DaoStmt<T>> constructor = classOfStmt.getConstructor(Connection.class, classOfT, String.class);
return (DaoStmt<T>) constructor.newInstance(option.conn, option.recordInfo, option.schemaName);
} catch (Exception e) {
logException(e);
throw new IllegalArgumentException(e);
}
}
@Override public void executeStmt() throws SQLException {
checkStmtGeneration(sqlStmts);
resultset = executeStmt(sqlStmts);
closeStmts(sqlStmts);
}
private void checkStmtGeneration(List<DaoStmt<T>> stmts) throws SQLException {
for (DaoStmt<T> eachStmt : stmts) {
if (eachStmt.checkStmtGeneration() == false) {
logException(new IllegalStateException(SystemMessage.REQUEST_FAILED));
throw new IllegalStateException(SystemMessage.REQUEST_FAILED);
}
}
}
private List<T> executeStmt(List<DaoStmt<T>> stmts) throws SQLException {
List<T> results = new ArrayList<>();
for (DaoStmt<T> eachStmt : stmts) {
eachStmt.executeStmt();
results = addToResults(eachStmt, results);
}
return results;
}
private List<T> addToResults(DaoStmt<T> stmt, List<T> results) {
List<T> stmtResults = stmt.getResultset();
for (T eachResult : stmtResults) {
results.add(eachResult);
}
return results;
}
@Override public void close() {
closeStmts(sqlStmts);
clear();
}
private void closeStmts(List<DaoStmt<T>> stmts) {
for (DaoStmt<T> eachStmt : stmts) {
eachStmt.close();
}
}
private void clear() {
sqlStmts = DefaultValue.list();
resultset = DefaultValue.list();
}
@Override public List<T> getResultset() {
try {
return tryToGetResultset();
} catch (Exception e) {
logException(e);
throw new IllegalStateException(SystemMessage.INTERNAL_ERROR);
}
}
@SuppressWarnings("unchecked")
private List<T> tryToGetResultset() throws CloneNotSupportedException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
List<T> results = new ArrayList<>();
for (T eachResult : this.resultset) {
T resultCloned = (T) eachResult.clone();
results.add(resultCloned);
}
return results;
}
private void checkArgument(List<DaoStmtExecOption<T>> options, Class<? extends DaoStmt<T>> classOfStmt, Class<T> classOfT) {
if (options == null) {
logException(new NullPointerException("options" + SystemMessage.NULL_ARGUMENT));
throw new NullPointerException("options" + SystemMessage.NULL_ARGUMENT);
}
if (classOfStmt == null) {
logException(new NullPointerException("classOfStmt" + SystemMessage.NULL_ARGUMENT));
throw new NullPointerException("classOfStmt" + SystemMessage.NULL_ARGUMENT);
}
if (classOfT == null) {
logException(new NullPointerException("classOfT" + SystemMessage.NULL_ARGUMENT));
throw new NullPointerException("classOfT" + SystemMessage.NULL_ARGUMENT);
}
if (options.isEmpty()) {
logException(new IllegalArgumentException("options" + SystemMessage.EMPTY_ARGUMENT));
throw new IllegalArgumentException("options" + SystemMessage.EMPTY_ARGUMENT);
}
checkEachOption(options);
}
private void checkEachOption(List<DaoStmtExecOption<T>> options) {
for (DaoStmtExecOption<T> eachOption: options) {
if (eachOption.recordInfo == null) {
logException(new NullPointerException("recordInfo" + SystemMessage.NULL_ARGUMENT));
throw new NullPointerException("recordInfo" + SystemMessage.NULL_ARGUMENT);
}
if (eachOption.schemaName == null) {
logException(new NullPointerException("schemaName" + SystemMessage.NULL_ARGUMENT));
throw new NullPointerException("schemaName" + SystemMessage.NULL_ARGUMENT);
}
if (eachOption.conn == null) {
logException(new NullPointerException("conn" + SystemMessage.NULL_ARGUMENT));
throw new NullPointerException("conn" + SystemMessage.NULL_ARGUMENT);
}
}
}
private void checkBuild(List<DaoStmt<T>> stmts) {
if (stmts.isEmpty()) {
logException(new NullPointerException("sqlStatements" + SystemMessage.EMPTY_ARGUMENT));
throw new IllegalArgumentException("sqlStatements" + SystemMessage.EMPTY_ARGUMENT);
}
}
private List<DaoStmtExecOption<T>> makeClone(List<DaoStmtExecOption<T>> options) {
List<DaoStmtExecOption<T>> results = new ArrayList<>();
for (DaoStmtExecOption<T> eachOption : options) {
DaoStmtExecOption<T> eachResult = makeClone(eachOption);
results.add(eachResult);
}
return results;
}
@SuppressWarnings("unchecked")
private DaoStmtExecOption<T> makeClone(DaoStmtExecOption<T> option) {
try {
if (option == null)
return null;
return (DaoStmtExecOption<T>) option.clone();
} catch (CloneNotSupportedException e) {
logException(e);
throw new IllegalStateException(e);
}
}
protected void logException(Exception e) {
Class<?> clazz = stmtClass;
if (clazz == null)
clazz = this.getClass();
SystemLog.logError(clazz, e);
}
}
| true
|
4006b387b4d1b21c82c70891bf0525d2aa5dc6f3
|
Java
|
szdengl/mimiduo-parent
|
/mimiduo-manager/mimiduo-manager-service/src/main/java/net/mimiduo/boot/service/impl/business/MoServiceImpl.java
|
UTF-8
| 769
| 1.84375
| 2
|
[] |
no_license
|
package net.mimiduo.boot.service.impl.business;
import net.mimiduo.boot.dao.BaseDao;
import net.mimiduo.boot.dao.bussiness.MoDao;
import net.mimiduo.boot.pojo.business.Mo;
import net.mimiduo.boot.service.busindess.MoService;
import net.mimiduo.boot.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MoServiceImpl extends BaseServiceImpl<Mo,Long> implements MoService {
@Autowired
private MoDao moDao;
@Override
public BaseDao<Mo, Long> getDao() {
return this.moDao;
}
@Override
public Mo findByMobileAndLinkid(String mobile, String linkid) {
return this.moDao.findByMobileAndLinkid(mobile,linkid);
}
}
| true
|
6c140a8121d16352b4bab120ad9bb9cb95eb8d16
|
Java
|
matheusfreire/Capstone-Project
|
/myshops/app/src/main/java/com/msf/myshops/util/Constants.java
|
UTF-8
| 446
| 1.882813
| 2
|
[] |
no_license
|
package com.msf.myshops.util;
public enum Constants {
SHOP("SHOP"),
NEW_SHOP_IMPL("NEW_SHOP_IMPL"),
PATTERN_DATE_BR("dd/MM/yyyy"),
SHOP_PREFERENCES("UID_SHOP"),
NOTIFICATION_CHANNEL("MY_SHOP"),
KEY_NEW_ITEM_FRAG("NEW_ITEM_FRAGMENT"),
KEY_UNIQUE("users"),
CHANNEL_ID("0");
private String key;
Constants(String key){
this.key = key;
}
public String getKey() {
return key;
}
}
| true
|
d2e487c7a94135c7d58430e798e307b90d8c77a0
|
Java
|
Krigu/bookstore
|
/bookstore-jpa/src/test/java/org/books/data/dto/MarshallerTest.java
|
UTF-8
| 2,598
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
package org.books.data.dto;
import org.testng.Assert;
import org.testng.annotations.Test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
public class MarshallerTest {
@Test
public void testMarshallOneItem() throws JAXBException {
String rsXml = "<orderRequest>\n" +
" <customerNr>C-1</customerNr>\n" +
" <items>\n" +
" <bookInfo>\n" +
" <isbn>1935182994</isbn>\n" +
" <title>Java EE</title>\n" +
" <price>15.80</price>\n" +
" </bookInfo>\n" +
" <quantity>3</quantity>\n" +
" </items>\n" +
"</orderRequest>";
JAXBContext jaxbContext = JAXBContext.newInstance(OrderRequest.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
OrderRequest response = (OrderRequest) unmarshaller.unmarshal(new ByteArrayInputStream(rsXml.getBytes()));
Assert.assertEquals("1935182994", response.getItems().get(0).getBook().getIsbn());
}
@Test
public void testMarshallMultipleItems() throws JAXBException {
String rsXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<orderRequest>\n" +
" <customerNr>C-1</customerNr>\n" +
" <items>\n" +
" <bookInfo>\n" +
" <isbn>1935182994</isbn>\n" +
" <title>Java EE</title>\n" +
" <price>15.00</price>\n" +
" </bookInfo>\n" +
" <quantity>3</quantity>\n" +
" </items>\n" +
" <items>\n" +
" <bookInfo>\n" +
" <isbn>1935182994</isbn>\n" +
" <title>Java EE</title>\n" +
" <price>15.00</price>\n" +
" </bookInfo>\n" +
" <quantity>3</quantity>\n" +
" </items>\n" +
"</orderRequest>";
JAXBContext jaxbContext = JAXBContext.newInstance(OrderRequest.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
OrderRequest response = (OrderRequest) unmarshaller.unmarshal(new ByteArrayInputStream(rsXml.getBytes()));
Assert.assertEquals(2, response.getItems().size());
Assert.assertEquals("1935182994", response.getItems().get(0).getBook().getIsbn());
}
}
| true
|
f6e0f5b5ae978da6d392cef006805356ace5eb07
|
Java
|
cnsgithub/primefaces
|
/src/main/java/org/primefaces/component/tree/UITreeNode.java
|
UTF-8
| 1,229
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2009-2019 PrimeTek.
*
* 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.primefaces.component.tree;
public class UITreeNode extends UITreeNodeBase {
public static final String COMPONENT_TYPE = "org.primefaces.component.UITreeNode";
public String getIconToRender(boolean expanded) {
String icon = getIcon();
if (icon != null) {
return icon;
}
else {
String expandedIcon = getExpandedIcon();
String collapsedIcon = getCollapsedIcon();
if (expandedIcon != null && collapsedIcon != null) {
return expanded ? expandedIcon : collapsedIcon;
}
}
return null;
}
}
| true
|
f86cbf9932c9adbecc8559fb25b2e5d841b5c296
|
Java
|
RubiMaistro/codes-prog2
|
/EPAM/Creation Design Patterns/SingleObject.java
|
ISO-8859-2
| 1,412
| 2.78125
| 3
|
[] |
no_license
|
/*
* Egyke programtervezsi minta
*
* Egy obijektumra korltozza az osztly ltrehozhat pldnyainak a szmt
*
* Memrit sporol, mert nem lesz minden alkalommal ltrehozva, amikor kell, csak egyszer s jra s jra lesz hasznlva
* A globlis vltozkkal szemben gyakran az egykket rszestik elnyben, mivel:
* Nem szennyezik a nvteret szksgtelen vltozkkal.
* Lehetv teszik a lusta allokcit s inicializcit, mg a globlis vltozk mindig fogyasztanak erforrsokat.
* Az egyke hasznlhat lusta inicializcival. Ekkor a pldny csak az osztlymetdus els hvsakor jn ltre.
* Ha ezt prhuzamos krnyezetben hasznljk, akkor biztostani kell, hogy ne legyen race condition, klnben
* tbb szl is ltrehozhat egy pldnyt, ami kritikus a rendszer szempontjbl, s annak sszeomlst
* okozhatja
*/
package CreationDesignPatterns;
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
| true
|
b6b7017e67c05dce7d22c6b46488afb4d6d5c1c4
|
Java
|
angeojohnym/amersouq-angeo
|
/app/src/main/java/com/shopping/techxform/amersouq/activities/ViewWishList.java
|
UTF-8
| 6,614
| 2
| 2
|
[] |
no_license
|
package com.shopping.techxform.amersouq.activities;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.shopping.techxform.amersouq.R;
import com.shopping.techxform.amersouq.RetrofitHelpers.ApiClient;
import com.shopping.techxform.amersouq.RetrofitHelpers.ApiInterface;
import com.shopping.techxform.amersouq.RetrofitHelpers.Models.DeleteWishData.DeleteWishModel;
import com.shopping.techxform.amersouq.RetrofitHelpers.Models.WishOutput.WishAd;
import com.shopping.techxform.amersouq.RetrofitHelpers.Models.WishOutput.WishOutputList;
import com.shopping.techxform.amersouq.Utils.Constants;
import com.shopping.techxform.amersouq.adapters.WishListAdapter;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
public class ViewWishList extends AppCompatActivity {
RecyclerView wishlist_rv;
Activity activity;
Context context;
WishListAdapter wishListAdapter;
boolean page_end = false;
int page = 0;
List<WishAd> wishAds = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_wish_list);
wishlist_rv = (RecyclerView) findViewById(R.id.wishlist_td);
activity = this;
context = this;
wishlist_rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
// Recycle view scrolling down...
if (!page_end) {
if (recyclerView.canScrollVertically(RecyclerView.FOCUS_DOWN) == false) {
page++;
// Toast.makeText(getApplicationContext(), "Loading....", Toast.LENGTH_LONG).show();
// String page_string = Integer.toString(page);
set_all_wish();
}
}
}
}
});
set_all_wish();
}
public void set_all_wish() {
wishlist_rv.setAdapter(null);
wishAds.clear();
int userid = getSharedPreferences(Constants.pref_name, Context.MODE_PRIVATE).getInt(Constants.user_id, 0);
final KProgressHUD hud = KProgressHUD.create(ViewWishList.this)
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("Please wait")
.show();
ApiInterface apiService =
ApiClient.getRideClient().create(ApiInterface.class);
Call<WishOutputList> call = apiService.get_wish_list(Integer.toString(userid), Integer.toString(page));
call.enqueue(new Callback<WishOutputList>() {
@Override
public void onResponse(Call<WishOutputList> call, retrofit2.Response<WishOutputList> response) {
hud.dismiss();
// wishAds.clear();
String URL = call.request().url().toString();
System.out.println("Retrofit URL : " + URL);
if (response.code() == 200) {
WishOutputList responseBody = response.body();
try {
String status = responseBody.getCode();
if (status.equals("200")) {
if (responseBody.getWishAds().size() > 0) {
wishAds.addAll(responseBody.getWishAds());
wishListAdapter = new WishListAdapter(wishAds, activity, context);
wishlist_rv.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
wishlist_rv.setItemAnimator(new DefaultItemAnimator());
wishlist_rv.setNestedScrollingEnabled(false);
wishlist_rv.setAdapter(wishListAdapter);
} else {
page_end = true;
}
} else {
page_end = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
hud.dismiss();
}
@Override
public void onFailure(Call<WishOutputList> call, Throwable t) {
hud.dismiss();
}
});
}
public void remove_wish(String wish_id) {
// final ArrayList<SpinnerModel> loc_list = new ArrayList<>();
// loc_list.add(new SpinnerModel("0", "Select Location"));
final KProgressHUD hud = KProgressHUD.create(activity)
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("Please wait")
.show();
ApiInterface apiService =
ApiClient.getRideClient().create(ApiInterface.class);
Call<DeleteWishModel> call = apiService.remove_wishlist(wish_id);
call.enqueue(new Callback<DeleteWishModel>() {
@Override
public void onResponse(Call<DeleteWishModel> call, retrofit2.Response<DeleteWishModel> response) {
hud.dismiss();
String URL = call.request().url().toString();
System.out.println("Retrofit URL : " + URL);
if (response.code() == 200) {
DeleteWishModel responseBody = response.body();
try {
String status = responseBody.getCode();
if (status.equals("200")) {
System.out.println("AMER SOUQ :::: Ads deleted " + status);
set_all_wish();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
hud.dismiss();
}
@Override
public void onFailure(Call<DeleteWishModel> call, Throwable t) {
hud.dismiss();
}
});
}
}
| true
|