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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c8fff91be9e0675a2843ba3e786da7fd20ea185f
|
Java
|
tarantelot/AdrenalinCity
|
/app/src/main/java/project/taras/ua/adrenalincity/Activity/MovieMVC/StarView/StarView.java
|
UTF-8
| 4,112
| 2.375
| 2
|
[] |
no_license
|
package project.taras.ua.adrenalincity.Activity.MovieMVC.StarView;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import project.taras.ua.adrenalincity.R;
/**
* Created by Taras on 17.05.2017.
*/
public class StarView extends View {
private float ratingPercent = 0f;
private float ratingScore = 0f;
private Bitmap filledStar;
private Bitmap emptyStar;
private Paint paintText;
private Context context;
private int displayHeight;
private int displayWidth;
public StarView(Context context) {
super(context);
init(context);
}
public StarView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context){
this.context = context;
this.displayWidth = measureDisplay().widthPixels;
this.displayHeight = measureDisplay().heightPixels;
initComponentsSize();
filledStar = BitmapFactory.decodeResource(context.getResources(), R.drawable.filled_star);
filledStar = Bitmap.createScaledBitmap(filledStar, 100, 100, true);
emptyStar = BitmapFactory.decodeResource(context.getResources(), R.drawable.empty_star);
emptyStar = Bitmap.createScaledBitmap(emptyStar, 100, 100, true);
paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
paintText.setTextSize(textHeight);
//paintText.setTextAlign(Paint.Align.CENTER);
paintText.setColor(Color.WHITE);
}
int starHeight;
int starWidth;
int textHeight;
int viewHeight;
int viewWidth;
private void initComponentsSize(){
starHeight = displayHeight / 10;
starWidth = displayHeight / 13;
textHeight = starHeight / 5;
viewWidth = starWidth;
viewHeight = starHeight + textHeight;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpec = MeasureSpec.makeMeasureSpec(viewWidth, MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
setMeasuredDimension(widthSpec, heightSpec);
}
@Override
protected void onDraw(Canvas canvas) {
drawStar(canvas);
drawRating(canvas);
}
private void drawStar(Canvas canvas){
canvas.drawBitmap(emptyStar, 0f, 0f, null);
canvas.save();
//Log.v("measurheight", ""+getMeasuredHeight());
//canvas.clipRect(0, (getMeasuredHeight() - 25) - (getMeasuredHeight() - 25) * ratingPercent, getWidth(), getMeasuredHeight() - 25);
canvas.clipRect(0, starHeight - starHeight * ratingPercent, viewWidth, starHeight);
canvas.drawBitmap(filledStar, 0f, 0f, null);
canvas.restore();
}
private void drawRating(Canvas canvas){
Rect bounds = new Rect();
paintText.getTextBounds(rating_score, 0, rating_score.length(), bounds);
int height = bounds.height();
int width = bounds.width();
Log.v("t_w", ""+width);
canvas.drawText(rating_score, starWidth / 2 - (width / 2), viewHeight - textHeight, paintText);
//canvas.drawText();
}
float perc;
String rating_score = "";
public void setRating(float percent){
perc = percent / 5;
this.ratingPercent = perc;
this.ratingScore = percent;
this.rating_score = String.valueOf(Math.floor(ratingScore * 100) / 100)+"/5";
Log.i("perc_inf", ""+perc);
invalidate();
}
public DisplayMetrics measureDisplay() {
DisplayMetrics metrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
return metrics;
}
}
| true
|
2d1ba1c32b91c15b1e9e513f3e1e273bd9adb65a
|
Java
|
muneendrag/javaprograms
|
/eclipse-workspace/Learnjava/src/oopsConcept/HybridInheritance.java
|
UTF-8
| 536
| 3.6875
| 4
|
[] |
no_license
|
package oopsConcept;
class A1{
void m1() {
System.out.println("A1");
}
}
interface I1{
void m2();
}
interface I2{
void m3();
}
public class HybridInheritance extends A1 implements I1,I2{
@Override
public void m3() {
System.out.println("m3 method from interfece I2");
}
@Override
public void m2() {
System.out.println("m2 method from interfece I1");
}
public static void main(String[] args) {
HybridInheritance hi=new HybridInheritance();
hi.m1();
hi.m2();
hi.m3();
}
}
| true
|
5956a2409d50fa4a64ead6f1b3b4afbdc48def78
|
Java
|
StephenChio/deyan
|
/OneTech_common/src/main/java/com/OneTech/common/util/CodeUtils/SaltUtils.java
|
UTF-8
| 233
| 1.90625
| 2
|
[] |
no_license
|
package com.OneTech.common.util.CodeUtils;
import org.apache.commons.codec.digest.DigestUtils;
public class SaltUtils {
public static String getSalt(String str){
return DigestUtils.md5Hex(str).substring(0,10);
}
}
| true
|
2614552228a6349a0509b55c78b8c3aea2fe063a
|
Java
|
airufei/xCode
|
/src/main/java/com/cn/cooxin/admin/entity/Role.java
|
UTF-8
| 546
| 1.75
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.cn.cooxin.admin.entity;
import com.cn.cooxin.code.entity.BaseEntitys;
/**
* 角色信息Entity
* @author airufei
* @version 2017-01-18
*/
public class Role extends BaseEntitys {
private static final long serialVersionUID = 1L;
private String name; // 角色名称
public Role() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true
|
9583c95fd94173e2799cd0f57d2a9bc7e482c1cd
|
Java
|
ahmadshakla/postPc_ex4
|
/app/src/main/java/com/example/fun/UnCompletedTodoActivity.java
|
UTF-8
| 4,079
| 2.59375
| 3
|
[] |
no_license
|
package com.example.fun;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class UnCompletedTodoActivity extends AppCompatActivity {
private static final String TODO_TO_MOVE = "todoToMove";
private static final int UNFINISHED_CODE = 1;
private static final String TIME_FORMAT = "dd.MM.yyyy HH:mm";
private static final String CREATE_TODO = "Created on: ";
private static final String MODIFY_TODO = "Last modified: ";
private static final String CONTENT_CHANGED = "the TODO content was changed successfully! ";
public static final String MOVED_INDEX = "moved index";
private Button apply;
private Button mark;
private TextView modification;
private EditText text;
private Gson gson;
private int index;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_un_completed_todo);
apply = findViewById(R.id.un_mark_button);
mark = findViewById(R.id.delete_button);
TextView creation = findViewById(R.id.creation_textView);
modification = findViewById(R.id.modification_textView);
text = findViewById(R.id.editText);
final Intent intent = getIntent();
gson = new Gson();
final Todo todo = gson.fromJson(intent.getStringExtra(TODO_TO_MOVE), Todo.class);
index = intent.getIntExtra(MOVED_INDEX,0);
text.setText(todo.getTodoText());
creation.setText(CREATE_TODO + todo.getCreationTime());
modification.setText(MODIFY_TODO + todo.getModificationTime());
handleModifyingButton(intent, todo);
handleMarkingButton(intent, todo);
}
/**
* handles what to do when we press the mark button
*
* @param intent the intent we are updating
* @param todo the todoItem we are handling
*/
private void handleMarkingButton(final Intent intent, final Todo todo) {
mark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
todo.markDone();
String updatedTodo = gson.toJson(todo);
intent.putExtra(TODO_TO_MOVE, updatedTodo);
intent.putExtra(MOVED_INDEX, index);
Toast.makeText(UnCompletedTodoActivity.this, "TODO " + todo.getTodoText() + " is now DONE. BOOM!",
Toast.LENGTH_SHORT).show();
setResult(RESULT_OK, intent);
finish();
}
});
}
/**
* handles what to do when we press the modify button
*
* @param intent the intent we are updating
* @param todo the todoItem we are handling
*/
private void handleModifyingButton(final Intent intent, final Todo todo) {
apply.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View view) {
String newText = text.getText().toString();
todo.setTodoText(newText);
String newTime = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault()).format(new Date());
todo.setModificationTime(newTime);
modification.setText(MODIFY_TODO + newTime);
String updatedTodo = gson.toJson(todo);
intent.putExtra(TODO_TO_MOVE, updatedTodo);
intent.putExtra(MOVED_INDEX, index);
setResult(RESULT_OK, intent);
Toast.makeText(UnCompletedTodoActivity.this, CONTENT_CHANGED,
Toast.LENGTH_SHORT).show();
}
});
}
}
| true
|
ab681136895c059f5b8642261c18037c25b9a07a
|
Java
|
hmntstr/File-Classification-java
|
/Fileclassification1.java
|
UTF-8
| 9,173
| 3.046875
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.io.File;
import javax.swing.*;
class Dictionary
{
File folder;
File[] listOfFiles;
LinkedHashSet<String> hs=new LinkedHashSet<String>();
int res[][],size;
String ans="";
Dictionary(File folder)
{
this.folder=folder;
File[] listOfFiles1=folder.listFiles();
listOfFiles=listOfFiles1;
int res1[][]=new int[listOfFiles.length][1000000];
res=res1;
}
String openmake()
{
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
String fileName =listOfFiles[i].getName() ;
String fN = listOfFiles[i].getAbsolutePath();
// This will reference one line at a time
String line = null;
try
{
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fN);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens())
{
String temp=st.nextToken();
if(hs.contains(temp)==true)
{
Iterator it=hs.iterator();
int k=0;
while(it.hasNext())
{
if(it.next().equals(temp))
{
break;
}
k++;
}
res[i][k]=res[i][k]+1;
}
else if(temp.equals("the") || temp.equals("a") || temp.equals("is") || temp.equals("there") || temp.equals("was") || temp.equals("will") || temp.equals("I") || temp.equals("an") || temp.equals("am") || temp.equals("are") || temp.equals("this") || temp.equals("that") ){}
else if(hs.contains(temp)==false)
{
res[i][hs.size()]=1;
hs.add(temp);
}
}
}
ans=ans+"\n"+fileName+ "read complete";
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
ans=ans+"\nUnable to open file '" + fileName + "'";
}
catch(IOException ex)
{
ans=ans+"\nError reading file '"+ fileName + "'";
}
}
if (listOfFiles[i].isDirectory())
{
File folder1 = new File(listOfFiles[i].getAbsolutePath());
File[] listOfFiles1 = folder1.listFiles();
for (int j = 0; j < listOfFiles1.length; j++)
{
if (listOfFiles1[j].isFile())
{
String fileName1 =listOfFiles1[j].getName() ;
String fN1 = listOfFiles1[j].getAbsolutePath();
String line1 = null;
try
{
FileReader fileReader1 = new FileReader(fN1);
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
while((line1 = bufferedReader1.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line1);
while (st.hasMoreTokens())
{
String temp=st.nextToken();
if(hs.contains(temp)==true)
{
Iterator it=hs.iterator();
int k=0;
while(it.hasNext())
{
if(it.next().equals(temp))
{
break;
}
k++;
}
res[i][k]=res[i][k]+1;
}
else if(temp.equals("the") || temp.equals("a") || temp.equals("is") || temp.equals("there") || temp.equals("was") || temp.equals("will") || temp.equals("I") || temp.equals("an") || temp.equals("am") || temp.equals("are") || temp.equals("this") || temp.equals("that") ){}
else if(hs.contains(temp)==false)
{
res[i][hs.size()]=1;
hs.add(temp);
}
}
}
bufferedReader1.close();
ans=ans+"\n"+fileName1;
}
catch(FileNotFoundException ex)
{
ans=ans+"\nUnable to open file '" + fileName1 + "'";
}
catch(IOException ex)
{
ans=ans+"\nError reading file '" + fileName1 + "'";
}
}
}
ans=ans+"\n---------------------------------------------------------------------------------------------------------";
ans=ans+"\n"+folder1.getName()+" read complete";
ans=ans+"\n---------------------------------------------------------------------------------------------------------";
}
}
size=hs.size();
return ans;
}
}
class Idf extends Dictionary
{
double idf[];
Idf(File folder)
{
super(folder);
}
void calculateidf()
{
double idf1[]=new double[super.size];
idf=idf1;
for(int i=0;i<hs.size();i++)
{
for(int j=0;j<listOfFiles.length;j++)
{
idf[i]=idf[i]+(double)res[j][i];
}
}
for(int i=0;i<hs.size();i++)
{
idf[i]=(Math.log((double)(listOfFiles.length/idf[i])))/(Math.log(2));
}
}
}
class Tfidf extends Idf
{
double tfidf[][];
Tfidf(File folder)
{
super(folder);
}
void calculatetfidf()
{
double tfidf1[][]=new double[listOfFiles.length][hs.size()];
tfidf=tfidf1;
for(int i=0;i<listOfFiles.length;i++)
{
for(int j=0;j<hs.size();j++)
{
tfidf[i][j]=res[i][j]*idf[j];
}
}
}
}
class D extends Tfidf
{
double d[];
D(File folder)
{
super(folder);
}
void calculated()
{
double d1[]=new double[listOfFiles.length];
d=d1;
for(int i=0;i<listOfFiles.length;i++)
{
for(int j=0;j<hs.size();j++)
{
d[i]=d[i]+tfidf[i][j]*tfidf[i][j];
}
d[i]=Math.sqrt(d[i]);
}
}
}
class NewFile extends D
{
String fN1;
String line1=null;
String ans="";
double q[];
NewFile(String fN1,File folder)
{
super(folder);
this.fN1=fN1;
}
String openq()
{
double q1[]=new double[hs.size()];
q=q1;
try
{
FileReader fileReader1 = new FileReader(fN1);
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
while((line1 = bufferedReader1.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line1);
while (st.hasMoreTokens())
{
String temp=st.nextToken();
if(hs.contains(temp)==true)
{
Iterator it=hs.iterator();
int k=0;
while(it.hasNext())
{
if(it.next().equals(temp))
{
break;
}
k++;
}
q[k]=q[k]+1;
}
}
}
}
catch(FileNotFoundException ex)
{
ans=ans+"\nUnable to open file '" + fN1 + "'";
}
catch(IOException ex)
{
ans=ans+"\nError reading file '" + fN1 + "'";
}
return ans;
}
}
class Q extends NewFile
{
double max=0;
Q(String fN1,File folder)
{
super(fN1,folder);
}
void calculateq()
{
for(int i=0;i<hs.size();i++)
{
if(max<q[i])
{
max=q[i];
}
}
for(int j=0;j<hs.size();j++)
{
q[j]=(q[j]/max)*idf[j];
}
}
}
class Query extends Q
{
double query=0;
Query(String fN1,File folder)
{
super(fN1,folder);
}
void calculatequery()
{
for(int i=0;i<hs.size();i++)
{
query=query+q[i]*q[i];
}
query=Math.sqrt(query);
}
}
class CosineSim extends Query
{
double cosSim[];
String ans="";
CosineSim(String fN1,File folder)
{
super(fN1,folder);
}
String calculatecossim()
{
double cosSim1[]=new double[listOfFiles.length];
cosSim=cosSim1;
for(int i=0;i<listOfFiles.length;i++)
{
for(int k=0;k<hs.size();k++)
{
cosSim[i]=cosSim[i]+tfidf[i][k]*q[k];
}
cosSim[i]=cosSim[i]/(d[i]*query);
}
System.out.print("\n");
DecimalFormat decFor = new DecimalFormat("0.00");
max=0;
int ind=0;
ans=ans+"\n---------------------------------------------------------------------------------------------------------";
ans=ans+"\nRelation Factor:";
ans=ans+"\n---------------------------------------------------------------------------------------------------------\n";
for(int i=0;i<listOfFiles.length;i++)
{
ans=ans+listOfFiles[i].getName()+"->"+decFor.format(cosSim[i])+" ";
ans=ans+"\n";
if(max<cosSim[i])
{
max=cosSim[i];
ind=i;
}
}
ans=ans+"\n---------------------------------------------------------------------------------------------------------";
ans=ans+"\nDOCUMENT RELATED TO FOLDER:"+listOfFiles[ind].getName();
ans=ans+"\n---------------------------------------------------------------------------------------------------------";
return ans;
}
}
public class Fileclassification1
{
public static void main(String[] args)
{
File folder = new File("G:\\HS\\challenging ass\\20news-18828");
String fN1 = "G:\\HS\\challenging ass\\20news-18828\\alt.atheism\\49960.txt";
CosineSim cob=new CosineSim(fN1,folder);
String ans=cob.openmake();
cob.calculateidf();
cob.calculatetfidf();
cob.calculated();
String ans1=cob.openq();
cob.calculateq();
cob.calculatequery();
String ans2=cob.calculatecossim();
System.out.println(ans2);
}
}
| true
|
fd8ab2d8562e027a8ddeeb70dc6fbe2bf3609446
|
Java
|
jeong-chan/SocialRunClub
|
/app/src/main/java/com/example/registerloginexample/User_DB.java
|
UTF-8
| 1,996
| 2.640625
| 3
|
[] |
no_license
|
package com.example.registerloginexample;
import java.util.ArrayList;
// 사용자의 개인정보와 현재 달린 경도와 위도
public class User_DB {
private String member_id;
private String member_name;
private int member_age;
private int member_height;
private double member_weight;
private String member_gender;
private ArrayList<String> latitude =new ArrayList<String>();
private ArrayList<String> longitude=new ArrayList<String>();
public String getMember_id() {
return member_id;
}
public String getMember_name() {
return member_name;
}
public int getMember_age() {
return member_age;
}
public int getMember_height() {
return member_height;
}
public double getMember_weight() {
return member_weight;
}
public String getMember_gender() {
return member_gender;
}
public ArrayList<String> get_latitude(){
return latitude;
}
public ArrayList<String> get_longitude(){
return longitude;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
public void setMember_age(int member_age) {
this.member_age = member_age;
}
public void setMember_height(int member_height) {
this.member_height = member_height;
}
public void setMember_weight(double member_weight) {
this.member_weight = member_weight;
}
public void setMember_gender(String member_gender) {
this.member_gender = member_gender;
}
//위도값 리스트 초기화후 다시 저장
public void setLatitude (ArrayList<String> latitude){
this.latitude.clear();
this.latitude = latitude;
}
public void setLongitude (ArrayList<String> longitude){
this.longitude.clear();
this.longitude = longitude;
}
}
| true
|
e3f499374a8b8bb0c7821417c290c81133682c43
|
Java
|
magicalpuffin/2018-APCSA
|
/Tetris/LBlockRight.java
|
UTF-8
| 7,603
| 2.71875
| 3
|
[] |
no_license
|
package Tetris;
import java.awt.Color;
import java.awt.Graphics;
public class LBlockRight extends Block implements Locatable
{
private int xPos=200;
private int yPos=0;
private int width=40;
private int height=120;
private int speed=1;
private int orientation=0;
private Color color;
public LBlockRight()
{
color=Color.BLACK;
}
//add the other set methods
public void setColor(Color col)
{
color=col;
}
public void setPos(int x, int y)
{
setX(x);
setY(y);
}
public void setX(int x)
{
xPos=x;
}
public void setY(int y)
{
yPos=y;
}
public void setWidth(int w)
{
width=w;
}
public void setHeight(int h)
{
height=h;
}
public void setSpeed(int s)
{
speed=s;
}
public int getX()
{
return xPos;
}
public int getY()
{
return yPos;
}
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
public Color getColor()
{
return color;
}
public int getSpeed()
{
return speed;
}
public void draw(Graphics window)
{
window.setColor(color);
if (orientation==0)
{
window.fillRect(this.getX(), this.getY(), getWidth(), getHeight());
window.fillRect(this.getX()+40, this.getY()+80, 40, 40);
}
if (orientation==1)
{
window.fillRect(this.getX(), this.getY(), getWidth(), getHeight());
window.fillRect(this.getX(), this.getY()+40, 40, 40);
}
if (orientation==2)
{
window.fillRect(this.getX()+40, this.getY(), getWidth(), getHeight());
window.fillRect(this.getX(), this.getY(), 40, 40);
}
if (orientation==3)
{
window.fillRect(this.getX(), this.getY(), getWidth(), getHeight());
window.fillRect(this.getX()+80, this.getY()-40, 40, 40);
}
}
public void draw(Graphics window, Color col)
{
window.setColor(col);
window.fillRect(this.getX(), this.getY(), getWidth(), getHeight());
}
public void rotate()
{
int temp=0;
if (orientation==0&&getX()<320)
{
temp=getWidth();
setWidth(getHeight());
setHeight(temp);
orientation=1;
System.out.println("1");
}
else if(orientation==1&&getX()<320)
{
temp=getWidth();
setWidth(getHeight());
setHeight(temp);
orientation=2;
System.out.println("2");
}
else if(orientation==2&&getX()<320)
{
temp=getWidth();
setWidth(getHeight());
setHeight(temp);
orientation=3;
System.out.println("3");
}
else if(orientation==3&&getX()<320)
{
temp=getWidth();
setWidth(getHeight());
setHeight(temp);
orientation=0;
System.out.println("0");
}
}
public boolean hitBottom(Block[][] blockActive, int[][] activated)
{
if (getY()>620&&orientation==0)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY())
{
activated[r][c]=1;
activated[r][c+1]=1;
activated[r][c+2]=1;
activated[r+1][c+2]=1;
setY(0);
}
}
}
return true;
}
if (getY()>660&&orientation==1)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY())
{
activated[r][c]=1;
activated[r][c+1]=1;
activated[r+1][c]=1;
activated[r+2][c]=1;
setY(0);
}
}
}
return true;
}
if (getY()>620&&orientation==2)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY())
{
activated[r][c]=1;
activated[r+1][c]=1;
activated[r+1][c+1]=1;
activated[r+1][c+2]=1;
setY(0);
}
}
}
return true;
}
if (getY()>660&&orientation==3)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY())
{
activated[r][c+1]=1;
activated[r+1][c+1]=1;
activated[r+2][c+1]=1;
activated[r+2][c]=1;
setY(0);
}
}
}
return true;
}
return false;
}
public boolean collided(Block[][] blockActive, int[][] activated)
{
if (orientation==0)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY()&&((activated[r][c+3]==1)||(activated[r+1][c+3]==1)))
{
activated[r][c]=1;
activated[r][c+1]=1;
activated[r][c+2]=1;
activated[r+1][c+2]=1;
setY(0);
return true;
}
}
}
}
if (orientation==1)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY()&&(activated[r][c+2]==1||activated[r+1][c+1]==1||activated[r+2][c+1]==1))
{
activated[r][c]=1;
activated[r][c+1]=1;
activated[r+1][c]=1;
activated[r+2][c]=1;
setY(0);
return true;
}
}
}
}
if (orientation==2)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY()&&(activated[r][c+1]==1||activated[r+1][c+3]==1))
{
activated[r][c]=1;
activated[r+1][c]=1;
activated[r+1][c+1]=1;
activated[r+1][c+2]=1;
setY(0);
return true;
}
}
}
}
if (orientation==3)
{
for (int r=0;r<blockActive.length;r++)
{
for (int c=0;c<blockActive[0].length;c++)
{
if (blockActive[r][c].getX()==getX()&&blockActive[r][c].getY()==getY()&&(activated[r][c+2]==1||activated[r+1][c+2]==1||activated[r+2][c+2]==1))
{
activated[r][c+1]=1;
activated[r+1][c+1]=1;
activated[r+2][c+1]=1;
activated[r+2][c]=1;
setY(0);
return true;
}
}
}
}
return false;
}
public boolean inBoundRight()
{
if (orientation==0)
{
if (getX()<320)
{
return true;
}
}
else if (orientation==1)
{
if (getX()<280)
{
return true;
}
}
else if (orientation==2)
{
if (getX()<320)
{
return true;
}
}
else if (orientation==3)
{
if (getX()<280)
{
return true;
}
}
return false;
}
public boolean equals(Object obj)
{
if (((Block)obj).getHeight()==getHeight()
&&((Block)obj).getWidth()==getWidth()
&&((Block)obj).getColor().equals(getColor()))
{
return true;
}
return false;
}
//add the other get methods
//add a toString() method - x , y , width, height, color
public String toString()
{
String output="";
output+=xPos+","+yPos+" Width:"+width+" Height:"+height+" "+color+"";
return output;
}
}
| true
|
ad97a649ae8441bf928d88e46935fda96b49aee3
|
Java
|
YuvrajVijay/Android-Studio-Java
|
/IntroFirestore/app/src/main/java/com/example/introfirestore/Journal.java
|
UTF-8
| 542
| 2.671875
| 3
|
[] |
no_license
|
package com.example.introfirestore;
public class Journal {
String title;
String thoughts;
public Journal() {
}
public Journal(String title, String thoughts) {
this.title = title;
this.thoughts = thoughts;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThoughts() {
return thoughts;
}
public void setThoughts(String thoughts) {
this.thoughts = thoughts;
}
}
| true
|
6f165fff7d234ece83bb4156810b41ab72652720
|
Java
|
Housum/javaporject
|
/ActOfJava/src/com/hotusm/designpattern/MediatorTest.java
|
GB18030
| 6,360
| 3.625
| 4
|
[] |
no_license
|
package com.hotusm.designpattern;
/**
*
* @author Hotusm
* ģʽ->ͣģʽ
* 1.ͣģʽǶΪģʽͣģʽװһϵжõķʽ
* ʹЩáӶʹǿԽɢϡЩеijЩ
* ֮÷ıʱӰ쵽һЩ֮áӶ
* ֤ЩÿԱ˴˶ر仯
* 2.ͨĽһĵĵи֮Э,ǽֱӵ,д
* ϵ
* 3.,Կ,CPUֹ֮ϵ:帺Щĺ,ֱ֮ͨãͼƬ:ͣģʽ2
* 4.Эͬ
*
* ͣģʽе:
* ɢ
*ͣģʽͨѶͬ¶֮Ľװͣ߶棬Ӷʹͬ¶֮ɢϣϿ
* һͬ¶ͿԶر仯ãǰǣһȫˡ
* ڼпƽ
* ͬ¶Ľװڵͣ߶漯йʹЩΪ仯ʱֻҪĵͣ߶Ϳˣ
* ȻѾõϵͳôչͣ߶ͬҪġ
* ۶ԶһԶ
* ûʹõͣģʽʱͬ¶֮ĹϵͨǶԶģͣ߶Ժͣ߶ͬ¶Ĺϵͨ
* ˫һԶ࣬öĹϵʵ֡
* ͣģʽȱ:
* ٵͣģʽһDZȱǣȼлͬ¶Ľdz࣬ұȽϸӣЩȫеͣߵʱ
* ᵼµͣ߶ʮָӣڹά
*/
public class MediatorTest {
public static void main(String[] args) {
MainMediator mediator = new MainMediator();
//ͬ
CDDriver cd = new CDDriver(mediator);
CPU cpu = new CPU(mediator);
Video vc = new Video(mediator);
Sound sc = new Sound(mediator);
//õ֪ͣͬ
mediator.setCdDriver(cd);
mediator.setCpu(cpu);
mediator.setVideo(vc);
mediator.setSound(sc);
//ʼӰѹ̷ʼ
cd.readCD();
}
}
//ͣ߶ӿ
interface Mediator{
public void changed(Colleague colleague);
}
//ͬ¶
abstract class Colleague{
protected Mediator mediator;
public Colleague(Mediator mediator) {
super();
this.mediator = mediator;
}
public Mediator getMediator() {
return mediator;
}
}
//ͬ
class CDDriver extends Colleague{
//ӹȡ
private String data="";
public CDDriver(Mediator mediator) {
super(mediator);
}
public String getData() {
return data;
}
public void readCD(){
//Ƶ,
this.data="One Price,ҵ";
mediator.changed(this);
}
}
//CPUͬ
class CPU extends Colleague{
private String videoData;
private String soundData;
public String getVideoData() {
return videoData;
}
public void setVideoData(String videoData) {
this.videoData = videoData;
}
public String getSoundData() {
return soundData;
}
public void setSoundData(String soundData) {
this.soundData = soundData;
}
public CPU(Mediator mediator) {
super(mediator);
}
public void executeData(String data){
//ݷֽǰƵݣƵ
String[] array = data.split(",");
this.videoData = array[0];
this.soundData = array[1];
//֪ͨ壬CPUɹ
getMediator().changed(this);
}
}
class Video extends Colleague{
public Video(Mediator mediator) {
super(mediator);
}
/**
* ʾƵ
*/
public void showData(String data){
System.out.println("տ:"+data);
}
}
class Sound extends Colleague{
public Sound(Mediator mediator) {
super(mediator);
}
/**
* ʾƵ
*/
public void showData(String data){
System.out.println(":"+data);
}
}
/**
* ʵĵͣ,Ще,ʹܹȷ,
* ϶Ȳ
* @author Hotusm
*
*/
class MainMediator implements Mediator{
private CDDriver cdDriver;
private CPU cpu;
private Sound sound;
private Video video;
public CDDriver getCdDriver() {
return cdDriver;
}
public void setCdDriver(CDDriver cdDriver) {
this.cdDriver = cdDriver;
}
public CPU getCpu() {
return cpu;
}
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
public Sound getSound() {
return sound;
}
public void setSound(Sound sound) {
this.sound = sound;
}
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
this.video = video;
}
//
@Override
public void changed(Colleague colleague) {
if(colleague instanceof CDDriver){
this.opeCDDriverReadData(cdDriver);
}
if(colleague instanceof CPU){
this.opeCPU((CPU)colleague);
}
}
private void opeCDDriverReadData(CDDriver cd){
//Ȼȡȡ
String data = cd.getData();
//ЩݴݸCPUд
cpu.executeData(data);
}
/**
* CPUݺĽ
*/
private void opeCPU(CPU cpu){
//ȻȡCPU
String videoData = cpu.getVideoData();
String soundData = cpu.getSoundData();
//ЩݴݸԿչʾ
video.showData(videoData);
sound.showData(soundData);
}
}
| true
|
0e52b4a13f82cde6a493560de8cef3c3f473fb38
|
Java
|
GeekAlliance/TaurusPlatform
|
/taurus-api-service/taurus-core/src/main/java/com/geekalliance/taurus/rdb/dialects/DbDialect.java
|
UTF-8
| 639
| 2.09375
| 2
|
[] |
no_license
|
package com.geekalliance.taurus.rdb.dialects;
import org.apache.ibatis.mapping.BoundSql;
/**
* @author maxuqiang
*/
public interface DbDialect {
/**
* 处理Like模糊查询特殊字符
* @param sql 原始sql
* @param parameterObject mybatis参数对象
* @param boundSql mybatis boundSql
* @return 处理后的sql
*/
String specialCharLike(String sql, Object parameterObject, BoundSql boundSql);
/**
* 处理Like模糊查询特殊字符
* @param param 需要处理的内容
* @return 处理后的值
*/
Object sqlEscapeChar(String param);
}
| true
|
45e2de65f9029fd15675b79bc7f613ee6feef0a9
|
Java
|
Sivakron-FM/FF2
|
/app/src/main/java/com/example/appication/ui/ViewAdaptor/Viewtype.java
|
UTF-8
| 124
| 1.554688
| 2
|
[] |
no_license
|
package com.example.appication.ui.ViewAdaptor;
public class Viewtype {
public static final int TYPE_MAIL_VIEW = 1;
}
| true
|
4bf364866a7855c3c9cbf517bef575f0e418379b
|
Java
|
Good-Old-Living/app-platform
|
/infra/Infra-Scheduler/src/main/java/meru/scheduler/provider/quartz/QuartzScheduler.java
|
UTF-8
| 1,672
| 2.1875
| 2
|
[] |
no_license
|
package meru.scheduler.provider.quartz;
import java.util.Random;
import meru.scheduler.Job;
import meru.scheduler.JobId;
import meru.scheduler.Scheduler;
import meru.scheduler.SchedulerLifyCycleListener;
import meru.scheduler.Trigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzScheduler implements Scheduler, SchedulerLifyCycleListener {
private String mName;
private org.quartz.Scheduler mScheduler;
public QuartzScheduler(String name) throws SchedulerException {
this.mName = name;
SchedulerFactory sf = new StdSchedulerFactory();
this.mScheduler = sf.getScheduler();
this.mScheduler.start();
}
public String getName() {
return this.mName;
}
public JobId submitJob(Job job,
Trigger trigger) {
JobDetail jobDetail = JobBuilder.newJob(QuartzJob.class)
.withIdentity(this.mName + new Random().nextInt(),
"default")
.build();
jobDetail.getJobDataMap()
.put("Job",
job);
try {
this.mScheduler.scheduleJob(jobDetail,
((QuartzTrigger) trigger).getTrigger());
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
return null;
}
public void stop() {
}
}
| true
|
d558ba6ccf51d9cc87f5866f152edef02862b4f4
|
Java
|
wongainia/sanguo
|
/src/com/vikings/sanguo/protos/MsgReqItemBuy.java
|
UTF-8
| 4,109
| 2.03125
| 2
|
[] |
no_license
|
// Generated by http://code.google.com/p/protostuff/ ... DO NOT EDIT!
// Generated from client.proto
package com.vikings.sanguo.protos;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import com.dyuproject.protostuff.GraphIOUtil;
import com.dyuproject.protostuff.Input;
import com.dyuproject.protostuff.Message;
import com.dyuproject.protostuff.Output;
import com.dyuproject.protostuff.Schema;
public final class MsgReqItemBuy implements Externalizable, Message<MsgReqItemBuy>, Schema<MsgReqItemBuy>
{
public static Schema<MsgReqItemBuy> getSchema()
{
return DEFAULT_INSTANCE;
}
public static MsgReqItemBuy getDefaultInstance()
{
return DEFAULT_INSTANCE;
}
static final MsgReqItemBuy DEFAULT_INSTANCE = new MsgReqItemBuy();
private Integer itemid;
private Integer amount;
private Integer currency;
public MsgReqItemBuy()
{
}
// getters and setters
// itemid
public boolean hasItemid(){
return itemid != null;
}
public Integer getItemid()
{
return itemid == null ? 0 : itemid;
}
public MsgReqItemBuy setItemid(Integer itemid)
{
this.itemid = itemid;
return this;
}
// amount
public boolean hasAmount(){
return amount != null;
}
public Integer getAmount()
{
return amount == null ? 0 : amount;
}
public MsgReqItemBuy setAmount(Integer amount)
{
this.amount = amount;
return this;
}
// currency
public boolean hasCurrency(){
return currency != null;
}
public Integer getCurrency()
{
return currency == null ? 0 : currency;
}
public MsgReqItemBuy setCurrency(Integer currency)
{
this.currency = currency;
return this;
}
// java serialization
public void readExternal(ObjectInput in) throws IOException
{
GraphIOUtil.mergeDelimitedFrom(in, this, this);
}
public void writeExternal(ObjectOutput out) throws IOException
{
GraphIOUtil.writeDelimitedTo(out, this, this);
}
// message method
public Schema<MsgReqItemBuy> cachedSchema()
{
return DEFAULT_INSTANCE;
}
// schema methods
public MsgReqItemBuy newMessage()
{
return new MsgReqItemBuy();
}
public Class<MsgReqItemBuy> typeClass()
{
return MsgReqItemBuy.class;
}
public String messageName()
{
return MsgReqItemBuy.class.getSimpleName();
}
public String messageFullName()
{
return MsgReqItemBuy.class.getName();
}
public boolean isInitialized(MsgReqItemBuy message)
{
return true;
}
public void mergeFrom(Input input, MsgReqItemBuy message) throws IOException
{
for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this))
{
switch(number)
{
case 0:
return;
case 10:
message.itemid = input.readUInt32();
break;
case 20:
message.amount = input.readUInt32();
break;
case 30:
message.currency = input.readUInt32();
break;
default:
input.handleUnknownField(number, this);
}
}
}
public void writeTo(Output output, MsgReqItemBuy message) throws IOException
{
if(message.itemid != null)
output.writeUInt32(10, message.itemid, false);
if(message.amount != null)
output.writeUInt32(20, message.amount, false);
if(message.currency != null)
output.writeUInt32(30, message.currency, false);
}
public String getFieldName(int number)
{
return Integer.toString(number);
}
public int getFieldNumber(String name)
{
return Integer.parseInt(name);
}
}
| true
|
7adcfff2aa281c76f4190ae037d67c38d0f6fddc
|
Java
|
sadvit/csvexample
|
/src/main/java/com/sadvit/exam/ui/mvp/contenteditor/ContentEditorPresenter.java
|
UTF-8
| 1,801
| 2.328125
| 2
|
[] |
no_license
|
package com.sadvit.exam.ui.mvp.contenteditor;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.layout.BorderPane;
import com.sadvit.exam.ui.mvp.baseeditor.BasePresenter.TypeViewer;
import com.sadvit.exam.ui.mvp.contentviewer.ContentViewerPresenter;
import com.sadvit.exam.ui.mvp.skeleton.AbstractPresenter;
/**
* Представляет собой редактор объектов - правую колонку
*/
public class ContentEditorPresenter extends AbstractPresenter<BorderPane, ContentEditorModel> {
@FXML
private BorderPane borderPane;
private ContentViewerPresenter contentViewerPresenter;
public void setContentViewerPresenter(ContentViewerPresenter contentViewerPresenter) {
this.contentViewerPresenter = contentViewerPresenter;
}
@Override
public BorderPane getView() {
return borderPane;
}
/**
* Меняет режим editor-a на необходимый.
* @param typeViewer
*/
public void changeMode(TypeViewer typeViewer) {
getModel().setTypeEditor(typeViewer);
refresh();
}
@FXML
public void onNewClickHandler() {
getModel().getCurrentEditor().createHandler();
refreshViewer();
}
@FXML
public void onSaveClickHandler() {
getModel().getCurrentEditor().updateHandler();
refreshViewer();
}
@FXML
public void onDeleteClickHandler() {
getModel().getCurrentEditor().deleteHandler();
refreshViewer();
}
private void setCenterNode(Node node) {
getView().setCenter(node);
}
private void refresh() {
setCenterNode(getModel().getCurrentEditor().getView());
}
private void refreshViewer() {
contentViewerPresenter.refreshViewer();
}
public void showType(int id) {
getModel().getCurrentEditor().withdraw(id);
}
}
| true
|
21d8f973539bbb3fa68618bbdeededff4ed06478
|
Java
|
ValeryTsybulka/JavaBatch6
|
/src/com/syntax/class03/HwAnnF15_01.java
|
UTF-8
| 299
| 2.953125
| 3
|
[] |
no_license
|
package com.syntax.class03;
public class HwAnnF15_01 {
public static void main(String[] args) {
double a=55.88;
double b=33.11;
if(a>b) {
System.out.println("Double value " + a + " is larger than " + b);
}else {
System.out.println("Double value "+a+" is smaller than "+b);
}
}
}
| true
|
a221b0cd8c2c0133dcc2244d3d89c9610a4a125c
|
Java
|
buithienai/DApp
|
/dapp/src/main/java/dapp/dapp/dto/SignedMessageDto.java
|
UTF-8
| 679
| 2.390625
| 2
|
[] |
no_license
|
package dapp.dapp.dto;
public class SignedMessageDto {
private int v;
private String r;
private String s;
public SignedMessageDto(int v, String r, String s) {
this.v = v;
this.r = r;
this.s = s;
}
public int getV() {
return v;
}
public SignedMessageDto setV(int v) {
this.v = v;
return this;
}
public String getR() {
return r;
}
public SignedMessageDto setR(String r) {
this.r = r;
return this;
}
public String getS() {
return s;
}
public SignedMessageDto setS(String s) {
this.s = s;
return this;
}
}
| true
|
eb0e8041141e74617919032c176028e1eba5a4f8
|
Java
|
sudheertest/sud-work
|
/seleniumMaven/src/main/java/org/selenium/framework/pages/CastLightPage.java
|
UTF-8
| 1,336
| 1.609375
| 2
|
[] |
no_license
|
package org.selenium.framework.pages;
import org.openqa.selenium.By;
import org.selenium.framework.baseModules.BasePage;
/**
* Created by sudheerl on 6/10/14.
*/
public class CastLightPage extends BasePage {
public String loginPage_emailid = "#email_login";
public String loginPage_password = "#password_login";
public By loginPage_submit_btn = By.cssSelector("#login > fieldset > div.actions > p > input");
public String loginPage_pagekey = "#tabs_holder > li.tab_home.active";
public String full_name_menu = "#full_name";
public String logout_link = "#logout_link";
public By logout_confirmation = By.cssSelector("a.button.secondary");
public String change_location = "a.address_popup_trigger";
public By change_location_typebox = By.cssSelector("input.location_field.ui-autocomplete-input");
public By change_location_update = By.id("address_submit");
public By zip_code = By.id("address_text");
public By provider_search_results = By.cssSelector("ul#provider_search_results>li a.provider_link");
public By provider_search_first_results = By.cssSelector("ul#provider_search_results>li:nth-of-type(1) a.provider_link");
public By welcome_dailog_after_login = By.cssSelector("div.pull-right>button.secondary");
public By accept_terms_after_login = By.name("commit");
}
| true
|
3667e619f5feffb56c9edbc8b903ac528decedd5
|
Java
|
FutureSoldiers/gulimall
|
/gulimall-seckill/src/main/java/com/atguigu/gulimall/seckill/config/MyRabbitConfig.java
|
UTF-8
| 937
| 1.914063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.atguigu.gulimall.seckill.config;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* @author FutureSoldiers
* @create 2020-12-04 16:39
*/
@Configuration
public class MyRabbitConfig {
/**
* 使用JSON 序列化机制,进行消息转换
* 配置 将消息发送 转为json
* @return
*/
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
| true
|
78f5970bebba8abf4eda67983e461aa098089c51
|
Java
|
VictorSithole/SasaiAssignmentResponse
|
/electronic-payments-business/src/test/java/com/econetwireless/epay/business/services/impl/CreditsServiceImplTest.java
|
UTF-8
| 3,080
| 2.09375
| 2
|
[] |
no_license
|
package com.econetwireless.epay.business.services.impl;
import com.econetwireless.epay.dao.subscriberrequest.api.SubscriberRequestDao;
import com.econetwireless.epay.domain.SubscriberRequest;
import com.econetwireless.utils.constants.SystemConstants;
import com.econetwireless.utils.enums.ResponseCode;
import com.econetwireless.utils.messages.AirtimeTopupRequest;
import com.econetwireless.utils.messages.AirtimeTopupResponse;
import com.econetwireless.utils.pojo.INCreditRequest;
import com.econetwireless.utils.pojo.INCreditResponse;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class CreditsServiceImplTest extends TestCase {
private String partnerCode, msisdn;
@Mock
private SubscriberRequestDao subscriberRequestDao;
@Before
public void init() {
partnerCode = "hot-recharge";
msisdn = "263782135087";
}
@Test
public void testCredit() {
AirtimeTopupRequest airtimeTopupRequest = new AirtimeTopupRequest();
airtimeTopupRequest.setAmount(100);
airtimeTopupRequest.setMsisdn(msisdn);
airtimeTopupRequest.setPartnerCode(partnerCode);
airtimeTopupRequest.setReferenceNumber("REF-1234");
final AirtimeTopupResponse airtimeTopupResponse = new AirtimeTopupResponse();
final SubscriberRequest subscriberRequest = populateSubscriberRequest(airtimeTopupRequest);
final SubscriberRequest createdSubscriberRequest = subscriberRequestDao.save(subscriberRequest);
final INCreditResponse inCreditResponse = new INCreditResponse();
inCreditResponse.setBalance(1000);
inCreditResponse.setMsisdn(msisdn);
inCreditResponse.setResponseCode(ResponseCode.SUCCESS.getCode());
inCreditResponse.setNarrative("Airtime Purchase");
airtimeTopupResponse.setResponseCode(inCreditResponse.getResponseCode());
airtimeTopupResponse.setNarrative(inCreditResponse.getNarrative());
airtimeTopupResponse.setMsisdn(airtimeTopupRequest.getMsisdn());
airtimeTopupResponse.setBalance(inCreditResponse.getBalance());
assertEquals(msisdn, airtimeTopupResponse.getMsisdn());
assertEquals("200", airtimeTopupResponse.getResponseCode());
assertEquals(1000d, airtimeTopupResponse.getBalance());
}
private static SubscriberRequest populateSubscriberRequest(final AirtimeTopupRequest airtimeTopupRequest) {
final SubscriberRequest subscriberRequest = new SubscriberRequest();
subscriberRequest.setRequestType(SystemConstants.REQUEST_TYPE_AIRTIME_TOPUP);
subscriberRequest.setPartnerCode(airtimeTopupRequest.getPartnerCode());
subscriberRequest.setMsisdn(airtimeTopupRequest.getMsisdn());
subscriberRequest.setReference(airtimeTopupRequest.getReferenceNumber());
subscriberRequest.setAmount(airtimeTopupRequest.getAmount());
return subscriberRequest;
}
}
| true
|
c03572c30711631351e008471d4ff28f20aecfb5
|
Java
|
dreamer888/zhihuinongmao
|
/zhnm/zhnm-miniapp/api/mallseller/src/main/java/com/wqwy/zhnm/seller/controller/SellerDynamicController.java
|
UTF-8
| 5,175
| 1.828125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright (c) 2015-2018 <a href="">wqwy</a> All rights reserved.
*/
package com.wqwy.zhnm.seller.controller;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import com.wqwy.zhnm.base.entity.SellerDynamic;
import com.wqwy.zhnm.base.service.SellerDynamicService;
import com.wqwy.zhnm.seller.base.BaseController;
import com.wqwy.zhnm.base.component.component.JsonResponse;
import com.wqwy.zhnm.base.component.component.PageJsonResponse;
import com.wqwy.zhnm.base.component.component.Pagenation;
import com.wqwy.zhnm.base.component.utils.ResultUtils;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/**
* createTime: 2018-05-08 18:51:09
* @author seven
* @version
*/
@RestController
@RequestMapping("/v1/")
public class SellerDynamicController extends BaseController {
@Autowired
private SellerDynamicService sellerDynamicService;
/**
*
* @date 2018-05-08 18:51:09
* @Title: findByPage
* @Description: TODO
* @param @param sellerDynamic
* @param @param pagenation
* @param @param request
* @param @return
* @return PageJsonResponse<List<SellerDynamic>>
* @throws
*/
@RequestMapping(value="sellerDynamics", method=RequestMethod.GET, produces={MediaType.APPLICATION_JSON_VALUE+";charset=utf-8"})
public PageJsonResponse<List<SellerDynamic>> findByPage(SellerDynamic sellerDynamic, Pagenation pagenation, HttpServletRequest request, Model model) {
Page<SellerDynamic> queryResultList = sellerDynamicService.findListByPage(sellerDynamic, pagenation);
pagenation.setTotal(queryResultList.getTotal());
return new PageJsonResponse<List<SellerDynamic>>(ResultUtils.SUCCESS, ResultUtils.SUCCESS_MSG, queryResultList, pagenation);
}
/**
*
* @date 2018-05-08 18:51:09
* @Title: findSellerDynamicDetail
* @Description: TODO
* @param @param sellerDynamic
* @param @param pagenation
* @param @param request
* @param @return
* @return JsonResponse<SellerDynamic>
* @throws
*/
@RequestMapping(value="sellerDynamics/{id}", method=RequestMethod.GET, produces={MediaType.APPLICATION_JSON_VALUE+";charset=utf-8"})
public JsonResponse<SellerDynamic> findSellerDynamicDetail(@PathVariable("id")Integer id, SellerDynamic sellerDynamic, HttpServletRequest request){
sellerDynamic = sellerDynamicService.get(id.toString());
return new JsonResponse<SellerDynamic>(ResultUtils.SUCCESS, ResultUtils.SUCCESS_MSG, sellerDynamic);
}
/**
*
* @date 2018-05-08 18:51:09
* @Title: modifySellerDynamicDetail
* @Description: TODO
* @param @param id
* @param @param sellerDynamic
* @param @param request
* @param @return
* @return JsonResponse<SellerDynamic>
* @throws
*/
@RequestMapping(value="sellerDynamics/{id}", method=RequestMethod.PATCH, produces={MediaType.APPLICATION_JSON_VALUE+";charset=utf-8"})
public JsonResponse<SellerDynamic> modifySellerDynamicDetail(@PathVariable("id")Integer id, @RequestBody SellerDynamic sellerDynamic, HttpServletRequest request){
sellerDynamic.setId(id);
sellerDynamicService.update(sellerDynamic);
return new JsonResponse<SellerDynamic>(ResultUtils.SUCCESS, ResultUtils.SUCCESS_MSG, sellerDynamicService.get(id.toString()));
}
/**
*
* @date 2018-05-08 18:51:09
* @Title: addSellerDynamic
* @Description: TODO
* @param @param sellerDynamic
* @param @param request
* @param @return
* @return JsonResponse<SellerDynamic>
* @throws
*/
@RequestMapping(value="sellerDynamics", method=RequestMethod.POST, produces={MediaType.APPLICATION_JSON_VALUE+";charset=utf-8"})
public JsonResponse<SellerDynamic> addSellerDynamic(@RequestBody SellerDynamic sellerDynamic, HttpServletRequest request){
sellerDynamicService.insert(sellerDynamic);
return new JsonResponse<SellerDynamic>(ResultUtils.SUCCESS, ResultUtils.SUCCESS_MSG, sellerDynamicService.findList(sellerDynamic).get(0));
}
/**
*
* @date 2018-05-08 18:51:09
* @Title: removeSellerDynamic
* @Description: TODO
* @param @param id
* @param @param request
* @param @return
* @return JsonResponse<>
* @throws
*/
@RequestMapping(value="sellerDynamics/{id}", method=RequestMethod.DELETE, produces={MediaType.APPLICATION_JSON_VALUE+";charset=utf-8"})
public JsonResponse<?> removeSellerDynamic(@PathVariable("id")Integer id, HttpServletRequest request){
sellerDynamicService.delete(id.toString());
return new JsonResponse<>(ResultUtils.SUCCESS, ResultUtils.SUCCESS_MSG);
}
}
| true
|
5b305f155c6a7a9ac4404f1a165be7946360504e
|
Java
|
rexen-lq/SpringBoot-Learning
|
/springboot2-demo-thymeleaf/src/main/java/com/bsutility/cert/exception/BusinessException.java
|
UTF-8
| 793
| 2.515625
| 3
|
[] |
no_license
|
package com.bsutility.cert.exception;
/**
* @author adminytf
*
*/
public class BusinessException extends Exception {
private static final long serialVersionUID = 1L;
private ExceptionEnum exceptionEnum;
public BusinessException() {
}
public BusinessException(String msg) {
this.exceptionEnum = ExceptionEnum.BUSINESS_ERROR.setErrorMsg(msg);
}
public BusinessException(ExceptionEnum exceptionEnum) {
this.exceptionEnum = exceptionEnum;
}
public ExceptionEnum getExceptionEnum() {
return exceptionEnum;
}
public void setExceptionEnum(ExceptionEnum exceptionEnum) {
this.exceptionEnum = exceptionEnum;
}
public String getErrorMsg() {
return this.exceptionEnum.getErrorMsg();
}
public String getErrorCode() {
return this.exceptionEnum.getErrorCode();
}
}
| true
|
bd3aa9c3324674721223c79b11eadf2e20acfc72
|
Java
|
davidromesp/D02
|
/workspace/Acme-Explorer/src/main/java/domain/Sponsorship.java
|
UTF-8
| 1,477
| 2.1875
| 2
|
[] |
no_license
|
package domain;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.SafeHtml;
import org.hibernate.validator.constraints.SafeHtml.WhiteListType;
import org.hibernate.validator.constraints.URL;
@Entity
@Access(AccessType.PROPERTY)
public class Sponsorship extends DomainEntity {
// Attributes
private String bannerUrl;
private String infoPage;
private CreditCard creditCard;
@NotBlank
@NotNull
@SafeHtml(whitelistType = WhiteListType.NONE)
@URL
public String getBannerUrl() {
return this.bannerUrl;
}
public void setBannerUrl(final String bannerUrl) {
this.bannerUrl = bannerUrl;
}
@NotBlank
@NotNull
@SafeHtml(whitelistType = WhiteListType.NONE)
@URL
public String getInfoPage() {
return this.infoPage;
}
public void setInfoPage(final String infoPage) {
this.infoPage = infoPage;
}
@Valid
public CreditCard getCreditCard() {
return this.creditCard;
}
public void setCreditCard(final CreditCard creditCard) {
this.creditCard = creditCard;
}
// Relationships
private Trip trip;
@Valid
// TODO: Relationship pattern
public Trip getTrip() {
return this.trip;
}
public void setTrip(final Trip trip) {
this.trip = trip;
}
}
| true
|
800fb4e26f4ed297d22a30025fd55b2778a06215
|
Java
|
josephhao/clientDemo
|
/socket-client/src/main/java/com/cw/client/udp/UdpSocketClient.java
|
UTF-8
| 1,135
| 3.078125
| 3
|
[] |
no_license
|
package com.cw.client.udp;
import java.io.*;
import java.net.*;
public class UdpSocketClient {
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getByName("localhost");
DatagramSocket ds = new DatagramSocket( 8809);
byte[] bytes = "tttttttttt".getBytes();
// 当 DatagramPacket 构造函数中 inetAddress 是目标IP , port 为 目标端口;
DatagramPacket datagramPacket = new DatagramPacket(bytes , bytes.length, inetAddress,8800);
ds.send(datagramPacket);
System.out.println("Client send over");
bytes = new byte[1024];
datagramPacket = new DatagramPacket(bytes, bytes.length);
ds.receive(datagramPacket);
String rep = new String(bytes , 0, datagramPacket.getLength());
System.out.println(rep);
if(!ds.isClosed()) {
ds.close();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
5cf4f99f173ef5b1c37345fb0b9495b14c35e80d
|
Java
|
jambestwick/HackWechat
|
/app/src/main/java/com/tencent/mm/plugin/freewifi/ui/a$2$1$1$1.java
|
UTF-8
| 6,857
| 1.679688
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.freewifi.ui;
import com.tencent.mm.hardcoder.HardCoderJNI;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.plugin.freewifi.ui.a.2.1.1;
import com.tencent.mm.plugin.report.service.g;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
class a$2$1$1$1 implements Runnable {
final /* synthetic */ String mDA;
final /* synthetic */ String mDn;
final /* synthetic */ String mDz;
final /* synthetic */ String mGJ;
final /* synthetic */ String mGK;
final /* synthetic */ 1 mGL;
a$2$1$1$1(1 1, String str, String str2, String str3, String str4, String str5) {
this.mGL = 1;
this.mGJ = str;
this.mDz = str2;
this.mDA = str3;
this.mGK = str4;
this.mDn = str5;
}
public final void run() {
Exception exception;
Writer stringWriter;
String stringWriter2;
g gVar;
Object[] objArr;
Throwable th;
x.i("MicroMsg.FreeWifi.FreeWifiBanner", "desc=it tries to ping. pingUrl= %s", new Object[]{this.mGJ});
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(this.mGJ);
long currentTimeMillis = System.currentTimeMillis();
HttpURLConnection httpURLConnection2 = (HttpURLConnection) url.openConnection();
if (httpURLConnection2 != null) {
try {
httpURLConnection2.setConnectTimeout(5000);
httpURLConnection2.setReadTimeout(5000);
httpURLConnection2.setInstanceFollowRedirects(false);
httpURLConnection2.setUseCaches(false);
httpURLConnection2.setRequestProperty("Pragma", "no-cache");
httpURLConnection2.setRequestProperty("Cache-Control", "no-cache");
int responseCode = httpURLConnection2.getResponseCode();
currentTimeMillis = System.currentTimeMillis() - currentTimeMillis;
g.pQN.h(12907, new Object[]{this.mDz, this.mDA, this.mGK, this.mDn, "", Long.valueOf(currentTimeMillis), Integer.valueOf(responseCode), "", "", ""});
x.i("MicroMsg.FreeWifi.FreeWifiBanner", "desc=ping ended. http response code = %d, cost=%d ms", new Object[]{Integer.valueOf(responseCode), Long.valueOf(currentTimeMillis)});
if (200 == responseCode) {
ag.y(new Runnable(this) {
final /* synthetic */ a$2$1$1$1 mGM;
{
this.mGM = r1;
}
public final void run() {
this.mGM.mGL.mGI.mGF.setVisibility(0);
}
});
} else if (HardCoderJNI.SCENE_QUIT_CHATTING == responseCode) {
x.i("MicroMsg.FreeWifi.FreeWifiBanner", "desc=http response 302 location = %s", new Object[]{httpURLConnection2.getHeaderField("Location")});
}
} catch (Exception e) {
Exception exception2 = e;
httpURLConnection = httpURLConnection2;
exception = exception2;
try {
stringWriter = new StringWriter();
exception.printStackTrace(new PrintWriter(stringWriter));
stringWriter2 = stringWriter.toString();
x.i("MicroMsg.FreeWifi.FreeWifiBanner", "ping encounter exception. " + stringWriter2);
if (stringWriter2 == null) {
stringWriter2 = "";
}
gVar = g.pQN;
objArr = new Object[10];
objArr[0] = this.mDz;
objArr[1] = this.mDA;
objArr[2] = this.mGK;
objArr[3] = this.mDn;
objArr[4] = "";
objArr[5] = Integer.valueOf(0);
objArr[6] = Integer.valueOf(0);
objArr[7] = "";
objArr[8] = "";
if (stringWriter2.length() > WXMediaMessage.DESCRIPTION_LENGTH_LIMIT) {
stringWriter2 = stringWriter2.substring(0, WXMediaMessage.DESCRIPTION_LENGTH_LIMIT);
}
objArr[9] = stringWriter2;
gVar.h(12907, objArr);
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
} catch (Throwable th2) {
th = th2;
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
throw th;
}
} catch (Throwable th3) {
Throwable th4 = th3;
httpURLConnection = httpURLConnection2;
th = th4;
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
throw th;
}
}
if (httpURLConnection2 != null) {
httpURLConnection2.disconnect();
}
} catch (Exception e2) {
exception = e2;
stringWriter = new StringWriter();
exception.printStackTrace(new PrintWriter(stringWriter));
stringWriter2 = stringWriter.toString();
x.i("MicroMsg.FreeWifi.FreeWifiBanner", "ping encounter exception. " + stringWriter2);
if (stringWriter2 == null) {
stringWriter2 = "";
}
gVar = g.pQN;
objArr = new Object[10];
objArr[0] = this.mDz;
objArr[1] = this.mDA;
objArr[2] = this.mGK;
objArr[3] = this.mDn;
objArr[4] = "";
objArr[5] = Integer.valueOf(0);
objArr[6] = Integer.valueOf(0);
objArr[7] = "";
objArr[8] = "";
if (stringWriter2.length() > WXMediaMessage.DESCRIPTION_LENGTH_LIMIT) {
stringWriter2 = stringWriter2.substring(0, WXMediaMessage.DESCRIPTION_LENGTH_LIMIT);
}
objArr[9] = stringWriter2;
gVar.h(12907, objArr);
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
}
}
| true
|
f77741bd5662ea99b5648d97ff7f286fdbad2d39
|
Java
|
zengyufei/dc-single
|
/src/main/java/com/zyf/lf/service/impl/OsOrderShipmentServiceImpl.java
|
UTF-8
| 542
| 1.53125
| 2
|
[] |
no_license
|
package com.zyf.lf.service.impl;
import com.zyf.lf.models.entity.OsOrderShipment;
import com.zyf.lf.mapper.OsOrderShipmentMapper;
import com.zyf.lf.service.IOsOrderShipmentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 订单配送表 服务实现类
* </p>
*
* @author zengyufei
* @since 2018-01-24
*/
@Service
public class OsOrderShipmentServiceImpl extends ServiceImpl<OsOrderShipmentMapper, OsOrderShipment> implements IOsOrderShipmentService {
}
| true
|
7b65c9f2d290fc7a410c64e4d319df61d249f16b
|
Java
|
quocvuphamdinh/Android-Music-App
|
/MusicAppCuaVu/app/src/main/java/vu/pham/musicappcuavu/song/SongsListAdapter.java
|
UTF-8
| 2,364
| 2.4375
| 2
|
[] |
no_license
|
package vu.pham.musicappcuavu.song;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import vu.pham.musicappcuavu.Music;
import vu.pham.musicappcuavu.R;
public class SongsListAdapter extends BaseAdapter {
private Context context;
private int layout;
private List<Music>musicList;
public SongsListAdapter(Context context, int layout, List<Music> musicList) {
this.context = context;
this.layout = layout;
this.musicList = musicList;
}
@Override
public int getCount() {
return musicList.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
private class ViewHolderSongLists{
ImageView imgHinhSong;
TextView txtTenSong, txtTenCasiSong;
ImageButton imgbtnPlaySong;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderSongLists holderSongLists;
if(convertView==null){
holderSongLists=new ViewHolderSongLists();
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(layout, null);
holderSongLists.imgHinhSong=(ImageView) convertView.findViewById(R.id.imageviewHinhSong);
holderSongLists.txtTenSong=(TextView) convertView.findViewById(R.id.textviewTenSong);
holderSongLists.txtTenCasiSong=(TextView) convertView.findViewById(R.id.textviewTenCaSiSong);
holderSongLists.imgbtnPlaySong=(ImageButton) convertView.findViewById(R.id.imagebuttonPlaySong);
convertView.setTag(holderSongLists);
}else{
holderSongLists= (ViewHolderSongLists) convertView.getTag();
}
Music music=musicList.get(position);
holderSongLists.imgHinhSong.setImageResource(music.getHinhAnh());
holderSongLists.txtTenSong.setText(music.getTenBaiHat());
holderSongLists.txtTenCasiSong.setText(music.getTenCaSi());
return convertView;
}
}
| true
|
dd4a6d45740a70b9a414dab50c4ac7314206db14
|
Java
|
kleekich/Lyber
|
/app/src/main/java/com/example/lyber/LyftApiService.java
|
UTF-8
| 1,768
| 2.328125
| 2
|
[] |
no_license
|
package com.example.lyber;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Headers;
/**
* Created by kangsik_kevin_lee on 8/31/17.
*/
public class LyftApiService {
private LyftService lyftApi;
private Call<LyftModel> mCall;
public LyftApiService(RetrofitClient retrofitClient){
lyftApi = retrofitClient.create(LyftApiService.LyftService.class);
}
public void getLyft(final ResponseHandler<LyftModel> callBack,
boolean isCancelable) {
Call<LyftModel> call = lyftApi.getEstimatePrice();
if (isCancelable) {
//if data is present return;
if (mCall != null) {
return;
} else {
mCall = call;
}
}
call.enqueue(new Callback<LyftModel>() {
@Override
public void onResponse(Call<LyftModel> call, Response<LyftModel> response) {
mCall = null;
if (response.isSuccessful()) {
callBack.onSuccess(response.body());
} else {
callBack.onError(response.code(), response.errorBody().toString());
}
}
@Override
public void onFailure(Call<LyftModel> call, Throwable t) {
mCall = null;
callBack.onError(-1, t.getMessage());
}
});
}
public interface LyftService {
@Headers({"Content-Type: application/json",
"Authorization: Bearer VCz8t0iW4Xq60kzG2bk9A70irK+bJMQxpVwoEvMrsWtpR0z3GfIoD5Yxw0ih39AQSkRiiYbnyj7yQFXTqsGxsLf3nhHIw3KzTZrIS31iZ+CvFovYwicNmFo="
})
@GET("cost?start_lat=37.7763&start_lng=-122.3918&end_lat=37.7972&end_lng=-122.4533")
Call<LyftModel> getEstimatePrice();
}
}
| true
|
b3fa055694d447249dc8817fb7b4ab58d685f174
|
Java
|
nskrobonja95/IsaProjekat
|
/IsaProjekat/src/main/java/edu/ftn/isa/dto/HotelDTO.java
|
UTF-8
| 461
| 2.375
| 2
|
[] |
no_license
|
package edu.ftn.isa.dto;
import edu.ftn.isa.model.Hotel;
import lombok.Data;
public @Data class HotelDTO {
private Long id;
private String name;
private String address;
private String promo;
private Long admin;
public static HotelDTO parseHotel(Hotel hotel) {
HotelDTO temp = new HotelDTO();
temp.setId(hotel.getId());
temp.setAddress(hotel.getAddress());
temp.setName(hotel.getName());
temp.setPromo(hotel.getPromo());
return temp;
}
}
| true
|
041b751a113fc4a73f188120a0f3b272805b489a
|
Java
|
bhagvatbhosle/Java_Practice
|
/Collection Demos/src/com/seed/inheritancedemos/MarketingExecutive.java
|
UTF-8
| 723
| 2.921875
| 3
|
[] |
no_license
|
package com.seed.inheritancedemos;
public class MarketingExecutive extends Manager {
private double kmTravelled;
private double TA;
public MarketingExecutive(int empId, String empName, double basSal, double pA, double fA, double OA,
double kmTravelled) {
super(empId, empName, basSal, pA, fA, OA);
this.kmTravelled = kmTravelled;
this.TA = 5 * kmTravelled;
}
public double getKmTravelled() {
return kmTravelled;
}
public void setKmTravelled(double kmTravelled) {
this.kmTravelled = kmTravelled;
}
@Override
public double calSal() {
return super.calSal() + this.TA;
}
@Override
public String toString() {
return super.toString() + " , " + this.kmTravelled + " , " + this.TA + " ] ";
}
}
| true
|
35d72b1f6e7f242932667890b53014765cd97bdc
|
Java
|
mobgen/halo-android
|
/sdk/halo-framework/src/main/java/com/mobgen/halo/android/framework/toolbox/bus/EventId.java
|
UTF-8
| 902
| 2.78125
| 3
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
package com.mobgen.halo.android.framework.toolbox.bus;
import android.support.annotation.NonNull;
import com.mobgen.halo.android.framework.common.annotations.Api;
/**
* The event id for a given event.
*/
public class EventId {
/**
* The id of the event.
*/
private String mEventId;
/**
* Consrtuctor for the event id.
*
* @param id The id.
*/
private EventId(@NonNull String id) {
mEventId = id;
}
/**
* Creates a new event.
*
* @param id The id of the event.
* @return The event id object created,.
*/
@Api(1.3)
@NonNull
public static EventId create(@NonNull String id) {
return new EventId(id);
}
/**
* Provides the id of this event.
*
* @return The id as a string of the event.
*/
@Api(1.3)
public String getId() {
return mEventId;
}
}
| true
|
6578e53e77d57ed0d4329cdb641b5c3734739981
|
Java
|
nkoterba/swagger-jaxrs-doclet
|
/swagger-doclet/src/test/resources/fixtures/classpathparamrequired/ClassPathParamRequiredResource.java
|
UTF-8
| 1,063
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package fixtures.classpathparamrequired;
import fixtures.paramrequired.*;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.DELETE;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
/**
* The ClassPathParamRequiredResource represents a jaxrs resource that has has PathParams
* defined in the Class path and then referenced in a constructor, field, task and then no tasks.
* Each method in this Resource, however, should have a required field generated for it in JSON
* for the taskId property.
* @author nkoterba
*/
@Path("/api/{taskId: [0-9]+}")
@SuppressWarnings("javadoc")
public class ClassPathParamRequiredResource {
@PathParam("taskId")
private long _taskId;
public ClassPathParamRequiredResource(@PathParam("taskId") long taskId) {
}
@GET
public void getNothing(@PathParam("taskId") long taskId) {
}
@DELETE
public void deleteNothing() {
}
@GET
@Path("/{item: [A-Za-z0-9]+}")
public String getItem(@PathParam("item") String item) {
return item;
}
}
| true
|
f21b0cd6ab0a03284b7db984e50f079a4340958a
|
Java
|
ufctester/plex-pvr
|
/src/main/java/io/askcloud/plex/pvr/utorrent/domain/ChangedTorrentList.java
|
UTF-8
| 4,494
| 1.609375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package io.askcloud.plex.pvr.utorrent.domain;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import javax.annotation.Generated;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.builder.EqualsBuilder;
@Generated("com.googlecode.jsonschema2pojo")
public class ChangedTorrentList {
private Integer build;
private List<String> files = new ArrayList<>();
private List<Object> label = new ArrayList<>();
private List<SingleListTorrent> torrentp = new ArrayList<>();
private List<String> torrentm = new ArrayList<>();
private String torrentc;
private List<Object> rssfeedp = new ArrayList<>();
private List<Object> rssfeedm = new ArrayList<>();
private List<Object> rssfilterp = new ArrayList<>();
private List<Object> rssfilterm = new ArrayList<>();
private Map<String, Object> additionalProperties = new HashMap<>();
public Integer getBuild() {
return build;
}
public void setBuild(Integer build) {
this.build = build;
}
public ChangedTorrentList withBuild(Integer build) {
this.build = build;
return this;
}
public List<String> getFiles() {
return files;
}
public void setFiles(List<String> files) {
this.files = files;
}
public ChangedTorrentList withFiles(List<String> files) {
this.files = files;
return this;
}
public List<Object> getLabel() {
return label;
}
public void setLabel(List<Object> label) {
this.label = label;
}
public ChangedTorrentList withLabel(List<Object> label) {
this.label = label;
return this;
}
public List<SingleListTorrent> getTorrentp() {
return torrentp;
}
public void setTorrentp(List<SingleListTorrent> torrentp) {
this.torrentp = torrentp;
}
public ChangedTorrentList withTorrentp(List<SingleListTorrent> torrentp) {
this.torrentp = torrentp;
return this;
}
public List<String> getTorrentm() {
return torrentm;
}
public void setTorrentm(List<String> torrentm) {
this.torrentm = torrentm;
}
public ChangedTorrentList withTorrentm(List<String> torrentm) {
this.torrentm = torrentm;
return this;
}
public String getTorrentc() {
return torrentc;
}
public void setTorrentc(String torrentc) {
this.torrentc = torrentc;
}
public ChangedTorrentList withTorrentc(String torrentc) {
this.torrentc = torrentc;
return this;
}
public List<Object> getRssfeedp() {
return rssfeedp;
}
public void setRssfeedp(List<Object> rssfeedp) {
this.rssfeedp = rssfeedp;
}
public ChangedTorrentList withRssfeedp(List<Object> rssfeedp) {
this.rssfeedp = rssfeedp;
return this;
}
public List<Object> getRssfeedm() {
return rssfeedm;
}
public void setRssfeedm(List<Object> rssfeedm) {
this.rssfeedm = rssfeedm;
}
public ChangedTorrentList withRssfeedm(List<Object> rssfeedm) {
this.rssfeedm = rssfeedm;
return this;
}
public List<Object> getRssfilterp() {
return rssfilterp;
}
public void setRssfilterp(List<Object> rssfilterp) {
this.rssfilterp = rssfilterp;
}
public ChangedTorrentList withRssfilterp(List<Object> rssfilterp) {
this.rssfilterp = rssfilterp;
return this;
}
public List<Object> getRssfilterm() {
return rssfilterm;
}
public void setRssfilterm(List<Object> rssfilterm) {
this.rssfilterm = rssfilterm;
}
public ChangedTorrentList withRssfilterm(List<Object> rssfilterm) {
this.rssfilterm = rssfilterm;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object other) {
return EqualsBuilder.reflectionEquals(this, other);
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| true
|
27c00a3ce3f894e62e68e2f078c921eae4a15a1b
|
Java
|
maningbo/testjavacode
|
/testjavacode/src/thinkinginjava/chapter10innerclasses/E18_NestedClass.java
|
UTF-8
| 671
| 3.296875
| 3
|
[] |
no_license
|
package thinkinginjava.chapter10innerclasses;
import thinkinginjava.chapter10innerclasses.E18_NestedClass.Nested;
/**
* E18_NestedClass.java
* Description:
*
* CreateDate: 2015年11月9日 上午8:46:54
*
* @author 马宁波
*/
public class E18_NestedClass {
static class Nested{
void f(){System.out.println("Nested.f");}
}
public static void main(String args[]){
Nested ne = new Nested();
ne.f();
Other o = new Other();
o.f();
}
}
class Other{
//Specifying the nested type outside
//the scope of the class:
//E18_NestedClass.Nested与Nested均可以
void f(){
Nested ne = new Nested();
ne.f();
}
}
| true
|
a88d4e79739ccaf7f87b52e78fe809e28c9afa1d
|
Java
|
canberkak/selsoft-demo
|
/src/main/java/com/kft2/selsoftdemo/application/exception/advice/ErrorResponse.java
|
UTF-8
| 431
| 1.96875
| 2
|
[] |
no_license
|
package com.kft2.selsoftdemo.application.exception.advice;
import lombok.Data;
import lombok.NonNull;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
@Data
public class ErrorResponse {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@NonNull
private String errorMessage;
private String timestamp = sdf.format(new Timestamp(System.currentTimeMillis()));
}
| true
|
6d50777c28e3d3eb7e98979e0de53e9cf0f746db
|
Java
|
sumit4-ttn/SDK
|
/molecule/java/src/main/java/com/hydrogen/molecule/model/CurrencyBalanceUpdateParams.java
|
UTF-8
| 2,719
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Molecule API Documentation
* The Hydrogen Molecule API
*
* OpenAPI spec version: 1.3.0
* Contact: info@hydrogenplatform.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.hydrogen.molecule.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModelProperty;
import java.util.UUID;
/**
* CurrencyBalanceUpdateParams
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-07-21T09:54:56.296Z")
public class CurrencyBalanceUpdateParams {
@SerializedName("wallet_id")
private UUID walletId = null;
@SerializedName("currency_id")
private UUID currencyId = null;
public CurrencyBalanceUpdateParams walletId(UUID walletId) {
this.walletId = walletId;
return this;
}
/**
* Get walletId
* @return walletId
**/
@ApiModelProperty(required = true, value = "")
public UUID getWalletId() {
return walletId;
}
public void setWalletId(UUID walletId) {
this.walletId = walletId;
}
public CurrencyBalanceUpdateParams currencyId(UUID currencyId) {
this.currencyId = currencyId;
return this;
}
/**
* Get currencyId
* @return currencyId
**/
@ApiModelProperty(required = true, value = "")
public UUID getCurrencyId() {
return currencyId;
}
public void setCurrencyId(UUID currencyId) {
this.currencyId = currencyId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CurrencyBalanceUpdateParams currencyBalanceUpdateParams = (CurrencyBalanceUpdateParams) o;
return Objects.equals(this.walletId, currencyBalanceUpdateParams.walletId) &&
Objects.equals(this.currencyId, currencyBalanceUpdateParams.currencyId);
}
@Override
public int hashCode() {
return Objects.hash(walletId, currencyId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CurrencyBalanceUpdateParams {\n");
sb.append(" walletId: ").append(toIndentedString(walletId)).append("\n");
sb.append(" currencyId: ").append(toIndentedString(currencyId)).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
|
e0eb1cb707b3a97203bbc24796b5317efdbfafe0
|
Java
|
Android-Academy/7_AC_InstaCreative
|
/app/src/main/java/com/vullnetlimani/instacreative/Adapters/NotificationAdapter.java
|
UTF-8
| 5,385
| 2.03125
| 2
|
[] |
no_license
|
package com.vullnetlimani.instacreative.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.vullnetlimani.instacreative.Fragments.PostDetailFragment;
import com.vullnetlimani.instacreative.Fragments.ProfileFragment;
import com.vullnetlimani.instacreative.Helper.Constants;
import com.vullnetlimani.instacreative.Helper.GlideEngine;
import com.vullnetlimani.instacreative.Model.Notification;
import com.vullnetlimani.instacreative.Model.Post;
import com.vullnetlimani.instacreative.Model.User;
import com.vullnetlimani.instacreative.R;
import java.util.List;
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder> {
private Context context;
private List<Notification> mNotifications;
public NotificationAdapter(Context context, List<Notification> mNotifications) {
this.context = context;
this.mNotifications = mNotifications;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.notification_item, parent, false);
return new NotificationAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Notification notification = mNotifications.get(position);
getUser(holder.imageProfile, holder.username, notification.getUserid());
holder.comment.setText(notification.getText());
if (notification.isIs_post()) {
holder.postImage.setVisibility(View.VISIBLE);
getPostImage(holder.postImage, notification.getPostid());
} else {
holder.postImage.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (notification.isIs_post()) {
context.getSharedPreferences(Constants.PREFS, Context.MODE_PRIVATE).edit().putString(Constants.POSTID, notification.getPostid()).apply();
((FragmentActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PostDetailFragment()).addToBackStack(PostDetailFragment.class.getSimpleName()).commit();
} else {
context.getSharedPreferences(Constants.PROFILE, Context.MODE_PRIVATE).edit().putString(Constants.PROFILE_ID, notification.getUserid()).apply();
((FragmentActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).addToBackStack(ProfileFragment.class.getSimpleName()).commit();
}
}
});
}
private void getPostImage(ImageView postImage, String postid) {
FirebaseDatabase.getInstance().getReference().child(Constants.POSTS).child(postid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Post post = snapshot.getValue(Post.class);
GlideEngine.createGlideEngine().loadImage(context, post.getImageurl(), R.drawable.ic_placeholder, postImage);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void getUser(ImageView imageProfile, TextView username, String userid) {
FirebaseDatabase.getInstance().getReference().child(Constants.USERS).child(userid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (!user.getImageurl().equals(Constants.IMAGE_DEFAULT_URL)) {
GlideEngine.createGlideEngine().loadImage(context, user.getImageurl(), imageProfile);
}
username.setText(user.getUsername());
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
@Override
public int getItemCount() {
return mNotifications.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageProfile;
public ImageView postImage;
public TextView username;
public TextView comment;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageProfile = itemView.findViewById(R.id.image_profile);
postImage = itemView.findViewById(R.id.post_image);
username = itemView.findViewById(R.id.username);
comment = itemView.findViewById(R.id.comment);
}
}
}
| true
|
eb472c93141d74695fb41053ac6eeb0cefdedea1
|
Java
|
Jingdan-Z/algorithm-practice
|
/sudoku.java
|
UTF-8
| 2,723
| 3.5625
| 4
|
[] |
no_license
|
import java.util.*
public class sudoku {
public static int[][] sudoku(int[][]matrix) {
int r = matrix.length;
int c = matrix[0].length;
int[][] result = new int[r][c];
int[] toStart = toFill(matrix);
helper(matrix, toStart[0], toStart[1]);
return result;
}
private static int[] toFill(int[][]m) {//find the position we need to fill
int[] space = new int[] {-1,-1};//initialize to r = -1 & c = -1
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
if (m[i][j] == 0) {
space[0] = i;
space[1] = j;
break;
}
}
}
return space;
}
private static boolean helper(int[][]m, int r, int c) {
//base case
if (r == -1 && c == -1) {//all spaces are filled
return true;
}
//recusion rule
for (int i = 1; i <= 9; i++) {//at each level the space can be filled with 1-9 numbers
if (isValid(m,r,c,i)) {//if it is valid to put i at this position
m[r][c] = i;
int[] next = toFill(m);
boolean flag = helper(m, next[0], next[1]);
if (flag) {
return true;
}else{
m[r][c] = 0;
}
}else{
continue;
}
}
return false;
}
private static boolean isValid(int[][]m, int row, int col, int num) {
int[][] newOne = m;
newOne[row][col] = num;
Map<Integer, Integer> occur = new HashMap<>();
for (int i = 1; i <= 9; i++) {//create a hashmap with 1-9 number
occur.put(i,0);
}
//check the row
for (int i = 0; i < newOne[row].length; i++) {
if (occur.get(newOne[row][i]) == 0) {
occur.put(newOne[row][i],1);
}else{
return false;
}
}
//check column
for (int i = 0; i < newOne.length; i++) {
if (occur.get(newOne[i][col]) == 1) {
occur.put(newOne[i][col],2);
}else{
return false;
}
}
//check the 3by3 matrix
int gapR = row%3;
int gapC = col%3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (occur.get(newOne[i+row-gapR+1][j+col-gapC+1]) == 1) {
occur.put(newOne[i+row-gapR+1][j+col-gapC+1],2);
}else{
return false;
}
}
}
return true;
}
}
| true
|
150a2949bca59ca0a0eb349385a34798d80ea154
|
Java
|
muCkk/MCPC-1.4
|
/src/net/minecraftforge/event/entity/player/EntityInteractEvent.java
|
UTF-8
| 396
| 1.9375
| 2
|
[] |
no_license
|
package net.minecraftforge.event.entity.player;
import net.minecraft.server.Entity;
import net.minecraft.server.EntityHuman;
import net.minecraftforge.event.Cancelable;
@Cancelable
public class EntityInteractEvent extends PlayerEvent
{
public final Entity target;
public EntityInteractEvent(EntityHuman var1, Entity var2)
{
super(var1);
this.target = var2;
}
}
| true
|
8eb103510bf7d1ec6f4cff89a24c03d9c1d3d7dd
|
Java
|
designreuse/GAPP
|
/src/main/java/edu/isep/controllers/AttribRoleController.java
|
UTF-8
| 2,151
| 2.28125
| 2
|
[] |
no_license
|
package edu.isep.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import edu.isep.beans.Tuteur;
import edu.isep.daoImp.AttribRoleJDBCTemplate;
import edu.isep.daoImp.MainJDBCTemplate;
@Controller
public class AttribRoleController {
private AttribRoleJDBCTemplate daoAttribRole;
private MainJDBCTemplate daoMain;
private Map<Integer, Tuteur> t;
public AttribRoleController(){
ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
daoAttribRole = (AttribRoleJDBCTemplate) context.getBean("attribRoleDAO");
daoMain = (MainJDBCTemplate) context.getBean("mainDAO");
t = new HashMap<Integer, Tuteur>();
}
@RequestMapping(value="/attribRole",method = RequestMethod.GET)
public String allTuteurs(HttpSession session,Model model){
int tuteurType = daoMain.tuteurType((String) session.getAttribute("email"));
System.out.println(tuteurType);
model.addAttribute("typeTuteur",tuteurType);
List<Tuteur> tuteurs = daoAttribRole.getTuteurs();
model.addAttribute("tuteurs",tuteurs);
return "attribRole";
}
@RequestMapping(value="/attribRole",method = RequestMethod.POST)
public String updateRole(HttpServletRequest request, Model model){
List<Tuteur> tuteurs = daoAttribRole.getTuteurs();
model.addAttribute("tuteurs",tuteurs);
for(int i=0;i<tuteurs.size();i++){
int id = tuteurs.get(i).getId();
if(request.getParameter("type-"+id) == null){
}else{
Tuteur tuteur = new Tuteur();
String type = request.getParameter("type-"+id);
tuteur.setId(id);
tuteur.setType(Integer.parseInt(type));
daoAttribRole.updateRole(tuteur);
}
}
return "redirect:attribRole";
}
}
| true
|
02f7c459a9f0adb9e5268cb2bd7ca6bacf99ba74
|
Java
|
jecy-8/project-of-jecy
|
/src/jecy/test/algorithm/sort/SortUtils.java
|
UTF-8
| 375
| 2.5
| 2
|
[] |
no_license
|
package jecy.test.algorithm.sort;
public class SortUtils {
public static String getArrayElements(int[] a) {
StringBuffer sb = new StringBuffer("{");
for (int i = 0; i < a.length; i ++) {
sb.append(a[i]).append(",");
}
sb.deleteCharAt(sb.toString().length() - 1);
sb.append("}");
return sb.toString();
}
}
| true
|
d1c0fa59238feccd93a408e4be22591927e572e9
|
Java
|
laenan/projetJEE-smartphone-A3
|
/JEE/src/main/java/fr/exia/repository/Menu_RestaurantRepository.java
|
UTF-8
| 305
| 1.703125
| 2
|
[] |
no_license
|
package fr.exia.repository;
import fr.exia.domain.Menu_Restaurant;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the Menu_Restaurant entity.
*/
public interface Menu_RestaurantRepository extends JpaRepository<Menu_Restaurant,Long> {
}
| true
|
dfb4668a790d17bce9af8233be5d93958e055995
|
Java
|
MatthewSamms/teksme
|
/tests/org.teksme.model.test/test/org/teksme/client/test/persistence/PersistenceTest.java
|
UTF-8
| 1,478
| 2
| 2
|
[] |
no_license
|
package org.teksme.client.test.persistence;
import java.util.Properties;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.teneo.PersistenceOptions;
import org.hibernate.cfg.Environment;
import org.junit.Before;
import org.teksme.model.teks.impl.TeksPackageImpl;
import org.teksme.model.teks.util.TeksResourceFactoryImpl;
public class PersistenceTest {
static Properties props = new Properties();
static final String dbName = "teksme";
ResourceSet resourceSet = null;
@Before
public void setResourceSet() {
// create resource set and resource
resourceSet = new ResourceSetImpl();
// Register XML resource factory
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("xml", new TeksResourceFactoryImpl());
props.setProperty(Environment.DRIVER, "com.mysql.jdbc.Driver");
props.setProperty(Environment.USER, "teksmeuser");
props.setProperty(Environment.URL, "jdbc:mysql://127.0.0.1:3306/"
+ dbName);
props.setProperty(Environment.PASS, "teksme");
props.setProperty(Environment.DIALECT,
org.hibernate.dialect.MySQLInnoDBDialect.class.getName());
// set a specific option
// see this page
// http://wiki.eclipse.org/Teneo/Hibernate/Configuration_Options
// for all the available options
props.setProperty(PersistenceOptions.CASCADE_POLICY_ON_NON_CONTAINMENT,
"REFRESH,PERSIST,MERGE");
TeksPackageImpl.init();
}
}
| true
|
b59a10da8ad32a2554b9fb3840ca3d4813d55a80
|
Java
|
Nothingtaro/Java-C
|
/ConditionalStatement/src/loop1.java
|
UTF-8
| 1,850
| 3.6875
| 4
|
[] |
no_license
|
public class loop1 {
public static void demo1() {
// int i;
for (int i = 1; i <= 10; i++) {
System.out.println(i);
System.out.println("--");
}
System.out.println("BYE");
}
public static void demo2() {
for (int i = 10; i >= 1; i--) {
System.out.println(i);
System.out.println("--");
}
System.out.println("BYE");
}
public static void sum1() {
int total = 0;
for (int i = 1; i <= 10; i++) {
total = total + i;
}
System.out.println(total);
}
public static int sum(int fromNum, int toNum) {
int total = 0;
for (int i = fromNum; i <= toNum; i++) {
total = total + i;
}
return total;
}
public static void MultiplicationTable(int n) {
for (int i = 1; i <= 12; i++) {
System.out.printf("%d x %d = %d\n", n, i, n*i);
}
}
public static void printChar() {
for (char c = 'A'; c <= 'Z' ; c++) {
System.out.printf("%c", c);
}
}
public static void printChar2() {
for (int c = 65; c <= 90 ; c++) {
System.out.printf("%d --> %c\n", c, (char)c);
}
}
public static void printCharBetter(char FromCh, char ToCh) {
for (char c = FromCh; c <= ToCh ; c++) {
System.out.printf("%d %04X %c\n", (int)c, (int)c, c);
}
}
public static void main(String args[]) {
// demo1();
// demo2();
// sum1();
// System.out.println(sum(1,100));
// MultiplicationTable(5);
// printChar();
// printChar2();
// printCharBetter('J', 'Z');
printCharBetter('ก', 'ฮ');
}
}
| true
|
850444fe93960ee92f1b4e6848d700d04a3926d4
|
Java
|
nayangandhi1987/EasyImageUpload
|
/internal/JungleeCommonLib/src/com/junglee/commonlib/location/LocationTracker.java
|
UTF-8
| 11,265
| 2.390625
| 2
|
[] |
no_license
|
package com.junglee.commonlib.location;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import com.junglee.commonlib.logging.Logger;
/**
* LocationTracker can be used to get the geo-location of the device. It can be used to get the geo-location one time,
* or it can also be requested to set up listeners to keep track of the location changes.
* <p>
* It can get the geo-location of the device using gps or network. If it gets the location from both the sources, then
* it tries to guess which one of those is more precise depending on different parameters. It can be used to get the
* location in terms of latitude/longitude, or more readable form like city, or city along with pincode and country.
* As of now, it is only used to get the location one time when the object is constructed. The listeners for the
* location updates are not implemented. If required those can be implemented to keep a continuous check on location
* changes.
*
* @author Nayan Gandhi <nggandhi@amazon.com>
* @since 1.0
*/
public class LocationTracker implements LocationListener {
private static final String TAG = "LocationTracker";
private Context context = null;
private boolean listenToUpdates = false;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
private static final int TWO_MINUTES = 1000 * 60 * 2;
private static final boolean NEED_FINE_LOCATION = true;
// Declaring a Location Manager
protected LocationManager locationManager;
/**
* The constructor of the Locationtracker. It internally retrieves the location one time, and then can keep listening to updates depending on the flag.
* @param c the activity context
* @param listenToUpdates whether it should retrieve location on time, or keep listening to location updates too.
*/
public LocationTracker(Context c, boolean listenToUpdates) {
this.context = c;
this.listenToUpdates = listenToUpdates;
retrieveLocation();
if(!this.listenToUpdates) {
stopUsingGPS();
}
}
/**
* Retrieves the geo-location of the device. It can use either or both of gps and network. If it gets the location from both the sources, then
* it tries to guess which one of those is more precise depending on different parameters.
* @return the location retrieved
*/
public Location retrieveLocation() {
try {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
if(!NEED_FINE_LOCATION) {
isGPSEnabled = false;
} else {
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Logger.info(TAG, "GPS_ENABLED:"+isGPSEnabled+", NTWRK_ENABLED:"+isNetworkEnabled);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
this.canGetLocation = false;
this.location = null;
this.latitude = 0.0;
this.longitude = 0.0;
showSettingsAlert();
} else {
Location gps_location = null, net_location = null;
this.canGetLocation = true;
// if Network Enabled get location from Network Provider
if (isNetworkEnabled) {
if(listenToUpdates) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (locationManager != null) {
net_location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if(listenToUpdates) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (locationManager != null) {
gps_location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
location = getBetterLocation(gps_location, net_location);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Unregisters for location updates
*/
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(LocationTracker.this);
}
}
/**
* Returns the latitude of the retrieved location.
* @return the current latitude
*/
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
/**
* Returns the longitude of the retrieved location.
* @return the current longitude
*/
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
/**
* It returns the location in a more readable form as string. For eg: "Bangalore - 560034, India"
* @return the location string
*/
public String getReadableLocation() {
String locationString = null;
if(location == null) return locationString;
Geocoder geocoder = new Geocoder(context.getApplicationContext(), Locale.getDefault());
try {
List<Address> myList = geocoder.getFromLocation(getLatitude(), getLongitude(), 1);
if(myList.size() > 0) {
Address addr = myList.get(0);
String locality = addr.getLocality();
String postalCode = addr.getPostalCode();
String country = addr.getCountryName();
if(postalCode != null) {
postalCode = String.format(" - %s", postalCode);
} else {
postalCode = "";
}
locationString = String.format("%s%s, %s", locality, postalCode, country);
}
} catch (IOException e) {
locationString = "Network Error";
}
return locationString;
}
/**
* It returns the city as a string. For eg: "Bangalore"
* @return the city
*/
public String getCity() {
String cityString = null;
if(location == null) return cityString;
Geocoder geocoder = new Geocoder(context.getApplicationContext(), Locale.getDefault());
try {
List<Address> myList = geocoder.getFromLocation(getLatitude(), getLongitude(), 1);
if(myList.size() > 0) {
Address addr = myList.get(0);
cityString = addr.getLocality();
}
} catch (IOException e) {
e.printStackTrace();
}
return cityString;
}
/**
* Shows the settings dialog to enable gps.
*/
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
// Setting Dialog Title
alertDialog.setTitle("GPS not enabled");
// Setting Dialog Message
alertDialog.setMessage("Do you want to enable it from the settings menu?");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.delete);
// On pressing Settings button
alertDialog.setNegativeButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
/**
* It compares the two location based on which one is newer or which one is more accurate if not much difference in their update time.
* @param location1 the first location
* @param location2 the second location
* @return location object corresponding to the better location
*/
protected Location getBetterLocation(Location location1, Location location2) {
if (location1 != null && location2 != null) {
// Check whether the new location fix is newer or older
long timeDelta = location1.getTime() - location2.getTime();
boolean firstIsNewer = timeDelta > TWO_MINUTES;
boolean secondIsNewer = timeDelta < -TWO_MINUTES;
if (firstIsNewer) {
return location1;
} else if (secondIsNewer) {
return location2;
}
int accuracyDelta = (int) (location1.getAccuracy() - location2.getAccuracy());
boolean firstMoreAccurate = accuracyDelta > 0;
if(firstMoreAccurate) {
return location1;
} else {
return location2;
}
} else if(location1 != null) {
return location1;
} else if(location2 != null) {
return location2;
} else {
return null;
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public IBinder onBind(Intent arg0) {
return null;
}
}
| true
|
5aa784069d291b7d23c73753f33916fa5329b104
|
Java
|
patrykacc/progress-tracker
|
/src/main/java/fit/body/tms/repositories/TrainingDayExerciseRepository.java
|
UTF-8
| 480
| 2
| 2
|
[] |
no_license
|
package fit.body.tms.repositories;
import fit.body.tms.entities.TrainingDayExercise;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource(path = "TrainingDayExercise")
public interface TrainingDayExerciseRepository extends CrudRepository<TrainingDayExercise, String > {
List<TrainingDayExercise> findAllByTrainingDayId(String trainingId);
}
| true
|
477f18066b2d63c145a721d0ef890eb9aef7aff2
|
Java
|
JetBrains/azure-tools-for-intellij
|
/Utils/AzureAuthenticationFilter/src/main/java/com/microsoft/azure/oidc/filter/configuration/authentication/AuthenticationConfigurationFactory.java
|
UTF-8
| 547
| 1.507813
| 2
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.oidc.filter.configuration.authentication;
import java.util.List;
import java.util.Map;
public interface AuthenticationConfigurationFactory {
AuthenticationConfiguration createAuthenticationConfiguration(List<String> exclusionUriPatternList,
List<String> authorisationUriPatternList, Map<String, List<String>> authorisationRoleMap);
}
| true
|
6baa58836062dfc3790e3297547ea1e65d64c367
|
Java
|
RajarshiBhattacharya-JA-17/JA-17-Lab-and-Assignments
|
/Lab_7/src/com/cg/eis/pl/UserInput.java
|
UTF-8
| 2,633
| 3.328125
| 3
|
[] |
no_license
|
/**
*
*/
package com.cg.eis.pl;
import java.util.Scanner;
import com.cg.eis.beans.Employee;
import com.cg.eis.service.EmployeeInsuranceSystem;
/**
* @author Rajarshi
*
*/
public class UserInput {
static Scanner sc = new Scanner(System.in);
static Long empId;
static String empName, empDesignation, empInsuranceScheme;
static double empSalary;
public static void input() {
char ch = 'y';
EmployeeInsuranceSystem emps = new EmployeeInsuranceSystem();
while(ch == 'y') {
System.out.println("Enter your choice:");
System.out.println();
System.out.println("1) Add New Employee Details\n"
+ "2) Find Employee By Employee ID\n"
+ "3) Display Employees Under a Particular Insurance Scheme\n"
+ "4) Delete Employee Record\n"
+ "5) Exit App\n");
int choice = sc.nextInt();
switch(choice) {
case 1://Add New Employee Record
System.out.println("Enter Employee Details");
System.out.println();
readDetails();
boolean added = emps.addEmployee(new Employee(empId, empDesignation,
empName, emps.getInsuranceScheme(empSalary, empDesignation),
empSalary));
if(added)
System.out.println("Employee Record Added Successfully");
System.out.println();
break;
case 2://Find Employee Details Using Employee ID
readEmpID();
emps.findEmployee(empId);
System.out.println();
break;
case 3://Display Employees Under a Particular Insurance Scheme
System.out.println("Enter Insurance Scheme:");
sc.nextLine();
empInsuranceScheme = sc.nextLine();
System.out.println();
System.out.println("Employees Under "+empInsuranceScheme+":");
emps.showEmployeeUnderInsuranceScheme(empInsuranceScheme);
System.out.println();
break;
case 4://Delete Employee Record
readEmpID();
emps.deleteEmployee(empId);
System.out.println();
break;
case 5://Exit App
ch = 'n';
break;
default:System.out.println("Invalid Choice Entered...");
System.out.println();
}
}
}
private static void readEmpID() {
// TODO Auto-generated method stub
System.out.println("Enter Employee ID:");
empId = sc.nextLong();
}
private static void readDetails() {
// TODO Auto-generated method stub
readEmpID();
System.out.println("Enter Employee Name:");
sc.nextLine();
empName = sc.nextLine();
System.out.println("Enter Employee Designation:");
sc.nextLine();
empDesignation = sc.nextLine();
System.out.println("Enter Employee Salary:");
empSalary = sc.nextDouble();
}
}
| true
|
7f3d33de15145823afb5cb40949dae10af1a7e8e
|
Java
|
robertcannon/jldLEMS
|
/src/org/lemsml/jlems/core/lite/model/OnEvent.java
|
UTF-8
| 265
| 1.726563
| 2
|
[] |
no_license
|
package org.lemsml.jlems.core.lite.model;
public class OnEvent extends OnAbstract {
public String port;
public OnEvent(String pn) {
super();
port = pn;
}
public OnEvent() {
super();
}
public String getPortName() {
return port;
}
}
| true
|
939189b90086b4b0972cbd797e9566e031a0b71f
|
Java
|
danielsvr/crossv
|
/java/CrossV/src/org/crossv/strategies/StrategicIterableByContext.java
|
UTF-8
| 356
| 2.234375
| 2
|
[] |
no_license
|
package org.crossv.strategies;
import org.crossv.Evaluator;
public class StrategicIterableByContext extends StrategicIterable {
public StrategicIterableByContext(Iterable<? extends Evaluator> evaluators) {
super(evaluators);
}
@Override
public StrategicIterator iterator() {
return new StrategicIteratorByContext(evaluators.iterator());
}
}
| true
|
ac5b60b517e92bb7fb1555c6e5a61c13996206db
|
Java
|
YunYungSeok/yys
|
/proxy/OldClient.java
|
UTF-8
| 189
| 1.679688
| 2
|
[] |
no_license
|
package proxy;
public class OldClient {
public static void main(String[] args) {
HelloWorld hello = new HelloWorldImpl();
System.out.println(hello.sayHello("JCLEE"));
}
}
| true
|
9afe9c5c43aa2beab67edb1e6eca9165ac3d433d
|
Java
|
guccio618/myLeetcode
|
/I_Facebook_LeetCode/src/Q013_Roman_to_Integer.java
|
UTF-8
| 1,684
| 3.8125
| 4
|
[] |
no_license
|
import java.util.*;
/*******
*
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
*
* */
public class Q013_Roman_to_Integer {
/*******************************************/
// solution1: using int[] hash
public int romanToInt(String s) {
if (s == null || s.length()==0) {
return 0;
}
int[] hash = new int[256];
hash[(int)('I')] = 1;
hash[(int)('V')] = 5;
hash[(int)('X')] = 10;
hash[(int)('L')] = 50;
hash[(int)('C')] = 100;
hash[(int)('D')] = 500;
hash[(int)('M')] = 1000;
int len = s.length();
int ans = hash[s.charAt(len - 1)];
for(int i = len - 2; i >= 0; i--){
char c1 = s.charAt(i);
char c2 = s.charAt(i + 1);
if(hash[c1] >= hash[c2]){
ans += hash[c1]; // 注意这里加的是c1 !!!
} else {
ans -= hash[c1];
}
}
return ans;
}
// solution 2: using hashmap
public int romanToInt2(String s) {
if (s == null || s.length()==0) {
return 0;
}
Map<Character, Integer> m = new HashMap<Character, Integer>();
m.put('I', 1);
m.put('V', 5);
m.put('X', 10);
m.put('L', 50);
m.put('C', 100);
m.put('D', 500);
m.put('M', 1000);
int length = s.length();
int result = m.get(s.charAt(length - 1));
for (int i = length - 2; i >= 0; i--) {
if (m.get(s.charAt(i + 1)) <= m.get(s.charAt(i))) {
result += m.get(s.charAt(i));
} else {
result -= m.get(s.charAt(i));
}
}
return result;
}
}
| true
|
fbeb51958d23b054317565d5f190e878984f911a
|
Java
|
louiskoo520/RestFulAPI
|
/src/main/java/com/lungcare/dicomfile/service/IUserService.java
|
UTF-8
| 778
| 1.914063
| 2
|
[] |
no_license
|
package com.lungcare.dicomfile.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.lungcare.dicomfile.entity.Login;
import com.lungcare.dicomfile.entity.User;
public interface IUserService {
public String login(HttpServletRequest request, String user_account,
String user_password);
public String checkUserName(String user_account);
public String register(String user_account, String user_password);
public List<User> getAllUsers();
public void addUser(String user_account, String user_name,
String user_password, int user_age, int user_gender, int user_role,
String user_tel, String user_address);
public void test();
public User getSessionUser();
public List<Login> getAllLoginInfo();
public void logout();
}
| true
|
acb5ea20990b68678c51988f5f5307884740bcc7
|
Java
|
clyao/mcms
|
/mcms/src/com/mingsoft/weixin/entity/OauthEntity.java
|
UTF-8
| 3,933
| 2.296875
| 2
|
[] |
no_license
|
/**
The MIT License (MIT) * Copyright (c) 2016 铭飞科技(mingsoft.net)
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.mingsoft.weixin.entity;
import com.mingsoft.base.entity.BaseEntity;
/**
* 铭飞科技微信
* Copyright: Copyright (c) 2014 - 2015
* @author 成卫雄 QQ:330216230
* Comments:网页授权2.0实体
* Create Date:2014-10-7
* Modification history:
*/
public class OauthEntity extends BaseEntity {
/**
* 自增长ID
*/
private int oauthId;
/**
* 微信基础信息Id
*/
private int oauthWeixinId;
/**
* 关联微信应用ID
*/
private int oauthAppId;
/**'
* 授权成功重定向地址
*/
private String oauthSuccessUrl;
/**
* 授权失败或者错误重定向地址
*/
private String oauthErrorUrl;
/**
* 授权类型
* 1.弹出授权界面可以获取到用户的详细信息
* 2.不弹出授权界面只能获取到用户的openId
*/
private int oauthType;
/**
* 授权描述
*/
private String oauthDescription;
public int getOauthWeixinId() {
return oauthWeixinId;
}
public void setOauthWeixinId(int oauthWeixinId) {
this.oauthWeixinId = oauthWeixinId;
}
/**
* 获取oauthId
* @return oauthId
*/
public int getOauthId() {
return oauthId;
}
/**
* 设置oauthId
* @param oauthId
*/
public void setOauthId(int oauthId) {
this.oauthId = oauthId;
}
/**
* 获取oauthAppId
* @return oauthAppId
*/
public int getOauthAppId() {
return oauthAppId;
}
/**
* 设置oauthAppId
* @param oauthAppId
*/
public void setOauthAppId(int oauthAppId) {
this.oauthAppId = oauthAppId;
}
/**
* 获取oauthSuccessUrl
* @return oauthSuccessUrl
*/
public String getOauthSuccessUrl() {
return oauthSuccessUrl;
}
/**
* 设置oauthSuccessUrl
* @param oauthSuccessUrl
*/
public void setOauthSuccessUrl(String oauthSuccessUrl) {
this.oauthSuccessUrl = oauthSuccessUrl;
}
/**
* 获取oauthErrorUrl
* @return oauthErrorUrl
*/
public String getOauthErrorUrl() {
return oauthErrorUrl;
}
/**
* 设置oauthErrorUrl
* @param oauthErrorUrl
*/
public void setOauthErrorUrl(String oauthErrorUrl) {
this.oauthErrorUrl = oauthErrorUrl;
}
/**
* 获取oauthType
* @return oauthType
*/
public int getOauthType() {
return oauthType;
}
/**
* 设置oauthType
* @param oauthType
*/
public void setOauthType(int oauthType) {
this.oauthType = oauthType;
}
/**
* 获取oauthDescription
* @return oauthDescription
*/
public String getOauthDescription() {
return oauthDescription;
}
/**
* 设置oauthDescription
* @param oauthDescription
*/
public void setOauthDescription(String oauthDescription) {
this.oauthDescription = oauthDescription;
}
}
| true
|
c20b68957b7c2785e732452fe2e0cca283033138
|
Java
|
moushao/WorkManager-master
|
/workmanager_lib/src/main/java/com/moushao/workmanager/lib/injection/Injection.java
|
UTF-8
| 299
| 1.773438
| 2
|
[] |
no_license
|
package com.moushao.workmanager.lib.injection;
import com.moushao.workmanager.lib.ReportRepository;
import com.moushao.workmanager.lib.work.ReportRepositoryImpl;
public class Injection {
public static ReportRepository getReportRepository() {
return new ReportRepositoryImpl();
}
}
| true
|
0ef97d0cc8cc528337e245fc2dda6566b3f689b1
|
Java
|
HenriqueDario/Ecommerce
|
/src/br/com/darioprod/ecommerce/controller/UpdateProduct.java
|
UTF-8
| 2,329
| 2.359375
| 2
|
[] |
no_license
|
package br.com.darioprod.ecommerce.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import br.com.darioprod.ecommerce.dao.ProductDAO;
import br.com.darioprod.ecommerce.model.Product;
@WebServlet("/editarProduto")
public class UpdateProduct extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
Product prod = new Product();
if(ServletFileUpload.isMultipartContent(req)){
try {
Map<String,List<FileItem>> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseParameterMap(req);
for(List<FileItem> itens : multiparts.values()){
for(FileItem item : itens){
if(item.isFormField()){
if(item.getFieldName().equals("nome")) {
prod.setNameProduct(item.getString());
}else if(item.getFieldName().equals("idProduct")){
prod.setIdProduct(Integer.parseInt(item.getString()));
}else if(item.getFieldName().equals("valor")){
prod.setPriceProduct(Double.parseDouble(item.getString()));
}else if(item.getFieldName().equals("descricaoProduto")){
prod.setDescribeProduct(item.getString());
}
}else{
prod.setPhotoProduct("images"+File.separator+item.getName());
String path = getServletContext().getRealPath("images")+File.separator+item.getName();
item.write(new File(path));
System.out.println(path);
}
}
}
ProductDAO pDao = new ProductDAO();
if(pDao.alterar(prod))
System.out.println("FOI");
resp.sendRedirect("areaADM.jsp");
}catch(Exception e){
e.printStackTrace();
req.getRequestDispatcher("areaADM.jsp").forward(req, resp);
}
}
}
}
| true
|
9cf1f688001cf0fd251afa33068bb705fb278c1a
|
Java
|
zksun/sunspace
|
/space-jini-platform/src/main/java/net/jini/core/lease/LeaseException.java
|
UTF-8
| 233
| 2.015625
| 2
|
[] |
no_license
|
package net.jini.core.lease;
/**
* Created by zksun on 25/01/2017.
*/
public class LeaseException extends Exception {
public LeaseException() {
}
public LeaseException(String reason) {
super(reason);
}
}
| true
|
fd8ae5e02f79373647bd75d14ec44e506fe585bb
|
Java
|
Viren-P/blogforum
|
/src/main/java/com/springdemo/springrestforum/controller/CategoryController.java
|
UTF-8
| 1,745
| 2.1875
| 2
|
[] |
no_license
|
package com.springdemo.springrestforum.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.springdemo.springrestforum.model.Category;
import com.springdemo.springrestforum.service.CategoryService;
@RestController
public class CategoryController {
@Autowired
CategoryService categoryService;
@GetMapping(path="/category")
public List<Category> getAll(){
return categoryService.getAll();
}
@GetMapping(path="/category/id/{id}")
public Category getById(@PathVariable("id") int id) {
return categoryService.getById(id);
}
@GetMapping(path="/category/name/{name}")
public Category getByName(@PathVariable("name") String name) {
return categoryService.getByName(name);
}
@PostMapping(path="/category/add")
public Category add(@RequestBody Category category) {
return categoryService.add(category);
}
@PutMapping(path="/category/update")
public Category update(@RequestBody Category category) {
return categoryService.update(category);
}
@DeleteMapping(path="/category/delete/id/{id}")
public void deleteById(@PathVariable int id) {
categoryService.deleteById(id);
}
@DeleteMapping(path="/category/delete/name/{name}")
public void deleteByName(@PathVariable String name) {
categoryService.deleteByName(name);
}
}
| true
|
6af5c26572b0060ebf92dd3deeec1ffa99f6025e
|
Java
|
DmitryKober/SchedulingProblem
|
/BaseAlgorithms/src/main/java/services/fitness/IndividualFitnessFunction.java
|
UTF-8
| 213
| 2.0625
| 2
|
[] |
no_license
|
package services.fitness;
import domain.ga.Individual;
/**
* User: dmitry
* Date: 28.01.12
* Time: 19:15
*/
public interface IndividualFitnessFunction {
public long evaluate(Individual individual);
}
| true
|
d41465440344273140b79ae925161235b2d42158
|
Java
|
OwlinLight/DB_proj
|
/src/main/java/pers/shayz/crud/bean/Problem.java
|
UTF-8
| 1,617
| 2.1875
| 2
|
[] |
no_license
|
package pers.shayz.crud.bean;
import java.util.Date;
public class Problem {
private Integer id;
private String title;
private String description;
private Integer topicId;
private Date publishedDate;
private Integer updatedDate;
private Integer click;
private String state;
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 == null ? null : title.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public Integer getTopicId() {
return topicId;
}
public void setTopicId(Integer topicId) {
this.topicId = topicId;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public Integer getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Integer updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getClick() {
return click;
}
public void setClick(Integer click) {
this.click = click;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state == null ? null : state.trim();
}
}
| true
|
336eecf496ee1cf88d8f840ec770617cfb5d2f4f
|
Java
|
logandillard/game-players
|
/src/com/dillard/nn/LayerBatchActivation.java
|
UTF-8
| 868
| 2.03125
| 2
|
[] |
no_license
|
package com.dillard.nn;
import java.io.Serializable;
import java.util.List;
public class LayerBatchActivation implements Serializable {
private static final long serialVersionUID = 1L;
public final List<double[]> inputs;
public final List<double[]> outputs;
public final double[] means;
public final double[] variances;
public final double[] inverseStdDev;
public final List<double[]> batchNormalizedH;
public LayerBatchActivation(List<double[]> batchInputs, List<double[]> batchOutputs, double[] means,
double[] variances, double[] inverseStdDev, List<double[]> batchNormalizedH) {
this.inputs = batchInputs;
this.outputs = batchOutputs;
this.means = means;
this.variances = variances;
this.inverseStdDev = inverseStdDev;
this.batchNormalizedH = batchNormalizedH;
}
}
| true
|
6a340d07899cb76e9c6d214a91a4cca6c20c78ff
|
Java
|
julienlinder/StockArc
|
/StockArc/src/main/java/ch/hearc/stockarc/service/UserService.java
|
UTF-8
| 3,277
| 2.265625
| 2
|
[] |
no_license
|
package ch.hearc.stockarc.service;
import java.util.ArrayList;
import java.util.Arrays;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import ch.hearc.stockarc.model.NewUser;
import ch.hearc.stockarc.model.PasswordResetToken;
import ch.hearc.stockarc.model.Person;
import ch.hearc.stockarc.model.Role;
import ch.hearc.stockarc.model.User;
import ch.hearc.stockarc.model.UserCreationToken;
import ch.hearc.stockarc.repository.PasswordResetTokenRepository;
import ch.hearc.stockarc.repository.PeopleRepository;
import ch.hearc.stockarc.repository.RoleRepository;
import ch.hearc.stockarc.repository.UserCreationTokenRepository;
import ch.hearc.stockarc.repository.UserRepository;
@Service
public class UserService implements IUserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PeopleRepository peopleRepository;
@Autowired
private PasswordResetTokenRepository passwordTokenRepository;
@Autowired
private UserCreationTokenRepository creationTokenRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public void save(User user) {
Role roleUser = roleRepository.findByName("ROLE_USER");
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new ArrayList<>(roleRepository.findAll()));
user.setRoles(Arrays.asList(roleUser));
userRepository.save(user);
}
@Override
public User findByName(String name) {
return userRepository.findByName(name);
}
@Override
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
@Override
public void createPasswordResetTokenForUser(User user, String token) {
final PasswordResetToken myToken = new PasswordResetToken(token, user);
passwordTokenRepository.save(myToken);
}
@Override
public void createUserCreationTokenForUser(User user, String token) {
final UserCreationToken myToken = new UserCreationToken(token, user);
creationTokenRepository.save(myToken);
}
@Override
public void changeUserPassword(final User user, final String password) {
user.setPassword(bCryptPasswordEncoder.encode(password));
userRepository.save(user);
}
@Override
public void changeUserName(final User user, final String name) {
user.setName(name);
userRepository.save(user);
}
@Override
public User createNewPartialUser(@Valid NewUser newUser) {
Role roleUser = roleRepository.findByName("ROLE_USER");
User user = new User();
user.setEmail(newUser.getEmail());
user.setRoles(Arrays.asList(roleUser));
User savedUser = userRepository.save(user);
if (newUser.getExistingPerson().equals("Yes")) {
Person person = peopleRepository.findById(newUser.getPerson().getId()).get();
person.setUser(savedUser);
peopleRepository.save(person);
}
return savedUser;
}
}
| true
|
ab466007ecaba68966ecd1423b4a5b1c9b232ca5
|
Java
|
Eversor11/TiraLabra
|
/Tiralabra/src/gui/Kayttoliittyma.java
|
UTF-8
| 91,178
| 2.265625
| 2
|
[] |
no_license
|
package gui;
import apuneuvot.MatriisienLukija;
import apuneuvot.MatriisienTallentaja;
import java.util.Scanner;
import javax.swing.JOptionPane;
import logiikka.Matriisilaskin;
/**
* Kayttoliittyma-luokka, joka perii JFrame-luokan ja toimii matriisilaskimen
* graafisena käyttöliittymänä. Toteutettu Netbeansin GUI-builderilla.
*
* @author Eversor
*/
public class Kayttoliittyma extends javax.swing.JFrame {
private Scanner lukija;
private MatriisienLukija matriisienlukija;
private MatriisienTallentaja tallentaja;
private Matriisilaskin laskin;
/**
* Konstruktori, joka luo uudet ilmentymät MatriisienLukijasta,
* -Tallentajasta sekä Matriisilaskin -luokista niiden private-muuttujiin.
* Lopuksi initialisoi komponentit.
*/
public Kayttoliittyma() {
matriisienlukija = new MatriisienLukija();
tallentaja = new MatriisienTallentaja();
laskin = new Matriisilaskin();
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() {
alustaPanel = new javax.swing.JPanel();
matriisiAPanel = new javax.swing.JPanel();
rivitALabel = new javax.swing.JLabel();
rivitAText = new javax.swing.JTextField();
sarakkeetALabel = new javax.swing.JLabel();
sarakkeetAText = new javax.swing.JTextField();
matriisiAScroll = new javax.swing.JScrollPane();
matriisiAText = new javax.swing.JTextArea();
lataaAText = new javax.swing.JTextField();
neliomatriisiALabel = new javax.swing.JLabel();
symmetrinenALabel = new javax.swing.JLabel();
antisymmetrinenALabel = new javax.swing.JLabel();
kaantyvaALabel = new javax.swing.JLabel();
ortogonaalinenALabel = new javax.swing.JLabel();
determinanttiALabel = new javax.swing.JLabel();
tiedotAButton = new javax.swing.JButton();
ortogonaalinenATulosLabel = new javax.swing.JLabel();
determinanttiATulosLabel = new javax.swing.JLabel();
antisymmetrinenATulosLabel = new javax.swing.JLabel();
kaantyvaATulosLabel = new javax.swing.JLabel();
symmetrinenATulosLabel = new javax.swing.JLabel();
neliomatriisiATulosLabel = new javax.swing.JLabel();
transpoosiAButton = new javax.swing.JButton();
kaanteismatriisiAButton = new javax.swing.JButton();
potenssiinAButton = new javax.swing.JButton();
potenssiinAText = new javax.swing.JTextField();
lataaAButton = new javax.swing.JButton();
matriisiALabel = new javax.swing.JLabel();
summaaButton = new javax.swing.JButton();
vahennaButton = new javax.swing.JButton();
kerroButton = new javax.swing.JButton();
matriisiBPanel = new javax.swing.JPanel();
rivitBLabel = new javax.swing.JLabel();
rivitBText = new javax.swing.JTextField();
sarakkeetBLabel = new javax.swing.JLabel();
sarakkeetBText = new javax.swing.JTextField();
matriisiBScroll = new javax.swing.JScrollPane();
matriisiBText = new javax.swing.JTextArea();
lataaBText = new javax.swing.JTextField();
neliomatriisiBLabel = new javax.swing.JLabel();
symmetrinenBLabel = new javax.swing.JLabel();
antisymmetrinenBLabel = new javax.swing.JLabel();
kaantyvaBLabel = new javax.swing.JLabel();
ortogonaalinenBLabel = new javax.swing.JLabel();
determinanttiBLabel = new javax.swing.JLabel();
tiedotBButton = new javax.swing.JButton();
ortogonaalinenBTulosLabel = new javax.swing.JLabel();
determinanttiBTulosLabel = new javax.swing.JLabel();
antisymmetrinenBTulosLabel = new javax.swing.JLabel();
kaantyvaBTulosLabel = new javax.swing.JLabel();
symmetrinenBTulosLabel = new javax.swing.JLabel();
neliomatriisiBTulosLabel = new javax.swing.JLabel();
transpoosiBButton = new javax.swing.JButton();
kaanteismatriisiBButton = new javax.swing.JButton();
potenssiinBButton = new javax.swing.JButton();
potenssiinBText = new javax.swing.JTextField();
lataaBButton = new javax.swing.JButton();
matriisiBLabel = new javax.swing.JLabel();
matriisiCPanel = new javax.swing.JPanel();
rivitCLabel = new javax.swing.JLabel();
rivitCText = new javax.swing.JTextField();
sarakkeetCLabel = new javax.swing.JLabel();
sarakkeetCText = new javax.swing.JTextField();
matriisiCScroll = new javax.swing.JScrollPane();
matriisiCText = new javax.swing.JTextArea();
tallennaCText = new javax.swing.JTextField();
neliomatriisiCLabel = new javax.swing.JLabel();
symmetrinenCLabel = new javax.swing.JLabel();
antisymmetrinenCLabel = new javax.swing.JLabel();
kaantyvaCLabel = new javax.swing.JLabel();
ortogonaalinenCLabel = new javax.swing.JLabel();
determinanttiCLabel = new javax.swing.JLabel();
tiedotCButton = new javax.swing.JButton();
ortogonaalinenCTulosLabel = new javax.swing.JLabel();
determinanttiCTulosLabel = new javax.swing.JLabel();
antisymmetrinenCTulosLabel = new javax.swing.JLabel();
kaantyvaCTulosLabel = new javax.swing.JLabel();
symmetrinenCTulosLabel = new javax.swing.JLabel();
neliomatriisiCTulosLabel = new javax.swing.JLabel();
transpoosiCButton = new javax.swing.JButton();
kaanteismatriisiCButton = new javax.swing.JButton();
potenssiinCButton = new javax.swing.JButton();
potenssiinCText = new javax.swing.JTextField();
tallennaCButton = new javax.swing.JButton();
vastausmatriisiLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Matriisilaskin");
setMinimumSize(new java.awt.Dimension(720, 480));
setResizable(false);
alustaPanel.setPreferredSize(new java.awt.Dimension(720, 480));
matriisiAPanel.setPreferredSize(new java.awt.Dimension(209, 420));
rivitALabel.setText("Rivit");
rivitAText.setMinimumSize(new java.awt.Dimension(28, 20));
sarakkeetALabel.setText("Sarakkeet");
sarakkeetAText.setMinimumSize(new java.awt.Dimension(28, 20));
matriisiAText.setColumns(17);
matriisiAText.setRows(5);
matriisiAScroll.setViewportView(matriisiAText);
lataaAText.setText("matriisi.txt");
neliomatriisiALabel.setText("Neliömatriisi");
symmetrinenALabel.setText("Symmetrinen");
antisymmetrinenALabel.setText("Antisymmetrinen");
kaantyvaALabel.setText("Kääntyvä");
ortogonaalinenALabel.setText("Ortogonaalinen");
determinanttiALabel.setText("Determinantti");
tiedotAButton.setText("Määritä tiedot");
tiedotAButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tiedotAButtonActionPerformed(evt);
}
});
ortogonaalinenATulosLabel.setText("-");
determinanttiATulosLabel.setText("-");
antisymmetrinenATulosLabel.setText("-");
kaantyvaATulosLabel.setText("-");
symmetrinenATulosLabel.setText("-");
neliomatriisiATulosLabel.setText("-");
transpoosiAButton.setText("Transpoosi");
transpoosiAButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
transpoosiAButtonActionPerformed(evt);
}
});
kaanteismatriisiAButton.setText("Käänteismatriisi");
kaanteismatriisiAButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
kaanteismatriisiAButtonActionPerformed(evt);
}
});
potenssiinAButton.setText("Potenssiin");
potenssiinAButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
potenssiinAButtonActionPerformed(evt);
}
});
potenssiinAText.setText("2");
potenssiinAText.setMinimumSize(new java.awt.Dimension(28, 20));
lataaAButton.setText("Lataa");
lataaAButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lataaAButtonActionPerformed(evt);
}
});
matriisiALabel.setText("Matriisi A");
javax.swing.GroupLayout matriisiAPanelLayout = new javax.swing.GroupLayout(matriisiAPanel);
matriisiAPanel.setLayout(matriisiAPanelLayout);
matriisiAPanelLayout.setHorizontalGroup(
matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(matriisiAScroll, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tiedotAButton)
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addComponent(lataaAButton)
.addGap(4, 4, 4)
.addComponent(lataaAText))
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(symmetrinenALabel)
.addComponent(neliomatriisiALabel))
.addGap(36, 36, 36)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(neliomatriisiATulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(symmetrinenATulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(antisymmetrinenALabel)
.addComponent(kaantyvaALabel)
.addComponent(ortogonaalinenALabel)
.addComponent(determinanttiALabel))
.addGap(18, 18, 18)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(antisymmetrinenATulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(kaantyvaATulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ortogonaalinenATulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(determinanttiATulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addComponent(rivitALabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rivitAText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(matriisiALabel)
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addComponent(sarakkeetALabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sarakkeetAText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addComponent(transpoosiAButton)
.addComponent(kaanteismatriisiAButton)
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addComponent(potenssiinAButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(potenssiinAText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(52, Short.MAX_VALUE))
);
matriisiAPanelLayout.setVerticalGroup(
matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiAPanelLayout.createSequentialGroup()
.addComponent(matriisiALabel)
.addGap(17, 17, 17)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rivitALabel)
.addComponent(rivitAText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sarakkeetALabel)
.addComponent(sarakkeetAText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(matriisiAScroll, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lataaAText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lataaAButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(neliomatriisiALabel)
.addComponent(neliomatriisiATulosLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(symmetrinenALabel)
.addComponent(symmetrinenATulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(antisymmetrinenALabel)
.addComponent(antisymmetrinenATulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(kaantyvaALabel)
.addComponent(kaantyvaATulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ortogonaalinenALabel)
.addComponent(ortogonaalinenATulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(determinanttiALabel)
.addComponent(determinanttiATulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tiedotAButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(transpoosiAButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(kaanteismatriisiAButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiAPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(potenssiinAButton)
.addComponent(potenssiinAText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(51, Short.MAX_VALUE))
);
summaaButton.setText("+");
summaaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
summaaButtonActionPerformed(evt);
}
});
vahennaButton.setText("-");
vahennaButton.setPreferredSize(new java.awt.Dimension(41, 23));
vahennaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
vahennaButtonActionPerformed(evt);
}
});
kerroButton.setText("*");
kerroButton.setPreferredSize(new java.awt.Dimension(41, 23));
kerroButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
kerroButtonActionPerformed(evt);
}
});
matriisiBPanel.setPreferredSize(new java.awt.Dimension(209, 420));
rivitBLabel.setText("Rivit");
rivitBText.setMinimumSize(new java.awt.Dimension(28, 20));
sarakkeetBLabel.setText("Sarakkeet");
sarakkeetBText.setMinimumSize(new java.awt.Dimension(28, 20));
matriisiBText.setColumns(17);
matriisiBText.setRows(5);
matriisiBScroll.setViewportView(matriisiBText);
lataaBText.setText("matriisi.txt");
neliomatriisiBLabel.setText("Neliömatriisi");
symmetrinenBLabel.setText("Symmetrinen");
antisymmetrinenBLabel.setText("Antisymmetrinen");
kaantyvaBLabel.setText("Kääntyvä");
ortogonaalinenBLabel.setText("Ortogonaalinen");
determinanttiBLabel.setText("Determinantti");
tiedotBButton.setText("Määritä tiedot");
tiedotBButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tiedotBButtonActionPerformed(evt);
}
});
ortogonaalinenBTulosLabel.setText("-");
determinanttiBTulosLabel.setText("-");
antisymmetrinenBTulosLabel.setText("-");
kaantyvaBTulosLabel.setText("-");
symmetrinenBTulosLabel.setText("-");
neliomatriisiBTulosLabel.setText("-");
transpoosiBButton.setText("Transpoosi");
transpoosiBButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
transpoosiBButtonActionPerformed(evt);
}
});
kaanteismatriisiBButton.setText("Käänteismatriisi");
kaanteismatriisiBButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
kaanteismatriisiBButtonActionPerformed(evt);
}
});
potenssiinBButton.setText("Potenssiin");
potenssiinBButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
potenssiinBButtonActionPerformed(evt);
}
});
potenssiinBText.setText("2");
potenssiinBText.setMinimumSize(new java.awt.Dimension(28, 20));
lataaBButton.setText("Lataa");
lataaBButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
lataaBButtonActionPerformed(evt);
}
});
matriisiBLabel.setText("Matriisi B");
javax.swing.GroupLayout matriisiBPanelLayout = new javax.swing.GroupLayout(matriisiBPanel);
matriisiBPanel.setLayout(matriisiBPanelLayout);
matriisiBPanelLayout.setHorizontalGroup(
matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(matriisiBScroll, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tiedotBButton)
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addComponent(lataaBButton)
.addGap(4, 4, 4)
.addComponent(lataaBText))
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(symmetrinenBLabel)
.addComponent(neliomatriisiBLabel))
.addGap(36, 36, 36)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(neliomatriisiBTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(symmetrinenBTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(antisymmetrinenBLabel)
.addComponent(kaantyvaBLabel)
.addComponent(ortogonaalinenBLabel)
.addComponent(determinanttiBLabel))
.addGap(18, 18, 18)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(antisymmetrinenBTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(kaantyvaBTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ortogonaalinenBTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(determinanttiBTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addComponent(rivitBLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rivitBText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(matriisiBLabel)
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addComponent(sarakkeetBLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sarakkeetBText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addComponent(transpoosiBButton)
.addComponent(kaanteismatriisiBButton)
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addComponent(potenssiinBButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(potenssiinBText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(61, Short.MAX_VALUE))
);
matriisiBPanelLayout.setVerticalGroup(
matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiBPanelLayout.createSequentialGroup()
.addComponent(matriisiBLabel)
.addGap(17, 17, 17)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rivitBLabel)
.addComponent(rivitBText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sarakkeetBLabel)
.addComponent(sarakkeetBText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(matriisiBScroll, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lataaBText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lataaBButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(neliomatriisiBLabel)
.addComponent(neliomatriisiBTulosLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(symmetrinenBLabel)
.addComponent(symmetrinenBTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(antisymmetrinenBLabel)
.addComponent(antisymmetrinenBTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(kaantyvaBLabel)
.addComponent(kaantyvaBTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ortogonaalinenBLabel)
.addComponent(ortogonaalinenBTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(determinanttiBLabel)
.addComponent(determinanttiBTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tiedotBButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(transpoosiBButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(kaanteismatriisiBButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiBPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(potenssiinBButton)
.addComponent(potenssiinBText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
matriisiCPanel.setPreferredSize(new java.awt.Dimension(209, 420));
rivitCLabel.setText("Rivit");
rivitCText.setMinimumSize(new java.awt.Dimension(28, 20));
sarakkeetCLabel.setText("Sarakkeet");
sarakkeetCText.setMinimumSize(new java.awt.Dimension(28, 20));
matriisiCText.setColumns(17);
matriisiCText.setRows(5);
matriisiCScroll.setViewportView(matriisiCText);
tallennaCText.setText("vastaus.txt");
neliomatriisiCLabel.setText("Neliömatriisi");
symmetrinenCLabel.setText("Symmetrinen");
antisymmetrinenCLabel.setText("Antisymmetrinen");
kaantyvaCLabel.setText("Kääntyvä");
ortogonaalinenCLabel.setText("Ortogonaalinen");
determinanttiCLabel.setText("Determinantti");
tiedotCButton.setText("Määritä tiedot");
tiedotCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tiedotCButtonActionPerformed(evt);
}
});
ortogonaalinenCTulosLabel.setText("-");
determinanttiCTulosLabel.setText("-");
antisymmetrinenCTulosLabel.setText("-");
kaantyvaCTulosLabel.setText("-");
symmetrinenCTulosLabel.setText("-");
neliomatriisiCTulosLabel.setText("-");
transpoosiCButton.setText("Transpoosi");
transpoosiCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
transpoosiCButtonActionPerformed(evt);
}
});
kaanteismatriisiCButton.setText("Käänteismatriisi");
kaanteismatriisiCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
kaanteismatriisiCButtonActionPerformed(evt);
}
});
potenssiinCButton.setText("Potenssiin");
potenssiinCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
potenssiinCButtonActionPerformed(evt);
}
});
potenssiinCText.setText("2");
potenssiinCText.setMinimumSize(new java.awt.Dimension(28, 20));
tallennaCButton.setText("Tallenna");
tallennaCButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tallennaCButtonActionPerformed(evt);
}
});
vastausmatriisiLabel.setText("Vastausmatriisi C");
javax.swing.GroupLayout matriisiCPanelLayout = new javax.swing.GroupLayout(matriisiCPanel);
matriisiCPanel.setLayout(matriisiCPanelLayout);
matriisiCPanelLayout.setHorizontalGroup(
matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(matriisiCScroll, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tiedotCButton)
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addComponent(tallennaCButton)
.addGap(4, 4, 4)
.addComponent(tallennaCText))
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(symmetrinenCLabel)
.addComponent(neliomatriisiCLabel))
.addGap(36, 36, 36)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(neliomatriisiCTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(symmetrinenCTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(antisymmetrinenCLabel)
.addComponent(kaantyvaCLabel)
.addComponent(ortogonaalinenCLabel)
.addComponent(determinanttiCLabel))
.addGap(18, 18, 18)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(antisymmetrinenCTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(kaantyvaCTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ortogonaalinenCTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(determinanttiCTulosLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addComponent(rivitCLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addComponent(rivitCText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sarakkeetCLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sarakkeetCText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, matriisiCPanelLayout.createSequentialGroup()
.addComponent(vastausmatriisiLabel)
.addGap(23, 23, 23)))))
.addComponent(transpoosiCButton)
.addComponent(kaanteismatriisiCButton)
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addComponent(potenssiinCButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(potenssiinCText, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(72, Short.MAX_VALUE))
);
matriisiCPanelLayout.setVerticalGroup(
matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(matriisiCPanelLayout.createSequentialGroup()
.addComponent(vastausmatriisiLabel)
.addGap(17, 17, 17)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rivitCLabel)
.addComponent(rivitCText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sarakkeetCLabel)
.addComponent(sarakkeetCText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(matriisiCScroll, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tallennaCText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tallennaCButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(neliomatriisiCLabel)
.addComponent(neliomatriisiCTulosLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(symmetrinenCLabel)
.addComponent(symmetrinenCTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(antisymmetrinenCLabel)
.addComponent(antisymmetrinenCTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(kaantyvaCLabel)
.addComponent(kaantyvaCTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ortogonaalinenCLabel)
.addComponent(ortogonaalinenCTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(determinanttiCLabel)
.addComponent(determinanttiCTulosLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tiedotCButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(transpoosiCButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(kaanteismatriisiCButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(matriisiCPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(potenssiinCButton)
.addComponent(potenssiinCText, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout alustaPanelLayout = new javax.swing.GroupLayout(alustaPanel);
alustaPanel.setLayout(alustaPanelLayout);
alustaPanelLayout.setHorizontalGroup(
alustaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(alustaPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(matriisiAPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(alustaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(summaaButton)
.addComponent(vahennaButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(kerroButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(matriisiBPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(matriisiCPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addContainerGap())
);
alustaPanelLayout.setVerticalGroup(
alustaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(alustaPanelLayout.createSequentialGroup()
.addGroup(alustaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(alustaPanelLayout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(summaaButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(vahennaButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(kerroButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(matriisiAPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE)
.addComponent(matriisiBPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE)
.addComponent(matriisiCPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alustaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(alustaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Metodi, joka summaa käyttöliitymän matriisit A ja B keskenään ja näyttää
* summamatriisin käyttöliittymän vastausmatriisi C:ssä. Aluksi käyttö-
* liittymän tietojen perusteella lataa ja luo matriisit A ja B, jonka
* jälkeen päivittää niiden esitysmuodon käyttöliittymään jos eivät ole
* null. Tämän jälkeen tarkastaa toteuttavatko matriisit yhteenlaskusäännön,
* jonka jälkeen summaa matriisit ja näyttää summamatriisin vastausmatriisi
* C:nä, jos kaikki on ok.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void summaaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_summaaButtonActionPerformed
double[][] matriisiA = lataaJaLuoMatriisi(rivitAText.getText(),
sarakkeetAText.getText(),
matriisiAText.getText(), 'A');
double[][] matriisiB = lataaJaLuoMatriisi(rivitBText.getText(),
sarakkeetBText.getText(),
matriisiBText.getText(), 'B');
if(matriisiA == null || matriisiB == null){
return;
}
naytaA(matriisiA);
naytaB(matriisiB);
if(!tarkastaSumma(matriisiA, matriisiB)){
return;
}
double[][] matriisiC = laskin.summaa(matriisiA, matriisiB);
naytaC(matriisiC);
}//GEN-LAST:event_summaaButtonActionPerformed
/**
* Metodi, joka määrittää matriisin tiedot käyttöliittymän oikeisiin
* kohtiin. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee ja päivittää tiedot, jos matriisi ei ole
* null. Jos tietoja ei voida määrittää (esim. ei kääntyvä), asettaa
* käyttöliittymään niiden tietojen kohdalle viivan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void tiedotAButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tiedotAButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitAText.getText(),
sarakkeetAText.getText(),
matriisiAText.getText(), 'A');
if(matriisi == null){
return;
}
neliomatriisiATulosLabel.setText("" + laskin.onkoNeliomatriisi(matriisi));
symmetrinenATulosLabel.setText("" + laskin.onkoSymmetrinen(matriisi));
antisymmetrinenATulosLabel.setText("" + laskin.onkoAntisymmetrinen(matriisi));
try {
determinanttiATulosLabel.setText("" + laskin.laskeDeterminantti(matriisi));
kaantyvaATulosLabel.setText("" + laskin.onkoKaantyva(matriisi));
ortogonaalinenATulosLabel.setText("" + laskin.onkoOrtogonaalinen(matriisi));
} catch (Exception e) {
determinanttiATulosLabel.setText("-");
kaantyvaATulosLabel.setText("-");
ortogonaalinenATulosLabel.setText("-");
}
naytaA(matriisi);
}//GEN-LAST:event_tiedotAButtonActionPerformed
/**
* Metodi, joka määrittää matriisin tiedot käyttöliittymän oikeisiin
* kohtiin. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee ja päivittää tiedot, jos matriisi ei ole
* null. Jos tietoja ei voida määrittää (esim. ei kääntyvä), asettaa
* käyttöliittymään niiden tietojen kohdalle viivan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void tiedotBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tiedotBButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitBText.getText(),
sarakkeetBText.getText(),
matriisiBText.getText(), 'B');
if(matriisi == null){
return;
}
neliomatriisiBTulosLabel.setText("" + laskin.onkoNeliomatriisi(matriisi));
symmetrinenBTulosLabel.setText("" + laskin.onkoSymmetrinen(matriisi));
antisymmetrinenBTulosLabel.setText("" + laskin.onkoAntisymmetrinen(matriisi));
try {
determinanttiBTulosLabel.setText("" + laskin.laskeDeterminantti(matriisi));
kaantyvaBTulosLabel.setText("" + laskin.onkoKaantyva(matriisi));
ortogonaalinenBTulosLabel.setText("" + laskin.onkoOrtogonaalinen(matriisi));
} catch (Exception e) {
determinanttiBTulosLabel.setText("-");
kaantyvaBTulosLabel.setText("-");
ortogonaalinenBTulosLabel.setText("-");
}
naytaB(matriisi);
}//GEN-LAST:event_tiedotBButtonActionPerformed
/**
* Metodi, joka määrittää matriisin tiedot käyttöliittymän oikeisiin
* kohtiin. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee ja päivittää tiedot, jos matriisi ei ole
* null. Jos tietoja ei voida määrittää (esim. ei kääntyvä), asettaa
* käyttöliittymään niiden tietojen kohdalle viivan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void tiedotCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tiedotCButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitCText.getText(),
sarakkeetCText.getText(),
matriisiCText.getText(), 'C');
if(matriisi == null){
return;
}
neliomatriisiCTulosLabel.setText("" + laskin.onkoNeliomatriisi(matriisi));
symmetrinenCTulosLabel.setText("" + laskin.onkoSymmetrinen(matriisi));
antisymmetrinenCTulosLabel.setText("" + laskin.onkoAntisymmetrinen(matriisi));
try {
determinanttiCTulosLabel.setText("" + laskin.laskeDeterminantti(matriisi));
kaantyvaCTulosLabel.setText("" + laskin.onkoKaantyva(matriisi));
ortogonaalinenCTulosLabel.setText("" + laskin.onkoOrtogonaalinen(matriisi));
} catch (Exception e) {
determinanttiCTulosLabel.setText("-");
kaantyvaCTulosLabel.setText("-");
ortogonaalinenCTulosLabel.setText("-");
}
naytaC(matriisi);
}//GEN-LAST:event_tiedotCButtonActionPerformed
/**
* Metodi, joka vähentää käyttöliitymän matriisit A ja B keskenään ja
* näyttää erotusmatriisin käyttöliittymän vastausmatriisi C:ssä. Aluksi
* käyttöliittymän tietojen perusteella lataa ja luo matriisit A ja B, jonka
* jälkeen päivittää niiden esitysmuodon käyttöliittymään jos eivät ole
* null. Tämän jälkeen tarkastaa toteuttavatko matriisit vähennyslasku-
* säännön, jonka jälkeen vähentää matriisit keskenään ja näyttää
* erotusmatriisin vastausmatriisi C:nä, jos kaikki on ok.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void vahennaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vahennaButtonActionPerformed
double[][] matriisiA = lataaJaLuoMatriisi(rivitAText.getText(),
sarakkeetAText.getText(),
matriisiAText.getText(), 'A');
double[][] matriisiB = lataaJaLuoMatriisi(rivitBText.getText(),
sarakkeetBText.getText(),
matriisiBText.getText(), 'B');
if(matriisiA == null || matriisiB == null){
return;
}
naytaA(matriisiA);
naytaB(matriisiB);
if(!tarkastaErotus(matriisiA, matriisiB)){
return;
}
double[][] matriisiC = laskin.vahenna(matriisiA, matriisiB);
naytaC(matriisiC);
}//GEN-LAST:event_vahennaButtonActionPerformed
/**
* Metodi, joka kertoo käyttöliitymän matriisit A ja B keskenään ja
* näyttää tulomatriisin käyttöliittymän vastausmatriisi C:ssä. Aluksi
* käyttöliittymän tietojen perusteella lataa ja luo matriisit A ja B, jonka
* jälkeen päivittää niiden esitysmuodon käyttöliittymään jos eivät ole
* null. Tämän jälkeen tarkastaa toteuttavatko matriisit kertolaskusäännön,
* jonka jälkeen yrittää kertoa matriisit keskenään käyttäen Strassenia. Jos
* matriisit eivät ole samankokoisia neliömatriiseja, kertoo matriisit
* keskenään käyttäen tavallista matriisin kertolaskua ja näyttää
* tulomatriisin vastausmatriisi C:nä, jos kaikki on ok.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void kerroButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kerroButtonActionPerformed
double[][] matriisiA = lataaJaLuoMatriisi(rivitAText.getText(),
sarakkeetAText.getText(),
matriisiAText.getText(), 'A');
double[][] matriisiB = lataaJaLuoMatriisi(rivitBText.getText(),
sarakkeetBText.getText(),
matriisiBText.getText(), 'B');
if(matriisiA == null || matriisiB == null){
return;
}
naytaA(matriisiA);
naytaB(matriisiB);
if(!tarkastaKertolasku(matriisiA, matriisiB)){
return;
}
double[][] matriisiC;
try {
matriisiC = laskin.kerroStrassenilla(matriisiA, matriisiB);
} catch (Exception e) {
matriisiC = laskin.kerro(matriisiA, matriisiB);
}
naytaC(matriisiC);
}//GEN-LAST:event_kerroButtonActionPerformed
/**
* Metodi, joka määrittää matriisin transpoosin käyttöliittymässä sen omaan
* kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen määrittää sen transpoosin, jos matriisi ei ole
* null. Lopuksi näyttää transpoosin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void transpoosiAButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_transpoosiAButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitAText.getText(),
sarakkeetAText.getText(),
matriisiAText.getText(), 'A');
if(matriisi == null){
return;
}
matriisi = laskin.transpoosaa(matriisi);
naytaA(matriisi);
}//GEN-LAST:event_transpoosiAButtonActionPerformed
/**
* Metodi, joka määrittää matriisin transpoosin käyttöliittymässä sen omaan
* kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen määrittää sen transpoosin, jos matriisi ei ole
* null. Lopuksi näyttää transpoosin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void transpoosiBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_transpoosiBButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitBText.getText(),
sarakkeetBText.getText(),
matriisiBText.getText(), 'B');
if(matriisi == null){
return;
}
matriisi = laskin.transpoosaa(matriisi);
naytaB(matriisi);
}//GEN-LAST:event_transpoosiBButtonActionPerformed
/**
* Metodi, joka määrittää matriisin transpoosin käyttöliittymässä sen omaan
* kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen määrittää sen transpoosin, jos matriisi ei ole
* null. Lopuksi näyttää transpoosin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void transpoosiCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_transpoosiCButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitCText.getText(),
sarakkeetCText.getText(),
matriisiCText.getText(), 'C');
if(matriisi == null){
return;
}
matriisi = laskin.transpoosaa(matriisi);
naytaC(matriisi);
}//GEN-LAST:event_transpoosiCButtonActionPerformed
/**
* Metodi, joka määrittää matriisin käänteismatriisin käyttöliittymässä sen
* omaan kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee sen käänteismatriisin, jos matriisi on
* neliömatriisi. Jos matriisi ei ole kääntyvä, avaa virhe-popupin. Lopuksi
* näyttää käänteismatriisin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void kaanteismatriisiAButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kaanteismatriisiAButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitAText.getText(),
sarakkeetAText.getText(),
matriisiAText.getText(), 'A');
if(!tarkastaNelio(matriisi)){
return;
}
try {
matriisi = laskin.invertoi(matriisi);
} catch (Exception e) {
virheInvertoi();
}
naytaA(matriisi);
}//GEN-LAST:event_kaanteismatriisiAButtonActionPerformed
/**
* Metodi, joka määrittää matriisin käänteismatriisin käyttöliittymässä sen
* omaan kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee sen käänteismatriisin, jos matriisi on
* neliömatriisi. Jos matriisi ei ole kääntyvä, avaa virhe-popupin. Lopuksi
* näyttää käänteismatriisin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void kaanteismatriisiBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kaanteismatriisiBButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitBText.getText(),
sarakkeetBText.getText(),
matriisiBText.getText(), 'B');
if(!tarkastaNelio(matriisi)){
return;
}
try {
matriisi = laskin.invertoi(matriisi);
} catch (Exception e) {
virheInvertoi();
}
naytaB(matriisi);
}//GEN-LAST:event_kaanteismatriisiBButtonActionPerformed
/**
* Metodi, joka määrittää matriisin käänteismatriisin käyttöliittymässä sen
* omaan kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee sen käänteismatriisin, jos matriisi on
* neliömatriisi. Jos matriisi ei ole kääntyvä, avaa virhe-popupin. Lopuksi
* näyttää käänteismatriisin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void kaanteismatriisiCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kaanteismatriisiCButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitCText.getText(),
sarakkeetCText.getText(),
matriisiCText.getText(), 'C');
if(!tarkastaNelio(matriisi)){
return;
}
try {
matriisi = laskin.invertoi(matriisi);
} catch (Exception e) {
virheInvertoi();
}
naytaC(matriisi);
}//GEN-LAST:event_kaanteismatriisiCButtonActionPerformed
/**
* Metodi, joka laskee matriisin potenssin käyttöliittymässä sen omaan
* kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee sen potenssin, jos matriisi on
* neliömatriisi. Jos matriisin potenssi -tekstin muunnoksessa
* kokonaisluvuksi tapahtuu virhe, avaa virhe-popupin. Lopuksi näyttää
* potenssimatriisin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void potenssiinAButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_potenssiinAButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitAText.getText(),
sarakkeetAText.getText(),
matriisiAText.getText(), 'A');
if(!tarkastaNelio(matriisi)){
return;
}
try {
matriisi = laskin.neliomatriisiPotenssiin(matriisi,
Integer.parseInt(potenssiinAText.getText()));
} catch (Exception e) {
virhePotenssi();
return;
}
naytaA(matriisi);
}//GEN-LAST:event_potenssiinAButtonActionPerformed
/**
* Metodi, joka laskee matriisin potenssin käyttöliittymässä sen omaan
* kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee sen potenssin, jos matriisi on
* neliömatriisi. Jos matriisin potenssi -tekstin muunnoksessa
* kokonaisluvuksi tapahtuu virhe, avaa virhe-popupin. Lopuksi näyttää
* potenssimatriisin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void potenssiinBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_potenssiinBButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitBText.getText(),
sarakkeetBText.getText(),
matriisiBText.getText(), 'B');
if(!tarkastaNelio(matriisi)){
return;
}
try {
matriisi = laskin.neliomatriisiPotenssiin(matriisi,
Integer.parseInt(potenssiinBText.getText()));
} catch (Exception e) {
virhePotenssi();
return;
}
naytaB(matriisi);
}//GEN-LAST:event_potenssiinBButtonActionPerformed
/**
* Metodi, joka laskee matriisin potenssin käyttöliittymässä sen omaan
* kohtaansa. Aluksi käyttöliittymän tietojen perusteella lataa ja luo
* matriisin, jonka jälkeen laskee sen potenssin, jos matriisi on
* neliömatriisi. Jos matriisin potenssi -tekstin muunnoksessa
* kokonaisluvuksi tapahtuu virhe, avaa virhe-popupin. Lopuksi näyttää
* potenssimatriisin käyttöliittymän omassa kohdassaan.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void potenssiinCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_potenssiinCButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitCText.getText(),
sarakkeetCText.getText(),
matriisiCText.getText(), 'C');
if(!tarkastaNelio(matriisi)){
return;
}
try {
matriisi = laskin.neliomatriisiPotenssiin(matriisi,
Integer.parseInt(potenssiinCText.getText()));
} catch (Exception e) {
virhePotenssi();
return;
}
naytaC(matriisi);
}//GEN-LAST:event_potenssiinCButtonActionPerformed
/**
* Metodi, joka lataa lataus -tekstin perusteella tiedostosta matriisin ja
* päivittää sen käyttöliittymässä omaan kohtaansa.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void lataaAButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lataaAButtonActionPerformed
lataa(lataaAText.getText(), 'A');
}//GEN-LAST:event_lataaAButtonActionPerformed
/**
* Metodi, joka lataa lataus -tekstin perusteella tiedostosta matriisin ja
* päivittää sen käyttöliittymässä omaan kohtaansa.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void lataaBButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lataaBButtonActionPerformed
lataa(lataaBText.getText(), 'B');
}//GEN-LAST:event_lataaBButtonActionPerformed
/**
* Metodi, joka tallentaa käyttöliittymän vastausmatriisi C:ssä olevan
* matriisin tallenna -tekstin perusteella tiedostoon. Aluksi
* käyttöliittymän tietojen perusteella lataa ja luo matriisin, jonka
* jälkeen yrittää tallentaa sen tiedostoon, jos matriisi ei ole null. Jos
* matriisin tallennuksessa tapahtuu virhe, avaa virhe-popupin.
*
* @param evt Painikkeen tapahtuma, jota ei hyödynnetä
*/
private void tallennaCButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tallennaCButtonActionPerformed
double[][] matriisi = lataaJaLuoMatriisi(rivitCText.getText(),
sarakkeetCText.getText(),
matriisiCText.getText(), 'C');
if(matriisi == null){
return;
}
try {
tallentaja.tallenna(matriisi, tallennaCText.getText());
} catch (Exception e) {
virheTallennus();
}
}//GEN-LAST:event_tallennaCButtonActionPerformed
/**
* Metodi, joka tarkastaa onko parametrina annettu matriisi neliömatriisi ja
* palauttaa true, jos on. Jos ei ole neliömatriisi, avaa virhe-popupin ja
* palauttaa false.
*
* @param matriisi Matriisi, josta halutaa tietää onko neliömatriisi, muotoa
* m x n
* @return Palauttaa true, jos on neliömatriisi
*/
private boolean tarkastaNelio(double[][] matriisi) {
if(matriisi == null){
return false;
} else if(!laskin.onkoNeliomatriisi(matriisi)){
virheEiNelio();
return false;
}
return true;
}
/**
* Metodi, joka lataa parametrina annetusta tiedostonimestä matriisin ja
* näyttää sen oikeassa kohdassa käyttöliittymässä. Jos tiedostonlukeminen
* epäonnistuu, avaa virhe-popupin.
*
* @param tiedostonimi Tiedostonimi, josta matriisi ladataan
* @param tunniste Tunniste-kirjain käyttöliittymän matriisille, jossa
* ladattu matriisi näytetään
*/
private void lataa(String tiedostonimi, char tunniste) {
try {
double[][] matriisi = matriisienlukija.lue(tiedostonimi);
if(tunniste == 'A') {
naytaA(matriisi);
} else {
naytaB(matriisi);
}
} catch (Exception e) {
virheLataus();
}
}
/**
* Metodi, joka lataa ja luo matriisin parametrina annettujen tietojen
* perusteella. Lataa aluksi rivit ja sarakkeet ja jos tämä epäonnistuu,
* niin palauttaa null. Muutoin palauttaa luoMatriisi-metodin tuottaman
* matriisin.
*
* @param rivit Merkkijono, joka sisältää matriisin rivimäärän
* @param sarakkeet Merkkijono, joka sisältää matriisin sarakemäärän
* @param matriisiS Merkkijono, joka sisältää matriisin alkiot
* @param tunniste Tunniste-kirjain käyttöliittymän matriisille, jossa
* ladattu ja luotu matriisi näytetään
* @return Palauttaa luoMatriisi-metodin tuottaman matriisin, muotoa m x n
*/
private double[][] lataaJaLuoMatriisi(String rivit, String sarakkeet,
String matriisiS, char tunniste) {
int rivitM = lataaRivit(rivit, tunniste);
if(rivitM == -1) {
return null;
}
int sarakkeetM = lataaSarakkeet(sarakkeet, tunniste);
if (sarakkeetM == -1) {
return null;
}
return luoMatriisi(rivitM, sarakkeetM, matriisiS, tunniste);
}
/**
* Metodi, joka lataa rivit parametrina annetusta merkkijonosta. Jos rivi-
* määrän lukeminen epäonnistuu, avaa virhe-popupin ja palauttaa -1.
*
* @param rivit Merkkijono, joka sisältää ladattavan rivimäärän
* @param tunniste Tunniste-kirjain käyttöliityymän matriisille, jolle
* mahdollinen virhe-popup osoitetaan
* @return Palauttaa ladatun rivimäärän
*/
private int lataaRivit(String rivit, char tunniste) {
try {
return Integer.parseInt(rivit);
} catch (Exception e) {
virheKoko(tunniste);
return -1;
}
}
/**
* Metodi, joka lataa sarakkeet parametrina annetusta merkkijonosta. Jos
* sarakemäärän lukeminen epäonnistuu, avaa virhe-popupin ja palauttaa -1.
*
* @param sarakkeet Merkkijono, joka sisältää ladattavan sarakemäärän
* @param tunniste Tunniste-kirjain käyttöliityymän matriisille, jolle
* mahdollinen virhe-popup osoitetaan
* @return Palauttaa ladatun sarakemäärän
*/
private int lataaSarakkeet(String sarakkeet, char tunniste) {
try {
return Integer.parseInt(sarakkeet);
} catch (Exception e) {
virheKoko(tunniste);
return -1;
}
}
/**
* Metodi, joka luo matriisin parametrina annettujen tietojen perusteella.
* Aluksi tarkastaa matriisin koon, eli että rivit ja sarakkeet ovat
* positiivisia kokonaislukuja. Tämän jälkeen tarkastaa, että matriisin
* alkiot sisältävässä merkkijonossa on vähintään tarvittava määrä merkkejä.
* Jos ei ole riittävästi merkkejä, niin avaa virhe-popupin. Tarkastusten
* epäonnistuessa palauttaa null. Lopuksi palauttaa lueMatriisi-metodin
* tuottaman matriisin.
*
* @param rivit Kokonaisluku, joka kertoo matriisin rivimäärän
* @param sarakkeet Kokonaisluku, joka kertoo matriisin sarakemäärän
* @param matriisiS Merkkijono, joka sisältää matriisin alkiot
* @param tunniste Tunniste-kirjain käyttöliittymän matriisille, jossa
* ladattu ja luotu matriisi näytetään
* @return Palauttaa lueMatriisi-metodin tuottaman matriisin, muotoa m x n
*/
private double[][] luoMatriisi(int rivit, int sarakkeet,
String matriisiS, char tunniste) {
if(!tarkastaKoko(rivit, sarakkeet, tunniste)) {
return null;
} else if(matriisiS.length() < 2 * (rivit - 1) * sarakkeet) {
virheMatriisi(tunniste);
return null;
}
return lueMatriisi(rivit, sarakkeet, matriisiS, tunniste);
}
/**
* Metodi, joka lukee parametrina annetuista tiedoista matriisin ja
* palauttaa sen, jos virheitä ei tapahdu. Jos tapahtuu virhe, avaa virhe-
* popupin ja palauttaa null.
*
* @param rivitM Kokonaisluku, joka kertoo matriisin rivimäärän
* @param sarakkeetM Kokonaisluku, joka kertoo matriisin sarakemäärän
* @param matriisiS Merkkijono, joka sisältää matriisin alkiot
* @param tunniste Tunniste-kirjain käyttöliittymän matriisille, jossa
* ladattu ja luotu matriisi näytetään
* @return Palauttaa luetun matriisin, muotoa m x n
*/
private double[][] lueMatriisi(int rivitM, int sarakkeetM, String matriisiS,
char tunniste) {
lukija = new Scanner(matriisiS);
double[][] matriisi = new double[rivitM][sarakkeetM];
for (int rivit = 0; rivit < rivitM; rivit++) {
for (int sarakkeet = 0; sarakkeet < sarakkeetM; sarakkeet++) {
try {
matriisi[rivit][sarakkeet] = Double.parseDouble(lukija.next());
} catch (Exception e) {
virheMatriisi(tunniste);
return null;
}
}
}
lukija.close();
return matriisi;
}
/**
* Metodi, joka näyttää matriisi A:n käyttöliittymän oikeassa kohdassa.
*
* @param A Matriisi, joka halutaan näyttää käyttöliittymässä, muotoa m x n
*/
private void naytaA(double[][] A) {
rivitAText.setText("" + A.length);
sarakkeetAText.setText("" + A[0].length);
matriisiAText.setText(matriisiStringiksi(A));
}
/**
* Metodi, joka näyttää matriisi B:n käyttöliittymän oikeassa kohdassa.
*
* @param B Matriisi, joka halutaan näyttää käyttöliittymässä, muotoa m x n
*/
private void naytaB(double[][] B) {
rivitBText.setText("" + B.length);
sarakkeetBText.setText("" + B[0].length);
matriisiBText.setText(matriisiStringiksi(B));
}
/**
* Metodi, joka näyttää matriisi C:n käyttöliittymän oikeassa kohdassa.
*
* @param C Matriisi, joka halutaa näyttää käyttöliittymässä, muotoa m x n
*/
private void naytaC(double[][] C) {
rivitCText.setText("" + C.length);
sarakkeetCText.setText("" + C[0].length);
matriisiCText.setText(matriisiStringiksi(C));
}
/**
* Metodi, joka muuttaa parametrina annetun matriisin merkkijonoksi.
*
* @param matriisi Matriisi, joka halutaan muuttaa merkkijonoksi,
* muotoa m x n
* @return Palauttaa matriisista luodun merkkijonon
*/
private String matriisiStringiksi(double[][] matriisi) {
String matriisiS = "";
for (int rivit = 0; rivit < matriisi.length; rivit++) {
for (int sarakkeet = 0; sarakkeet < matriisi[0].length; sarakkeet++) {
matriisiS += matriisi[rivit][sarakkeet]+" ";
}
matriisiS += "\n";
}
return matriisiS;
}
/**
* Metodi, joka tarkastaa toteuttavatko parametrina annetut matriisit
* matriisien yhteenlaskusäännön. Avaa virhe-popupin, jos eivät toteuta ja
* palauttaa tällöin false.
*
* @param A Ensimmäinen yhteenlaskettava matriisi, muotoa m x n
* @param B Toinen yhteenlaskettava matriisi, muotoa p x q
* @return Palauttaa true, jos matriisit toteuttavat matriisien
* yhteenlaskusäännön
*/
private boolean tarkastaSumma(double[][] A, double[][] B) {
if (A.length != B.length || A[0].length != B[0].length) {
virheSumma();
return false;
}
return true;
}
/**
* Metodi, joka tarkastaa toteuttavatko parametrina annetut matriisit
* matriisien vähennyslaskusäännön. Avaa virhe-popupin, jos eivät toteuta
* ja palauttaa tällöin false.
*
* @param A Matriisi, josta vähennetään toinen matriisi, muotoa m x n
* @param B Matriisi, joka vähennetään ensimmäisestä matriisista,
* muotoa p x q
* @return Palauttaa true, jos matriisit toteuttavat matriisien
* yhteenlaskusäännön
*/
private boolean tarkastaErotus(double[][] A, double[][] B) {
if (A.length != B.length || A[0].length != B[0].length) {
virheVahennys();
return false;
}
return true;
}
/**
* Metodi, joka tarkastaa toteuttavatko parametrina annetut matriisit
* matriisien kertolaskusäännön. Avaa virhe-popupin, jos eivät toteuta ja
* palauttaa tällöin false.
*
* @param A Vasemmalta luettuna ensimmäinen matriisi, joka kerrotaan,
* muotoa m x n
* @param B Vasemmalta luettuna toinen matriisi, joka kerrotaan,
* muotoa p x q
* @return Palauttaa true, jos matriisit toteuttavat matriisien
* kertolaskusäännön
*/
private boolean tarkastaKertolasku(double[][] A, double[][] B) {
if (A[0].length != B.length) {
virheKertolasku();
return false;
}
return true;
}
/**
* Metodi, joka tarkastaa ovatko parametrina annetut rivit ja sarakkeet
* suurempia kuin nolla. Jos eivät ole, niin avaa virhe-popupin ja palauttaa
* false.
*
* @param rivit Kokonaisluku, joka kertoo rivimäärän
* @param sarakkeet Kokonaisluku, joka kertoo sarakemäärän
* @param tunniste Tunniste-kirjain käyttöliittymän matriisille, jossa
* tarkastettu matriisi näytetään
* @return Palauttaa true, jos rivit ja sarakkeet ovat suurempia kuin nolla
*/
private boolean tarkastaKoko(int rivit, int sarakkeet, char tunniste) {
if(rivit <= 0 || sarakkeet <= 0) {
virheKoko(tunniste);
return false;
}
return true;
}
/**
* Metodi, joka toteuttaa virhe-popupin matriisin koon ollessa väärä.
*
* @param tunniste Tunniste-kirjain käyttöliittymän matriisille, jolle
* virhe-popup osoitetaan
*/
private void virheKoko(char tunniste) {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nTarkasta, että matriisin "+tunniste+" kokomäärityksissä"
+ "\nkäytetään vain positiivisia kokonaislukuja, eikä siellä"
+ "\nole ylimääräisiä välilyöntejä", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin matriisien yhteenlaskun
* epäonnistuessa.
*
*/
private void virheSumma() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nMatriisien yhteenlaskussa yhteenlaskettavien matriisien"
+ "\nkoot pitää olla samat", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin matriisien vähennyslaskun
* epäonnistuessa.
*
*/
private void virheVahennys() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nMatriisien vähennyslaskussa toisistaan vähennettävien"
+ "\nmatriisien koot pitää olla samat", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin matriisien kertolaskun
* epäonnistuessa.
*
*/
private void virheKertolasku() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nMatriisien kertolaskussa vasemmanpuoleisen matriisin"
+ "\nsarakkeiden määrä pitää olla sama kuin oikeanpuoleisen"
+ "\nmatriisin rivien määrä", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin matriisin ollessa jotain muuta kuin
* neliömatriisi.
*
*/
private void virheEiNelio() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nMatriisin pitää olla neliömatriisi", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin matriisin ollessa singulaarinen.
*
*/
private void virheInvertoi() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nMatriisi ei ole kääntyvä, joten sillä ei ole"
+ "\nkäänteismatriisia", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin potenssin ollessa pienempi kuin
* nolla.
*
*/
private void virhePotenssi() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nTarkasta, että olet antanut potenssiksi nollaa suuremman"
+ "\ntai yhtäsuuren arvon", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin tiedostonlatauksen epäonnistuttua.
*
*/
private void virheLataus() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nTarkasta, että ladattava tiedosto sijaitsee ohjelman"
+ "\nkanssa samassa hakemistopolussa", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin tallennuksen epäonnistuttua.
*
*/
private void virheTallennus() {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nTarkasta, että tallennettava tiedostonimi sisältää vain"
+ "\ntavallisia tiedostonimessä hyväksyttäviä merkkejä. "
+ "\nTiedostonimessä täytyy olla edes yksi merkki.", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* Metodi, joka toteuttaa virhe-popupin matriisin syötteen ollessa
* epäkelvollinen.
*
* @param tunniste Tunniste-kirjain käyttöliittymän matriisille, jolle
* virhe-popup osoitetaan
*/
private void virheMatriisi(char tunniste) {
JOptionPane.showMessageDialog(this, "Virhe:\n"
+ "\nMatriisin "+tunniste+" syötteessä tapahtui virhe. Tarkasta,"
+ "\nettä se sisältää vain liukulukuja. Tarkasta myös, että"
+ "\nalkioita on oikea määrä.", "Virhe",
JOptionPane.ERROR_MESSAGE);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Kayttoliittyma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Kayttoliittyma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Kayttoliittyma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Kayttoliittyma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Kayttoliittyma().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel alustaPanel;
private javax.swing.JLabel antisymmetrinenALabel;
private javax.swing.JLabel antisymmetrinenATulosLabel;
private javax.swing.JLabel antisymmetrinenBLabel;
private javax.swing.JLabel antisymmetrinenBTulosLabel;
private javax.swing.JLabel antisymmetrinenCLabel;
private javax.swing.JLabel antisymmetrinenCTulosLabel;
private javax.swing.JLabel determinanttiALabel;
private javax.swing.JLabel determinanttiATulosLabel;
private javax.swing.JLabel determinanttiBLabel;
private javax.swing.JLabel determinanttiBTulosLabel;
private javax.swing.JLabel determinanttiCLabel;
private javax.swing.JLabel determinanttiCTulosLabel;
private javax.swing.JButton kaanteismatriisiAButton;
private javax.swing.JButton kaanteismatriisiBButton;
private javax.swing.JButton kaanteismatriisiCButton;
private javax.swing.JLabel kaantyvaALabel;
private javax.swing.JLabel kaantyvaATulosLabel;
private javax.swing.JLabel kaantyvaBLabel;
private javax.swing.JLabel kaantyvaBTulosLabel;
private javax.swing.JLabel kaantyvaCLabel;
private javax.swing.JLabel kaantyvaCTulosLabel;
private javax.swing.JButton kerroButton;
private javax.swing.JButton lataaAButton;
private javax.swing.JTextField lataaAText;
private javax.swing.JButton lataaBButton;
private javax.swing.JTextField lataaBText;
private javax.swing.JLabel matriisiALabel;
private javax.swing.JPanel matriisiAPanel;
private javax.swing.JScrollPane matriisiAScroll;
private javax.swing.JTextArea matriisiAText;
private javax.swing.JLabel matriisiBLabel;
private javax.swing.JPanel matriisiBPanel;
private javax.swing.JScrollPane matriisiBScroll;
private javax.swing.JTextArea matriisiBText;
private javax.swing.JPanel matriisiCPanel;
private javax.swing.JScrollPane matriisiCScroll;
private javax.swing.JTextArea matriisiCText;
private javax.swing.JLabel neliomatriisiALabel;
private javax.swing.JLabel neliomatriisiATulosLabel;
private javax.swing.JLabel neliomatriisiBLabel;
private javax.swing.JLabel neliomatriisiBTulosLabel;
private javax.swing.JLabel neliomatriisiCLabel;
private javax.swing.JLabel neliomatriisiCTulosLabel;
private javax.swing.JLabel ortogonaalinenALabel;
private javax.swing.JLabel ortogonaalinenATulosLabel;
private javax.swing.JLabel ortogonaalinenBLabel;
private javax.swing.JLabel ortogonaalinenBTulosLabel;
private javax.swing.JLabel ortogonaalinenCLabel;
private javax.swing.JLabel ortogonaalinenCTulosLabel;
private javax.swing.JButton potenssiinAButton;
private javax.swing.JTextField potenssiinAText;
private javax.swing.JButton potenssiinBButton;
private javax.swing.JTextField potenssiinBText;
private javax.swing.JButton potenssiinCButton;
private javax.swing.JTextField potenssiinCText;
private javax.swing.JLabel rivitALabel;
private javax.swing.JTextField rivitAText;
private javax.swing.JLabel rivitBLabel;
private javax.swing.JTextField rivitBText;
private javax.swing.JLabel rivitCLabel;
private javax.swing.JTextField rivitCText;
private javax.swing.JLabel sarakkeetALabel;
private javax.swing.JTextField sarakkeetAText;
private javax.swing.JLabel sarakkeetBLabel;
private javax.swing.JTextField sarakkeetBText;
private javax.swing.JLabel sarakkeetCLabel;
private javax.swing.JTextField sarakkeetCText;
private javax.swing.JButton summaaButton;
private javax.swing.JLabel symmetrinenALabel;
private javax.swing.JLabel symmetrinenATulosLabel;
private javax.swing.JLabel symmetrinenBLabel;
private javax.swing.JLabel symmetrinenBTulosLabel;
private javax.swing.JLabel symmetrinenCLabel;
private javax.swing.JLabel symmetrinenCTulosLabel;
private javax.swing.JButton tallennaCButton;
private javax.swing.JTextField tallennaCText;
private javax.swing.JButton tiedotAButton;
private javax.swing.JButton tiedotBButton;
private javax.swing.JButton tiedotCButton;
private javax.swing.JButton transpoosiAButton;
private javax.swing.JButton transpoosiBButton;
private javax.swing.JButton transpoosiCButton;
private javax.swing.JButton vahennaButton;
private javax.swing.JLabel vastausmatriisiLabel;
// End of variables declaration//GEN-END:variables
}
| true
|
173d9a193b02bcfce308bcb29f65fb2ff1b7e9ba
|
Java
|
lisboy/blog
|
/src/main/java/lisboyblog/service/admin/impl/PendingServiceImpl.java
|
UTF-8
| 788
| 1.960938
| 2
|
[] |
no_license
|
package lisboyblog.service.admin.impl;
import lisboyblog.mapper.PendingMapper;
import lisboyblog.pojo.Pending;
import lisboyblog.service.admin.PendingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author FAN BOY
* @version 1.0
* @date 2020/9/13 12:34
*/
@Service
public class PendingServiceImpl implements PendingService {
@Autowired
PendingMapper pendingMapper;
@Override
public List<Pending> findAll() {
return pendingMapper.selectList(null);
}
@Override
public void addPending(Pending pending) {
pendingMapper.insert(pending);
}
@Override
public void deletdPend(Long id) {
pendingMapper.deleteById(id);
}
}
| true
|
08e59eca87a264546a34442f327271d5e5fc7a88
|
Java
|
hongweichang/mise-temp
|
/rmp-platform/src/main/java/com/neteast/rmp/rpc/serializer/impl/DateSerializer.java
|
UTF-8
| 4,828
| 2.53125
| 3
|
[] |
no_license
|
package com.neteast.rmp.rpc.serializer.impl;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import com.neteast.rmp.rpc.serializer.AbstractSerializer;
import com.neteast.rmp.rpc.serializer.MarshallException;
import com.neteast.rmp.rpc.serializer.ObjectMatch;
import com.neteast.rmp.rpc.serializer.UnmarshallException;
import com.neteast.rmp.util.DateUtil;
/**
* 类说明:
* 将 json转换为Date对象及将Date对象转换为json串的方法<br>
* 如果需要将json 转换为 Date ,则传入的json 的格式为
* {javaClass:'java.util.Date',time:'34893492384'} 或
* {javaClass:'java.util.Date',date:'20120131'}
* 如果希望自定义格式化方式,则json中提供format 属性即可
* Ex:{javaClass:'java.util.Date',date:'20120131',format:'yyyyMMdd'}
* 如果将Date转换为json ,则最终的结构格式为
* {"date":"20111231","time":{"date":31,"day":6,"hours":8,"minutes":0,"month":11,"seconds":0,"time":1325289600000,"timezoneOffset":-480,"year":111}}
* 创建时间: 2013-1-9 下午04:05:51<br>
* @author 李祥辉<br>
* @email lixh@neteast.com<br>
*/
public class DateSerializer extends AbstractSerializer
{
/**
* Unique serialisation id.
*/
private final static long serialVersionUID = 2;
/**
* Classes that this can serialise.
*/
private static Class[] _serializableClasses = new Class[] { Date.class,
Timestamp.class, java.sql.Date.class };
/**
* Classes that this can serialise to.
*/
private static Class[] _JSONClasses = new Class[] { JSONObject.class };
public Class[] getJSONClasses()
{
return _JSONClasses;
}
public Class[] getSerializableClasses()
{
return _serializableClasses;
}
public Object marshall( Object p, Object o)
throws MarshallException
{
long time;
if (o instanceof Date)
{
time = ((Date) o).getTime();
}
else
{
throw new MarshallException("cannot marshall date using class "
+ o.getClass());
}
JSONObject obj = new JSONObject();
try
{
obj.put("date", DateUtil.formatDate(new Date(time), "yyyyMMdd"));
obj.put("time", new Date(time));
}
catch (Exception e)
{
throw (MarshallException) new MarshallException(e.getMessage()).initCause(e);
}
return obj;
}
public ObjectMatch tryUnmarshall( Class clazz, Object o)
throws UnmarshallException
{
JSONObject jso = (JSONObject) o;
String java_class;
try
{
java_class = jso.getString("javaClass");
}
catch (Exception e)
{
throw new UnmarshallException("no type hint", e);
}
if (java_class == null)
{
throw new UnmarshallException("no type hint");
}
if (!(java_class.equals("java.util.Date")))
{
throw new UnmarshallException("not a Date");
}
return ObjectMatch.OKAY;
}
public Object unmarshall( Class clazz, Object o)
throws UnmarshallException
{
JSONObject jso = (JSONObject) o;
Long time = null;
if(!jso.has("time") && !jso.has("date"))
throw new UnmarshallException("Could not get the time or date in date serialiser");
if (jso.has("javaClass"))
{
try
{
clazz = Class.forName(jso.getString("javaClass"));
}
catch (ClassNotFoundException e)
{
throw new UnmarshallException(e.getMessage(), e);
}
catch(JSONException e)
{
throw new UnmarshallException("Could not find javaClass", e);
}
}
Object returnValue = null;
if (jso.has("date") && Date.class.equals(clazz))
{
String timestr = null;
try
{
timestr = jso.getString("date");
List list = null;
if(jso.has("format"))
{
list = new ArrayList();
list.add(jso.getString("format"));
}
returnValue = DateUtil.parseDate(timestr,list);
}catch(JSONException e)
{
throw new UnmarshallException("cant get date from json : " +jso.toString(),e);
}catch(Exception e)
{
throw new UnmarshallException("cant pase string to Date : " + timestr,e);
}
return returnValue;
}
try
{
time = jso.getLong("time");
}catch(JSONException e)
{
throw new UnmarshallException("cant case time to long :" + jso.toString(),e);
}
if (Date.class.equals(clazz))
{
returnValue = new Date(time);
}
else if (Timestamp.class.equals(clazz))
{
returnValue = new Timestamp(time);
}
else if (java.sql.Date.class.equals(clazz))
{
returnValue = new java.sql.Date(time);
}
if (returnValue == null)
{
throw new UnmarshallException("invalid class " + clazz);
}
return returnValue;
}
}
| true
|
bf5ad60b0304e09f25449a72331d8630e4c95821
|
Java
|
kunkun777/lyjz
|
/ihrm-attendance/src/main/java/com/zxc/attendance/dao/ExtraDutyConfigDao.java
|
UTF-8
| 567
| 2.0625
| 2
|
[] |
no_license
|
package com.zxc.attendance.dao;
import com.zxc.model.atte.entity.ExtraDutyConfig;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
public interface ExtraDutyConfigDao extends JpaRepository<ExtraDutyConfig, Long>, JpaSpecificationExecutor<ExtraDutyConfig> {
/**
* @return 根据公司和部门查询加班配置信息
*/
ExtraDutyConfig findByCompanyIdAndDepartmentId(String companyId, String departmentId);
}
| true
|
4718a27f8fe7a9f3d44bf044c7e4f761e8120b29
|
Java
|
landtlord/HoGentStarter
|
/src/main/java/be/hogent/landtlord/hogentstarter/domain/service/mappers/UserMapper.java
|
UTF-8
| 1,111
| 2.453125
| 2
|
[] |
no_license
|
package be.hogent.landtlord.hogentstarter.domain.service.mappers;
import be.hogent.landtlord.hogentstarter.domain.bussines.User;
import be.hogent.landtlord.hogentstarter.domain.service.dto.UserDTO;
import static java.util.Objects.isNull;
public class UserMapper implements Mapper<User, UserDTO> {
@Override
public User toObject(UserDTO userDTO) {
if (isNull(userDTO)) {
return null;
}
User user = new User();
user.setId(userDTO.getId());
user.setUserName(userDTO.getUserName());
user.setPassword(userDTO.getPassword());
user.setRole(userDTO.getRole());
user.setApproved(userDTO.isApproved());
return user;
}
@Override
public UserDTO toDTO(User user) {
if (isNull(user)) {
return null;
}
UserDTO userDTO = new UserDTO();
userDTO.setId(user.getId());
userDTO.setUserName(user.getUserName());
userDTO.setPassword(user.getPassword());
userDTO.setRole(user.getRole());
userDTO.setApproved(user.isApproved());
return userDTO;
}
}
| true
|
f4d38f0fb4700d02d0f2f85354bf34ccbf566b83
|
Java
|
beckmarc/ProductMatchingDataset
|
/src/main/java/wdc/productcorpus/util/DeduplicatorSerial.java
|
UTF-8
| 3,664
| 2.625
| 3
|
[] |
no_license
|
package wdc.productcorpus.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import org.json.JSONObject;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.converters.FileConverter;
import wdc.productcorpus.datacreator.OutputFilesCreator.DataImporter;
import wdc.productcorpus.datacreator.OutputFilesCreator.OutputOffer;
/**
* @author Anna Primpeli
* Removes duplicate offers. Duplicate offers appear because our extractor might assign different nodeIDs to the same entity.
* We recognize every unique entity by its url-identifier-identifiervalue-text.
* Duplicate offers may appear across files
*/
public class DeduplicatorSerial {
@Parameter(names = { "-out",
"-outputDir" }, required = false, description = "Folder where the outputfile(s) are written to.", converter = FileConverter.class)
private File outputDirectory = new File("C:\\Users\\User\\workspace\\TransferLearningDataCreator\\src\\main\\resources\\tmp");
@Parameter(names = { "-in",
"-inputDir" }, required = false, description = "Folder where the input is read from.", converter = FileConverter.class)
private File inputDirectory = new File("C:\\Users\\User\\workspace\\TransferLearningDataCreator\\src\\main\\resources\\tmp\\offers_clean.txt");
public static void main(String args[]) throws IOException {
DeduplicatorSerial dedup = new DeduplicatorSerial();
if (args.length>0) {
dedup.inputDirectory=new File(args[0]);
dedup.outputDirectory=new File(args[1]);
}
dedup.deduplicate();
}
long filteredLines = (long)0.0;
HashSet<String> keys = new HashSet<String>();
public void deduplicate() throws IOException {
//for (File f : inputDirectory.listFiles()) {
if (!inputDirectory.isDirectory()) {
ArrayList<String> deduplicatedData = new ArrayList<String>();
BufferedReader br = InputUtil.getBufferedReader(inputDirectory);
String line;
DataImporter importOffer = new DataImporter();
while ((line = br.readLine()) != null) {
JSONObject json = new JSONObject(line);
OutputOffer offer = importOffer.jsonToOffer(json);
//String lineParts[] = line.split("\\t");
//keys are pld, identifier value and text
//String domain = DomainUtil.getPayLevelDomainFromWholeURL(lineParts[2]);
//String key = lineParts[2]+""+""+lineParts[3]+""+lineParts[4]+""+lineParts[5];
String key = offer.getUrl()+offer.getIdentifierPropertiesAsOneString()+offer.getDescriptivePropertiesAsOneString();
System.out.println(key);
if (keys.contains(key)) {
filteredLines++;
continue;
}
else {
deduplicatedData.add(line);
keys.add(key);
}
if (deduplicatedData.size()%1000000==0) {
writeInFile(inputDirectory.getName(), deduplicatedData);
deduplicatedData=new ArrayList<String>();
}
}
//write last part
writeInFile(inputDirectory.getName(), deduplicatedData);
}
//}
afterProcess();
}
private void writeInFile(String fileName, ArrayList<String> data) throws IOException {
BufferedWriter writer = new BufferedWriter (new FileWriter(outputDirectory.toString()+"/"+fileName+"_DEDUP.json",true));
for (String line:data)
writer.write(line+"\n");
writer.flush();
writer.close();
}
private void afterProcess() {
System.out.println("Filtered lines because of duplicated pld-idproperty-idvalue-text: "+filteredLines);
System.out.println("Deduplicated output saved in: "+outputDirectory);
System.out.println("DONE");
}
}
| true
|
87fff123bb4c4e91d0d4ecee6822b1d498bf6252
|
Java
|
weikog/leyou-advance
|
/ly-search/src/main/java/com/leyou/search/utils/HighlightUtils.java
|
UTF-8
| 3,796
| 2.421875
| 2
|
[] |
no_license
|
package com.leyou.search.utils;
import com.leyou.common.utils.JsonUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* 搜索高亮工具类
*/
public class HighlightUtils {
public static void highlightField(NativeSearchQueryBuilder queryBuilder, String field) {
// 创建高亮字段
HighlightBuilder.Field titleField = new HighlightBuilder.Field(field);
// 设置高亮前缀
titleField.preTags("<font color='red'>");
// 设置高亮后缀
titleField.postTags("</font>");
// 设置文本截断
titleField.fragmentSize(50);
// 设置高亮字段(哪些字段需要高亮)
queryBuilder.withHighlightFields(titleField);
}
public static SearchResultMapper highlightBody(Class clazz, String field) {
return new SearchResultMapper() {
// 实现搜索结果映射的接口
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse sr,
Class<T> aClass,
Pageable pageable) {
// 第一个参数:List<T> content: 分页数据
List<T> content = new ArrayList<T>();
// 获取搜索命中的文档
SearchHits hits = sr.getHits();
// SearchHit:代表命中的一篇文档
for (SearchHit hit : hits) {
// 获取该文档对应的json字符串
String jsonStr = hit.getSourceAsString();
// 把json字符串解析成EsItem对象
Object object = JsonUtils.toBean(jsonStr, clazz);
// 获取标题高亮字段
// key : field的名称(title)
HighlightField titleHighlightField = hit.getHighlightFields().get(field);
// 判断标题高亮字段是否为空
if (titleHighlightField != null) {
// 获取标题的高亮内容
String title = titleHighlightField.getFragments()[0].toString();
// 设置标题高亮内容
try {
Method method = object.getClass().getMethod("set" + captureName(field), String.class);
method.invoke(object, title);
} catch (Exception e) {
e.printStackTrace();
}
}
// 添加到集合中
content.add((T) object);
}
// 第二个参数:Pageable pageable: 分页对象
// 第三个参数:long total: 总记录数
return new AggregatedPageImpl<T>(content, pageable,
sr.getHits().getTotalHits());
}
};
}
private static String captureName(String name) {
name = name.substring(0, 1).toUpperCase() + name.substring(1);
return name;
}
}
| true
|
ea80d6d60840b91489cf8dd485cabc39833faa3c
|
Java
|
ruchiraw/product-es
|
/modules/components/social/org.wso2.carbon.social.cassandra/src/main/java/org/wso2/carbon/social/cassandra/Constants.java
|
UTF-8
| 1,408
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.wso2.carbon.social.cassandra;
public class Constants {
public static final String BODY_COLUMN = "payload_body";
public static final String ID_COLUMN = "payload_id";
public static final String CONTEXT_ID_COLUMN = "payload_context_id";
public static final String TIMESTAMP_COLUMN = "Timestamp";
public static final String TARGET_JSON_PROP = "target";
public static final String CONTEXT_JSON_PROP = "context";
public static final String ID_JSON_PROP = "id";
public static final String STREAM_VERSION = "1.0.0";
public static final String STREAM_NAME = "org.wso2.social.activity";
public static final String STREAM_NAME_IN_CASSANDRA = STREAM_NAME.replaceAll("\\.", "_");
public static final String STREAM_DEF = "{ 'name':'" + STREAM_NAME + "'," +
" 'version':'" + STREAM_VERSION + "'," +
" 'nickName': 'Activity stream for WSO2 Social'," +
" 'description': 'store json object and mete-data describing each activity'," +
" 'tags':['social', 'activity']," +
" 'metaData':[" +
" ]," +
" 'correlationData':[" +
" ]," +
" 'payloadData':[" +
" {'name':'id','type':'STRING'}," +
" {'name':'context_id','type':'STRING'}," +
" {'name':'body','type':'STRING'}" +
" ]" +
"}";
}
| true
|
3e43ec4cc17d386401de339c24dbc12732deef61
|
Java
|
evilhawk00/AppGroup
|
/PzADSDK/src/com/prize/prizeappoutad/view/SlotAdView.java
|
UTF-8
| 6,407
| 1.875
| 2
|
[] |
no_license
|
package com.prize.prizeappoutad.view;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.prize.prizeappoutad.R;
import com.prize.prizeappoutad.bean.AdDetailsInfo;
import com.prize.prizeappoutad.bean.AppsItemBean;
import com.prize.prizeappoutad.constants.Constants;
import com.prize.prizeappoutad.manager.JumpingManager;
import com.prize.prizeappoutad.utils.JLog;
import com.prize.prizeappoutad.utils.MTAUtils;
import com.prize.prizeappoutad.utils.PreferencesUtils;
/**
* 插屏广告
*
* @author huangchangguo 2016.11.8
*
*/
public class SlotAdView {
private static final String TAG = "huang-SlotAdView";
private View mView;
private TextView mHide;
private Context context;
private WindowManager mWM;
private ImageView mSlotIv;
private RelativeLayout mSlotRl;
private AdDetailsInfo mAdDetailsInfo;
private WindowManager.LayoutParams mParams;
public SlotAdView(Context context) {
this.context = context;
mWM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// defined that sets up the layout params appropriately.
mParams = new WindowManager.LayoutParams();
// 指定宽高
mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mParams.setTitle("SlotAdView");
mParams.gravity = Gravity.CENTER;
// 指定格式,是否有焦点,是否可以触摸
mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
mParams.format = PixelFormat.TRANSLUCENT;
mParams.type = WindowManager.LayoutParams.TYPE_TOAST;
}
private boolean isShow = false;
public void show(String bannerUrl, AdDetailsInfo adDetailsInfo) {
if (bannerUrl == null && adDetailsInfo == null) {
return;
}
if (mView != null)
return;
MTAUtils.onJumpSlotAd(context);
this.mAdDetailsInfo = adDetailsInfo;
mView = View.inflate(context, R.layout.view_slot, null);
mView.setVisibility(View.GONE);
// mView = View.inflate(context, R.layout.activity_main, null);
mHide = (TextView) mView.findViewById(R.id.slot_tv_hide);
// mSlotRl = (RelativeLayout) mView.findViewById(R.id.slot_rl);
mSlotIv = (ImageView) mView.findViewById(R.id.slot_iv);
// Target<GlideDrawable> into =
// Glide.with(context).load(bannerUrl).into(mSlotIv);
JLog.i(TAG, "SlotView-show:waiting!");
// 监听图片加载是否失败
Glide.with(context).load(bannerUrl)
.into(new GlideDrawableImageViewTarget(mSlotIv) {
@Override
public void onResourceReady(GlideDrawable arg0,
GlideAnimation<? super GlideDrawable> arg1) {
mView.setVisibility(View.VISIBLE);
PreferencesUtils.clearOutAd(context);
Log.i(TAG, "SlotView-show:onResourceReady!");
super.onResourceReady(arg0, arg1);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
hide();
Log.i(TAG, "SlotView-show:onLoadFailed!");
super.onLoadFailed(e, errorDrawable);
}
});
// mSlotIv.setOnTouchListener(this);
mSlotIv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onClickEvent();
}
});
mHide.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
hide();
}
});
if (Constants.JLog) {
int versionCode = 0;
String versionName = null;
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
versionCode = pi.versionCode;
versionName = pi.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
Toast.makeText(
context,
"versionName:" + versionName + " versionCode:"
+ versionCode, Toast.LENGTH_LONG).show();
}
mWM.addView(mView, mParams);
}
public void hide() {
if (mView != null) {
if (mView.getParent() != null) {
mWM.removeView(mView);
}
mView = null;
}
}
// @Override
// public void onClick(View v) {
// int id = v.getId();
// switch (id) {
// case R.id.slot_tv_hide:
// hide();
// break;
// case R.id.slot_rl:
// onClickEvent();
// break;
//
// case R.id.slot_iv:
// Log.i(TAG, " onClick:slot_iv -----!");
// break;
// default:
// break;
// }
// }
private void onClickEvent() {
int detailTypeKey = mAdDetailsInfo.detailType;
Log.i(TAG, "onClick:detailType(1:onJumpAdWebView||2:onJumpDownload):"
+ detailTypeKey);
MTAUtils.onClickSlotAd(context);
if (detailTypeKey == 1) {
// 跳转URL
String jumpUrl = mAdDetailsInfo.jumpUrl;
if (jumpUrl != null)
JumpingManager.onJumpAdWebView(context, jumpUrl);
// JumpingManager.onJumpAdWebView2(context, jumpUrl, "详情");
// JumpingManager.onJumpOtherExplorer(context, jumpUrl);
} else if (detailTypeKey == 2) {
// 跳转下载
AppsItemBean appInfo = mAdDetailsInfo.appInfo;
if (appInfo != null)
JumpingManager.onJumpAdAppDownloadService(context, appInfo,
false);
}
hide();
}
// float downX, moveX;
// float downY, moveY;
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// switch (event.getAction()) {
// case MotionEvent.ACTION_DOWN:
// // downX = event.getRawX();
// downY = event.getRawY();
// break;
// case MotionEvent.ACTION_MOVE:
// // moveX = event.getRawX();
// moveY = event.getRawY();
// // mParams.x += (int) (moveX - downX);
// mParams.y += (int) (moveY - downY);
// // 更新当前View的位置
// mWM.updateViewLayout(mView, mParams);
// // downX = moveX;
// downY = moveY;
// break;
// case MotionEvent.ACTION_UP:
// break;
// }
// return false;
// }
}
| true
|
1422471e77c1b239de5ed25b56a21c446af8723b
|
Java
|
AdrianVinatoru/jpa
|
/src/main/java/com/tutorial/hibernate/service/UserService.java
|
UTF-8
| 344
| 2.09375
| 2
|
[] |
no_license
|
package com.tutorial.hibernate.service;
import com.tutorial.hibernate.entitites.UserEntity;
import java.util.List;
public interface UserService {
void saveUser(UserEntity userEntity);
List<UserEntity> getUsers();
void updateUser(UserEntity userEntity);
UserEntity getUserById(int id);
void deleteUser(int userId);
}
| true
|
acd70c35c7a0fcf7d2bcb027fa25bf53a8d6dfa9
|
Java
|
BuyoDe/ClassicAlgorithm
|
/数组中只出现一次的数.java
|
UTF-8
| 572
| 3.1875
| 3
|
[] |
no_license
|
package 剑指offer;
import java.util.ArrayList;
import java.util.List;
public class 数组中只出现一次的数 {
public void FindNumsAppearOnce(int [] array,int num1[],int num2[]){
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<array.length;i++){
if(!list.contains(array[i]))
list.add(array[i]);
else
list.remove(new Integer(array[i]));
}
if(list.size()>1){
num1[0] = list.get(0);
num2[0] = list.get(1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| true
|
62d14b22e66bf061d3445f43bc17aff499bd5467
|
Java
|
Gayaprasad786/javacoreall
|
/JavaCore/src/com/javaBasics/www/PrimeOrNot.java
|
UTF-8
| 512
| 3.59375
| 4
|
[] |
no_license
|
package com.javaBasics.www;
import java.util.Scanner;
public class PrimeOrNot {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Number : ");
int num=sc.nextInt();
int temp=0;
for (int i = 2; i<= num ; i++)
{
if(num%i == 0)
{
temp+=1;
}
}
if(temp==1) {
System.out.print("This Number is Prime");
}else {
System.out.println("This Number is not Prime");
}
sc.close();
}
}
| true
|
6795301ddfa298cd17718fe3a09e18bd1a642b98
|
Java
|
messi1913/jdfaster
|
/jdfaster/src/main/java/com/jdfaster/test/services/run/RunTestIn.java
|
UTF-8
| 528
| 1.921875
| 2
|
[] |
no_license
|
package com.jdfaster.test.services.run;
import com.jdfaster.test.services.get_list.GetTestListOut.TestInfo;
import com.jdfaster.test.services.set_configs.SetTestConfigsIn;
public class RunTestIn extends SetTestConfigsIn {
public RunTestIn() {
}
public RunTestIn(TestInfo testInfo) {
super();
this.testInfo = testInfo;
}
private TestInfo testInfo;
public TestInfo getTestInfo() {
return testInfo;
}
public void setTestInfo(TestInfo testInfo) {
this.testInfo = testInfo;
}
}
| true
|
7afd1c1b244c09501ca790bc54d8ad4cc2c94a5a
|
Java
|
shubhamv108/microservices-architectural-design-patterns
|
/saga/orchestrator/services/payment/src/main/java/architectures/microservices/design/saga/orchestrator/services/payment/events/PaymentsEventsHandler.java
|
UTF-8
| 1,575
| 2.1875
| 2
|
[] |
no_license
|
package architectures.microservices.design.saga.orchestrator.services.payment.events;
import architectures.microservices.design.saga.orchestrator.library.commons.events.PaymentCancelledEvent;
import architectures.microservices.design.saga.orchestrator.library.commons.events.PaymentProcessedEvent;
import architectures.microservices.design.saga.orchestrator.services.payment.data.Payment;
import architectures.microservices.design.saga.orchestrator.services.payment.data.PaymentRepository;
import org.axonframework.eventhandling.EventHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class PaymentsEventsHandler {
private final PaymentRepository paymentRepository;
@Autowired
public PaymentsEventsHandler(final PaymentRepository paymentRepository) {
this.paymentRepository = paymentRepository;
}
@EventHandler
public void on(PaymentProcessedEvent event) {
Payment payment = Payment.builder()
.paymentId(event.getPaymentId())
.orderId(event.getOrderId())
.paymentStatus("COMPLETED")
.timeStamp(new Date())
.build();
this.paymentRepository.save(payment);
}
@EventHandler
public void on(PaymentCancelledEvent event) {
Payment payment = this.paymentRepository.findById(event.getPaymentId()).get();
payment.setPaymentStatus(event.getPaymentStatus());
this.paymentRepository.save(payment);
}
}
| true
|
91f7d98a4b81dcbd92621b2fce1056cd1c1153e1
|
Java
|
Rulso/IBM-practicas
|
/Ej2/src/main/java/com/example/controller/Ej2Controller.java
|
UTF-8
| 857
| 1.929688
| 2
|
[] |
no_license
|
package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Ej2Controller {
//@Autowired
@PostMapping("/api/v1/sucursales")
public ResponseEntity<List<Bancos>> retrieveSucursalesRequest(@RequestBody RetrieveSucursalesRequest request){
log.info("Request received: {}",request);
List<Bancos> retrieveBancos= service.retrieveBancoEstado(request.getEstado());
return new ResponseEntity<>(retrieveBancos,HttpStatus.OK);
}
}
| true
|
34e7a3ba6d578929675b59ebfde8a918ce8c4eed
|
Java
|
tyang98/APCS
|
/CarProject/src/CarTester.java
|
UTF-8
| 1,515
| 4.0625
| 4
|
[] |
no_license
|
public class CarTester {
public static void main(String[] args)
{
Car car1 = new Car("2017 BMW M3", "Sedan" , 6, 15, 30);
System.out.println(car1);
System.out.println("Your car will drive now");
car1.driveCar(15); //Car drives 15 miles
System.out.println("Your car has driven: "
+ car1.getDistance() + " miles");
System.out.println("Your car is being refilled to the maximum"
+ " amount of fuel");
car1.totalFill(); //Refill car to max fuel amount
System.out.println("The cost of filling car to the maximum fuel is: " + car1.getFuelCost() + " dollars");
System.out.println("Your car's current fuel amount: "
+ car1.getFuel() + " gallons");
System.out.println("Your car will drive some more now");
car1.driveCar(100); //Car drives 100 miles
System.out.println("Your car has driven: "
+ car1.getDistance() + " miles");
System.out.println("Your car's fuel amount after the drive: "
+ car1.getFuel() + " gallons");
System.out.println("Car will be refilled with more fuel");
car1.incFuel(3); //Refill car with 3 gallons of fuel
System.out.println("The total cost of fuel after 2 refills: " + car1.getFuelCost() + " dollars");
System.out.println("Your car's fuel amount after refill: " + car1.getFuel() + " gallons");
}
}
| true
|
0c0ce413b19f03ebbc82cf8ee5c0f8dd56b8a7a8
|
Java
|
BeYkeRYkt/MinecraftServerDec
|
/src/net/minecraft/BlockHay.java
|
UTF-8
| 987
| 1.90625
| 2
|
[] |
no_license
|
package net.minecraft;
public class BlockHay extends baa {
public BlockHay() {
super(Material.GRASS);
this.setBlockState(this.L.b().a(M, el.b));
this.a(CreativeModeTab.BUILDING_BLOCKS);
}
public IBlockState setData(int var1) {
el var2 = el.b;
int var3 = var1 & 12;
if (var3 == 4) {
var2 = el.a;
} else if (var3 == 8) {
var2 = el.c;
}
return this.getBlockState().a(M, var2);
}
public int getData(IBlockState var1) {
int var2 = 0;
el var3 = (el) var1.b(M);
if (var3 == el.a) {
var2 |= 4;
} else if (var3 == el.c) {
var2 |= 8;
}
return var2;
}
protected bed e() {
return new bed(this, new bex[] { M });
}
protected ItemStack i(IBlockState var1) {
return new ItemStack(Item.getItemOf((Block) this), 1, 0);
}
public IBlockState a(World var1, Position var2, BlockFace var3, float var4, float var5, float var6, int var7, EntityLiving var8) {
return super.a(var1, var2, var3, var4, var5, var6, var7, var8).a(M, var3.k());
}
}
| true
|
2c316909516de1ed99323e39aa9742e14e4dbfaa
|
Java
|
BourgeoisThibault/PDS_Ing1
|
/pdsApp/src/app/models/other/datasetPieChart.java
|
UTF-8
| 1,144
| 2.859375
| 3
|
[] |
no_license
|
package app.models.other;
import java.util.ArrayList;
import org.jfree.data.general.DefaultPieDataset;
public class datasetPieChart {
private String key;
private int value;
private ArrayList<datasetPieChart> collect;
public datasetPieChart() {
this.key = "";
this.value = -1;
this.collect = new ArrayList();
}
public datasetPieChart(String key, int value) {
this.key = key;
this.value = value;
this.collect = null;
}
public String getKey() {
return this.key;
}
public int getValue() {
return this.value;
}
public void addToCollect(String key, int value) {
this.collect.add(new datasetPieChart(key, value));
}
public DefaultPieDataset getDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
for(int i=0 ; i<this.collect.size() ; i++) {
dataset.setValue(this.collect.get(i).getKey(), this.collect.get(i).getValue());
}
return dataset;
}
}
| true
|
fde1f5896c1cf1303415ad7a28747b8e917b4f82
|
Java
|
team7android/TugasAndroid
|
/app/src/main/java/com/andlab/tugasandroid/Result/Result.java
|
UTF-8
| 1,452
| 2.125
| 2
|
[] |
no_license
|
package com.andlab.tugasandroid.Result;
import com.google.gson.annotations.SerializedName;
/**
* Created by greatsoft on 09/11/18.
*/
public class Result {
@SerializedName("id_user")
String id_user;
@SerializedName("username")
String username;
@SerializedName("nama_user")
String nama_user;
@SerializedName("alamat")
String alamat;
@SerializedName("no_hp")
String no_hp;
public Result(){}
public Result(String id_user, String username, String nama_user, String alamat, String no_hp) {
this.id_user = id_user;
this.username = username;
this.nama_user = nama_user;
this.alamat = alamat;
this.no_hp = no_hp;
}
public String getId_user() {
return id_user;
}
public void setId_user(String id_user) {
this.id_user = id_user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNama_user() {
return nama_user;
}
public void setNama_user(String nama_user) {
this.nama_user = nama_user;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getNo_hp() {
return no_hp;
}
public void setNo_hp(String no_hp) {
this.no_hp = no_hp;
}
}
| true
|
f796a1f45405d32625375dc18220f41029d08b06
|
Java
|
Cscotttaakan/Data-Structures
|
/Google Drive/Dixon 430 2017/BinaryTree/src/BTreeNode.java
|
UTF-8
| 1,179
| 2.796875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author user
*/
public class BTreeNode extends GenericItemType{
private StringDataItem data = new StringDataItem();
BTreeNode lst;
BTreeNode rst;
int height;
BTreeNode()
{
lst = null;
rst = null;
}
BTreeNode(String a)
{
data.set(a);
lst = null;
rst = null;
}
BTreeNode(StringDataItem a)
{
data.set(a.get());
lst = null;
rst = null;
}
StringDataItem getData()
{
return data;
}
void setData(StringDataItem a)
{
data.set(a.get());
}
@Override
boolean isLess(GenericItemType a)
{
return data.isLess((StringDataItem) a);
}
@Override
boolean isEqual(GenericItemType a)
{
return data.isEqual((StringDataItem) a);
}
@Override
boolean isGreater(GenericItemType a)
{
return data.isGreater((StringDataItem) a);
}
}
| true
|
b741d88e3f139a622205d2a68340146b9aa9222e
|
Java
|
moutainhigh/foss
|
/pkp/pkp-waybill-share/src/main/java/com/deppon/foss/module/pickup/waybill/shared/dto/ModifyBillWriteoffDto.java
|
UTF-8
| 5,561
| 1.835938
| 2
|
[] |
no_license
|
/**
* initial comments.
*/
/*******************************************************************************
* Copyright 2013 PKP
*
* 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.
*
* PROJECT NAME : pkp-waybill-share
*
* FILE PATH : src/main/java/com/deppon/foss/module/pickup/waybill/shared/dto/ModifyBillWriteoffDto.java
*
* FILE NAME : ModifyBillWriteoffDto.java
*
* AUTHOR : FOSS接送货系统开发组
*
* HOME PAGE : http://www.deppon.com
*
* COPYRIGHT : Copyright (c) 2012 Deppon All Rights Reserved.
******************************************************************************/
package com.deppon.foss.module.pickup.waybill.shared.dto;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* 更改单DTO
*
* @author 026113-foss-linwensheng
*
*/
/**
* @author Administrator
*
*/
public class ModifyBillWriteoffDto implements Serializable {
/**
* 更改单序列号
*/
private static final long serialVersionUID = -5450085240043617968L;
// 更改单受理开始日期
private Date acceptStartDate;
// 更改单受理结速日期
private Date acceptEndDate;
// 大区
private String largeArea;
// 小区
private String smallArea;
// 核销状态
private String writeoffStatus;
// 运单号集合
private List<String> waybillNumbers;
// 起草部门编码
private String darftOrgCode;
private String empCode;
//运单开单时间
private Date createTime;
//更改单发起时间
private Date draftTime;
//更改单受理时间
private Date rfcOperateTime;
//运单出库时间
private Date signTime;
//大区编码
private String largeAreaCode;
//内部要求 、外部要求
private String changeType;
public String getChangeType() {
return changeType;
}
public void setChangeType(String changeType) {
this.changeType = changeType;
}
public String getLargeAreaCode() {
return largeAreaCode;
}
public void setLargeAreaCode(String largeAreaCode) {
this.largeAreaCode = largeAreaCode;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getDraftTime() {
return draftTime;
}
public void setDraftTime(Date draftTime) {
this.draftTime = draftTime;
}
public Date getRfcOperateTime() {
return rfcOperateTime;
}
public void setRfcOperateTime(Date rfcOperateTime) {
this.rfcOperateTime = rfcOperateTime;
}
public Date getSignTime() {
return signTime;
}
public void setSignTime(Date signTime) {
this.signTime = signTime;
}
/**
* 起草部门集合
*/
private List<String> darftOrgCodeList;
// 查询状态:查询已受理
private String status;
// 备注
private String writeOffNote;
//变更金额
private BigDecimal changeAmount;
//--------------快递新增属性
/**
* 产品类型
*/
private List<String> productType;
public List<String> getProductType() {
return productType;
}
public void setProductType(List<String> productType) {
this.productType = productType;
}
public List<String> getWaybillNumbers() {
return waybillNumbers;
}
public void setWaybillNumbers(List<String> waybillNumbers) {
this.waybillNumbers = waybillNumbers;
}
public String getWriteOffNote() {
return writeOffNote;
}
public void setWriteOffNote(String writeOffNote) {
this.writeOffNote = writeOffNote;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDarftOrgCode() {
return darftOrgCode;
}
public void setDarftOrgCode(String darftOrgCode) {
this.darftOrgCode = darftOrgCode;
}
public Date getAcceptStartDate() {
return acceptStartDate;
}
public void setAcceptStartDate(Date acceptStartDate) {
this.acceptStartDate = acceptStartDate;
}
public Date getAcceptEndDate() {
return acceptEndDate;
}
public void setAcceptEndDate(Date acceptEndDate) {
this.acceptEndDate = acceptEndDate;
}
public String getLargeArea() {
return largeArea;
}
public void setLargeArea(String largeArea) {
this.largeArea = largeArea;
}
public String getSmallArea() {
return smallArea;
}
public void setSmallArea(String smallArea) {
this.smallArea = smallArea;
}
public String getWriteoffStatus() {
return writeoffStatus;
}
public void setWriteoffStatus(String writeoffStatus) {
this.writeoffStatus = writeoffStatus;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public List<String> getDarftOrgCodeList() {
return darftOrgCodeList;
}
public void setDarftOrgCodeList(List<String> darftOrgCodeList) {
this.darftOrgCodeList = darftOrgCodeList;
}
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public BigDecimal getChangeAmount() {
return changeAmount;
}
public void setChangeAmount(BigDecimal changeAmount) {
this.changeAmount = changeAmount;
}
}
| true
|
7f4ea71ead00ed5c9a76e93f7d4778d762122a7d
|
Java
|
DULYhoit/Project2
|
/src/main/java/kr/or/eutchapedia/main/entity/MovieInfoVo.java
|
UTF-8
| 3,090
| 2.171875
| 2
|
[] |
no_license
|
package kr.or.eutchapedia.main.entity;
public class MovieInfoVo {
private String movieDocId;
private String title;
private String titleOrg;
private String nation;
private String movieRunningTime;
private String rating;
private String prodYear;
private String posterUri;
private String genre;
private String plot;
private String movieTrailer;
private int movieHitCount;
private int movieRankingIndex;
private int movieRanking;
private String moviePlatform;
private int commentLikeCount;
private String starRating;
private float ratingAvg;
public String getMovieDocId() {
return movieDocId;
}
public void setMovieDocId(String movieDocId) {
this.movieDocId = movieDocId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitleOrg() {
return titleOrg;
}
public void setTitleOrg(String titleOrg) {
this.titleOrg = titleOrg;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public String getMovieRunningTime() {
return movieRunningTime;
}
public void setMovieRunningTime(String movieRunningTime) {
this.movieRunningTime = movieRunningTime;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getProdYear() {
return prodYear;
}
public void setProdYear(String prodYear) {
this.prodYear = prodYear;
}
public String getPosterUri() {
return posterUri;
}
public void setPosterUri(String posterUri) {
this.posterUri = posterUri;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getPlot() {
return plot;
}
public void setPlot(String plot) {
this.plot = plot;
}
public String getMovieTrailer() {
return movieTrailer;
}
public void setMovieTrailer(String movieTrailer) {
this.movieTrailer = movieTrailer;
}
public int getMovieHitCount() {
return movieHitCount;
}
public void setMovieHitCount(int movieHitCount) {
this.movieHitCount = movieHitCount;
}
public int getMovieRankingIndex() {
return movieRankingIndex;
}
public void setMovieRankingIndex(int movieRankingIndex) {
this.movieRankingIndex = movieRankingIndex;
}
public int getMovieRanking() {
return movieRanking;
}
public void setMovieRanking(int movieRanking) {
this.movieRanking = movieRanking;
}
public String getMoviePlatform() {
return moviePlatform;
}
public void setMoviePlatform(String moviePlatform) {
this.moviePlatform = moviePlatform;
}
public int getCommentLikeCount() {
return commentLikeCount;
}
public void setCommentLikeCount(int commentLikeCount) {
this.commentLikeCount = commentLikeCount;
}
public String getStarRating() {
return starRating;
}
public void setStarRating(String starRating) {
this.starRating = starRating;
}
public float getRatingAvg() {
return ratingAvg;
}
public void setRatingAvg(float ratingAvg) {
this.ratingAvg = ratingAvg;
}
}
| true
|
cc140dee5d9083462551e504553f2260491346f7
|
Java
|
ksgergis/hackerranck
|
/algorithms/graph/JourneyToTheMoon.java
|
UTF-8
| 1,798
| 3.03125
| 3
|
[] |
no_license
|
//question link https://www.hackerrank.com/challenges/journey-to-the-moon
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfAstronuts = in.nextInt();
int numOfConnections = in.nextInt();
Graph graph = new Graph(numOfAstronuts);
for (int a1 = 0; a1 < numOfConnections; a1++) {
int astrount1 = in.nextInt();
int astrount2 = in.nextInt();
graph.addEdge(astrount1, astrount2);
}
boolean[] visited = new boolean[numOfAstronuts];
long numOfWays = 0;
List<Long> groups = new LinkedList<>();
List<Long> indv = new LinkedList<>();
for (int i = 0; i < numOfAstronuts; i++) {
if (!visited[i]) {
long relatedAstronuts = numOfAsronuts(graph, i, visited);
for (long groupNum : groups) {
numOfWays += (relatedAstronuts * groupNum);
}
numOfWays += +(relatedAstronuts * indv.size());
if (relatedAstronuts == 1) {
indv.add(relatedAstronuts);
} else {
groups.add(relatedAstronuts);
}
}
}
System.out.println(numOfWays);
}
static long numOfAsronuts(Graph graph, int astronutId, boolean[] visited) {
visited[astronutId] = true;
long numOfAsronuts = 1;
for (int neighbourAstronut : graph.getAdjNode(astronutId)) {
if (!visited[neighbourAstronut]) {
numOfAsronuts += numOfAsronuts(graph, neighbourAstronut, visited);
}
}
return numOfAsronuts;
}
}
class Graph {
LinkedList<Integer>[] edges;
public Graph(int n) {
edges = new LinkedList[n];
for (int i = 0; i < n; i++) {
edges[i] = new LinkedList<>();
}
}
public void addEdge(int u, int v) {
edges[u].add(v);
edges[v].add(u);
}
public LinkedList<Integer> getAdjNode(int u) {
return edges[u];
}
}
| true
|
62accb2b5ba3a6c6e40f53f8f782602afbcef0fa
|
Java
|
zubair193/CountryFlag
|
/app/src/main/java/com/example/muhammadzubair/countryflag/MyAdapter.java
|
UTF-8
| 2,474
| 2.359375
| 2
|
[] |
no_license
|
package com.example.muhammadzubair.countryflag;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context mContext;
private List<country> mData;
public MyAdapter(Context mContext, List<country> mData) {
this.mContext = mContext;
this.mData = mData;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view;
LayoutInflater minflater = LayoutInflater.from(mContext);
view = minflater.inflate(R.layout.cardview_layout, viewGroup, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int i) {
holder.tv_country_name.setText(mData.get(i).getName());
holder.img_country_flag_thumbnail.setImageResource(mData.get(i).getCounrty_flag_Thumbnail());
//set Click Listener
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,countryinfo.class);
// Passing Data to countryinfo Activity
intent.putExtra("c_name",mData.get(i).getName());
intent.putExtra("c_thumbnail", mData.get(i).getCounrty_flag_Thumbnail());
//Start the activity
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_country_name;
ImageView img_country_flag_thumbnail;
CardView cardView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
tv_country_name = (TextView) itemView.findViewById(R.id.country_name_id);
img_country_flag_thumbnail = (ImageView) itemView.findViewById(R.id.country_image_id);
cardView = (CardView) itemView.findViewById(R.id.cardview_id);
}
}
}
| true
|
27417b5d1239c0cd7f493e7a0a7a0a0e2c96c9f8
|
Java
|
GabrielVilen/software-analytics
|
/src/main/java/asm/R1/CoreFeatureChecker.java
|
UTF-8
| 2,343
| 2.703125
| 3
|
[] |
no_license
|
package asm.R1;
import java.io.*;
import java.nio.file.*;
import java.text.Collator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Created by gabriel on 2017-11-02.
*/
public class CoreFeatureChecker {
private final Path path;
private List<String> coreMethods;
private TreeMap<String, String> lineCountMap = new TreeMap<>(Collator.getInstance());
public CoreFeatureChecker(Path path) {
this.path = path;
TreeMap<String, File> fileMap = new TreeMap<>(Collator.getInstance());
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path p : stream) {
fileMap.put(p.toString(), p.toFile());
}
} catch (IOException | DirectoryIteratorException x) {
System.err.println(x);
}
Iterator<Map.Entry<String, File>> iterator = fileMap.entrySet().iterator();
coreMethods = DeprecatedVersionRemovalChecker.getLines(iterator.next().getValue());
while (iterator.hasNext()) {
countCoreFeatures(iterator.next().getValue());
}
printMap(lineCountMap);
}
private void printMap(Map<String, String> lineCountMap) {
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("RQs_result/1.1/" + path.getFileName() + "-TOTAL-core-res.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.setOut(out);
for (Map.Entry<String, String> entry : lineCountMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue()); //
}
}
private void countCoreFeatures(File file) {
List<String> cmpLines = DeprecatedVersionRemovalChecker.getLines(file);
int coreMethodsCount = 0;
int totalMethodsCount = 0;
for (String coreMethod : coreMethods) {
// check if file contains the core method
if (cmpLines.contains(coreMethod)) {
coreMethodsCount++;
}
totalMethodsCount++;
}
lineCountMap.put(file.getName(), coreMethodsCount + "/" + totalMethodsCount);
}
public static void main(String [] args ) {
new CoreFeatureChecker(Paths.get(args[0]));
}
}
| true
|
31a78cab81f7d92ee9bff24ac8a2e21abe5b43a0
|
Java
|
ozgengunay/goldennode-group
|
/goldennode-client/src/main/java/com/goldennode/client/service/ConditionService.java
|
UTF-8
| 1,006
| 2.21875
| 2
|
[] |
no_license
|
package com.goldennode.client.service;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import com.goldennode.client.GoldenNodeException;
public interface ConditionService {
public void await(String lockId, String conditionId, String threadId) throws GoldenNodeException;
public void awaitUninterruptibly(String lockId, String conditionId, String threadId) throws GoldenNodeException;
public long awaitNanos(String lockId, String conditionId, String threadId, long nanosTimeout) throws GoldenNodeException;
public boolean await(String lockId, String conditionId, String threadId, long time, TimeUnit unit) throws GoldenNodeException;
public boolean awaitUntil(String lockId, String conditionId, String threadId, Date deadline) throws GoldenNodeException;
public void signal(String lockId, String conditionId, String threadId) throws GoldenNodeException;
public void signalAll(String lockId, String conditionId, String threadId) throws GoldenNodeException;
}
| true
|
5629a77f193d567cbe22745d929e1d82c18bf575
|
Java
|
Yat3s/Caper
|
/app/src/main/java/com/yat3s/demo/caper/widget/ViewWrapper.java
|
UTF-8
| 751
| 2.53125
| 3
|
[] |
no_license
|
package com.yat3s.demo.caper.widget;
import android.view.View;
/**
* Created by Yat3s on 17/12/2016.
* Email: hawkoyates@gmail.com
* GitHub: https://github.com/yat3s
*/
public class ViewWrapper {
private View targetView;
public ViewWrapper(View targetView) {
this.targetView = targetView;
}
public void setWidth(int width) {
targetView.getLayoutParams().width = width;
targetView.requestLayout();
}
public void setHeight(int height) {
targetView.getLayoutParams().height = height;
targetView.requestLayout();
}
public int getWidth() {
return targetView.getLayoutParams().width;
}
public int getHeight() {
return targetView.getLayoutParams().height;
}
}
| true
|
6d98c8b2d06f84b400bd835b89fbea0c15978ae7
|
Java
|
BaseMax/PopularAndroidSource
|
/cab.snapp.passenger.play_184.apk-decompiled/sources/com/raizlabs/android/dbflow/structure/a/c.java
|
UTF-8
| 590
| 2.0625
| 2
|
[] |
no_license
|
package com.raizlabs.android.dbflow.structure.a;
public abstract class c<TModel, CacheClass> {
/* renamed from: a reason: collision with root package name */
private CacheClass f5199a;
public abstract void addModel(Object obj, TModel tmodel);
public abstract void clear();
public abstract TModel get(Object obj);
public abstract TModel removeModel(Object obj);
public abstract void setCacheSize(int i);
public c(CacheClass cacheclass) {
this.f5199a = cacheclass;
}
public CacheClass getCache() {
return this.f5199a;
}
}
| true
|
a453dd2abe534bf887231d3d2f01f04b112b0f0c
|
Java
|
chuileyiyefeng/CustomerView
|
/app/src/main/java/com/example/rico/customerview/layoutManager/CardTouchListener.java
|
UTF-8
| 1,242
| 2.359375
| 2
|
[] |
no_license
|
package com.example.rico.customerview.layoutManager;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import com.example.rico.customerview.adapter.BaseAdapter;
public class CardTouchListener extends ItemTouchHelper.SimpleCallback {
private BaseAdapter adapter;
public CardTouchListener(BaseAdapter adapter) {
super(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT | ItemTouchHelper.DOWN | ItemTouchHelper.UP);
this.adapter = adapter;
}
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
if (adapter.getItemCount()<=1) {
return makeFlag(0,0);
}
return super.getMovementFlags(recyclerView, viewHolder);
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
int position = viewHolder.getAdapterPosition();
adapter.removePosition(position);
}}
| true
|
d1fa37b9ddbfde89cbbfb1e6a32db815d2c21f66
|
Java
|
vanchpuck/StegoTest
|
/src/ru/jonnygold/stego/ImageStegoFactory.java
|
UTF-8
| 5,796
| 2.484375
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ru.jonnygold.stego;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.*;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import ru.jonnygold.wavelet.Signal;
import ru.jonnygold.wavelet.SignalFactory;
//import sun.security.jca.GetInstance;
/**
*
* @author Vanchpuck
*/
class ImageStegoFactory implements StegoFactory{
private static ImageStegoFactory factory;
private ImageStegoFactory(){}
public static ImageStegoFactory getInstance(){
if(factory == null){
return new ImageStegoFactory();
}
return factory;
}
@Override
public Stego createStego(File file) throws IOException {
// BufferedImage bi = ImageIO.read(file);
// List<Signal> sl = new ArrayList<Signal>();
// sl.addAll(getSignalList(bi));
// File type determination
String type = getFileExt(file);
if(!type.equalsIgnoreCase("bmp") && !type.equalsIgnoreCase("png") && !type.equalsIgnoreCase("jpg") ){
throw new IOException("Формат файла не поддерживается");
}
// Initialize List to hold amount of Signals
List<Signal> signalList = new ArrayList<Signal>();
// Prepare reader
// ImageReader reader = ImageIO.getImageReadersByFormatName(getFileExt(file)).next();
// ImageInputStream inStream = ImageIO.createImageInputStream(file);
// reader.setInput(inStream);
// Read all images from file
/*** НА ДАННОМ ЭТАПЕ ПИШЕМ ТОЛЬКО В ПЕРВОЕ ИЗОБРАЖЕНИЕ ***/
BufferedImage image = ImageIO.read(file);
int imgType = image.getType();
if(
imgType != BufferedImage.TYPE_3BYTE_BGR
&& imgType != BufferedImage.TYPE_4BYTE_ABGR
&& imgType != BufferedImage.TYPE_4BYTE_ABGR_PRE
&& imgType != BufferedImage.TYPE_BYTE_GRAY
){
throw new IOException("Inappropriate image type. Only 24, 32 bit images and grayscale images are desired.");
}
signalList.addAll(getSignalList(image));
// Create and return stego
return new Stego(signalList);
}
public void putStego(File file, Stego stego) throws IOException{
// Image container retrieving
BufferedImage image = ImageIO.read(file);
// Convert JPG into PNG (JPG in not supported yet)
String fileExt = getFileExt(file);
if(getFileExt(file).equalsIgnoreCase("JPG")) {
fileExt = "PNG";
}
putSignal(image, stego.getSignalList());
// if(getFileExt(file).equals("JPG")) {
// file.renameTo(new File(getFileName(file)+".png"));
// }
ImageIO.write(image, fileExt, file);
if(getFileExt(file).equals("JPG")) {
file.renameTo(new File(getFileName(file)+".png"));
}
}
private List<Signal> getSignalList(BufferedImage image){
/***
* ДОБАВИТЬ ПРОВЕРКУ ТИПА ИЗОБРАЖЕНИЯ!!!
*/
// Initialize List for Signals storing
List<Signal> signalList = new ArrayList<Signal>();
int width = image.getWidth();
int height = image.getHeight();
Raster raster = image.getRaster();
// Get signal from color band component and add into the List of Signals
double[] data = new double[width * height];
for(int i=0; i<raster.getNumBands(); i++){
//System.out.println(" Get color band "+i);
data = new double[width * height];
raster.getSamples(0, 0, width, height, i, data);
signalList.add(SignalFactory.createSignal2D(data, height, width));
}
return signalList;
}
private void putSignal(BufferedImage image, List<Signal> signalList){
WritableRaster raster = image.getRaster();
if(raster.getNumBands() != signalList.size()){
throw new IllegalStateException("Неподходящее изображение");
}
int width = image.getWidth();
int height = image.getHeight();
//System.out.println("signalList.size(): "+signalList.size());
double[] data;
for(int i=0; i<signalList.size(); i++){
/*** ДОБАВИТЬ ПРОВЕРКУ СООТВЕТСТВИЯ РАЗМЕРОВ ***/
data = signalList.get(i).getData();
normalize(data);
raster.setSamples(0, 0, width, height, i, data);
}
}
private void normalize(double[] data){
for(int i=0; i<data.length; i++){
if(data[i] < 0) data[i] = 0;//Math.abs(data[i]);
if(data[i] > 255) data[i] = 255;
}
}
private String getFileExt(File file){
String fileName = file.getName();
return fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()).toUpperCase();
}
private String getFileName(File file){
String fileName = file.getName();
return fileName.substring(0, fileName.lastIndexOf("."));
}
}
| true
|
55f8f07dd5aaf57c4de77bd2057da23c8d88edfe
|
Java
|
ipholo/crackingTheCodeInterviewPersonalSolutions
|
/test/crackingthecodinginterviewpersonalsolutions/stacksAndQueues/StackWithMinTest.java
|
UTF-8
| 1,496
| 3.171875
| 3
|
[] |
no_license
|
/*
* Test to Stack With Min class.
*/
package crackingthecodinginterviewpersonalsolutions.stacksAndQueues;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
/*
* @author Leopoldo Hernandez
* @linktourl http://www.ipolo.hol.es
*/
public class StackWithMinTest {
StackWithMin stack;
@Before
public void setUp() {
stack = new StackWithMin();
}
@Test
public void testMin() {
stack.push(78);
assertEquals(78, stack.min());
stack.push(67);
stack.push(100);
stack.push(54);
assertEquals(54, stack.min());
stack.pop();
assertEquals(67, stack.min());
stack.pop();
stack.pop();
assertEquals(78, stack.min());
stack.push(12);
stack.push(1);
assertEquals(1, stack.min());
}
@Test
public void testMin_assertEmptyStack() {
assertEquals(-1, stack.min());
assertEquals(-1, stack.min());
assertEquals(-1, stack.min());
}
@Test
public void testMin_assertMinOperation() {
stack.push(32);
stack.push(12);
stack.push(40);
assertEquals(12, stack.min());
stack.pop();
stack.pop();
assertEquals(32, stack.min());
stack.push(1);
assertEquals(1, stack.min());
}
}
| true
|
744272cb280f9d93333fdec1fdecc00dc454b499
|
Java
|
nelson1122/SigeodepSIG
|
/src/java/model/dao/RelationVariablesFacade.java
|
UTF-8
| 1,200
| 2.0625
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.pojo.RelationVariables;
/**
*
* @author SANTOS
*/
@Stateless
public class RelationVariablesFacade extends AbstractFacade<RelationVariables> {
@PersistenceContext(unitName = "SIGEODEPPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RelationVariablesFacade() {
super(RelationVariables.class);
}
public int findMaxId() {
try {
String hql = "Select MAX(x.idRelationVariables) from RelationVariables x";
return em.createQuery(hql, Integer.class).getSingleResult();
} catch (Exception e) {
return 0;
}
}
public List<RelationVariables> findByRelationGroup(Integer idRelationGroup) {
String hql = "Select x from RelationVariables x where x.idRelationGroup.idRelationGroup=:id";
return em.createQuery(hql).setParameter("id", idRelationGroup).getResultList();
}
}
| true
|
7165a5c07faac04f562d5f5c586f2e53b5c85c3f
|
Java
|
kirillmega000/Java_labs
|
/CalculatorSource/src/Calculator.java
|
UTF-8
| 4,527
| 3.140625
| 3
|
[] |
no_license
|
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Scanner;
//парсинг строки в выражение
public class Calculator {
public static void main(String[] args) throws ScriptException {
Scanner sc=new Scanner(System.in);
String expression = sc.nextLine();
System.out.println(complicatedSequence(expression));
}
public static String complicatedSequence(String seq){
int maxn=countMaxPriority(seq),n=0;
String prevseq;
int n1=0,n2=0;
for(int i=maxn;i>0;i--){
for(int j=0;j<seq.length();j++){
if(seq.charAt(j)=='('){
n += 1;
if(n==i){
n1=j;
}
}
else if(seq.charAt(j)==')'){
if(n==i){
n2=j;
prevseq=primalSequence(seq.substring(n1+1,n2));
seq=seq.replace(seq.substring(n1,n2+1),prevseq);
j=n1;
}
n -= 1;
}
}
n=0;
System.out.println(seq);
}
return primalSequence(seq);
}
private static int countMaxPriority(String seq){//поиск максимального приоритета операции(в скобочках)
int n = 0;
int maxn = 0;
for(int i=0;i<seq.length();i++){
if(seq.charAt(i)=='('){
n += 1;
if(n>maxn) maxn=n;
}
else if(seq.charAt(i)==')'){
n -= 1;
}
}
return maxn;
}
private static String primalSequence(String seq){//парсинг элементарного выражения(без скобок)
int i=0;
while(i<seq.length()-1) {//парсинг умножения и деления(по правилам математики они первые)
i+=1;
if (seq.charAt(i) == '*') {
Pair fin=binaryOperation(seq,'*',i);
seq=fin.seq;
i=fin.num;
}
if (seq.charAt(i) == '/') {
Pair fin=binaryOperation(seq,'/',i);
seq=fin.seq;
i=fin.num;
}
}
i=0;
while(i<seq.length()-1){//парсинг сложения и вычитания
i+=1;
if(seq.charAt(i)=='+'){
Pair fin=binaryOperation(seq,'+',i);
seq=fin.seq;
i=fin.num;
}
if(seq.charAt(i)=='-'){
Pair fin=binaryOperation(seq,'-',i);
seq=fin.seq;
i=fin.num;
}
}
return seq;
}
private static Pair binaryOperation(String seq,char op,int i){
int n1 = i - 1;//поиск границ для элементарной операции
int n2 = i + 1;
while(((seq.charAt(n1)>47)&&(seq.charAt(n1)<58)&&(n1>0))||(seq.charAt(n1)==46)) {
n1 -= 1;
}
while(((seq.charAt(n2)>47)&&(seq.charAt(n2)<58)&&(n2<seq.length()-1))||(seq.charAt(n2)==46)) {
n2 += 1;
}
//сдвиг границ операции(если мы не с краю строки)
if(n1!=0)
n1+=1;
if(n2!=seq.length()-1)
n2-=1;
//сама операция
Float num= Float.valueOf(0);
if(op=='*')
num=Float.parseFloat(seq.substring(n1,i))*Float.parseFloat(seq.substring(i+1,n2+1));
if(op=='/')
num=Float.parseFloat(seq.substring(n1,i))/Float.parseFloat(seq.substring(i+1,n2+1));
if(op=='+')
num=Float.parseFloat(seq.substring(n1,i))+Float.parseFloat(seq.substring(i+1,n2+1));
if(op=='-')
num=Float.parseFloat(seq.substring(n1,i))-Float.parseFloat(seq.substring(i+1,n2+1));
//возвращение значений(сама преобразованная строка и номер символа для продолжения преобразования строки);
String seqprev=seq.substring(0,n1);
String seqnext=seq.substring(n2+1,seq.length());
seq=seqprev+num.toString()+seqnext;
return new Pair(n1,seq);
}
}
| true
|
7027d184fd055a74b9860dde6e5cfaa50380078c
|
Java
|
sunjiecheng/java-web
|
/01-mall-servlet/src/main/java/service/PropertyService.java
|
UTF-8
| 1,373
| 2.546875
| 3
|
[
"Apache-2.0",
"GPL-3.0-only"
] |
permissive
|
package service;
import bean.Product;
import bean.Property;
import bean.PropertyValue;
import dao.PropertyDAO;
import dao.PropertyValueDAO;
import java.util.HashMap;
import java.util.List;
public class PropertyService {
private PropertyDAO dao = new PropertyDAO();
public int getTotal(int cid) {return dao.getTotal(cid);}
public void add(Property bean) {
dao.add(bean);
}
public void update(Property bean) {
dao.update(bean);
}
public void delete(int id) {
dao.delete(id);
}
public Property get(int id){
return dao.get(id);
}
public List<Property> list(int cid,int start ,int count){
return dao.list(cid,start,count);
}
public List<Property> list(int cid){return dao.list(cid,0,Short.MAX_VALUE);}
public HashMap<Property,PropertyValue> list(Product p){
HashMap<Property,PropertyValue> result = new HashMap<>();
List<Property> PropertiesInCategory = this.list(p.getCategory().getId());
for (Property pt: PropertiesInCategory) {
PropertyValue value = new PropertyValueDAO().get(pt.getId(),p.getId());
if(null==value){
value = new PropertyValue();
value.setProduct(p);
value.setProperty(pt);
}
result.put(pt,value);
}
return result;
}
}
| true
|
f144f7ae4a9cda631d2faac4a306b70bfa43d9ea
|
Java
|
SofiaBrittoSchwartz/CWLTScheduleGenerator
|
/Algorithm/Algorithm/src/Master.java
|
UTF-8
| 31,779
| 2.921875
| 3
|
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Scanner;
import com.google.gson.*;
public class Master {
private static final int FAILED_SHIFT_SCORE = 100;
protected HashMap<Shift, ArrayList<Tutor>> availabilityMap; //Maps a shift to a list of tutors available during that time. Preliminary data structure that holds this information before we can score the tutors and shifts and put the
protected ArrayList<Tutor> tutors; //Master list of all tutors
protected ArrayList<Shift> shifts; //unordered master list of all shifts
protected PriorityQueue<Shift> shiftQ; //master list of all shifts ordered by their score
protected static boolean DEBUG = false; //variable that turns on(true)/off(false) print statements. I left this as *not* final so that I can selectively print some things and not others when debugging
protected static final int MIN_LENGTH = 2; //minimum number of consecutive hours a tutor is preferred to work
protected static final int MAX_LENGTH = 3; //maximum number of consecutive hours a tutor is allowed to work
protected static final int BUSY = 2;
protected static final int AVAILABLE = 0;
protected static final int PREFERRED = 1;
protected static final int CLOSED = -1;
protected static final String WRITING_ADVISOR = "Writing Advisor";
protected static final String ACADEMIC_CONSULTANT = "Academic Consultant";
protected static final int AFTERNOON_WRITING_ADVISOR = 2; //the number of writing advisors needed for the afternoon
private int minCount = 0; //used to count how many shifts have min number of tutors
private int maxCount = 0; //used to count how many shifts have max number of Tutors
public Master(){
shifts = new ArrayList<Shift>();
tutors = new ArrayList<Tutor>();
shiftQ = new PriorityQueue<Shift>();
availabilityMap = new HashMap<Shift, ArrayList<Tutor>>();
createShiftList();
}
public void readFile() throws FileNotFoundException{
String fileName = "Fall2017AvailabilitySubjectsPreferencesVeteranFullName.csv";
Scanner sc = new Scanner(new File(fileName));
String firstLine = sc.nextLine();
Scanner fl = new Scanner(firstLine); //this first line of the csv tells us which shifts are changing in the format of D-T (e.g. 3-14 represents Wednesday at 2pm)
fl.useDelimiter(",+");
fl.next(); //don't care about id tag
int shiftIndex = 0; //this serves as an index when trekking through our list of Shifts
ArrayList<Shift> shiftsToModify = new ArrayList<Shift>(); //this is a list of the shifts we'll be modifying based on the input file. It will contain, in order, the shifts the CSV represents
processAllShifts(fl, shiftIndex, shiftsToModify);
processAllTutors(sc, shiftsToModify);
checkForSingleShift();
for(Shift s : shifts){
s.availableTutors.addAll(availabilityMap.get(s));
s.calculateScore();
print(s+": ");//+s.availableTutors);
for(Tutor t : s.availableTutors){
print("("+t+", "+s.scoreAdjustmentMap.get(t)+")");
}
println();
}
removeEmptyShifts();
shiftQ.addAll(shifts);
////////////////////////
}
public void generateSchedule(){ //this is all messed up. don't look at it yet
while(shiftsNeedTutors()){//first we make sure every shift possible has the mininimum number of tutors
Shift shift = shiftQ.poll();
if(shift.calculateScore() > 0 && shift.hasAvailableTutors() && !shift.hasMin()){
while(!shift.hasMin()){
assign(shift);
}
shiftQ.add(shift);
}
}
while(numTutorHours() > 0){ //now we fill the shifts until the tutors don't have any more hours to work
Shift shift = shiftQ.poll();
if(shift.calculateScore() > 0 && shift.hasAvailableTutors()){
assign(shift);
shiftQ.add(shift);
}
}
}
private int calculateScore(){
int score = 0;
score -= shiftPopulationScore()/10; //(least important)
score += preferenceScore()*2; //check for preferences (fourth)
for(Shift s : shifts){
if(!subjectDuplicate(s)) score += 3; //check for duplicate subjects
}
score += 3*writingAdvisorScore();
//distributing veterans -- during closing shift in the fall AND every shift on sunday (at least opening and closing) AND distrbuting them around (highest)
//new people work at least one shift during the day (before 5) (second)
for(Tutor t : tutors){
if(t.worksDaytimeShift()) score+= 5;
}
// DEBUG = true;
// println(score);
return score;
}
private int shiftPopulationScore() {
int weight = 0;
for(int i = 1; i <= Shift.MAX_TUTORS; i++){
// println("Shifts with " + i + " tutors: " + numShiftsWithNumTutors(i));
weight+= i*i*numShiftsWithNumTutors(i); //check how many high-population shifts there are
}
return weight;
}
private int writingAdvisorScore(){
int score = 0;
for(Shift s : shifts){
if(s.hasSubject(WRITING_ADVISOR)){
score++;
if(s.day != Day.Friday && s.time == 15){
score++;
}
if(s.time >= 16){
score++;
}
}
}
return score;
}
private int preferenceScore(){
// int numTutorHours = 0;
int numPrefHours = 0;
for(Shift s : shifts){
// numTutorHours += s.assignedTutors.size();
for(Tutor t : s.assignedTutors){
if(s.preferredTutors.contains(t)) numPrefHours++;
}
}
// println(numPrefHours+", "+numTutorHours);
return numPrefHours;
}
private void subjectCheck(){ //checks for duplicate subjects in all shifts
for(Shift s : shifts){
if(subjectDuplicate(s)){
println(s +": "+ s.assignedTutors);
}
}
}
private boolean subjectDuplicate(Shift s){//sees if there are tutors of the same subject working this shift (excluding WAs)
for(Tutor t : s.assignedTutors){
for(String subject : t.subjects){
if(!subject.equals(WRITING_ADVISOR) && !subject.equals(ACADEMIC_CONSULTANT)){
for(Tutor tu : s.assignedTutors){
if(t!=tu && tu.subjects.contains(subject)){
return true;
}
}
}
}
}
return false;
}
private void removeEmptyShifts() {
ArrayList<Shift> toRemove = new ArrayList<Shift>();
for(Shift s : shifts){
if(s.availableTutors.isEmpty()){
toRemove.add(s);
}
}
for(Shift s : toRemove){
shifts.remove(s);
}
}
private void assign(Shift shift) {
Tutor tutor = getBestTutor(shift);
// Tutor tutor = shift.availableTutors.poll();
if(assignShift(shift, tutor)) assignConsecutiveShift(shift, tutor);
}
private Tutor getBestTutor(Shift shift) { // does this even make sense
Tutor tutor = writingAdvisorCheck(shift);
Tutor firstChoice = tutor;
ArrayList<Tutor> offLoad = new ArrayList<Tutor>();
while(hasTutorSubject(shift, tutor) && !shift.availableTutors.isEmpty()){
offLoad.add(tutor);
tutor = writingAdvisorCheck(shift);
}
if(shift.availableTutors.isEmpty() && hasTutorSubject(shift, tutor)){
offLoad.add(tutor);
tutor = firstChoice;
}
shift.availableTutors.addAll(offLoad);
shift.reheapify();
return tutor;
}
private boolean hasTutorSubject(Shift shift, Tutor tutor){ //returns whether or not the subjects that this Tutor tutors are all already represented for this shift
if(tutor.subjects.size()==1 && tutor.subjects.contains(WRITING_ADVISOR)) return false; //if they are a writing advisor, we don't really care as much
for(String subject : tutor.subjects){
if(!shift.hasSubject(subject)){
return false;
}
}
return true;
}
private Tutor writingAdvisorCheck(Shift shift) {
Tutor tutor;
if(!shift.hasSubject(WRITING_ADVISOR) && !shift.availableTutors.peek().isWritingAdvisor() && shift.hasSubjectAvailable(WRITING_ADVISOR)){ //if this shift doesn't have a writing advisor yet AND the next tutor that would be assigned isn't a writing advisor
ArrayList<Tutor> offLoad = new ArrayList<Tutor>(); //holds the tutors we're polling until we find a writing advisor
while(!shift.availableTutors.peek().isWritingAdvisor()){
offLoad.add(shift.availableTutors.poll());
}
tutor = shift.availableTutors.poll();
shift.availableTutors.addAll(offLoad);
}
else{
tutor = shift.availableTutors.poll();
}
return tutor;
}
private boolean consecutiveCheck(){ //after the schedule has been generated, this method will be called to check if each tutor is working consecutive shifts (rather than single shifts), returning true if every tutor has no single shifts
for(Tutor t : tutors){
boolean[] checked = new boolean[t.assignedShifts.size()];
boolean failed = false;//if the tutor has multiple single shifts, we don't want to print them twice
for(int i = 0; i < t.assignedShifts.size(); i++){
Shift s = t.assignedShifts.get(i);
if(!checked[i]){
Shift next = nextShift(s);
Shift prev = previousShift(s);
if(next!=null){
if(t.assignedShifts.contains(next)){
checked[i] = true;
checked[t.assignedShifts.indexOf(next)] = true;
}
}
if(prev!=null){
if(t.assignedShifts.contains(prev)){
checked[i] = true;
checked[t.assignedShifts.indexOf(prev)] = true;
}
}
}
}
for(boolean c : checked){
if(!c && !failed){
failed = true; //dont want to print multiple times for one person
println(t +": "+t.assignedShifts);
// return false; //comment out this line if you want this method to print all the tutors who work single hours
}
}
}
// println(true);
return true;
}
private boolean worksConsecutiveShift(Shift shift, Tutor tutor){ //determines whether or not a Tutor is working a shift that is adjacent to this one
Shift next = nextShift(shift);
Shift prev = previousShift(shift);
if(next != null){
if(tutor.assignedShifts.contains(next)){
return true;
}
}
if(prev != null){
if(tutor.assignedShifts.contains(prev)){
return true;
}
}
return false;
}
private int numShiftsAdjacent(Tutor tutor, Shift shift){//returns the length of the run that would be created if this shift were assigned to this tutor (-1)
Shift next = nextShift(shift);
Shift prev = previousShift(shift);
int numNexts = 0;
while(next != null && tutor.assignedShifts.contains(next)){
numNexts++;
next = nextShift(next);
}
int numPrevs = 0;
while(prev != null && tutor.assignedShifts.contains(prev)){
numPrevs++;
prev = previousShift(prev);
}
return numPrevs+numNexts;
}
private int numConsecutiveShifts(Tutor t){
int[] adjacents = new int[t.assignedShifts.size()];
int max = 0;
for(int i = 0; i < adjacents.length; i++){
adjacents[i] = numShiftsAdjacent(t, t.assignedShifts.get(i));
if(adjacents[i] > max){
max = adjacents[i];
}
}
return max+1;
}
private Shift previousShift(Shift shift){//returns the shift immediately before this one or null if it's the first shift of the day or after a break
if(!shift.firstShiftOfDay()){
try{
Shift prev = shifts.get(shifts.indexOf(shift)-1);
if(prev.adjacentTo(shift)){
return prev;
}
}
catch(IndexOutOfBoundsException e){//we catch this because if we remove the last shift of the day (like Friday at 3pm) because it has no available tutors, then this exception will be thrown,
return null;
}
}
return null;
}
private Shift nextShift(Shift shift){//returns the shift immediately after this one or null if it's the last shift of the day or before a break
if(!shift.lastShiftOfDay()){
try{
Shift next = shifts.get(shifts.indexOf(shift)+1);
if(next.adjacentTo(shift)){
return next;
}
}
catch(IndexOutOfBoundsException e){ //we catch this because if we remove the last shift of the day (like Friday at 3pm) because it has no available tutors, then this exception will be thrown,
return null;
}
}
return null;
}
private boolean assignShift(Shift shift, Tutor tutor) { //assigns a tutor to a shift, returning true on success or false if it cannot assign this tutor to this shift
if(numShiftsAdjacent(tutor, shift) < MAX_LENGTH && tutor.numShiftsNeeded>0 && !shift.hasMax()){ //we don't want to add to this shift unless it won't create a run of 3 or more
shift.assignedTutors.add(tutor);
tutor.numShiftsNeeded--;
tutor.assignedShifts.add(shift);
purge(tutor);
refreshScores(shift, tutor);
return true;
}
shift.scoreAdjustment+=FAILED_SHIFT_SCORE;
return false;
}
private boolean assignConsecutiveShift(Shift shift, Tutor tutor){
if(!worksConsecutiveShift(shift, tutor)){
boolean consecutiveAssigned = false;
Shift previous = previousShift(shift);
Shift next = nextShift(shift);
if(previous != null){
if(previous.availableTutors.contains(tutor) && !previous.assignedTutors.contains(tutor) && !hasTutorSubject(previous, tutor)){//if the tutor can work the previous shift but hasn't been assigned to it yet, do
if(assignShift(previous, tutor)){
consecutiveAssigned = true;
previous.availableTutors.remove(tutor); //need to remove the tutor because it won't get removed otherwise
}
}
}
if(next !=null && !consecutiveAssigned){//same deal, but we don't want to assign another shift if we already did above
if(next.availableTutors.contains(tutor) && !next.assignedTutors.contains(tutor) && !hasTutorSubject(next, tutor)){
if(assignShift(next, tutor)){
consecutiveAssigned = true;
next.availableTutors.remove(tutor); //need to remove the tutor because it won't get removed otherwise
}
}
}
int run = numConsecutiveShifts(tutor);
if(!consecutiveAssigned && numConsecutiveShifts(tutor)>MIN_LENGTH && tutor.numShiftsNeeded==0){//if we failed to assign a consecutive shift on the last shift and we have an extra long run, then we can move things around
//find the beginning or end of the run and unassign it,
unassignTutor(findEndOfRun(tutor, run), tutor);
//then unassign this most recent shift too
unassignTutor(shift, tutor);
}
else if(!consecutiveAssigned && tutor.numShiftsNeeded>0){//otherwise, if we still have time to spare, try getting rid of this one anyway.
unassignTutor(shift, tutor);
shift.availableTutors.remove(tutor);
if(previous!=null) previous.availableTutors.remove(tutor);
if(next!=null) next.availableTutors.remove(tutor);
}
return consecutiveAssigned;
}
return true;
}
private Shift findEndOfRun(Tutor tutor, int run) {//this method returns the least constrained Shift in a run of shifts of a given length. e.g. if sberling had a 3-hour run of shifts, this method would look at the first and last hour of that run and return the one with a higher score
Shift[] ends = new Shift[2];
for(Shift s : tutor.assignedShifts){
if(numShiftsAdjacent(tutor,s) == run-1){ //if this is true, then s is part of the run
if(!tutor.assignedShifts.contains(previousShift(s))){//if it doesn't contain the previous shift, then this is the beginning of the run
ends[0]=s;
}
if(!tutor.assignedShifts.contains(nextShift(s))){
ends[1]=s;
}
}
}
if(ends[0].calculateScore() > ends[1].calculateScore()){
return ends[0];
}
return ends[1];
}
private void unassignTutor(Shift shift, Tutor tutor) {
shift.assignedTutors.remove(tutor);
tutor.assignedShifts.remove(shift);
// if(!shift.availableTutors.contains(tutor)) shift.availableTutors.add(tutor);
unpurge(tutor);
tutor.numShiftsNeeded++;
refreshScores(shift, tutor);
}
private void unpurge(Tutor tutor) {
if(tutor.numShiftsNeeded<=0){//if the tutor was booked (i.e. previously purged)
for(Shift s : tutor.availableShifts){ //unpurge
if(!s.availableTutors.contains(tutor) && !tutor.assignedShifts.contains(s)) s.availableTutors.add(tutor);
}
}
}
private void refreshScores(Shift shift, Tutor tutor) {//refreshes the given tutor and shift scores and all shifts that have that tutor in their availability map, reheapifying where necessary
tutor.calculateAvailabilityRatio();
for(Shift s : tutor.availableShifts){//refresh all shifts that had this tutor in its availableTutor queue
if(s.availableTutors.contains(tutor)){
s.reheapify();
s.calculateScore();
}
}
shift.calculateScore();
shift.reheapify();
reheapifyShifts();
}
private void reheapifyShifts(){
ArrayList<Shift> temp = new ArrayList<Shift>();
temp.addAll(shiftQ);
shiftQ.clear();
shiftQ.addAll(temp);
}
private void purge(Tutor tutor) { //removes all tutors that no longer have hours to work
if(tutor.numShiftsNeeded <= 0){
for(Shift s : tutor.availableShifts){
s.availableTutors.remove(tutor);
}
}
}
//possible make this local variable
private int numTutorHours(){//calculates the total number of hours left to assign. i.e. if every tutor had 4 hours left and there were 40 tutors, this method would return 160
int total = 0;
for(Tutor t : tutors){
total += t.numShiftsNeeded;
}
return total;
}
private boolean shiftsNeedTutors(){//runs through all the shifts and figures out if there is a shift that still needs tutors
for(Shift shift : shifts){
if(!shift.hasMin() && shift.availableTutors.size() >= Shift.MIN_TUTORS){
return true;
}
}
return false;
}
private void createShiftList() {
for(Day day : Day.values()){ //for each day in the week
for(int i = day.getFirstAppointment(); i <= day.getLastAppointment() && i>=0; i++){ //for each shift in the day
Shift shift = new Shift(day, i); //create the shift
shifts.add(shift); //add it to the list of shifts
availabilityMap.put(shift, new ArrayList<Tutor>());
}
}
}
private void blackOutShift(Day day, int time){
Shift toRemove = null;
for(Shift shift : shifts){
if(shift.day == day && shift.time == time){
toRemove = shift;
break;
}
else if(shift.day.compareTo(day)>0){ //if we get past the day of the shift we're trying to remove, we know it doesn't exist and we can break
break;
}
}
shifts.remove(toRemove);
}
private void processAllShifts(Scanner fl, int shiftIndex, ArrayList<Shift> shiftsToModify) {
while(fl.hasNext()){
String shift = fl.next();
String[] dayTime = shift.split("-");
int day = Integer.parseInt(dayTime[0]); //integer representing the day of the week with 0=sunday and so on
int time = Integer.parseInt(dayTime[1]); //the time in 24h format
shiftIndex = processShift(shiftIndex, shiftsToModify, day, time);
}
fl.close();
}
private int processShift(int shiftIndex, ArrayList<Shift> shiftsToModify, int day, int time) {
/*we're advancing shift index until the shift represented by that index matches the shift read in from the input
* the reason we do this is just in case the 'shifts' list of Shifts is a superset of the list of shifts in the csv*/
println("the masterlist of shifts has " + shifts.get(shiftIndex) + " at the current index");
while(shifts.get(shiftIndex).day.compareTo(Day.values()[day]) < 0){ //comparing 'day' to the day of the "current shift" represented by 'shiftIndex'
println("advancing to get to the correct day...");
shiftIndex++;
}
if(shifts.get(shiftIndex).day.compareTo(Day.values()[day]) == 0){ //the "current shift" in our list of shifts and 'day' now match
println("found the correct day: " + shifts.get(shiftIndex));
while(shifts.get(shiftIndex).time < time){ //comparing 'time' to the time of the "current shift" represented by 'shiftIndex'
println("advancing to get to the correct time...");
shiftIndex++;
}
if(shifts.get(shiftIndex).time == time){
println("found the correct time: " + shifts.get(shiftIndex) + "! adding this shift to the list of shifts to modify.");
shiftsToModify.add(shifts.get(shiftIndex)); //we've found the shift that our csv is looking for!
}
}
if(shifts.get(shiftIndex).day.compareTo(Day.values()[day]) > 0 || shifts.get(shiftIndex).time > time){
println("UH OH SOMETHING WENT WRONG. The Shifts from input file got mismatched from the masterlist of shifts");
}
println("");
return shiftIndex;
}
private void processAllTutors(Scanner sc, ArrayList<Shift> shiftsToModify) {
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] both;
String name;
String studentID;
if(line.isEmpty()){
continue;
}
String[] tokens = line.split(",+");
if(tokens.length > 0){
both = tokens[0].split("~");
// DEBUG = true;
// println(Arrays.toString(both));
// DEBUG = false;
studentID = both[0];
name = both[1];
if(tutorContains(studentID)){ //if we find a tutor already in the system, then we should skip them
println(studentID + " already exists. there must be a problem. skipping this tutor for now");
continue;
}
processTutor(shiftsToModify, studentID, name, tokens);
}
}
sc.close();
for(Tutor t : tutors){ //calculate the availability ratios for tutors now
println(t+": "+t.calculateAvailabilityRatio());
}
}
private void processTutor(ArrayList<Shift> shiftsToModify, String studentID, String name, String[] tokens) {
Tutor tutor = new Tutor(studentID, name);
int consecutive = 0; // the running total of consecutive shifts the tutor is available for
tutors.add(tutor);
println("--------------------------");
println("Processing " + tutor + ":\n--------------------------");
for(int i = 1; i < tokens.length; i++){
try{
int available = Integer.parseInt(tokens[i]); //1 if the student is available at this time, and a 0 if not
if(available > 2){ //then the file is indicating the number of hours needed by the tutor
tutor.setNumShiftsNeeded(available);
}
else if(available == -2){
tutor.isVeteran = true;
}
else{
int shiftIndex = i-1; //shiftIndex
// if(available == 1) available = 0;
Shift shift = (shiftsToModify.get(shiftIndex));
Shift mostRecent = tutor.availableShifts.isEmpty() ? null : tutor.availableShifts.get(tutor.availableShifts.size()-1); //the most recently assigned shift, shifts are added to 'shiftsToModify' chronologically
println(shift + " consecutive: " + consecutive);
println("the most recent available shift is " + mostRecent);
print("Evaluating...");
switch(available){
case BUSY: //tutor is unavailable for this shift
consecutive = unavailable(tutor, consecutive, mostRecent);
break;
case PREFERRED://tutor prefers this shift
shift.prefer(tutor);
consecutive = available(tutor, consecutive, shift, mostRecent);
break;
case AVAILABLE:
consecutive = available(tutor, consecutive, shift, mostRecent);
break;
default:
println("AVAILABILITY NOT 2 OR 0, SOMETHING IS WRONG");
break;
}
println();
}
}
catch(NumberFormatException e){
String subject = tokens[i];
tutor.subjects.add(subject);
}
}
println(tutor +": "+tutor.subjects);
println(tutor + " is available for the following shifts: ");
for(Shift s : tutor.availableShifts){
println(s);
}
println("");
}
private int available(Tutor tutor, int consecutive, Shift shift, Shift mostRecent) {
println(" Available!");
consecutive = (mostRecent!=null && mostRecent.adjacentTo(shift)) ? consecutive+1 : 1; //increment the run or start over at 1 if it's a new day
if(!shift.lastShiftOfDay() || consecutive >= MIN_LENGTH){ //if it's the lastShift, then we need to be on a run of consecutive shifts to add this one
add(tutor, shift);
}
return consecutive;
}
private int unavailable(Tutor tutor, int consecutive, Shift mostRecent) {
println(" x");
if(consecutive > 0 && consecutive < MIN_LENGTH){ //if the tutor hasn't reached the minimum number of hours, but more than 0 (i.e. not a run of unavailability) then remove the most recent shift because that means it's isolated
println(tutor + " is not available for " + MIN_LENGTH + " consecutive hours on " + mostRecent + ". So we are removing this shift from their availability.");
if(mostRecent!=null) remove(tutor, mostRecent);
}
consecutive = 0; //reset the run
return consecutive;
}
private void add(Tutor tutor, Shift shift) {
tutor.availableShifts.add(shift); //add this shift to the tutor's list of available shifts
availabilityMap.get(shift).add(tutor); //add this tutor to the map of available tutors
}
private void remove(Tutor tutor, Shift shift) { //removes the associated availability between tutor and shift
tutor.availableShifts.remove(shift);
availabilityMap.get(shift).remove(tutor);
}
private void checkForSingleShift(){//checks for any single shifts in a tutor's availability
for(Tutor tutor : tutors){
for(int i = 0; i < tutor.availableShifts.size(); i++){
if(i>0 && i < tutor.availableShifts.size()-1){
Shift prev = tutor.availableShifts.get(i-1);
Shift current = tutor.availableShifts.get(i);
Shift next = tutor.availableShifts.get(i+1);
if(!current.adjacentTo(prev) && !current.adjacentTo(next)){
println(tutor + " has a single shift at " + current);
// remove(tutor, current);
}
}
if(i==0){
Shift current = tutor.availableShifts.get(i);
Shift next = tutor.availableShifts.get(i+1);
if(!current.adjacentTo(next)){
println(tutor + " has a single shift at " + current);
// remove(tutor, current);
}
}
if(i==tutor.availableShifts.size()-1){
Shift prev = tutor.availableShifts.get(i-1);
Shift current = tutor.availableShifts.get(i);
if(!current.adjacentTo(prev)){
println(tutor + " has a single shift at " + current);
remove(tutor, current);
}
}
}
}
}
private boolean tutorContains(String studentID) { //determines whether or not the tutors list already contains a Tutor with the input studentID
for(Tutor t : tutors){
if(t.studentID.equalsIgnoreCase(studentID)){
return true;
}
}
return false;
}
private int[] maxTutors(){
int[] maxInfo = new int[2];// maxInfo[0] will be the number of tutors working the busiest shifts, and maxInfo[1] will be how many shifts have that number of tutors
for(Shift shift : shifts){
if(shift.assignedTutors.size() > maxInfo[0]){
maxInfo[0] = shift.assignedTutors.size();
maxInfo[1] = 1;
}
else if(shift.assignedTutors.size() == maxInfo[0]){
maxInfo[1]++;
}
}
return maxInfo;
}
private int numShiftsWithNumTutors(int numTutors){
int num = 0;
for(Shift shift : shifts){
if(shift.assignedTutors.size() == numTutors){
num++;
}
}
return num;
}
public static void println(){
if(DEBUG) System.out.println();
}
public static void println(Object x){
if(DEBUG){
System.out.println(x);;
}
}
public static void print(Object x){
if(DEBUG){
System.out.print(x);;
}
}
public static void print(){
if(DEBUG){
System.out.print("");
}
}
public void printSchedule(){
int[][] sched = new int[7][24];
for(Shift shift : shifts){
for(int i = 0; i < Day.values().length; i++){
if(shift.day == Day.values()[i]){
sched[i][shift.time] = shift.assignedTutors.size();
}
}
}
println(" 9am 10am 11am 12pm 1pm 2pm 3pm 4pm 5pm 6pm 7pm 8pm");
for(int i = 0; i < sched.length-1; i++){//-1 to exclude saturday
print(Day.values()[i].toString().substring(0, 1)+" : ");
for(int j = 9; j <= 20; j++){
if((i==0 && (j < 12 || j > 17)) || (i==5 && j > 15)){
print(" ");
}
else{
print(sched[i][j]+" ");
}
if(sched[i][j] == Shift.MIN_TUTORS){
minCount++;
}
else if(sched[i][j] >= Shift.MAX_TUTORS){
maxCount++;
}
}
println();
}
}
public static String printShiftSubjects(Shift s){
String o = "[";
for(Tutor t : s.assignedTutors){
o += printTutorSubjects(t) + ", ";
}
o = o.substring(0, o.length()-2);
return o + "]";
}
public static String printTutorSubjects(Tutor t){
String o = "(";
for(String s : t.subjects){
o+= s+", ";
}
o = o.substring(0, o.length()-2);
return o+")";
}
public static void main(String[] args) throws FileNotFoundException{
// long start = System.currentTimeMillis();
// int max = -2000;
// int maxLoc = -1;
//
// for(int i = 100; i >= -100; i--){
// int score = test(i);
// if(score>max){
// max = score;
// maxLoc = i;
// }
//
// println(i+": "+score);
// }
// println();
// println(maxLoc+":"+max);
// long finish = System.currentTimeMillis();
// println("\n" + (finish-start) + "ms");
println(test(-22));
}
private void finalizeSchedule(){
for(Shift s : shifts){
s.finalizeTutors();
}
}
private String fileToString(File file) throws FileNotFoundException{
Scanner scan = new Scanner(file);
StringBuilder sb = new StringBuilder();
while(scan.hasNext()){
sb.append(scan.next() +" ");
}
scan.close();
return sb.toString();
}
private String toJson(){
Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
// Type typeOfSrc = new TypeToken<ArrayList<Tutor>>(){}.getType();
reorderShifts();
String json = gson.toJson(shifts);//, typeOfSrc);
println(json);
return json;
}
private void fromJson() throws FileNotFoundException{
Gson gson = new Gson();
File file;
file = new File("tutorList1.json");
String json = fileToString(file);
println(json);
TutorJSON[] tj = gson.fromJson(json, TutorJSON[].class);
println(Arrays.toString(tj));
// Tutor t = new Tutor(tj[0]);
}
private int earliestTime(){
int earliest = 25;
for(Shift s : shifts){
if(s.time < earliest) earliest = s.time;
}
return earliest;
}
private boolean truthCheck(boolean[] ordered){//returns true if all elements of the input array are true. used for reordering the shifts
for(int i = 0; i < ordered.length; i++){
if(ordered[i] == false) return false;
}
return true;
}
private void reorderShifts(){
ArrayList<Shift> orderedShifts = new ArrayList<Shift>();
boolean[] ordered = new boolean[shifts.size()]; //marking whether or not the shift at this index has been put in the ordered arraylist
int currentTime = earliestTime();
while(!truthCheck(ordered)){
for(int i = 0; i < shifts.size(); i++){
if(!ordered[i] && shifts.get(i).time == currentTime){
orderedShifts.add(shifts.get(i));
ordered[i] = true;
}
}
currentTime++;
}
// println("Shifts ordered by time: " + orderedShifts);
shifts = orderedShifts;
}
private static int test(int pref) throws FileNotFoundException {
DEBUG = true;
Shift.PREFERENCE_ADJUSTMENT=pref;
Master m = new Master();
m.readFile();
println(m.shifts.size());
println("---------------------------------------------------------------------------------");
long start = System.currentTimeMillis();
m.generateSchedule();
long finish = System.currentTimeMillis();
for(Shift s : m.shifts){
println(s+": "+printShiftSubjects(s));
}
println();
for(Tutor t : m.tutors){
t.sortAssignedShifts();
println(t+"("+m.numConsecutiveShifts(t)+"): "+t.assignedShifts);
}
println();
m.printSchedule();
println("Number of shifts with max # tutors: "+m.maxCount);
println("Number of shifts with min # tutors: "+m.minCount);
println("There are "+ m.maxTutors()[1] + " shifts with " + m.maxTutors()[0] + " tutors working, the highest of any shift\n");
m.calculateScore();
println();
println("Tutors who have single shifts:");
m.consecutiveCheck();
println();
println("Shifts that have duplicate subjects:");
m.subjectCheck();
m.preferenceScore();
println("\n" + (finish-start) + "ms");
DEBUG = true;
m.finalizeSchedule();
PrintWriter out = new PrintWriter("testOutput.json");
out.println(m.toJson());
out.close();
m.fromJson();
return m.calculateScore();
}
}
| true
|
b1f65c79c21f7cab16a9bc8c2341bc255887669c
|
Java
|
pericasimic/DjoleAPP
|
/src/djoleapp/business/model/Occupant.java
|
UTF-8
| 4,268
| 2.390625
| 2
|
[] |
no_license
|
package djoleapp.business.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Occupant implements Serializable {
private long id;
private String firstNameOccupant;
private String lastNameOccupant;
private String identificationNumber;
private String phoneNumber;
private String mail;
private String note;
private double sum;
private Flat home;
private List<SeparateSection> sections = new ArrayList<>();
private List<Debit> debits = new ArrayList<>();
private List<BankAccount> bankAccounts = new ArrayList<>();
private List<AccountCalculation> listAccountCalc = new ArrayList<>();
private List<BankingStatement> listStatements = new ArrayList<>();
private boolean isAdd = false;
public Occupant() {
}
public Occupant(long id) {
this.id = id;
}
public Occupant(long id, String firstNameOccupant, String lastNameOccupant, String identificationNumber, String phoneNumber, String mail) {
this.id = id;
this.firstNameOccupant = firstNameOccupant;
this.lastNameOccupant = lastNameOccupant;
this.identificationNumber = identificationNumber;
this.phoneNumber = phoneNumber;
this.mail = mail;
}
public void setSections(List<SeparateSection> sections) {
this.sections = sections;
}
public List<SeparateSection> getSections() {
return sections;
}
public List<Debit> getDebits() {
return debits;
}
public void setDebits(List<Debit> debits) {
this.debits = debits;
}
public String getFirstNameOccupant() {
return firstNameOccupant;
}
public void setFirstNameOccupant(String firstNameOccupant) {
this.firstNameOccupant = firstNameOccupant;
}
public String getLastNameOccupant() {
return lastNameOccupant;
}
public void setLastNameOccupant(String lastNameOccupant) {
this.lastNameOccupant = lastNameOccupant;
}
public String getIdentificationNumber() {
return identificationNumber;
}
public void setIdentificationNumber(String identificationNumber) {
this.identificationNumber = identificationNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public List<AccountCalculation> getListAccountCalc() {
return listAccountCalc;
}
public void setListAccountCalc(List<AccountCalculation> listAccountCalc) {
this.listAccountCalc = listAccountCalc;
}
public List<BankingStatement> getListStatements() {
return listStatements;
}
public void setListStatements(List<BankingStatement> listStatements) {
this.listStatements = listStatements;
}
public void setBankAccounts(List<BankAccount> bankAccounts) {
this.bankAccounts = bankAccounts;
}
public List<BankAccount> getBankAccounts() {
return bankAccounts;
}
public double getSum() {
double sumAll = 0;
for (Debit d : debits) {
sumAll += d.getDebit();
}
sum = sumAll;
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public boolean isIsAdd() {
return isAdd;
}
public void setIsAdd(boolean isAdd) {
this.isAdd = isAdd;
}
public Flat getHome() {
return home;
}
public void setHome(Flat home) {
this.home = home;
}
@Override
public String toString() {
return id + ". " + firstNameOccupant + " " + lastNameOccupant;
}
}
| true
|
9ec720e346968c948d86df64d779eefe97ee0e31
|
Java
|
stuxo/REDAndroid
|
/app/src/main/java/ch/redacted/data/model/Artist.java
|
UTF-8
| 4,849
| 1.820313
| 2
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package ch.redacted.data.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by sxo on 16/02/17.
*/
public class Artist {
@SerializedName("status")
public String status;
@SerializedName("response")
public Response response;
public static class Tags implements Comparable<Tags> {
@SerializedName("name")
public String name;
@SerializedName("count")
public int count;
@Override
public int compareTo(Tags tags) {
if (this.count > tags.count)
return -1;
else if (this.count == tags.count){
return 0;
}
else {
return 1;
}
}
}
public static class SimilarArtists {
}
public static class Statistics {
@SerializedName("numGroups")
public int numGroups;
@SerializedName("numTorrents")
public int numTorrents;
@SerializedName("numSeeders")
public int numSeeders;
@SerializedName("numLeechers")
public int numLeechers;
@SerializedName("numSnatches")
public int numSnatches;
}
public static class Torrent {
@SerializedName("id")
public int id;
@SerializedName("groupId")
public int groupId;
@SerializedName("media")
public String media;
@SerializedName("format")
public String format;
@SerializedName("encoding")
public String encoding;
@SerializedName("remasterYear")
public int remasterYear;
@SerializedName("remastered")
public boolean remastered;
@SerializedName("remasterTitle")
public String remasterTitle;
@SerializedName("remasterRecordLabel")
public String remasterRecordLabel;
@SerializedName("scene")
public boolean scene;
@SerializedName("hasLog")
public boolean hasLog;
@SerializedName("hasCue")
public boolean hasCue;
@SerializedName("logScore")
public int logScore;
@SerializedName("fileCount")
public int fileCount;
@SerializedName("freeTorrent")
public boolean freeTorrent;
@SerializedName("size")
public long size;
@SerializedName("leechers")
public int leechers;
@SerializedName("seeders")
public int seeders;
@SerializedName("snatched")
public int snatched;
@SerializedName("time")
public String time;
@SerializedName("hasFile")
public int hasFile;
}
public static class Torrentgroup {
@SerializedName("groupId")
public int groupId;
@SerializedName("groupName")
public String groupName;
@SerializedName("groupYear")
public int groupYear;
@SerializedName("groupRecordLabel")
public String groupRecordLabel;
@SerializedName("groupCatalogueNumber")
public String groupCatalogueNumber;
@SerializedName("tags")
public List<String> tags;
@SerializedName("releaseType")
public int releaseType;
@SerializedName("groupVanityHouse")
public boolean groupVanityHouse;
@SerializedName("hasBookmarked")
public boolean hasBookmarked;
@SerializedName("torrent")
public List<Torrent> torrent;
}
public static class Requests {
@SerializedName("requestId")
public int requestId;
@SerializedName("categoryId")
public int categoryId;
@SerializedName("title")
public String title;
@SerializedName("year")
public int year;
@SerializedName("timeAdded")
public String timeAdded;
@SerializedName("votes")
public int votes;
@SerializedName("bounty")
public long bounty;
}
public static class Response {
@SerializedName("id")
public int id;
@SerializedName("name")
public String name;
@SerializedName("notificationsEnabled")
public boolean notificationsEnabled;
@SerializedName("hasBookmarked")
public boolean hasBookmarked;
@SerializedName("image")
public String image;
@SerializedName("body")
public String body;
@SerializedName("vanityHouse")
public boolean vanityHouse;
@SerializedName("tags")
public List<Tags> tags;
@SerializedName("similarArtists")
public List<SimilarArtists> similarArtists;
@SerializedName("statistics")
public Statistics statistics;
@SerializedName("torrentgroup")
public List<Torrentgroup> torrentgroup;
@SerializedName("requests")
public List<Requests> requests;
}
}
| true
|
6cc0618fecc52566aa7b3a01df614bc2d7927b77
|
Java
|
krendil/asi-estimator
|
/src/asi/server/GetHistoryServlet.java
|
UTF-8
| 2,590
| 2.5
| 2
|
[] |
no_license
|
package asi.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import asi.beans.ChatToDatastore;
import com.google.appengine.api.datastore.EntityNotFoundException;
public class GetHistoryServlet extends HttpServlet {
/**
* auto-generated
*/
private static final long serialVersionUID = 5514918310492869453L;
/**
* Queries datastore and and reponds with xml or error.
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Check for error getting XML from datastore
try {
processStream( req.getInputStream(), resp.getOutputStream() );
} catch ( EntityNotFoundException e ) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
"The requested information does not exist.");
}
}
/**
* actual processing
* @param inputStream
* @param outputStream
* @throws IOException
*/
public void processStream(InputStream inputStream,
OutputStream outputStream) throws IOException, EntityNotFoundException {
long key = getKey( inputStream ); // may throw EntityNotFoundException
String xml = getXML(key);
sendResponse( outputStream, xml);
}
/**
* Query datastore for this item
* @param key
* @return
* @throws Exception
*/
private String getXML(long key) throws EntityNotFoundException {
String xml = null;
xml = ChatToDatastore.dsLoadHistory( key );
return xml;
}
/**
* writes xml response to response object.
* @param resp
* @param xml
* @throws IOException
*/
private void sendResponse(OutputStream resp, String xml) throws IOException {
OutputStreamWriter out = new OutputStreamWriter(resp);
out.write(xml);
out.close();
}
/**
* Get stream and query database, returning the database's response
* @param req
* @return
* @throws IOException
*/
private long getKey(InputStream req) throws IOException {
String key = "";
BufferedReader in = new BufferedReader(
new InputStreamReader(req));
String inputLine;
while ((inputLine = in.readLine()) != null)
key += inputLine;
in.close();
return Long.parseLong(key);
}
}
| true
|