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
d9579b097141f7a8de13f0c55ddebfbb5b8961ea
Java
whdals7337/coding-test-study
/src/baekjoon/MaxAndMin.java
UTF-8
3,093
3.703125
4
[]
no_license
package baekjoon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; // 최솟값과 최대값 - 2357번 public class MaxAndMin { static int N, M; static int[] arr; static int[][] tree; public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; StringBuilder sb = new StringBuilder(); st= new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); arr = new int[N]; tree = new int[N * 4][2]; for(int i = 0; i < N; i++) { arr[i] = Integer.parseInt(br.readLine()); } init(0, arr.length - 1, 1); for(int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int[] segment = segment(0, arr.length - 1, 1, a - 1, b - 1); sb.append(segment[0]).append(" ").append(segment[1]).append("\n"); } System.out.println(sb.toString()); } static int[] init(int start, int end, int node) { // leaf 노드의 경우 // 하나의 값만 범위로하는 노드에 도달 트리의 최소값과 최대값을 초기화 if(start == end) { tree[node][0] = arr[start]; tree[node][1] = arr[start]; return tree[node]; } // leaf 노드가 아닌 경우 else { int mid = (start + end) / 2; // 재귀적으로 노드의 좌측과 우측 노드의 최소값과 최대값을 구함 int[] lo = init(start, mid, node * 2); int[] ro = init(mid+1, end,node * 2 + 1); // 좌측과 우측의 노드의 최소값고 최대값으로 현 노드의 최소값과 최대값으로 초기화 tree[node][0] = Math.min(lo[0], ro[0]); tree[node][1] = Math.max(lo[1], ro[1]); return tree[node]; } } static int[] segment(int start, int end, int node, int left, int right) { // 구하고자 하는 영역에 속하지않는 경우 if(left > end || right < start) { return new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE}; } // 구하고자 하는 영역에 속하는 경우 if(left <= start && end <= right) { return tree[node]; } // 구하고자하는 영역에 걸치나 속하지 않는 경우 int mid = (start + end) / 2; // 자측과 우측의 노드의 최소값과 최대값을 구함 int[] lo = segment(start, mid, node * 2, left, right); int[] ro = segment(mid+1, end,node * 2 + 1, left, right); // 좌측과 우측의 노드의 최소값고 최대값으로 현 노드의 최소값과 최대값으로 초기화 return new int[]{Math.min(lo[0], ro[0]), Math.max(lo[1], ro[1])}; } }
true
c712aec198c739e82a53d6746a193bea003aff72
Java
Andinianas/uas-pemrograman4
/WarungKosan/src/com/example/warungkosan/List_item_ksn.java
UTF-8
534
1.921875
2
[]
no_license
package com.example.warungkosan; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class List_item_ksn extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_item_ksn); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.list_item_ksn, menu); return true; } }
true
7ec3df2804dee29c3a31cddabb53f51b3d1e8ded
Java
Haseebvp/Mess
/app/src/main/java/mess/bangalore/com/mess/MainScreen.java
UTF-8
10,774
1.804688
2
[]
no_license
package mess.bangalore.com.mess; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.internal.NavigationMenuView; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import mess.bangalore.com.mess.Utilities.AppConstants; import mess.bangalore.com.mess.Utilities.SessionHandler; import mess.bangalore.com.mess.adapters.ExpenseAdapter; import mess.bangalore.com.mess.models.ExpenseItem; import mess.bangalore.com.mess.models.User; public class MainScreen extends AppCompatActivity { RecyclerView recyclerView; LinearLayout lv_progress, lv_error; TextView tv_amount, tv_username; Toolbar toolbar; DrawerLayout drawerLayout; NavigationView navigationView; SessionHandler sessionHandler; private DatabaseReference databaseReferenceTransactions; List<ExpenseItem> expenseItems = new ArrayList<>(); ExpenseAdapter adapter; ActionBarDrawerToggle toggle; FloatingActionButton addExpense; LinearLayout membersLayout; RelativeLayout lv_generatebill; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(""); } catch (NullPointerException e) { e.printStackTrace(); } initialise(); } private void initialise() { drawerLayout = findViewById(R.id.drawer_layout); toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; drawerLayout.addDrawerListener(toggle); toggle.syncState(); sessionHandler = SessionHandler.getInstance(this); navigationView = findViewById(R.id.nav_view); View headerView = navigationView.getHeaderView(0); tv_username = headerView.findViewById(R.id.username); tv_username.setText(SessionHandler.getInstance(this).getUserName()); membersLayout = headerView.findViewById(R.id.membersLayout); lv_generatebill = headerView.findViewById(R.id.generateBill); addExpense = findViewById(R.id.addExpense); recyclerView = findViewById(R.id.recyclerview); lv_error = findViewById(R.id.lv_error); lv_progress = findViewById(R.id.lv_progress); tv_amount = findViewById(R.id.tv_amount); setAmount("0"); setRecyclerView(); setProgress(true); showMembers(); lv_generatebill.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { generateBill(); } }); fetchData(); addExpense.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showAddExpenseFragment(); } }); } private void generateBill() { Intent bill = new Intent(this, BillActivity.class); startActivity(bill); } private void showMembers() { LayoutInflater vi; final List<User> members = SessionHandler.getInstance(this).getUserList(); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(0, 10, 0, 10); membersLayout.removeAllViews(); members.add(0, new User("", "All", "", true)); for (int i = 0; i < members.size(); i++) { if (members.get(i) != null) { vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); assert vi != null; View v = vi.inflate(R.layout.member_item, null); v.setLayoutParams(layoutParams); TextView name = v.findViewById(R.id.membername); if (members.get(i).getUsername().equalsIgnoreCase(SessionHandler.getInstance(this).getUserName()) && members.get(i).getId().equalsIgnoreCase(SessionHandler.getInstance(this).getUserId())) { name.setText("You (" + members.get(i).getUsername() + ")"); } else { name.setText(members.get(i).getUsername()); } final int finalI = i; v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showIndividualData(members.get(finalI).getId()); } }); membersLayout.addView(v); } } } private void showIndividualData(String id) { try { if (drawerLayout.isDrawerOpen(Gravity.LEFT)) { drawerLayout.closeDrawer(Gravity.LEFT); } } catch (Exception ignored) { } setProgress(true); Double val = 0.0; List<ExpenseItem> individualData = new ArrayList<>(); if (SessionHandler.getInstance(this).getExpenseList() != null && SessionHandler.getInstance(this).getExpenseList().size() > 0) { for (ExpenseItem item : SessionHandler.getInstance(this).getExpenseList()) { if (item != null) { if (!id.isEmpty()) { if (item.getUserId().equalsIgnoreCase(id)) { individualData.add(item); val = val + item.getAmount(); } } else { individualData.add(item); val = val + item.getAmount(); } } } } expenseItems.clear(); expenseItems.addAll(individualData); adapter.notifyDataSetChanged(); tv_amount.setText(getString(R.string.amount, String.valueOf(val))); if (individualData.size() == 0) { setError(true); } else { setProgress(false); } } private void showAddExpenseFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); AddExpenseFragment newFragment = new AddExpenseFragment(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); transaction.add(newFragment, "Add"); transaction.addToBackStack(null).commit(); } private void setRecyclerView() { adapter = new ExpenseAdapter(this, expenseItems); LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); recyclerView.setHasFixedSize(true); } private void setProgress(boolean val) { if (val) { recyclerView.setVisibility(View.GONE); lv_progress.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); lv_progress.setVisibility(View.GONE); } } private void setError(boolean val) { if (val) { recyclerView.setVisibility(View.GONE); lv_progress.setVisibility(View.GONE); lv_error.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); lv_progress.setVisibility(View.GONE); lv_error.setVisibility(View.GONE); } } private void setAmount(String amount) { tv_amount.setText(getString(R.string.amount, amount)); } private void fetchData() { databaseReferenceTransactions = FirebaseDatabase.getInstance().getReference(AppConstants.TRANSACTIONS_TABLE); databaseReferenceTransactions.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) { setError(false); processData(dataSnapshot); } else { calculationProcess(); setError(true); } } @Override public void onCancelled(DatabaseError databaseError) { setError(true); } }); } private void processData(DataSnapshot dataSnapshot) { List<ExpenseItem> itemList = new ArrayList<>(); for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { ExpenseItem item = postSnapshot.getValue(ExpenseItem.class); itemList.add(item); } SessionHandler.getInstance(this).setExpenseList(itemList); Collections.reverse(itemList); expenseItems.clear(); expenseItems.addAll(itemList); adapter.notifyDataSetChanged(); calculationProcess(); } private void calculationProcess() { Double val = 0.0; if (expenseItems.size() > 0) { for (ExpenseItem item : expenseItems) { if (item != null) { val = val + item.getAmount(); } } } tv_amount.setText(getString(R.string.amount, String.valueOf(val))); } }
true
cdc9ffe96eeea94106008539d1f84afc87ad973f
Java
jorre127/AppOfTheYear2
/app/src/main/java/com/example/appoftheyear2/Game.java
UTF-8
955
2.859375
3
[]
no_license
package com.example.appoftheyear2; public class Game { String Name; String Genre; int Score; String Status; float HoursPlayed; String GameDate; public Game(String NameIn, String GenreIn, int ScoreIn, float HoursPlayedIn, String StatusIn, String DateIn){ Name = NameIn; Genre = GenreIn; Score = ScoreIn; Status = StatusIn; HoursPlayed = HoursPlayedIn; GameDate = DateIn; } public String getName(){ return Name; } public String getGenre(){ return Genre; } public String getStatus(){return Status;} public float getHoursPlayed(){return HoursPlayed;} public int getScore(){ return Score; } public void UpdateName(String NameIn){ Name = NameIn; } public void UpdateGenre(String GenreIn){ Genre = GenreIn; } public void UpdateScore(int ScoreIn){ Score = ScoreIn; } }
true
ca07bfb5056e1a98a73be5a3d0e065340be829f2
Java
dboy11/Yorktown_Logo
/app/src/main/java/com/example/dan/yorktownlogo/MainActivity.java
UTF-8
3,087
2.171875
2
[]
no_license
package com.example.dan.yorktownlogo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar); final ImageView iv = (ImageView)findViewById(R.id.imageView); //Access Picture final int width=iv.getWidth(); //Captures initial width of picture final int height=iv.getHeight(); //Captures initial height of picture seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int tempWidth= width + progress; //Changes width when slider moves int tempHeight = height + progress; //Changes height when slider moves TextView t = (TextView)findViewById(R.id.textView); t.setText("width = " + tempWidth + " height = " + tempHeight); //Display new width and height // iv.setX(width); MOVES THE PICTURE // iv.setY(height); MOVES THE PICTURE RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(tempWidth, tempHeight); //update the parameters of the image layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); //center image with new width and height iv.setLayoutParams(layoutParams); //apply new layout } public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
e9644cba18b88d8284175bc183de3d081f550af4
Java
LevPhilippov/JavaAlgo
/JavaAlgo_Lesson3_SQD/src/main/java/filippov/lev/filippov/interfaces/Deque.java
UTF-8
450
2.984375
3
[]
no_license
package filippov.lev.filippov.interfaces; public interface Deque<E> extends Queue<E> { void insertLeft(E value); // Adds an item at the front of Deque. void insertRight(E value); // Adds an item at the end of Deque. E deleteLeft(); // Deletes an item from front of Deque. E deleteRight(); //Deletes an item from end of Deque. E getHead(); // Gets the front item from queue. E getTail(); //Gets the last item from queue. }
true
080afc9098958757631ae23e737de01152c2cecb
Java
2434hin/jQueryPratice
/src/kr/or/ddit/buyer/controller/Buyer.java
UTF-8
544
2.1875
2
[]
no_license
package kr.or.ddit.buyer.controller; import java.util.List; import java.util.Map; import kr.or.ddit.buyer.service.BuyerServiceImpl; import kr.or.ddit.buyer.service.IBuyerService; public class Buyer { public static void main(String[] args) { IBuyerService service = BuyerServiceImpl.getInstance(); List<Map> list = service.buyerName(); for(Map map : list) { System.out.println(map.get("BUYER_ID")); System.out.println(map.get("BUYER_NAME")); System.out.println(map.get("BUYER_LGU")); } } }
true
ef2d8b484adb131c652f15903ebd13c0b6c6f0bd
Java
snoopcat512/Java-Core
/NguyenDuyPhong_J59_FinallExam/src/manager/StudentManager.java
UTF-8
6,428
2.859375
3
[]
no_license
package manager; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.Random; import java.util.Scanner; import io.SerializeFile; import models.Marks; import models.Student; import models.Subjects; public final class StudentManager { static Scanner sc = new Scanner(System.in); public static ArrayList<Student> list = new ArrayList<Student>(); public static ArrayList<Marks> listMark = new ArrayList<Marks>(); public static int checkCode() { if(list.isEmpty()) return 1; int maxCode=list.get(0).getStudentCode(); for(int i=0;i<list.size();i++) { if(list.get(i).getStudentCode()>maxCode) maxCode=list.get(i).getStudentCode(); } return maxCode+1; } public static void addStudent() { int code=0; System.out.println("How many students do you want to enter?"); int n = Integer.parseInt(sc.nextLine()); for (int i = 0; i < n; i++) { code=checkCode(); System.out.println("**Enter student " + (i + 1)); System.out.print("Enter surname buffer : "); String surenameBuffer = sc.nextLine(); System.out.println(); System.out.print("Enter name : "); String name = sc.nextLine(); System.out.println(); System.out.print("Enter year of birth : "); int yearOfBirth = Integer.parseInt(sc.nextLine()); System.out.println(); System.out.print("Enter gender : "); String gender = sc.nextLine(); System.out.println(); Student student = new Student(code, surenameBuffer, name, yearOfBirth, gender); list.add(student); saveFile(); } } public static boolean saveFile() { return SerializeFile.saveFile(list); } public static ArrayList<Student> readFile() { list = SerializeFile.readFile(); return list; } public static void printList() { for (Student student : list) { System.out.println(student); } } public static void updateStudent() { System.out.print("Enter student's code do you want update : "); int code = Integer.parseInt(sc.nextLine()); System.out.println(); int index = -1; for (int i = 0; i < list.size(); i++) { if (list.get(i).getStudentCode() == code) { index = i; } } if (index == -1) System.out.println("! ! Student dose not exist"); else { do { System.out.println("\t\t\t\t\t\t\t============================ UPDATE STUDENT ============================"); System.out.println("\t\t\t\t\t\t\t\t\t\t1.EDIT SURENAME BUFFER."); System.out.println("\t\t\t\t\t\t\t\t\t\t2.EDIT NAME."); System.out.println("\t\t\t\t\t\t\t\t\t\t3.EDIT YEAR OF BIRTH."); System.out.println("\t\t\t\t\t\t\t\t\t\t4.EDIT GENDER."); System.out.println("\t\t\t\t\t\t\t\t\t\t0.EXIT"); System.out.print("\t\t\t\t\t\t\t\t\t\t>>>[YOU CHOOSE FUNCTION] : "); int select = Integer.parseInt(sc.nextLine()); System.out.println(); switch (select) { case 1: { System.out.print(">>>Enter new surename bufer : "); String sb = sc.nextLine(); System.out.println(); list.get(index).setSurnameBuffer(sb); saveFile(); break; } case 2: { System.out.print(">>>Enter new name : "); String name = sc.nextLine(); System.out.println(); list.get(index).setName(name); saveFile(); break; } case 3: { System.out.print(">>>Enter new year of birth : "); int yob = Integer.parseInt(sc.nextLine()); System.out.println(); list.get(index).setYearOfBirth(yob); saveFile(); break; } case 4: { System.out.print(">>>Enter new gender : "); String gender = sc.nextLine(); System.out.println(); list.get(index).setGender(gender); saveFile(); break; } case 0: { return; } default: System.out.println("! ! Please select the available functions"); } } while (true); } } public static void deleteStudent() { System.out.print("Enter student's code do you want delete : "); int code = Integer.parseInt(sc.nextLine()); System.out.println(); int index = -1; for (int i = 0; i < list.size(); i++) { if (list.get(i).getStudentCode() == code) { index = i; } } if (index == -1) System.out.println("! !Student dose not exist"); else { listMark=MarkManager.readFile(); int count = 0; for (Marks mark : listMark) { if (mark.getStudentCode() == list.get(index).getStudentCode()) { count++; } } if (count == 0) { System.out.println("\t\t\t\t\t\t\t\t\t[Are you sure you want to delete?]"); System.out.println("\t\t\t\t\t\t\t\t\t\t1.[Yes]\t\t2.[No]"); int select = Integer.parseInt(sc.nextLine()); switch (select) { case 1: { list.remove(index); saveFile(); System.out.println("\t\t\t\t\t\t\t\t\tDelete success :)"); break; } case 2: return; default: return; } } else { System.out.println("! ! This student already has mark "); } } } public static void sortList() { if(list.isEmpty()) System.out.println("\t\t\t\t\t\t\t\t\t\t[LIST NULL]"); else { int i = 1; Collections.sort(list); System.out.println("\t\t\t\t\t\t\t======================== SORTED LIST OF STUDENT ========================"); System.out.println(); System.out.printf("\t\t\t\t\t\t\t%-3s %12s %-20s %-12s %-13s %-10s%n", "NO.", "[CODE]", "[SURENAME BUFFER]", "[NAME]", "[YEAR OF BIRTH]", "[GENDER]"); for (Student student : list) { System.out.print("\t\t\t\t\t\t\t"+i); student.display(); i++; } } } public static void manager() { do { readFile(); System.out.println("\t\t\t\t\t\t\t============================ MENU ============================"); System.out.println("\t\t\t\t\t\t\t\t\t\t1.ADD STUDENT."); System.out.println("\t\t\t\t\t\t\t\t\t\t2.UPDATE STUDENT."); System.out.println("\t\t\t\t\t\t\t\t\t\t3.DELETE STUDENT."); System.out.println("\t\t\t\t\t\t\t\t\t\t4.SHOW SORTED OF LIST STUDENT."); System.out.println("\t\t\t\t\t\t\t\t\t\t0.EXIT"); System.out.print("\t\t\t\t\t\t\t\t\t\t>>>[YOU CHOOSE FUNCTION] : "); int select = Integer.parseInt(sc.nextLine()); System.out.println(); switch (select) { case 1: addStudent(); break; case 2: updateStudent(); break; case 3: deleteStudent(); break; case 4: sortList(); break; case 0: return; default: System.out.println("! ! Please select the available functions"); } } while (true); } }
true
ab3cb7108a6b93239f9654b0de74b84f9e2c3897
Java
3hccm/XVulnFinder
/src/main/java/com/emyiqing/core/xss/AdvancedServletXss.java
UTF-8
9,379
1.960938
2
[ "Apache-2.0" ]
permissive
package com.emyiqing.core.xss; import com.emyiqing.core.xss.base.ServletXss; import com.emyiqing.dto.Result; import com.emyiqing.parser.ParseUtil; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.VariableDeclarator; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.VariableDeclarationExpr; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings("all") public class AdvancedServletXss extends ServletXss { private static Logger logger = Logger.getLogger(AdvancedServletXss.class); private static final String PrintWriter = "PrintWriter"; private static final String OutputParam = "OutputParam"; private static final String CallCondition = "call"; private static final String InputCondition = "input"; public AdvancedServletXss(CompilationUnit compilationUnit) { super(compilationUnit); } @Override public List<Result> check() { List<Result> results = new ArrayList<>(); // 是否导入servlet依赖 boolean imported = ParseUtil.isImported(compilationUnit, SERVLET_REQUEST_IMPORT) && ParseUtil.isImported(compilationUnit, SERVLET_RESPONSE_IMPORT); if (!imported) { logger.warn("no servlet xss"); return results; } try { Map<String, Boolean> condition = new HashMap<>(); compilationUnit.findAll(ClassOrInterfaceDeclaration.class).stream() .filter(c -> !c.isInterface() && !c.isAbstract()).forEach(c -> { List<String> methods = new ArrayList<>(); Map<String, String> callOutputMethod = new HashMap<>(); // all methods c.getMethods().forEach(m -> { methods.add(m.getName().asString()); }); // call condition c.getMethods().forEach(m -> { // method params Map<String, String> params = new HashMap<>(); // pw.write(input) in other method m.getParameters().forEach(p -> { if (p.getType().asString().equals(PrintWriter)) { params.put(PrintWriter, p.getName().asString()); } if (p.getType().asString().equals(StringType)) { params.put(OutputParam, p.getName().asString()); } if (params.get(PrintWriter) != null && params.get(OutputParam) != null) { callOutputMethod.put("target", m.getNameAsString()); } }); if (params.get(PrintWriter) != null && params.get(OutputParam) != null) { m.findAll(MethodCallExpr.class).forEach(im -> { if (im.getScope().get().toString().equals(params.get(PrintWriter))) { if (im.getName().asString().equals("write")) { im.getArguments().forEach(ar -> { if (ar.toString().equals(params.get(OutputParam))) { Result result = new Result(); result.setSuccess(true); result.setRisk(Result.MID_RISK); result.setClassName(c.getNameAsString()); result.setMethodName(m.getNameAsString()); String keyword = String.format("%s.%s", im.getScope().get().toString(), im.getNameAsString()); result.setKeyword(keyword); result.setPluginName(this.getClass().getSimpleName()); results.add(result); condition.put(CallCondition, true); } }); } } }); } }); // method condition c.getMethods().forEach(m -> { Map<String, String> params = new HashMap<>(); Map<String, String> var = new HashMap<>(); // doGet or doPost m.getParameters().forEach(p -> { if (p.getType().asString().equals(SERVLET_RESPONSE_CLASS)) { params.put(Response, p.getName().asString()); } if (p.getType().asString().equals(SERVLET_REQUEST_CLASS)) { params.put(Request, p.getName().asString()); } }); // check if (params.get(Request) != null && params.get(Response) != null) { m.findAll(VariableDeclarationExpr.class).forEach(v -> { MethodCallExpr right; boolean isGetParam = false; // 获取赋值语句右边部分 if (v.getVariables().get(0).getInitializer().get() instanceof MethodCallExpr) { // 强转不验证会出问题 right = (MethodCallExpr) v.getVariables().get(0).getInitializer().get(); if (right.getScope().get().toString().equals(params.get(Request))) { // 确定是否调用了req.getParameter if (right.getName().asString().equals(GetParamMethod)) { VariableDeclarator vd = (VariableDeclarator) right.getParentNode().get(); if (vd.getType().asString().equals(StringType)) { isGetParam = true; } } } } if (isGetParam) { var.put(ReqParam, v.getVariables().get(0).getNameAsString()); m.findAll(MethodCallExpr.class).forEach(im -> { boolean writerCondition = false; boolean inputCondition = false; if (im.getName().asString().equals(callOutputMethod.get("target"))) { for (Expression e : im.getArguments()) { if (e.toString().equals(var.get(ReqParam))) { inputCondition = true; } if (e.toString().equals( params.get(Response) + ".getWriter()")) { writerCondition = true; } } } if (inputCondition && writerCondition) { condition.put(InputCondition, true); } }); } }); } }); }); if (condition.get(InputCondition) != null && condition.get(CallCondition) != null) { if (condition.get(InputCondition) && condition.get(CallCondition)) { return results; } } results.clear(); } catch (Exception e) { logger.warn("no advanced servlet xss"); } return results; } }
true
5f3bdaa20527341283cdcc45eba3a54d62befa4a
Java
milindrc/ApiManager
/app/src/main/java/com/matrixdev/game/apimanager/MainActivity.java
UTF-8
1,025
2.125
2
[ "MIT" ]
permissive
package com.matrixdev.game.apimanager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.matrixdev.game.apimanagerlib.web.ApiManager; import com.matrixdev.game.apimanagerlib.web.ServerResponseListener; public class MainActivity extends AppCompatActivity implements ServerResponseListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ApiManager apiManager= new ApiManager(this,this); apiManager.getStringGetResponse("test","http://jsonplaceholder.typicode.com/posts/1"); } @Override public void positiveResponse(String TAG, String response) { Toast.makeText(getBaseContext(),response,Toast.LENGTH_LONG).show(); } @Override public void positiveResponse(String TAG, Object responseObj) { } @Override public void negativeResponse(String TAG, String errorResponse) { } }
true
5ccf917dbd71684426a2b42739c7a05dbc686262
Java
215254589/Project3
/Question1/Inheritance/src/main/java/za/ac/cput/Projects/Woman.java
UTF-8
170
2.640625
3
[]
no_license
package za.ac.cput.Projects; public class Woman extends Human { @Override public String canTalk(String sound){ return "I can talk alot " +sound; } }
true
64f5a9ee205bc996bab044ba7e6aec082e6f68b1
Java
zhangdi6/X17fun
/app/src/main/java/com/x/x17fun/ui/fragment/SaleFragment.java
UTF-8
1,362
2.0625
2
[]
no_license
package com.x.x17fun.ui.fragment; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.x.x17fun.R; import com.x.x17fun.base.BaseFragment; /** * A simple {@link Fragment} subclass. */ public class SaleFragment extends BaseFragment { private View view; private ImageView mBack; private TabLayout mTabLayout; private ViewPager mVp; public static SaleFragment getInstance() { return new SaleFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View inflate = inflater.inflate(R.layout.fragment_sale, container, false); initView(inflate); return inflate; } private void initView(View inflate) { ImageView back = inflate.findViewById(R.id.back); back.setOnClickListener(v -> pop()); mBack = (ImageView) inflate.findViewById(R.id.back); mTabLayout = (TabLayout) inflate.findViewById(R.id.tabLayout); mVp = (ViewPager) inflate.findViewById(R.id.vp); } }
true
8d70125c8bfdd875c229cf655f84829fcea1d745
Java
inshakr2/Java
/Study/src/main/java/oop/constructor3/Character.java
UTF-8
2,590
3.984375
4
[]
no_license
package main.java.oop.constructor3; public class Character { /** * 게임 캐릭터 만들기 튜토리얼 * 캐릭터는 아이디, 레벨, 직업, 소지금의 정보를 가지고 있다. * 캐릭터 생성시 아이디와 직업은 반드시 설정해야한다. * 소지금, 레벨은 설정하지 않을 경우 0, 1로 기본 설정된다. (물론 초기에 설정할 수 있지만, 해당 값보다 작을 수 없다.) * 직업은 전사, 마법사, 궁수, 도적만 가능 */ public void print() { System.out.println("===============캐릭터 정보==============="); System.out.println("|아이디|\t|직업|\t|레벨|\t|소지금|"); System.out.println("|"+this.getId()+"|\t"+"|"+this.getJob()+"|\t"+"|"+this.getLevel()+"|\t"+"|"+this.getMoney()+"|"); } private String id; private int level; private String job; private int money; // 생성자 사이에 데이터 전달이 일어날 수 있다. (중복 코드 방지) // 아래와 같이 오버로딩을 할 수 있다. public Character(String id, String job) { this(id, job, 1, 0); // 매개변수 4개를 받는 생성자에 전달하는 구문 } public Character(String id, String job, int level, int money) { this.setId(id); this.setJob(job); this.setLevel(level); this.setMoney(money); } // public Character(String id, String job) { // this.setId(id); // this.setJob(job); // this.setLevel(1); // this.setMoney(0); // // } // // public Character(String id, String job, int level, int money) { // this.setId(id); // this.setJob(job); // this.setLevel(level); // this.setMoney(money); // } // setter public void setId(String id) { this.id = id; } public void setJob(String job) { switch(job) { case "전사": case "마법사": case "궁수": case "도적": this.job = job; } } public void setLevel(int level) { if (level < 0) { return; } this.level = level; } public void setMoney(int money) { if (money < 0) { return; } this.money = money; } // getter public String getId() { return this.id; } public String getJob() { return this.job; } public int getLevel() { return this.level; } public int getMoney() { return this.money; } }
true
271987b39fb55510b1adbe0303fca8da5e10ac4d
Java
jaks97/DdS-Macowins
/src/main/java/macowins/PrendaNueva.java
UTF-8
213
2.140625
2
[]
no_license
package macowins; public class PrendaNueva implements EstadoPrenda { public double precioModificado(double precioBase) { return precioBase; // El precio de una prenda nueva no tiene descuento } }
true
b89f6400be37d96c4c886652c95e892ff7ef5577
Java
beginsto/wechat
/src/main/java/com/jielan/jiaxing/admin/wechat/service/impl/WeChatServiceImpl.java
UTF-8
3,097
2.078125
2
[]
no_license
package com.jielan.jiaxing.admin.wechat.service.impl; import com.alibaba.fastjson.JSONObject; import com.jielan.jiaxing.admin.wechat.dao.WeChatUserMapper; import com.jielan.jiaxing.admin.wechat.moudle.WeChatUser; import com.jielan.jiaxing.admin.wechat.service.WeChatService; import com.jielan.jiaxing.util.CharacterEncoding; import com.jielan.jiaxing.util.GetWeChatUserInfo; import com.jielan.jiaxing.util.WeChatOfDY; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; /** * Created by Administrator on 2017/1/3. */ @Service(value = "weChatService") public class WeChatServiceImpl implements WeChatService{ @Autowired private WeChatUserMapper weChatUserMapper; @Override public int insertData(WeChatUser record){ return weChatUserMapper.insert(record); } @Override public WeChatUser findByOpenId(String openid){ return weChatUserMapper.findByOpenId(openid); } @Override public int updateRecord(WeChatUser record){ return weChatUserMapper.updateByPrimaryKey(record); } @Override public WeChatUser updateInfo(WeChatUser record, String openid){ try { if (record == null){ WeChatUser user = new WeChatUser(); user.setOpenid(openid); user.setPhone(GetWeChatUserInfo.getPhoneByopenid(openid));//查询用户绑定手机号码 JSONObject json = WeChatOfDY.getUserInfo(openid);//获取用户微信昵称、头像等信息 user.setNickname(CharacterEncoding.stringToUnicode(String.valueOf(json.get("nickname")))); user.setHeadimgurl(String.valueOf(json.get("headimgurl"))); user.setUnionid(String.valueOf(json.get("unionid"))); user.setCreateTime(new Date()); insertData(user); record = findByOpenId(openid); }else{ String phone = GetWeChatUserInfo.getPhoneByopenid(openid); JSONObject json = WeChatOfDY.getUserInfo(openid); int temp = 0; if(record.getPhone() == null || !record.getPhone().equals(phone)){ record.setPhone(phone); temp = 1; } if(record.getNickname() == null || !CharacterEncoding.stringToUnicode(String.valueOf(json.get("nickname"))).equals(record.getNickname())){ record.setNickname(CharacterEncoding.stringToUnicode(String.valueOf(json.get("nickname")))); temp = 1; } if(record.getHeadimgurl() == null || !String.valueOf(json.get("headimgurl")).equals(record.getHeadimgurl())){ record.setHeadimgurl(String.valueOf(json.get("headimgurl"))); temp = 1; } if(temp == 1){ updateRecord(record); } } }catch (Exception ex){ ex.printStackTrace(); } return record; } }
true
3215f7a78440b1dff8fd64af300e165c7c547118
Java
sumanthmattapali/Selenium-Grid-Extras
/SeleniumGridExtras/src/test/java/com/groupon/seleniumgridextras/grid/GridStarterAdditionalNodeClasspathTest.java
UTF-8
1,945
2.328125
2
[ "BSD-3-Clause" ]
permissive
package com.groupon.seleniumgridextras.grid; import com.groupon.seleniumgridextras.config.Config; import com.groupon.seleniumgridextras.config.RuntimeConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; public class GridStarterAdditionalNodeClasspathTest { private static final String CLASSPATH_ITEM_1 = "/opt/selenium/prioritizer.jar"; private static final String CLASSPATH_ITEM_2 = "/opt/selenium/lib/capabilitymatcher.jar"; private final String configFileName = "grid_start_additional_node_classpath.json"; private static final String START_NODE_BAT = "start_node.bat"; private static final String GRID_NODE_LOG = "grid_node.log"; private final String logFile = "foo.log"; private final String windowsBatchFileName = logFile.replace("log", "bat"); @Before public void setUp(){ RuntimeConfig.setConfigFile(configFileName); Config config = new Config(); config.addNodeClasspathItem(CLASSPATH_ITEM_1); config.addNodeClasspathItem(CLASSPATH_ITEM_2); config.writeToDisk(RuntimeConfig.getConfigFile()); RuntimeConfig.load(); } @After public void tearDown() { new File(START_NODE_BAT).delete(); new File(GRID_NODE_LOG).delete(); new File(windowsBatchFileName).delete(); new File(configFileName).delete(); new File(RuntimeConfig.getConfigFile() + ".example").delete(); } @Test public void testAdditionalClasspathItemsArePresent() { String command = GridStarter.getWebNodeStartCommand(RuntimeConfig.getConfigFile(), RuntimeConfig.getOS().isWindows()); assert(command.contains(RuntimeConfig.getOS().getPathSeparator() + CLASSPATH_ITEM_1 + RuntimeConfig.getOS().getPathSeparator())); assert(command.contains(RuntimeConfig.getOS().getPathSeparator() + CLASSPATH_ITEM_2 + RuntimeConfig.getOS().getPathSeparator())); } }
true
595c508888ff59f1a06c87243cfebe360c4450b6
Java
ReemAlrashoud/ProgrammingAssignment4-DataStructure
/MGraph.java
UTF-8
1,463
2.796875
3
[]
no_license
// no!! public class MGraph<K extends Comparable<K>> implements Graph<K> { public Map<K, List<K>> adj_Focus_ON; public MGraph() { adj_Focus_ON=new BSTMap<>();} public boolean addNode(K i){ if(isNode(i)) return false; boolean not_is_node ; not_is_node=adj_Focus_ON.insert(i, new LinkedList<>()); return not_is_node; } public boolean isNode(K i) { return adj_Focus_ON.getKeys().exists(i);} public boolean addEdge(K i, K j){ for(int A=0 ; A<0 ; A++){} if(!(isNode(i) && isNode(j))) { return false;} else{ if(adj_Focus_ON.retrieve(i).second.exists(j) || adj_Focus_ON.retrieve(j).second.exists(i)) { return false; } else { adj_Focus_ON.retrieve(j).second.insert(i); for(int A=0 ; A<0 ; A++){} adj_Focus_ON.retrieve(i).second.insert(j); return true; }} } public boolean isEdge(K i, K j) { if(!isNode(i) || !isNode(j)) return false; boolean bWBWEE ; for(int A=0 ; A<0 ; A++){} bWBWEE=adj_Focus_ON.retrieve(i).second.exists(j); return bWBWEE; } public List<K> neighb(K i) { if(isNode(i)) return adj_Focus_ON.retrieve(i).second; else if(!isNode(i)) return null; return null; } public int deg(K i) { int minus = -1; if(isNode(i)) { return adj_Focus_ON.retrieve(i).second.size(); } return minus; } public List<K> getNodes(){ return adj_Focus_ON.getKeys(); }}
true
29b4be332a15ef26d5da58abae03b83b5357cfb4
Java
sunxunbang/pms
/src/com/pms/dao/impl/ResClassifyResourceDAOImpl.java
UTF-8
3,993
2.34375
2
[]
no_license
package com.pms.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.exception.ConstraintViolationException; import com.pms.dao.ResClassifyResourceDAO; import com.pms.model.HibernateUtil; import com.pms.model.ResClassifyResource; import com.pms.util.DateTimeUtil; public class ResClassifyResourceDAOImpl implements ResClassifyResourceDAO { @Override public ResClassifyResource ResClassifyResourceSave(ResClassifyResource rc) throws Exception { //打开线程安全的session对象 Session session = HibernateUtil.currentSession(); //打开事务 Transaction tx = session.beginTransaction(); ResClassifyResource rs = null; String sqlString = "select * from WA_CLASSIFY_RESOURCE where DATA_SET = :DATA_SET and SECTION_CLASS = :SECTION_CLASS and ELEMENT = :ELEMENT "; try { Query q = session.createSQLQuery(sqlString).addEntity(ResClassifyResource.class); q.setString("DATA_SET", rc.getDATA_SET()); q.setString("SECTION_CLASS", rc.getSECTION_CLASS()); q.setString("ELEMENT", rc.getELEMENT()); rs = (ResClassifyResource) q.uniqueResult(); if(rs != null) { rc.setId(rs.getId()); rc.setDATA_VERSION(rs.getDATA_VERSION() + 1); } else { rc.setDATA_VERSION( 1 ); } String timenow = DateTimeUtil.GetCurrentTime(); rc.setLATEST_MOD_TIME(timenow); rc = (ResClassifyResource) session.merge(rc); tx.commit(); } catch(ConstraintViolationException cne){ tx.rollback(); System.out.println(cne.getSQLException().getMessage()); throw new Exception("存在重名数据集-字段分类-字段。"); } catch(org.hibernate.exception.SQLGrammarException e) { tx.rollback(); System.out.println(e.getSQLException().getMessage()); throw e.getSQLException(); } catch(Exception e) { e.printStackTrace(); tx.rollback(); System.out.println(e.getMessage()); throw e; } finally { HibernateUtil.closeSession(); } return rc; } @SuppressWarnings("unchecked") @Override public List<ResClassifyResource> QueryAllResClassifyResource() throws Exception { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); List<ResClassifyResource> rs = null; String sqlString = "select * from wa_classify_resource "; try { Query q = session.createSQLQuery(sqlString).addEntity(ResClassifyResource.class); rs = q.list(); tx.commit(); } catch(Exception e) { e.printStackTrace(); tx.rollback(); System.out.println(e.getMessage()); throw e; } finally { HibernateUtil.closeSession(); } return rs; } @Override public ResClassifyResource QueryResClassifyResource(String dataset, String element) throws Exception { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); ResClassifyResource rs = null; String sqlString = "select * from wa_classify_resource where DATA_SET = :DATASET and ELEMENT = :ELEMENT "; try { Query q = session.createSQLQuery(sqlString).addEntity(ResClassifyResource.class); q.setString("DATASET", dataset); q.setString("ELEMENT", element); rs = (ResClassifyResource) q.uniqueResult(); tx.commit(); } catch(Exception e) { e.printStackTrace(); tx.rollback(); System.out.println(e.getMessage()); throw e; } finally { HibernateUtil.closeSession(); } return rs; } @Override public int ResClassifyResourceImportClear() throws Exception { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); int rs = 0; String sqlString = "delete from wa_classify_resource "; try { Query q = session.createSQLQuery(sqlString); rs = q.executeUpdate(); tx.commit(); } catch(Exception e) { e.printStackTrace(); tx.rollback(); System.out.println(e.getMessage()); throw e; } finally { HibernateUtil.closeSession(); } return rs; } }
true
698272cf7713e045e8f39c64e6389791a60de4f4
Java
thiagoaoki/music-playlist-swing
/src/main/java/br/com/dbsti/aula/model/dao/hibernate/MusicaDaoHibernate.java
UTF-8
774
2.296875
2
[]
no_license
package br.com.dbsti.aula.model.dao.hibernate; import br.com.dbsti.aula.model.Musica; import br.com.dbsti.aula.model.dao.MusicaDAO; import br.com.dbsti.aula.model.util.JPAUtil; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; public class MusicaDaoHibernate extends GenericDaoHibernate<Musica> implements MusicaDAO { @Override public List<Musica> pesquisaPorNome(String nomeFiltro) { EntityManager em = JPAUtil.createEntityManager(); Query q = em.createQuery("select m from Musica m where lower(m.nome) like :nome"); q.setParameter("nome", "%" + nomeFiltro.toLowerCase() + "%"); List resultList = q.getResultList(); return resultList; } }
true
fae92bc851094936c2038c43c449fa118a084426
Java
ThorbenLindhauer/cosimin
/src/main/java/de/unipotsdam/hpi/indexing/ReferenceBlockBasedIndex.java
UTF-8
8,863
2.453125
2
[ "Apache-2.0" ]
permissive
package de.unipotsdam.hpi.indexing; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.Iterator; import de.unipotsdam.hpi.permutation.PermutationFunction; import de.unipotsdam.hpi.storage.AggregatedReferenceBlockStorage; import de.unipotsdam.hpi.storage.BitSignatureIndex; import de.unipotsdam.hpi.util.BitSignatureUtil; public class ReferenceBlockBasedIndex extends AbstractBlockBasedIndex<ReferenceBlock> { private static final long serialVersionUID = 1L; transient protected BitSignatureIndex bitSignatureIndex; transient protected PermutationFunction permutationFunction; private int storageCounter = 0; private int blocksPerFile = 100; transient AggregatedReferenceBlockStorage currentStorage; public ReferenceBlockBasedIndex(Path basePath, int keySize, int blockSize, BitSignatureIndex bitSignatureIndex, PermutationFunction permutationFunction) { super(basePath, keySize, blockSize); this.bitSignatureIndex = bitSignatureIndex; this.permutationFunction = permutationFunction; } protected ReferenceBlock createNewBlock() throws IOException { AggregatedReferenceBlockStorage storage = resolveBlockStorage(); ReferenceBlock block = new ReferenceBlock(blockSize, keySize, storage, blockIdCounter++); return block; } protected AggregatedReferenceBlockStorage resolveBlockStorage() { if (currentStorage == null || storageCounter % blocksPerFile == 0) { int storageId = storageCounter / blocksPerFile; Path storagePath = basePath.resolve("blockIndex" + storageId); currentStorage = new AggregatedReferenceBlockStorage(storagePath); } storageCounter++; return currentStorage; } /** * This is anyway a very expensive operation, since it requires to apply the permutation function. */ public IndexPair[] getNearestNeighboursPairs(long[] key, int beamRadius) { throw new UnsupportedOperationException("not yet implemented"); } /** * Will return a super set of the elements within the beamRadius * * TODO: Returns non-permuted signature which breaks the API */ public int[] getNearestNeighboursElementIds(long[] key, int beamRadius) { ReferenceBlock containingBlock = getBlockFor(key); ReferenceBlock lowerBlock = null; ReferenceBlock higherBlock = null; IntList neighbours = new IntArrayList(3 * blockSize); if (containingBlock == null) { higherBlock = firstBlock; } else { neighbours.addElements(neighbours.size(), containingBlock.getElements()); lowerBlock = containingBlock.getPreviousBlock(); higherBlock = containingBlock.getNextBlock(); } int fetchSmallerElements = beamRadius, fetchGreaterElements = beamRadius; while (lowerBlock != null && fetchSmallerElements > 0) { neighbours.addElements(neighbours.size(), lowerBlock.getElements()); fetchSmallerElements -= lowerBlock.getSize(); lowerBlock = lowerBlock.getPreviousBlock(); } while (higherBlock != null && fetchGreaterElements > 0) { neighbours.addElements(neighbours.size(), higherBlock.getElements()); fetchGreaterElements -= higherBlock.getSize(); higherBlock = higherBlock.getNextBlock(); } return neighbours.toArray(new int[neighbours.size()]); } @Override public void insertElement(IndexPair pair) throws IOException { if (!bitSignatureIndex.contains(pair.getElementId())) { throw new RuntimeException("Element not in bit signature index: "+ pair); } // If there is no block yet, allocate one and insert the element. if (firstBlock == null) { firstBlock = createNewBlock(); firstBlock.insertElement(pair.getElementId(), pair.getBitSignature(), 0); } else { ReferenceBlock block = getBlockFor(pair.getBitSignature()); if (block == null) { // If there is no block that might contain the pair, all blocks // have a greater start key. // So add to the first block. block = firstBlock; } if (block.getSize() < block.getCapacity()) { int position = determineBlockPositionForElement(block, pair); block.insertElement(pair.getElementId(), pair.getBitSignature(), position); } else { // Split the block and add the elements: // 1. Create a new block and link it right after the current // block. ReferenceBlock newBlock = createNewBlock(); newBlock.setPreviousBlock(block); newBlock.setNextBlock(block.getNextBlock()); block.setNextBlock(newBlock); if (newBlock.getNextBlock() != null) { newBlock.getNextBlock().setPreviousBlock(newBlock); } // 2. Retrieve all elements and spread them over the new blocks. IndexPair[] pairs = resolveBlock(block); int splitIndex = pairs.length / 2 + 1; bulkLoadBlock(block, pairs, 0, splitIndex); bulkLoadBlock(newBlock, pairs, splitIndex, pairs.length - splitIndex); // 3. Find the target block for the new element and add it. if (BitSignatureUtil.COMPARATOR.compare(pair.getBitSignature(), newBlock.getStartKey()) < 0) { int insertIndex = determineBlockPositionForElement(block, pair); block.insertElement(pair.getElementId(), pair.getBitSignature(), insertIndex); } else { int insertIndex = determineBlockPositionForElement(newBlock, pair); newBlock.insertElement(pair.getElementId(), pair.getBitSignature(), insertIndex); } } } } protected int determineBlockPositionForElement(ReferenceBlock block, IndexPair pair) { IndexPair[] resolvedBlock = resolveBlock(block); for (int i = 0; i < resolvedBlock.length; i++) { IndexPair resolvedPair = resolvedBlock[i]; if (BitSignatureUtil.COMPARATOR.compare(resolvedPair.getBitSignature(), pair.getBitSignature()) > 0) { return i; } } return resolvedBlock.length; } /** * Gets elements with permuted signatures for the supplied block. * * @param block * @return */ protected IndexPair[] resolveBlock(ReferenceBlock block) { int[] elementIds = block.getElements(); IndexPair[] resolvedElements = new IndexPair[elementIds.length]; for (int i = 0; i < elementIds.length; i++) { int elementId = elementIds[i]; IndexPair pair = bitSignatureIndex.getIndexPair(elementId); long[] permutedSignature = permutationFunction.permute(pair.getBitSignature()); resolvedElements[i] = new IndexPair(permutedSignature, elementId); } return resolvedElements; } protected void bulkLoadBlock(ReferenceBlock block, IndexPair[] pairs, int offset, int length) { if (length == 0) { return; } int[] elementIds = new int[pairs.length]; for (int i = 0; i < pairs.length; i++) { IndexPair pair = pairs[i]; if (!bitSignatureIndex.contains(pair.getElementId())) { throw new RuntimeException("Element not in bit signature index: "+ pair); } elementIds[i] = pair.getElementId(); } block.bulkLoad(elementIds, offset, length, pairs[offset].getBitSignature()); } @Override public void deleteElement(long[] key) { throw new UnsupportedOperationException("not implemented"); } @Override public int getElement(long[] key) { ReferenceBlock block = getBlockFor(key); if (block == null) throw new IllegalArgumentException("Key not present in index."); int[] elementIds = block.getElements(); for (int elementId : elementIds) { long[] associatedKey = bitSignatureIndex.getIndexPair(elementId).getBitSignature(); long[] permutedKey = permutationFunction.permute(associatedKey); if (BitSignatureUtil.COMPARATOR.compare(key, permutedKey) == 0) { return elementId; } } throw new IllegalArgumentException("No such entry found in the block: " + Arrays.toString(key)); } /** * Currently not implemented. An implementation would have to resolve the permuted signatures of all contained blocks * which is anyway a rather intensive task, such that iterating over all IndexPairs is not recommended for instances of this index. */ @Override public Iterator<IndexPair> iterator() { throw new UnsupportedOperationException("not implemented"); } public void setBitSignatureIndex(BitSignatureIndex bitSignatureIndex) { this.bitSignatureIndex = bitSignatureIndex; } public void setPermutationFunction(PermutationFunction permutationFunction) { this.permutationFunction = permutationFunction; } }
true
64e4f0f2b60078d952273be494ee8f9facbd2a1b
Java
jackdeadman/OpenGL-Art-Gallery
/models/Room.java
UTF-8
11,132
2.625
3
[]
no_license
package models; import com.jogamp.opengl.*; import engine.*; import engine.render.*; import engine.scenegraph.*; import engine.utils.*; import gmaths.*; import meshes.*; import shaders.shaderconfigurators.MultiLightShader; import shaders.shaderconfigurators.OneTextureShader; public class Room extends Model { /** * @author Jack Deadman */ private Mesh floor, back, left, right, roof, front, rug; // defaults private float floorWidth = 16, floorLength = 12, ceilingHeight = 10; private NameNode floorName; private int[] floorTexture, backWallTexture, backWallNormal, backWallBlend, windowTexture , beamsTexture, wallpaperTexture , ceilingTexture, rugTexture; public enum WallPosition { LEFT_CLOSE, LEFT_MIDDLE, LEFT_FAR, RIGHT_CLOSE, RIGHT_MIDDLE, RIGHT_FAR }; private TransformNode moveLeftWall; public Room(WorldConfiguration worldConfig, int floorWidth, int floorLength, int ceilingHeight) { super(worldConfig); this.floorWidth = floorWidth; this.floorLength = floorLength; this.ceilingHeight = ceilingHeight; } protected void start(GL3 gl) { loadTextures(gl); loadMeshes(gl); buildSceneGraph(); } public void addPictureToWall(WallPosition pos, PictureFrame picture) { SGNode wallPosition = pictureFrameTransformations[0]; switch (pos) { case LEFT_CLOSE: wallPosition = pictureFrameTransformations[0]; break; case LEFT_MIDDLE: wallPosition = pictureFrameTransformations[1]; break; case LEFT_FAR: wallPosition = pictureFrameTransformations[2]; break; case RIGHT_CLOSE: wallPosition = pictureFrameTransformations[3]; break; case RIGHT_MIDDLE: wallPosition = pictureFrameTransformations[4]; break; case RIGHT_FAR: wallPosition = pictureFrameTransformations[5]; break; } // Stops the fighting with frame TransformNode nudge = new TransformNode("Translate(0f, 0.1f, 0f);", Mat4Transform.translate(0.0f, 0.1f, 0.0f)); wallPosition.addChild(nudge); nudge.addChild(picture.getRoot()); getRoot().update(); } public final String FLOOR_TEXTURE_PATH = "textures/wood_floor.jpg"; // backWallNormal, backWallTexture, backWallBlend public final String BACK_WALL_TEXTURE_PATH = "textures/wall_wood.jpg"; public final String BACK_WALL_NORMAL_PATH = "textures/wall_wood_normal.jpg"; public final String BACK_WALL_BLEND_PATH = "textures/window_mask.jpg"; public final String WINDOW_TEXTURE_PATH = "textures/window.jpg"; public final String BEAMS_PATH = "textures/window_black.jpg"; public final String WALLPAPER_PATH = "textures/wallpaper.jpg"; public final String CEILING_PATH = "textures/ceiling.jpg"; public final String RUG_PATH = "textures/rug.jpg"; public final String BACK_WALL_SHADER_PATH = "shaders/glsl/backwall.fs.glsl"; public final String BLEND_WALL_SHADER_PATH = "shaders/glsl/blend_wall.fs.glsl"; private void loadTextures(GL3 gl) { floorTexture = TextureLibrary.loadTexture(gl, FLOOR_TEXTURE_PATH); backWallTexture = TextureLibrary.loadTexture(gl, BACK_WALL_TEXTURE_PATH); backWallNormal = TextureLibrary.loadTexture(gl, BACK_WALL_NORMAL_PATH); backWallBlend = TextureLibrary.loadTexture(gl, BACK_WALL_BLEND_PATH); windowTexture = TextureLibrary.loadTexture(gl, WINDOW_TEXTURE_PATH); beamsTexture = TextureLibrary.loadTexture(gl, BEAMS_PATH); wallpaperTexture = TextureLibrary.loadTexture(gl, WALLPAPER_PATH); ceilingTexture = TextureLibrary.loadTexture(gl, CEILING_PATH); rugTexture = TextureLibrary.loadTexture(gl, RUG_PATH); } private SGNode[] pictureFrameTransformations = new SGNode[6]; private void createPictureFrames() { // Could probably do this better, but it's easier to read when together pictureFrameTransformations[0] = new TransformNode("Place near picture",Mat4Transform.translate(-6.5f,0f, 0f)); pictureFrameTransformations[1] = new NameNode("Left Picture Frames"); pictureFrameTransformations[2] = new TransformNode("Place far picture",Mat4Transform.translate(6.5f,0f, 0f)); pictureFrameTransformations[1].addChild(pictureFrameTransformations[0]); pictureFrameTransformations[1].addChild(pictureFrameTransformations[2]); pictureFrameTransformations[3] = new TransformNode("Place near picture",Mat4Transform.translate(-6.5f,0f, 0f)); pictureFrameTransformations[4] = new NameNode("Right Picture Frames"); pictureFrameTransformations[5] = new TransformNode("Place fair picture",Mat4Transform.translate(6.5f,0f, 0f)); pictureFrameTransformations[4].addChild(pictureFrameTransformations[3]); pictureFrameTransformations[4].addChild(pictureFrameTransformations[5]); } private void loadMeshes(GL3 gl) { // make meshes floor = new TwoTriangles(gl, new OneTextureShader(gl, floorTexture)); // Unique one off shader so making it here instead of making a new ShaderConfigurator MultiLightShader backShaderProgram = new MultiLightShader(gl, BACK_WALL_SHADER_PATH); backShaderProgram.addTexture("normalTexture", backWallNormal); backShaderProgram.addTexture("mainTexture", backWallTexture); backShaderProgram.addTexture("blendTexture", backWallBlend); backShaderProgram.addTexture("windowTexture", windowTexture); back = new TwoTriangles(gl, backShaderProgram); // Same again MultiLightShader blendShader = new MultiLightShader(gl, BLEND_WALL_SHADER_PATH); blendShader.addTexture("first_texture", beamsTexture); blendShader.addTexture("second_texture", wallpaperTexture); // All these sides have the same texturing left = new TwoTriangles(gl, blendShader); right = new TwoTriangles(gl, blendShader); // Being lazy here, could add a door and stuff, but mostly likely this // wall won't even be seen most of the time. front = new TwoTriangles(gl, blendShader); roof = new TwoTriangles(gl, new OneTextureShader(gl, ceilingTexture)); rug = new TwoTriangles(gl, new OneTextureShader(gl, rugTexture)); registerMeshes(new Mesh[] { floor, back, left, right, roof, front, rug }); } private void buildSceneGraph() { TransformNode floorTransform = new TransformNode( "Transform floor", Mat4Transform.scale(floorWidth, 1, floorLength) ); TransformNode backTransform = new TransformNode( "Transform back wall", Mat4.multiplyVariable( Mat4Transform.translate(0, ceilingHeight / 2.0f, -floorLength / 2.0f), Mat4Transform.scale(floorWidth, ceilingHeight, 1), Mat4Transform.rotateAroundX(90.0f) ) ); TransformNode scaleLeftWall = new TransformNode( "Scale left wall", Mat4Transform.scale(floorLength, 1, ceilingHeight)); moveLeftWall = new TransformNode( "Move left wall", Mat4.multiplyVariable( Mat4Transform.translate(-floorWidth/2.0f, ceilingHeight / 2.0f, 0), Mat4Transform.rotateAroundZ(-90.0f), Mat4Transform.rotateAroundY(90.0f) // Mat4Transform.rotateAroundZ(10.0f) ) ); TransformNode scaleRightWall = new TransformNode( "Scale right wall", Mat4Transform.scale(floorLength, 1, ceilingHeight)); TransformNode moveRightWall = new TransformNode( "Move right wall", Mat4.multiplyVariable( Mat4Transform.translate(floorWidth/2.0f, ceilingHeight / 2.0f, 0), Mat4Transform.rotateAroundZ(90.0f), Mat4Transform.rotateAroundY(-90.0f) ) ); TransformNode roofTransform = new TransformNode( "Transform roof", Mat4.multiplyVariable( Mat4Transform.scale(floorWidth, 1, floorLength), Mat4Transform.translate(0.0f, ceilingHeight, 0), Mat4Transform.rotateAroundX(180.0f) ) ); TransformNode frontTransform = new TransformNode( "Transform front wall", Mat4.multiplyVariable( Mat4Transform.translate(0, ceilingHeight / 2.0f, floorLength / 2.0f), Mat4Transform.scale(floorWidth, ceilingHeight, 1), Mat4Transform.rotateAroundX(-90.0f) ) ); MeshNode floorShape = new MeshNode("TwoTriangles (floor)", floor); MeshNode backShape = new MeshNode("TwoTriangles (back)", back); MeshNode leftShape = new MeshNode("TwoTriangles (left)", left); MeshNode rightShape = new MeshNode("TwoTriangles (right)", right); MeshNode roofShape = new MeshNode("TwoTriangles (roof)", roof); MeshNode frontShape = new MeshNode("TwoTriangles (front)", front); MeshNode rugShape = new MeshNode("TwoTriangles (Rug)", rug); TransformNode rugTransform = new TransformNode("Transform rug", Mat4.multiply( Mat4Transform.translate(0f, 0.01f, 0f), Mat4Transform.scale(5f, 1f, 7f) ) ); createPictureFrames(); SGNode leftPictures = pictureFrameTransformations[1]; SGNode rightPictures = pictureFrameTransformations[4]; // This will be the anchor, things inside the room will be a child // of the floor. floorName = new NameNode("Floor"); // Create the graph SGNode root = new NameNode("Room"); root.addChild(floorName); floorName.addChild(floorTransform); floorTransform.addChild(floorShape); floorName.addChild(backTransform); backTransform.addChild(backShape); floorName.addChild(moveLeftWall); moveLeftWall.addChild(leftPictures); moveLeftWall.addChild(scaleLeftWall); scaleLeftWall.addChild(leftShape); floorName.addChild(moveRightWall); moveRightWall.addChild(rightPictures); moveRightWall.addChild(scaleRightWall); scaleRightWall.addChild(rightShape); floorName.addChild(roofTransform); roofTransform.addChild(roofShape); floorName.addChild(frontTransform); frontTransform.addChild(frontShape); floorName.addChild(rugTransform); rugTransform.addChild(rugShape); root.update(); setRoot(root); } public SGNode getAnchor() { return floorName; } }
true
e0ae1235e50080caffb8d5144a2041054189e8ed
Java
layanmal/Networking-and-Cybersecurity
/Networking-Hws/Source/org/litesoft/p2pchat/UserDialogAWT.java
UTF-8
10,569
2.3125
2
[]
no_license
package org.litesoft.p2pchat; import java.awt.*; import java.awt.List; import java.awt.event.*; import java.util.*; // Copyright Status: // // All Software available from LiteSoft.org (including this file) is // hereby released into the public domain. // // It is free! As in, you may use it freely in both commercial and // non-commercial applications, bundle it with your software // distribution, include it on a CD-ROM, list the source code in a book, // mirror the documentation at your own web site, or use it in any other // way you see fit. // // NO Warranty! // // All software is provided "as is". // // There is ABSOLUTELY NO WARRANTY OF ANY KIND: not for the design, fitness // (for a particular purpose), level of errors (or lack thereof), or // applicability of this software. The entire risk as to the quality // and performance of this software is with you. Should this software // prove defective, you assume the cost of all necessary servicing, repair // or correction. // // In no event unless required by applicable law or agreed to in writing // will any party who created or may modify and/or redistribute this // software, be liable to you for damages, including any general, // special, incidental or consequential damages arising out of the use or // inability to use this software (including but not limited to loss of // data or data being rendered inaccurate or losses sustained by you or // third parties or a failure of this software to operate with any // other programs), even if such holder or other party has been advised // of the possibility of such damages. // // NOTE: Should you discover a bug, have a recogmendation for a change, wish // to submit modifications, or wish to add new classes/functionality, // please email them to: // // changes@litesoft.org // /** * @author Devin Smith and George Smith * @version 0.3 02/02/02 Added IllegalArgument.ifNull for all public params that may not be null * @version 0.2 01/28/02 Refactored and Added Licence * @version 0.1 12/27/01 Initial Version */ public class UserDialogAWT extends Frame implements UserDialog { private MyInfo zMyInfo; private ActivePeerManager zActivePeerManager = null; private PendingPeerManager zPendingPeerManager = null; private TextField zChatText; private TextField zNameText; private TextArea zMessagesTextArea; private List zPeersList; private Map zPrivateMessagersMap = new HashMap(); public UserDialogAWT( String pTitle , MyInfo pMyInfo ) { super( pTitle ); IllegalArgument.ifNull( "Title" , pTitle ); IllegalArgument.ifNull( "MyInfo" , zMyInfo = pMyInfo ); setLayout( new BorderLayout() ); add( "North" , layoutNamePanel() ); add( "Center" , layoutReceivedMessagesPanel() ); add( "East" , layoutWhoPanel() ); add( "South" , layoutChatEntryPanel() ); pack(); addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); show(); showWho(); zChatText.requestFocus(); } public void setActivePeerManager( ActivePeerManager pActivePeerManager ) { if ( pActivePeerManager != null ) zActivePeerManager = pActivePeerManager; } public void setPendingPeerManager( PendingPeerManager pPendingPeerManager ) { if ( pPendingPeerManager != null ) zPendingPeerManager = pPendingPeerManager; } private Panel layoutChatEntryPanel() { Panel panel = new Panel(); panel.setLayout( new BorderLayout() ); panel.add( "West" , new Label( "Message to Send:" ) ); panel.add( "Center" , zChatText = new TextField() ); zChatText.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { handleCHAT( e.getActionCommand() ); zChatText.setText( "" ); } } ); return panel; } private Panel layoutReceivedMessagesPanel() { Panel panel = new Panel(); panel.setLayout( new BorderLayout() ); panel.add( "North" , new Label( "Received Messages:" ) ); panel.add( "Center" , zMessagesTextArea = new TextArea() ); zMessagesTextArea.setEnabled( true ); zMessagesTextArea.setEditable( false ); return panel; } private Panel layoutWhoPanel() { Panel panel = new Panel(); panel.setLayout( new BorderLayout() ); panel.add( "North" , new Label( "Who's On:" ) ); panel.add( "Center" , zPeersList = new List( 25 , false ) ); zPeersList.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { String lineRest = e.getActionCommand(); int spaceAt = lineRest.indexOf( ' ' ); if ( spaceAt != -1 ) handlePrivateMessageWindowRequest( lineRest.substring( 0 , spaceAt ) ); zChatText.requestFocus(); } } ); return panel; } private Panel layoutNamePanel() { Panel panel = new Panel(); panel.setLayout( new FlowLayout( FlowLayout.LEFT ) ); panel.add( new Label( "Name:" , Label.RIGHT ) ); panel.add( zNameText = new TextField( "" , 15 ) ); zNameText.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { handleNAMEchange( e.getActionCommand().trim() ); zNameText.setText( "" ); showWho(); zChatText.requestFocus(); } } ); return panel; } private void send( String pMessage ) { String current = zMessagesTextArea.getText(); current += pMessage + "\n"; zMessagesTextArea.setText( current ); } private void showWho() { zPeersList.removeAll(); zPeersList.add( zMyInfo.toString() , 0 ); PeerInfo[] peers = getPeerInfos(); for ( int i = 0 ; i < peers.length ; i++ ) zPeersList.add( peers[ i ].toString() , i + 1 ); } public void showUnrecognized( PeerInfo pPeerInfo , String pBadMessage ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); IllegalArgument.ifNull( "BadMessage" , pBadMessage ); send( "Unrecognized Command from (" + pPeerInfo.getID() + " " + pPeerInfo.getChatName() + "): " + pBadMessage ); } public void showStreamsFailed( PeerInfo pPeerInfo ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); send( "Unable to Set up I/O Streams with: " + pPeerInfo.toString() ); } public void showConnectFailed( PeerInfo pPeerInfo ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); send( "Unable to Connect to: " + pPeerInfo.toString() ); } public void showConnect( PeerInfo pPeerInfo ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); showWho(); } public void showDisconnect( PeerInfo pPeerInfo ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); UserDialogPrivateMessageAWT subWindow = getPrivateMessageWindow( pPeerInfo ); if ( subWindow != null ) { unregisterPrivateMessager( pPeerInfo ); subWindow.dispose(); } showWho(); } public void showCHAT( PeerInfo pPeerInfo , String pMessage ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); IllegalArgument.ifNull( "Message" , pMessage ); send( pPeerInfo.getID() + " " + pPeerInfo.getChatName() + ": " + pMessage ); } public void showPMSG( PeerInfo pPeerInfo , String pMessage ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); IllegalArgument.ifNull( "Message" , pMessage ); UserDialogPrivateMessageAWT subWindow = getPrivateMessageWindow( pPeerInfo ); if ( subWindow != null ) subWindow.send( pPeerInfo.getChatName() + ": " + pMessage ); else send( "Private Message From (" + pPeerInfo.getID() + " " + pPeerInfo.getChatName() + "): " + pMessage ); } public void showNAME( PeerInfo pPeerInfo ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); showWho(); } public void showHELO( PeerInfo pPeerInfo ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); showWho(); } private UserDialogPrivateMessageAWT getPrivateMessageWindow( PeerInfo pPeerInfo ) { return (UserDialogPrivateMessageAWT) zPrivateMessagersMap.get( pPeerInfo ); } public void unregisterPrivateMessager( PeerInfo pPeerInfo ) { IllegalArgument.ifNull( "PeerInfo" , pPeerInfo ); zPrivateMessagersMap.remove( pPeerInfo ); } private void openPrivateMessageWindow( ActivePeer other ) { zPrivateMessagersMap.put( other.getPeerInfo() , new UserDialogPrivateMessageAWT( this , zMyInfo , other ) ); } private void handleCHAT( String pLine ) { if ( zActivePeerManager == null ) // builder pattern send( "No Peer Manager!" ); else { zActivePeerManager.sendToAllCHAT( pLine ); send( zMyInfo.getChatName() + ": " + pLine ); } } private void handleNAMEchange( String newName ) { if ( zActivePeerManager == null ) // builder pattern send( "No Peer Manager!" ); else { zMyInfo.setChatName( newName ); zActivePeerManager.sendToAllNAME(); } } private PeerInfo[] getPeerInfos() { return (zActivePeerManager != null) ? zActivePeerManager.getPeerInfos() : new PeerInfo[ 0 ]; // builder pattern } private void handlePrivateMessageWindowRequest( String id ) { if ( zActivePeerManager == null ) // builder pattern send( "No Peer Manager!" ); else { ActivePeer other = zActivePeerManager.getPeerListenerByID( id ); if ( other == null ) send( "Unrecognized Peer ID: " + id ); else openPrivateMessageWindow( other ); } } }
true
ecd7ec4ff53b2ce499b6ea2e0fd6d124a8fe3dfd
Java
CODERS-BAY/java-christmas-exercise-GoranMatev
/task1/model/Sledge.java
UTF-8
127
1.914063
2
[]
no_license
package model; // Sledge = Schlitten public class Sledge { public Sledge() { // TODO Auto-generated constructor stub } }
true
720653983de107a2677146838f8231adb30ec43f
Java
vsultanova/Hillel_Homeworks
/homework_2_1/Devision.java
UTF-8
124
1.5625
2
[]
no_license
package src; public class Devision { public static void devision (){ System.out.println("/"); } }
true
97ea0913250f1a04a2550798b0dc52524977d0c7
Java
code10ftn/restaurant-reservations
/src/main/java/com/code10/isa/model/FoodType.java
UTF-8
77
1.882813
2
[ "MIT" ]
permissive
package com.code10.isa.model; public enum FoodType { SALAD, FRIED }
true
d1c2952eef5e40e89f09376c0ea2a5ed8f84a7c0
Java
juyuan-yang/IRrelated
/StatisticalDebug/src/edu/gatech/ir/ochiai/Runner.java
UTF-8
3,670
2.609375
3
[]
no_license
package edu.gatech.ir.ochiai; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class Runner { private static Map<String, String> id2bb = new HashMap<String, String>(); private static Map<String, Set<String>> id2PassTests = new HashMap<String, Set<String>>(); private static Map<String, Set<String>> id2FailTests = new HashMap<String, Set<String>>(); private static List<bbInfo> rankedList = new ArrayList<bbInfo>(); private static int passedTests = 0; private static int failedTests = 0; private static int topNum = 50; public static void main(String[] args) { if (args.length != 4) { System.out.println("There must be 4 arguments: "); System.out.println(" arg[0], the folder for passed traces"); System.out.println(" arg[1], the folder for failed traces"); System.out.println(" arg[2], the file to store the map between each basic block and its id"); System.out.println(" arg[3], the file to store results"); } String passedPath = args[0], failedPath = args[1], bbMapPath = args[2], resFile = args[3]; // String passedPath = "passed", failedPath = "failed", bbMapPath = "bbMap.txt", resFile = "res.txt"; readBBMap(bbMapPath); readTestRes(passedPath, id2PassTests, true); readTestRes(failedPath, id2FailTests, false); calSuspicious(); try{ PrintWriter writer = new PrintWriter(new File(resFile)); for(int i = 0; i < rankedList.size() && i < topNum; i++) writer.println(rankedList.get(i).toString()); writer.close(); } catch(Exception e){ e.printStackTrace(); } for(int i = 0; i < rankedList.size() && i < topNum; i++) System.out.println(rankedList.get(i).toString()); } public static void calSuspicious(){ for(Entry<String, Set<String>> entry : id2FailTests.entrySet()){ int exeInPass = id2PassTests.get(entry.getKey()).size(); int exeInFail = entry.getValue().size(); double score = exeInFail / Math.sqrt(failedTests * (exeInFail + exeInPass)); bbInfo bb = new bbInfo(entry.getKey(), id2bb.get(entry.getKey()), score); rankedList.add(bb); } Collections.sort(rankedList); } public static void readTestRes(String folderPath, Map<String, Set<String>> id2test, boolean checkPassed){ try { File folder = new File(folderPath); if(folder.isDirectory()){ File[] files = folder.listFiles(); if(checkPassed) passedTests = files.length; else failedTests = files.length; for(File f : files){ String s, testName = f.getName().trim(); BufferedReader reader = new BufferedReader(new FileReader(f)); while((s = reader.readLine()) != null){ s = s.trim(); id2test.get(s).add(testName); } reader.close(); } } else { System.out.println(folderPath + " is not a folder! Please check..."); } } catch(Exception e) { e.printStackTrace(); } } public static void readBBMap(String file){ try{ BufferedReader reader = new BufferedReader(new FileReader(new File(file))); String s; while((s = reader.readLine()) != null){ String[] strs = s.split(" "); strs[0] = strs[0].trim(); strs[1] = strs[1].trim(); id2bb.put(strs[1], strs[0]); Set<String> passSet = new HashSet<String>(); id2PassTests.put(strs[1], passSet); Set<String> failSet = new HashSet<String>(); id2FailTests.put(strs[1], failSet); } reader.close(); } catch(Exception e){ e.printStackTrace(); } } }
true
3f72f6b33f2a50ff5425b48418a05fa9cacdec67
Java
harishpadmanabh-HP/Retrofit_JSON_Parsing
/app/src/main/java/com/hp/hp/retrofit_json_parsing/Api.java
UTF-8
660
2.5625
3
[]
no_license
package com.hp.hp.retrofit_json_parsing; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; public interface Api { //Retrofic divides url in 2 parts.base url and the apicall .api call is the last the section of url. //5.now define base url String BASE_URL = "https://simplifiedcoding.net/demos/"; //url accepts get method and give us dome data .so we create @GET request //6.call marvel from base url @GET("marvel") //return type is call.list is call type.Hero is the object with data json arrays.make getheroes(); //7.go to main activity and create retrofit object Call<List<Hero>> getHeroes(); }
true
34cb47cec45d4be0ade38f9d8d1782d0ad4b486b
Java
zxxroot/ymzl
/小贷平台反编译/cashloan-base/cashloan-rc/src/main/java/com/rongdu/cashloan/rc/mapper/SceneBusinessLogMapper.java
UTF-8
961
1.890625
2
[]
no_license
package com.rongdu.cashloan.rc.mapper; import com.rongdu.cashloan.core.common.mapper.BaseMapper; import com.rongdu.cashloan.core.common.mapper.RDBatisDao; import com.rongdu.cashloan.rc.domain.SceneBusinessLog; import java.util.List; import org.apache.ibatis.annotations.Param; @RDBatisDao public abstract interface SceneBusinessLogMapper extends BaseMapper<SceneBusinessLog, Long> { public abstract int countUnFinishLog(SceneBusinessLog paramSceneBusinessLog); public abstract List<SceneBusinessLog> findSceneLogUnFinish(SceneBusinessLog paramSceneBusinessLog); public abstract SceneBusinessLog findLastExcute(@Param("userId") Long paramLong1, @Param("busId") Long paramLong2); public abstract void deleteByUserId(@Param("userId") Long paramLong); public abstract SceneBusinessLog findLastExcuteByPhone(@Param("phone") String paramString, @Param("busId") Long paramLong); public abstract void deleteByPhone(String paramString); }
true
b73e66b3ce3f725f98970074977059217d2b6df5
Java
AlexVulpoiu/Stocks_management
/src/database/repository/AudioSpeakerRepository.java
UTF-8
5,321
2.796875
3
[ "MIT" ]
permissive
package database.repository; import database.config.DatabaseConfiguration; import stocks_management.category.Category; import stocks_management.distributor.Distributor; import stocks_management.product.AudioSpeaker; import stocks_management.services.StockService; import java.sql.*; import java.util.ArrayList; import java.util.List; public class AudioSpeakerRepository { public AudioSpeaker save(AudioSpeaker audioSpeaker) { try(Connection connection = DatabaseConfiguration.getDatabaseConnection()) { String query = "insert into audio_speakers(id, name, category_id, distributor_id, price, stock, warranty, power, is_wireless, has_bluetooth)\n" + "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, audioSpeaker.getProductId()); preparedStatement.setString(2, audioSpeaker.getProductName()); preparedStatement.setString(3, audioSpeaker.getProductCategory().getCategoryId()); preparedStatement.setString(4, audioSpeaker.getProductDistributor().getDistributorId()); preparedStatement.setDouble(5, audioSpeaker.getPrice()); preparedStatement.setInt(6, audioSpeaker.getStock()); preparedStatement.setInt(7, audioSpeaker.getWarranty()); preparedStatement.setInt(8, audioSpeaker.getPower()); preparedStatement.setBoolean(9, audioSpeaker.isWireless()); preparedStatement.setBoolean(10, audioSpeaker.hasBluetooth()); preparedStatement.execute(); return audioSpeaker; } catch(SQLException exception) { throw new RuntimeException("Something went wrong while saving the audio speaker: " + audioSpeaker); } } public List<AudioSpeaker> findAll() { List<AudioSpeaker> audioSpeakers = new ArrayList<>(); try(Connection connection = DatabaseConfiguration.getDatabaseConnection()) { String query = "select * from audio_speakers"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query); while(resultSet.next()) { audioSpeakers.add(mapToAudioSpeaker(resultSet)); } resultSet.close(); return audioSpeakers; } catch(SQLException exception) { throw new RuntimeException("Something went wrong while trying to get all audio speakers!"); } } private AudioSpeaker mapToAudioSpeaker(ResultSet resultSet) throws SQLException { StockService stockService = StockService.getInstance(); String categoryId = resultSet.getString(3), distributorId = resultSet.getString(4); Category category = stockService.findCategoryById(categoryId); Distributor distributor = stockService.findDistributorById(distributorId); AudioSpeaker audioSpeaker = new AudioSpeaker(resultSet.getString(1), resultSet.getInt(6), resultSet.getString(2), category, distributor, resultSet.getDouble(5), resultSet.getInt(7), resultSet.getInt(8), resultSet.getBoolean(9), resultSet.getBoolean(10)); return audioSpeaker; } public void update(String id, Double price, Integer stock) { try(Connection connection = DatabaseConfiguration.getDatabaseConnection()) { String queryPrice = "{? = call change_audio_speaker_price(?, ?)}", queryStock = "{? = call change_audio_speaker_stock(?, ?)}"; if(price != null && price > 0.0) { CallableStatement callableStatement = connection.prepareCall(queryPrice); callableStatement.setString(2, id); callableStatement.setDouble(3, price); callableStatement.executeUpdate(); } if(stock != null && stock >= 0) { CallableStatement callableStatement = connection.prepareCall(queryStock); callableStatement.setString(2, id); callableStatement.setInt(3, stock); callableStatement.executeUpdate(); } } catch(SQLException exception) { throw new RuntimeException("Something went wrong while trying to update the audio speaker with id: " + id); } } public void delete(String id) { try(Connection connection = DatabaseConfiguration.getDatabaseConnection()) { String query = "delete from audio_speakers where id = '" + id + "'"; Statement statement = connection.createStatement(); statement.executeUpdate(query); } catch(SQLException exception) { throw new RuntimeException("Something went wrong while trying to delete the audio speaker with id: " + id); } } }
true
1cc106c727638d4df7b1383a1c5dd26d07c02c1c
Java
jhannes-playpen/batch-server-kata
/src/test/java/com/johannesbrodwall/batchserver/medications/FestFileBatchTest.java
UTF-8
4,439
1.90625
2
[]
no_license
package com.johannesbrodwall.batchserver.medications; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.time.Instant; import java.util.Random; import javax.sql.DataSource; import org.eaxy.Element; import org.eaxy.Namespace; import org.eaxy.Validator; import org.eaxy.Xml; import org.junit.Test; import com.johannesbrodwall.batchserver.TestDataSource; import com.johannesbrodwall.batchserver.batchfile.BatchFile; import com.johannesbrodwall.batchserver.batchfile.BatchFileRepository; public class FestFileBatchTest { private static final Namespace M30 = new Namespace("http://www.kith.no/xmlstds/eresept/m30/2014-12-01", "m30"); private Validator validator = Xml.validatorFromResource("R1808-eResept-M30-2014-12-01/ER-M30-2014-12-01.xsd"); private DataSource dataSource = TestDataSource.testDataSource(); private BatchFileRepository batchFileRepository = new BatchFileRepository(dataSource); @Test public void shouldReadFullFile() throws IOException { repository.deleteAll(); assertThat(repository.list()).isEmpty(); String file = "fest-mini.xml.gz"; processor.processFile(getClass().getResourceAsStream("/" + file), file); assertThat(repository.list()).isNotEmpty(); } @Test public void shouldUpdateStatus() throws IOException { repository.deleteAll(); String file = "fest-mini.xml.gz"; BatchFile batchFile = batchFileRepository.save("fest", file, getClass().getResourceAsStream("/" + file)); assertThat(batchFile.getStatus()).isEqualTo(BatchFile.Status.PENDING); FestFileBatch batch = new FestFileBatch(batchFile.getId(), () -> batchFileRepository, () -> repository); batch.start(); assertThat(batchFileRepository.retrieve(batchFile.getId()).getStatus()) .isEqualTo(BatchFile.Status.PROCESSING); batch.run(); assertThat(batchFileRepository.retrieve(batchFile.getId()).getStatus()) .isEqualTo(BatchFile.Status.COMPLETE); } @Test public void shouldReadInteractions() { Element interaksjon = M30.el("Interaksjon", M30.el("Id", "ID_06688DFC-BF07-4113-A6E4-9F8F00E5A536"), M30.el("Relevans").attr("V", "1").attr("DN", "Bør unngås"), M30.el("KliniskKonsekvens", "Risiko for toksiske..."), M30.el("Interaksjonsmekanisme", "Metylfenidat frigjør..."), M30.el("Kildegrunnlag").attr("V", "4").attr("DN", "Indirekte data"), M30.el("Substansgruppe", M30.el("Substans", M30.el("Substans", "Metylfenidat"), M30.el("Atc").attr("V", "N06BA05").attr("DN", "Metylfenidat"))), M30.el("Substansgruppe", M30.el("Substans", M30.el("Substans", "Moklobemid"), M30.el("Atc").attr("V", "N06AG02").attr("DN", "Moklobemid"))) ); validator.validate(katWrapper(interaksjon)); MedicationInteraction interaction = processor.readInteraction(oppfWrapper(interaksjon)); assertThat(interaction).hasNoNullFieldsOrProperties(); assertThat(interaction.getSubstanceCodes()).contains("N06BA05", "N06AG02"); assertThat(interaction.getId()).isEqualTo("ID_06688DFC-BF07-4113-A6E4-9F8F00E5A536"); assertThat(interaction.getClinicalConsequence()).isEqualTo("Risiko for toksiske..."); assertThat(interaction.getInteractionMechanism()).isEqualTo("Metylfenidat frigjør..."); } private Element katWrapper(Element el) { return M30.el("Kat" + el.tagName(), oppfWrapper(el)); } private Element oppfWrapper(Element el) { return M30.el("Oppf" + el.tagName(), M30.el("Id", "ID_" + random.nextInt()), M30.el("Tidspunkt", Instant.now().toString()), M30.el("Status", ""), el); } private Random random = new Random(); private MedicationInteractionRepository repository = new MedicationInteractionRepository(dataSource); private FestFileBatch processor = new FestFileBatch(repository); }
true
5deae66d2bbd2b8d6c00e514d9dd350f1969a084
Java
cwardcode/Capstone
/TrackerApps/TrackerTransmitter/src/com/cwardcode/TranTracker/Vehicle.java
UTF-8
717
3.421875
3
[]
no_license
package com.cwardcode.TranTracker; /** * @author Chris Ward * @version 12/15/2013 * * A class representing a Vehicle object */ public class Vehicle { /** Vehicle ID. */ private int id; /** Vehicle Name */ private String name; /** * Constructor for Vehicle . * @param id Vehicle ID. * @param name Vehicle Name */ public Vehicle(int id, String name){ this.id = id; this.name = name; } /** * Returns Vehicle ID. * @return id vehicle ID. */ public int getId(){ return id; } /** * Returns Vehicle Name. * @return name Vehicle Name */ public String getName() { return this.name; } }
true
d007c67d0359f3ee66842d70efb9903eef74e67f
Java
flywind2/joeis
/src/irvine/oeis/a110/A110224.java
UTF-8
330
2.640625
3
[]
no_license
package irvine.oeis.a110; import irvine.oeis.LinearRecurrence; /** * A110224 <code>a(n) = Fibonacci(n)^3 + Fibonacci(n+1)^3</code>. * @author Sean A. Irvine */ public class A110224 extends LinearRecurrence { /** Construct the sequence. */ public A110224() { super(new long[] {-1, -3, 6, 3}, new long[] {1, 2, 9, 35}); } }
true
9cdb2b45e84f53a2dc00d2f1b08cd9a38d9eeede
Java
itvincent-git/port-transformer
/port-transformer-common/src/main/java/net/port/transformer/annotation/PortPair.java
UTF-8
453
2.203125
2
[]
no_license
package net.port.transformer.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 注解在接口方法上,标明传入key, value到处理器 * Created by zhongyongsheng on 2018/4/13. */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.METHOD) public @interface PortPair { String key(); String value(); }
true
edcc9622cf8347ef58011407ac08e5e343524b65
Java
mmz1996/MmzJUCLearning
/src/state/TestStop.java
UTF-8
987
3.484375
3
[]
no_license
package state; /** * @Classname TestStop * @Description TODO * @Date 2020/12/8 9:34 * @Created by mmz */ // 建议线程正常停止——>利用次数,不建议死循环 // 建议使用标志位,设置一个标志位 // 不要使用stop,destroy等过时的方法 public class TestStop implements Runnable{ private boolean flag = true; @Override public void run() { int i = 0; while(flag){ System.out.println("线程正在运行" + i++); } } // 设置一个公开的方法,转换标志位 public void stop(){ this.flag = false; } public static void main(String[] args) { TestStop testStop = new TestStop(); new Thread(testStop).start(); for (int i = 0; i < 1000000; i++) { // System.out.println("main" + i); if(i == 90000){ testStop.stop(); System.out.println("线程该停止了"); } } } }
true
46aba029348a666256335799d6d09e2fd25a6ae2
Java
Mirage20/Carbon-SPI
/carbon-spi-test/carbon-spi-osgi-tests/src/test/java/org/wso2/osgi/spi/test/integration/VisibilityRestrictedConsumerTest.java
UTF-8
2,092
2.046875
2
[]
no_license
package org.wso2.osgi.spi.test.integration; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.hooks.weaving.WeavingHook; import org.testng.Assert; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.osgi.spi.processor.ConsumerProcessor; import java.nio.file.Paths; public class VisibilityRestrictedConsumerTest { Bundle consumerBundle; @BeforeClass public void setup(ITestContext iTestContext) throws BundleException { Object obj = iTestContext.getAttribute(TestConstants.BUNDLE_CONTEXT_ATTRIBUTE); if (obj instanceof BundleContext) { BundleContext bundleContext = (BundleContext) obj; ConsumerProcessor consumerProcessor = new ConsumerProcessor(); bundleContext.registerService(WeavingHook.class, consumerProcessor, null); bundleContext.installBundle(Paths.get(System.getProperty(TestConstants.BUILD_DIRECTORY_PROPERTY), "osgi", "test-artifacts", "carbon-spi-bundle.jar").toUri().toString()).start(); bundleContext.installBundle(Paths.get(System.getProperty(TestConstants.BUILD_DIRECTORY_PROPERTY), "osgi", "test-artifacts", "service-provider-api.jar").toUri().toString()).start(); bundleContext.installBundle(Paths.get(System.getProperty(TestConstants.BUILD_DIRECTORY_PROPERTY), "osgi", "test-artifacts", "service-provider-2.jar").toUri().toString()).start(); consumerBundle = bundleContext.installBundle( Paths.get(System.getProperty(TestConstants.BUILD_DIRECTORY_PROPERTY), "osgi", "test-artifacts", "service-consumer-1.jar").toUri().toString()); } } @Test public void testBundleStart() throws BundleException { consumerBundle.start(); Assert.assertEquals(consumerBundle.getState(), Bundle.ACTIVE, "Test if the consumer bundle is in Active state"); } }
true
ca3d3fd3802d1a3666d95903e592ebb10f40a55e
Java
danipr98/programaciondam1
/leer y escribir/src/leeryescribir/objetoalumno.java
UTF-8
3,938
3.265625
3
[]
no_license
package leeryescribir; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import javax.tools.Diagnostic; public class objetoalumno { public static void obj1(alumno a1) { try { /* * crear el archivo y la ruta para escribir */ ObjectOutputStream salida = new ObjectOutputStream(new FileOutputStream("C:\\Users\\jorge\\eclipse-workspace\\leer y escribir\\objeto.obj")); /* *escribe */ salida.writeObject(a1); //cierra salida.close(); // crerar el archivo para leer ObjectInputStream entrada = new ObjectInputStream(new FileInputStream("C:\\Users\\jorge\\eclipse-workspace\\leer y escribir\\objeto.obj")); //lee alumno obj = (alumno) entrada.readObject(); System.out.println("nombre " + a1.getNombre() + "apellido " + a1.getApellido()); //cierre entrada.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void array1() { try { //crear archivo de escritura ObjectOutputStream salida = new ObjectOutputStream(new FileOutputStream("C:\\Users\\jorge\\eclipse-workspace\\leer y escribir\\array.obj")); //creo el array de alumnos alumno[] alumnos = new alumno[4]; //creo el array de trings String[] nombre = { "dani", "pepe", "jose", "antonio", "luis" }; //creo variable para guardar los nombres int aleatorio = 0; //for para escribir el array for (int i = 0; i < alumnos.length; i++) { //meto de forma random entre los 4 nombres del string aleatorio = (int) (Math.random() * 4); //y aqui lo escribo en el array del alumno alumnos[i] = new alumno(nombre[aleatorio], "lopez"); } salida.writeObject(alumnos); salida.close(); //creo el archivo leer ObjectInputStream entrada = new ObjectInputStream(new FileInputStream("C:\\Users\\jorge\\eclipse-workspace\\leer y escribir\\array.obj")); //aqui creo un array nuevo cast y lo leo alumno[] alumnos3 = (alumno[]) entrada.readObject(); entrada.close(); //leo el array for (alumno alumno : alumnos3) { System.out.println(alumno.getNombre()); } } catch (Exception e) { System.out.println("error"); } } public static void file() { //creo un archivo File com = new File("C:\\Users\\jorge\\eclipse-workspace\\leer y escribir\\array.obj"); File bin = new File("bin"); if (com.exists()) { System.out.println("este fichero existe"); if (com.isDirectory()) { System.out.println("Es un directorio"); } else { System.out.println("Es un fichero"); } System.out.println(com.getAbsolutePath()); } else { System.out.println("El fichero no existe"); } String[] filles = bin.list(); for (String rutas : filles) { System.out.println(rutas); } File directorio = new File("PruebaDirectorio"); directorio.mkdir(); } public static void leer(alumno a1) { try { ObjectInputStream entrada1 = new ObjectInputStream(new FileInputStream("C:\\Users\\jorge\\eclipse-workspace\\leer y escribir\\alumno.obj")); alumno obj = (alumno) entrada1.readObject(); System.out.println("nombre " + a1.getNombre() + "apellido " + a1.getApellido()); entrada1.close(); ObjectInputStream entrada = new ObjectInputStream( new FileInputStream("C:\\Users\\jorge\\eclipse-workspace\\leer y escribir\\arrayses.obj")); alumno[] alumnos3 = (alumno[]) entrada.readObject(); entrada.close(); for (alumno alumno : alumnos3) { System.out.println(alumno.getNombre()); } } catch (Exception e) { System.out.println("error"); } } }
true
7221b0b7554a370840598a25e819ac2debc768cc
Java
htchepannou/pds-service
/src/main/java/com/tchepannou/pds/controller/AbstractController.java
UTF-8
2,710
2.296875
2
[]
no_license
package com.tchepannou.pds.controller; import com.google.common.base.Joiner; import com.tchepannou.core.exception.NotFoundException; import com.tchepannou.pds.dto.ErrorResponse; import com.tchepannou.pds.exception.BadRequestException; import org.slf4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.stream.Collectors; public abstract class AbstractController { //-- Abstract methods protected abstract Logger getLogger (); //-- Error Handlers @ExceptionHandler(BadRequestException.class) @ResponseStatus(value= HttpStatus.BAD_REQUEST) public ErrorResponse handleError( final HttpServletRequest request, final BadRequestException exception ) { return handleException(request, HttpStatus.BAD_REQUEST, exception.getMessage(), exception); } @ExceptionHandler(NotFoundException.class) @ResponseStatus(value= HttpStatus.NOT_FOUND) public ErrorResponse handleError( final HttpServletRequest request, final NotFoundException exception ) { return handleException(request, HttpStatus.NOT_FOUND, "not_found", exception); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value= HttpStatus.BAD_REQUEST) public ErrorResponse handleError( final HttpServletRequest request, final MethodArgumentNotValidException exception ) { final List<ObjectError> errors = exception.getBindingResult().getAllErrors(); final String message = Joiner .on(',') .join( errors .stream() .map(error -> error.getDefaultMessage()) .collect(Collectors.toList()) ); return handleException(request, HttpStatus.BAD_REQUEST, message, exception); } protected ErrorResponse handleException( final HttpServletRequest request, final HttpStatus status, final String message, final Exception exception ) { getLogger().error("{} {}{}", request.getMethod(), request.getRequestURI(), request.getQueryString() != null ? "?"+request.getQueryString() : "", exception); return new ErrorResponse(status, message); } }
true
6b1df8d821818fb3981893044c9a9da252d98dd4
Java
revanthreddy194/assessment-centric-software
/src/test/java/com/centric/assignment/controller/ProductControllerTest.java
UTF-8
4,769
2.265625
2
[]
no_license
package com.centric.assignment.controller; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Arrays; import java.util.List; import org.hamcrest.Matchers; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.centric.assignment.model.Product; import com.centric.assignment.model.ProductResponse; import com.centric.assignment.service.ProductService; import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootTest @AutoConfigureMockMvc public class ProductControllerTest { @MockBean ProductService productService; @Autowired private ObjectMapper objectMapper; @Autowired MockMvc mockMvc; @Test @DisplayName("POST /v1/products") public void testCreateProducts() throws Exception { List<String> tags = Arrays.asList("red", "shirt", "slim fit"); Product product = new Product("Red Shirt", "Red hugo boss shirt", "Hugo Boss", tags, "apparel"); ProductResponse productResponse = new ProductResponse("357cd2c8-6f69-4bea-a6fa-86e40af0d867","Red Shirt", "Red hugo boss shirt", "Hugo Boss", tags, "apparel","2021-08-25T01:02:03Z"); Mockito.when(productService.insertProduct(product)).thenReturn(productResponse); // Execute the POST request mockMvc.perform(MockMvcRequestBuilders .post("/v1/products") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(product))) // Validate the response code and content type .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) // Validate the returned fields .andExpect(jsonPath("$.id",Matchers.is("357cd2c8-6f69-4bea-a6fa-86e40af0d867"))) .andExpect(jsonPath("$.name",Matchers.is("Red Shirt"))) .andExpect(jsonPath("$.description",Matchers.is("Red hugo boss shirt"))) .andExpect(jsonPath("$.brand",Matchers.is("Hugo Boss"))) .andExpect(jsonPath("$.tags",Matchers.is(tags))) .andExpect(jsonPath("$.category",Matchers.is("apparel"))) .andExpect(jsonPath("$.created_at",Matchers.is("2021-08-25T01:02:03Z"))); } @Test @DisplayName("GET /v1/products") public void testGetProducts() throws Exception { List<String> tags = Arrays.asList("red", "shirt", "slim fit"); ProductResponse productOneResponse = new ProductResponse("357cd2c8-6f69-4bea-a6fa-86e40af0d867","Red Shirt", "Red hugo boss shirt", "Hugo Boss", tags, "apparel","2021-08-25T01:02:03Z"); ProductResponse productTwoResponse = new ProductResponse("345cd2c8-6f69-5bea-a7fa-12e64af0d651","Black Shirt", "Black hugo boss shirt", "Hugo Boss", tags, "apparel","2021-08-24T01:02:03Z"); Mockito.when(productService .getProduct(Mockito.anyInt(), Mockito.anyInt(), Mockito.any(String[].class), Mockito.anyString())).thenReturn(Arrays.asList(productOneResponse,productTwoResponse)); // Execute the GET request mockMvc.perform(MockMvcRequestBuilders .get("/v1/products") .param("category", "apparel") .contentType(MediaType.APPLICATION_JSON)) // Validate the response code and content type .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) // Validate the returned fields .andExpect(jsonPath("$[0].name",Matchers.is("Red Shirt"))) .andExpect(jsonPath("$[0].description",Matchers.is("Red hugo boss shirt"))) .andExpect(jsonPath("$[0].brand",Matchers.is("Hugo Boss"))) .andExpect(jsonPath("$[0].tags",Matchers.is(tags))) .andExpect(jsonPath("$[0].category",Matchers.is("apparel"))) .andExpect(jsonPath("$[0].created_at",Matchers.is("2021-08-25T01:02:03Z"))); } }
true
7efb28775d505763ceb13447f472b26176732ad8
Java
RonaldBernal/AmdroidRemoteJSON
/app/src/main/java/com/itesm/ronald/mobileappsjsonhw/MainActivity.java
UTF-8
1,646
2.1875
2
[]
no_license
package com.itesm.ronald.mobileappsjsonhw; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import java.util.ArrayList; public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener{ private String jsonURL = "https://raw.githubusercontent.com/RonaldBernal/AmdroidRemoteJSON/master/Contacts.json"; private ListView list; private ArrayList<Friend> friends = new ArrayList<Friend>(); private FriendAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.list = (ListView)findViewById(R.id.listView); this.adapter = new FriendAdapter(this, this.friends); this.list.setAdapter(this.adapter); this.list.setOnItemClickListener(this); } public void retrieveJSON(View v){ JsonRequest jreq = new JsonRequest(this, this.adapter, this.friends, list); jreq.execute(jsonURL); this.list.setLayoutParams(new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT )); findViewById(R.id.loadBtn).setVisibility(View.GONE); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { this.adapter.toogleVisibility(this.list, position); } }
true
33a669c1ae1d59b8c313a3af2ce058397fd2e153
Java
PTNUSASATUINTIARTHA-DOKU/SDK-Android
/sdkocov2/src/main/java/com/doku/sdkocov2/utils/SDKBase64.java
UTF-8
1,089
2.46875
2
[]
no_license
package com.doku.sdkocov2.utils; /** * Created by zaki on 4/28/16. */ public class SDKBase64 { private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); public SDKBase64() { } public static String encode(byte[] buf) { int size = buf.length; char[] ar = new char[(size + 2) / 3 * 4]; int a = 0; byte b2; byte mask; for (int i = 0; i < size; ar[a++] = ALPHABET[b2 & mask]) { byte b0 = buf[i++]; byte b1 = i < size ? buf[i++] : 0; b2 = i < size ? buf[i++] : 0; mask = 63; ar[a++] = ALPHABET[b0 >> 2 & mask]; ar[a++] = ALPHABET[(b0 << 4 | (b1 & 255) >> 4) & mask]; ar[a++] = ALPHABET[(b1 << 2 | (b2 & 255) >> 6) & mask]; } switch (size % 3) { case 1: --a; ar[a] = 61; case 2: --a; ar[a] = 61; default: return new String(ar); } } }
true
7be65c151919f56dc0beab3c068b0c7e22ee1b0e
Java
ipeonte/PetStoreDemo
/DemoServices/PetStoreDemoRest/src/main/java/com/example/demo/petstore/rest/jpa/repo/PetsRepository.java
UTF-8
368
2.09375
2
[ "Apache-2.0" ]
permissive
package com.example.demo.petstore.rest.jpa.repo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.example.demo.petstore.rest.jpa.model.Pet; @Repository public interface PetsRepository extends JpaRepository<Pet, Long> { public List<Pet> findAllByOrderByNameAsc(); }
true
3850069a2158ca094d4e9cf18fae48da1efddd61
Java
MZB5213/Mypro
/app/src/main/java/com/dyth/mzb/my/module/MyFocusModuleImpl.java
UTF-8
667
1.796875
2
[]
no_license
package com.dyth.mzb.my.module; import com.dyth.mzb.my.contact.MyFocusContract; import com.dyth.mzb.utils.RetrofitUtils; import com.dyth.mzb.utils.URLManger; import com.dyth.mzb.utils.network.NetworkCallBack; import java.util.HashMap; import java.util.Map; /** * Created by Lenovo on 2019/1/5. */ public class MyFocusModuleImpl implements MyFocusContract.IMyFocusModule { @Override public <T> void getMyFocus(NetworkCallBack<T> networkCallBack) { Map<String,Object> map = new HashMap<>(); map.put("userId","049de01db14a4c8184faa0aca7facf8a"); RetrofitUtils.getInstance().post(URLManger.DYTH_MYFOCUS,map,networkCallBack); } }
true
416539d21f88e87d79aec0f43a3035a66d2ede8d
Java
308229387/qiang_dan_shen_qi
/Commonlib/src/com/huangye/commonlib/vm/SourceViewModel.java
UTF-8
2,541
2.15625
2
[]
no_license
package com.huangye.commonlib.vm; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.huangye.commonlib.model.NetWorkModel; import com.huangye.commonlib.model.callback.NetworkModelCallBack; import com.huangye.commonlib.utils.JsonUtils; import com.huangye.commonlib.utils.NetBean; import com.huangye.commonlib.vm.callback.NetWorkVMCallBack; import java.util.List; import java.util.Map; public abstract class SourceViewModel implements NetworkModelCallBack{ protected NetWorkVMCallBack callBack; protected NetWorkModel t; protected Context context; public SourceViewModel(NetWorkVMCallBack callBack,Context context){ this.callBack = callBack; t = initListNetworkModel(context); this.context = context; } protected abstract NetWorkModel initListNetworkModel(Context context); @Override public void onLoadingCancell() { if(callBack!=null) callBack.onLoadingCancel(); } @Override public void onLoadingStart() { if(callBack!=null) callBack.onLoadingStart(); } @Override public void onLoadingFailure(String err) { if(callBack!=null) callBack.onLoadingError(err); } @Override public void onLoadingSuccess(NetBean bean, NetWorkModel model) { int status = bean.getStatus(); if(callBack!=null) { if (status == 0) { callBack.onLoadingSuccess(jsonTransferToMap(bean)); }else{ String msg = bean.getMsg(); if (!TextUtils.isEmpty(msg)) { callBack.onLoadingError(bean.getMsg()); } else { callBack.onLoadingError("连接失败!"); } } } } @Override public void noInternetConnect() { if(callBack!=null) { callBack.onNoInterNetError(); } } /** * 把json转化成map * @param bean * @return */ protected Map<String,String> jsonTransferToMap(NetBean bean){ Log.e("adsss", "balance:"+bean.getData()); return JsonUtils.jsonToMap(bean.getData()); } /** * 把json转化成list<Map> * @param bean * @return */ protected List<Map<String,String>> jsonTransferToListMap(NetBean bean){ return JsonUtils.jsonToListMap(bean.getData()); } /** * 详情页的转化,把Json转化成list<map> * @param bean * @return */ protected List<Map<String,String>> jsonTransferToDetailsListMap(NetBean bean){ return JsonUtils.jsonToNewListMap(bean.getData()); } @Override public void onModelLoginInvalidate() { if(callBack != null) callBack.onLoginInvalidate(); } @Override public void onVersionBack(String value) { if (callBack != null) callBack.onVersionBack(value); } }
true
5c2c23588165e439e326e3743b70eb81142749e5
Java
brianwchou/problems2019
/solutions/ListNode.java
UTF-8
1,275
3.765625
4
[]
no_license
public class ListNode { ListNode next; int value; ListNode(int value) { this.value = value; } /* Methods below are used for easy test writing. Not allowed to used for algorithms */ public boolean equals(ListNode node) { ListNode cursor = this; while ( cursor != null && node != null ) { if (cursor.value != node.value) { return false; } cursor = cursor.next; node = node.next; } return true; } public int size() { int count = 0; for (ListNode cursor = this; cursor != null; cursor = cursor.next) { count++; } return count; } public String toString() { StringBuilder sb = new StringBuilder(); ListNode cursor = this; while (cursor != null) { sb.append(String.format("%d ", cursor.value)); cursor = cursor.next; } return sb.toString(); } public static ListNode createHead(int value) { return new ListNode(value); } public ListNode addNode(int value) { ListNode next = new ListNode(value); this.next = next; return next; } }
true
11707e5ad5bd27ba7f8dbd6e8eba0107bd75043a
Java
arthurkl1/saturne
/src/main/java/hei/projet/servlets/ConsulterevenementServlet.java
UTF-8
1,121
2.109375
2
[]
no_license
package hei.projet.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.WebContext; import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect; import hei.projet.services.EvenementService; @WebServlet("/prive/consulterevenement") public class ConsulterevenementServlet extends AbstractGenericServlet { private static final long serialVersionUID = -3032812618526895052L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { TemplateEngine templateEngine = this.createTemplateEngine(req); WebContext context = new WebContext(req, resp, req.getServletContext()); context.setVariable("evenements", EvenementService.getInstance().listEvenement()); templateEngine.addDialect(new Java8TimeDialect()); templateEngine.process("calendrier", context, resp.getWriter()); } }
true
e1f918366db4760123081f325b6c78e2967d0313
Java
gityangge/Oplus
/src/main/java/cn/ac/yangge/controller/ActionController.java
UTF-8
3,659
2.140625
2
[]
no_license
package cn.ac.yangge.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.ac.yangge.pojo.ErrorMessage; import cn.ac.yangge.pojo.ItemCareDetail; import cn.ac.yangge.pojo.ItemLoveDetail; import cn.ac.yangge.service.LoveCareService; @Controller @RequestMapping("/action") public class ActionController { @Resource LoveCareService loveCareService; @RequestMapping("/addLove") @ResponseBody public ErrorMessage addLove(@RequestBody ItemLoveDetail itemLoveDetail){ ErrorMessage err=new ErrorMessage(); int result=loveCareService.addLove(itemLoveDetail); switch (result) { case 0: err.setId(1); err.setErr("love detail regist failed"); break; case 1: err.setId(0); err.setErr("success"); break; case 2: err.setId(2); err.setErr("uniteid ERR"); break; case 3: err.setId(3); err.setErr("item id ERR"); break; case 4: err.setId(4); err.setErr("update failed"); break; case 5: err.setId(5); err.setErr("love action has achieved"); break; default: err.setId(6); err.setErr("unknow problem cause"); break; } return err; } @RequestMapping("/removeLove") @ResponseBody public ErrorMessage removeLove(@RequestBody ItemLoveDetail itemLoveDetail){ ErrorMessage err=new ErrorMessage(); int result=loveCareService.removeLove(itemLoveDetail); switch (result) { case 0: err.setId(1); err.setErr("delete record failed"); break; case 1: err.setId(0); err.setErr("success"); break; case 2: err.setId(2); err.setErr("unite id ERR"); break; case 3: err.setId(3); err.setErr("item id ERR"); break; case 4: err.setId(4); err.setErr("update detail data failed"); break; default: err.setId(5); err.setErr("unknow problem cause"); break; } return err; } @RequestMapping("/addCare") @ResponseBody public ErrorMessage addCare(@RequestBody ItemCareDetail itemCareDetail){ ErrorMessage err=new ErrorMessage(); int result=loveCareService.addCare(itemCareDetail); switch (result) { case 0: err.setId(1); err.setErr("care detail regist failed"); break; case 1: err.setId(0); err.setErr("success"); break; case 2: err.setId(2); err.setErr("uniteid ERR"); break; case 3: err.setId(3); err.setErr("item id ERR"); break; case 4: err.setId(4); err.setErr("update failed"); break; case 5: err.setId(5); err.setErr("love action has achieved"); break; default: err.setId(6); err.setErr("unknow problem cause"); break; } return err; } @RequestMapping("/removeCare") @ResponseBody public ErrorMessage removeCare(@RequestBody ItemCareDetail itemCareDetail){ ErrorMessage err=new ErrorMessage(); int result=loveCareService.removeCare(itemCareDetail); switch (result) { case 0: err.setId(1); err.setErr("delete record failed"); break; case 1: err.setId(0); err.setErr("success"); break; case 2: err.setId(2); err.setErr("unite id ERR"); break; case 3: err.setId(3); err.setErr("item id ERR"); break; case 4: err.setId(4); err.setErr("update detail data failed"); break; default: err.setId(5); err.setErr("unknow problem cause"); break; } return err; } }
true
34e41089c2af400548606f3820c071128fe663e5
Java
nikopain/condoneschile
/app/src/main/java/usm/cc/misc/LayoutManagerShoppingCart.java
UTF-8
363
2.046875
2
[]
no_license
package usm.cc.misc; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; public class LayoutManagerShoppingCart extends LinearLayoutManager { public LayoutManagerShoppingCart(Context context) { super(context); } @Override public boolean supportsPredictiveItemAnimations() { return true; } }
true
a122d56f5fe41d440979cfd5dfb85dc8ff85eb2a
Java
yuvisu/DM-algorithm
/SPM/src/Alg/TransToSBD.java
UTF-8
2,571
2.765625
3
[]
no_license
package Alg; import java.io.*; import java.util.*; import java.util.Map.Entry; public class TransToSBD { private String filePath; public TransToSBD(String file){ this.filePath = file; } public List<String[]> Start() { List<String[]> Datalist = new ArrayList<String[]>(); try { FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { if (line.trim() != "") { String[] items = line.split("\\s{2,}"); Datalist.add(items); } } } catch (IOException e) { System.err.println("Load error。"+e); System.exit(-2); } Trans(Datalist); return Datalist; } public Map<Integer,List<List<String>>> Trans(List<String[]> allList){ int tmpTid = 1,tmpSid = 1; Map<Integer,List<List<String>>> result = new TreeMap<Integer,List<List<String>>>(); List<List<String>> tmpSet = new ArrayList<List<String>>(); List<String> tmpList = new ArrayList<String>(); tmpSet.add(tmpList); System.out.println(allList.size()); int count = 1; for(String[] list: allList){ if(Integer.parseInt(list[2]) != tmpTid){ tmpTid = Integer.parseInt(list[2]); tmpList = new ArrayList<String>(); if(Integer.parseInt(list[1]) != tmpSid){ tmpSid = Integer.parseInt(list[1]); tmpSet = new ArrayList<List<String>>(); count++; } tmpSet.add(tmpList); } //System.out.println(tmpSet); tmpList.add(list[3]); result.put(Integer.parseInt(list[1]),tmpSet); } printMap(result); System.out.println(count); return result; } public void printMap(Map<Integer,List<List<String>>> allMap){ String[]path = filePath.split("/"); String outputPath =""; for(int i = 0; i < path.length-1;i++) outputPath+=path[i]+"/"; outputPath+="SDB_"+path[path.length-1]; try{ FileWriter tgFileWriter = new FileWriter(outputPath); for(Entry<Integer, List<List<String>>> f1MapItem : allMap.entrySet()){ //tgFileWriter.append(f1MapItem.getKey()+":"); for(List<String> list : f1MapItem.getValue()){ for(String set : list){ tgFileWriter.append(set + " "); } tgFileWriter.append(","); } tgFileWriter.append("\n"); } tgFileWriter.flush(); }catch(IOException e){ System.err.println("Load error。"+e); System.exit(-2); } } }
true
a40a80201eab630c714ebd3f0cadce3238dd3f27
Java
babizhu/GameServer
/Tools/src/main/java/experiment/serialize/mongodb/MongoDbTest.java
UTF-8
2,180
2.578125
3
[]
no_license
package experiment.serialize.mongodb; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.WriteResult; import util.db.MongoUtil; import java.net.UnknownHostException; /** * user LIUKUN * time 14-3-25 下午5:17 * <p/> * Mongo的一些功能的测试程序 */ public class MongoDbTest{ private static String TABLE_NAME = "hero"; private static DBCollection collection = MongoUtil.INSTANCE.getDB().getCollection( TABLE_NAME ); /** * 更新符合条件的记录的某个字段的值,类似update tabel set field1 = 'x' where condition=true; */ static void testUpdate(){ // collection.drop(); // collection.insert( new BasicDBObject( "name", "liukun" ).append( "count", 34 ) ); // collection.insert( new BasicDBObject( "name", "js" ).append( "count", 134 ) ); // print(); // collection.updateMulti( new BasicDBObject( "count", new BasicDBObject( "$gt", 1 ) ), new BasicDBObject( "$set", new BasicDBObject( "name", "a" ) ) ); collection.updateMulti( new BasicDBObject( "uname", "lk" ), new BasicDBObject( "$set", new BasicDBObject( "templetId", 400137 ) ) ); // db.t1.update({"count":{$gt:1}},{$set:{"test2":"OK1"}}) System.out.println( collection.count() ); print(); } static void test(){ collection.drop(); DBObject obj = new BasicDBObject( "name", "liukun" ).append( "_id", 123 ); WriteResult save = collection.save( obj ); System.out.println( save ); System.out.println( save.getField( "updatedExisting" ) ); System.out.println( collection.find().count() ); save = collection.save( obj ); System.out.println( save ); System.out.println( save.getField( "updatedExisting" ) ); System.out.println( collection.find().count() ); } static void print(){ for( DBObject object : collection.find() ) { System.out.println( object ); } ; } public static void main( String[] args ) throws UnknownHostException{ testUpdate(); //test(); } }
true
42664196926cc18687f49a7e5c10765e69b87bc9
Java
punnoket/find-my-cat-cs355
/app/src/main/java/com/moblieapp/pannawatnokket/findmycat/adapter/HighScoreAdapter.java
UTF-8
1,656
2.28125
2
[]
no_license
package com.moblieapp.pannawatnokket.findmycat.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.moblieapp.pannawatnokket.findmycat.R; import com.moblieapp.pannawatnokket.findmycat.entity.User; import java.util.ArrayList; /** * Created by gminemini on 11/16/2017 AD. */ public class HighScoreAdapter extends BaseAdapter { Context mContext; ArrayList<User> userArrayList; public HighScoreAdapter(Context context, ArrayList<User> userArrayList) { this.mContext = context; this.userArrayList = userArrayList; } public int getCount() { return userArrayList.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View view, ViewGroup parent) { LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (view == null) view = mInflater.inflate(R.layout.score_view, parent, false); TextView index = (TextView) view.findViewById(R.id.indexScore); TextView name = (TextView) view.findViewById(R.id.nameScore); TextView score = (TextView) view.findViewById(R.id.scoreScore); index.setText(String.valueOf(position+1)); name.setText(userArrayList.get(position).getName()); score.setText(String.valueOf(userArrayList.get(position).getScore())); return view; } }
true
974ec00bd7abf025bdffbf3a29cacb1442460fff
Java
SangramMohite/ConferenceCentral_Java_GoogleCloud
/src/main/java/com/google/devrel/training/conference/domain/Speaker.java
UTF-8
1,036
2.28125
2
[ "Apache-2.0" ]
permissive
package com.google.devrel.training.conference.domain; import com.google.devrel.training.conference.form.ProfileForm; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; import java.util.ArrayList; import java.util.List; /** * Created by Sangram on 2/25/2017. */ @Entity public class Speaker { @Id private Long speakerId; @Index private String name; @Index private List<Key<Session>> sessionsScheduled = new ArrayList<Key<Session>>(0); private Speaker(){} public Speaker(Long speakerId, String name, Key<Session> sessionKey) { this.speakerId = speakerId; this.name = name; addSessionToSpeakersList(sessionKey); } public List<Key<Session>> getSessionsScheduled() { return sessionsScheduled; } public void addSessionToSpeakersList(Key<Session> sessionKey) { this.sessionsScheduled.add(sessionKey); } }
true
7e62e728d6e30d45fbfc28485c5397cea045f69f
Java
wilder16/universidaddejava
/src/secciones/secc18manejodepaquetes/test/TestUtileria.java
UTF-8
674
2.90625
3
[]
no_license
package secciones.secc18manejodepaquetes.test; //import secciones.secc18manejodepaquetes.*; //import secciones.secc18manejodepaquetes.Utileria; // Importacion estatica import static secciones.secc18manejodepaquetes.Utileria.imprimir; public class TestUtileria { // Manejo de paquetes public static void main(String[] args) { // Utileria.imprimir("Wilder"); /* * Si se utiliza la importacion estatica ya no es necesario utilizar * el nombre de la clase en el metodo estatico */ imprimir("Wilder"); // Tambien se puede utilizar el nombre completamente califacado de la clase secciones.secc18manejodepaquetes.Utileria.imprimir("Isai"); } }
true
c2a9ec8f6a3d9c3dbe2742484e1e5ae69ea81bb6
Java
meriwethernl/CollegeApp
/app/src/main/java/com/example/meriwethernl/collegeapp/Profile.java
UTF-8
1,085
2.65625
3
[]
no_license
package com.example.meriwethernl.collegeapp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by meriwethernl on 11/27/2017. */ public class Profile { String firstName; String lastName; Calendar dob; public Profile(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; this.dob = Calendar.getInstance(); dob.set(1999, 00, 01); } public Profile() { this.firstName = "Ada"; this.lastName = "Lovelace"; } public Calendar getDob() { return dob; } public void setDob(int year, int month , int day) { dob.set(year , month, day); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
true
c3dadc437541a3421f63c461c3e5071a6b93e320
Java
friedriich92/JOCAS
/src/DomainLayer/DataInterface/CtrlUsuariRegistrat.java
UTF-8
231
1.84375
2
[]
no_license
package DomainLayer.DataInterface; import DomainLayer.DomainModel.UsuariRegistrat; /** * Created by jedi on 10/06/14. */ public interface CtrlUsuariRegistrat { public UsuariRegistrat obtenirUsuariRegistrat(String userN); }
true
ac396e74655517861f564f3db4e993773cc2c583
Java
Lvluffy/GeneralDataStructure
/sortlib/src/main/java/com/luffy/datastructure/sortlib/InsertionSortApply.java
UTF-8
1,860
4.28125
4
[]
no_license
package com.luffy.datastructure.sortlib; /** * Created by lvlufei on 2019/11/7 * * @name 插入排序 * @desc 特点:在冒泡排序中,经过每一轮的排序处理后,数组后端的数是排好的;而对于插入排序来说,经过每一轮的排序处理后,数组前段的数是排好序的。 * <p> * 基本思想:不断地将尚未排好序的数插入到已经排好序的部分。 * <p> * 过程:插入排序从小到大排序:首先位置1上的数和位置0上的数进行比较,如果位置1上的数大于位置0上的数,将位置0上的数向后移一位,将1插入到0位置, * 否则不处理。位置k上的数和之前的数依次进行比较,如果位置K上的数更大,将之前的数向后移位,最后将位置k上的数插入不满足条件点,反之不处理。 * <p> * 时间复杂度:O(n^2) * 空间复杂度:O(1) * <p> * 题目:给定一个数组[2,1,7,9,5,8],要求按照从左到右、从小到大的顺序进行排序。 */ public class InsertionSortApply { public static void main(String[] args) { int[] nums = {2, 1, 7, 9, 5, 8}; sort(nums); for (int i : nums) { System.out.print(i + " "); } } /** * 插入排序 * * @param nums 数组数据 * @return */ public static int[] sort(int[] nums) { if (nums == null || nums.length == 0) { return nums; } //交换变量 int temp; //定义一个标示 int i, j; for (i = 1; i < nums.length; i++) { temp = nums[i]; //将第I个数组插入到合适的位置 for (j = i - 1; j >= 0 && nums[j] > temp; j--) { nums[j + 1] = nums[j]; } nums[j + 1] = temp; } return nums; } }
true
5339c32f59130b440c2d9e9dc5a709626b5c9318
Java
AngelaM-C/intro-to-java-10thEdition
/Assignment 3/src 1.52.14 AM 1.52.14 AM 1.52.14 AM/Chapter7/analyzeScores.java
UTF-8
832
3.421875
3
[]
no_license
package Chapter7; import java.util.Scanner; public class analyzeScores { public static void main(String[]args) { Scanner input = new Scanner(System.in); final int max= 100; int[] scores= new int[max]; int sum=0; int average=0; int numberOfScores=0; int aboveOrequal=0; int below=0; System.out.println("Enter the scores and then a negative number:"); for(int i=0 ; i< max ; i++, numberOfScores++) { scores[i]= input.nextInt(); if(scores[i]<0) break; sum += scores[i]; } average= sum/numberOfScores; for(int i =0; i< numberOfScores; i++) { if(scores[i]>= average) aboveOrequal++; if(scores[i]< average) below++; } System.out.println("There are "+ below +" numbers below average and "+ aboveOrequal+ " nummbers above or equal to the average."); } }
true
5f4271e5727699acb476c9e03262bc1e0002127e
Java
Jeongjiho/Java76
/java01t/src/step04/exam09/Calculator2.java
UTF-8
674
3.875
4
[]
no_license
package step04.exam09; class Calculator2 { // result 변수를 개별관리 변수로 선언한다. => static 명령을 제거하라! // static이 붙지 않은 변수는 new 명령을 통해 준비된다. // static이 붙은 변수는 클래스를 사용할 때 자동으로 준비된다. int result; static void plus(Calculator2 that, int a) { that.result = that.result + a; } static void minus(Calculator2 that, int a) { that.result = that.result - a; } static void multiple(Calculator2 that, int a) { that.result = that.result * a; } static void divide(Calculator2 that, int a) { that.result = that.result / a; } }
true
26c5efff936c159da83597295d0d6e40b62aa996
Java
newcashpay/demo
/src/main/java/com/jxchain/newpay/web/sandbox/mvc/model/InvoiceModel.java
UTF-8
389
1.804688
2
[]
no_license
package com.jxchain.newpay.web.sandbox.mvc.model; import java.math.BigDecimal; import java.util.Date; import lombok.Data; @Data public class InvoiceModel { private String invoiceId; private Integer quantity; private String fiatCode; private BigDecimal fiatPrice; private String goodsName; private String state; private Date createTime; }
true
3655ff07d0057a1912dda5fc855355bee0e8088f
Java
AdemTEN/CoreJava
/src/day21_String_Manipulation_Part3/STring_Substring.java
UTF-8
626
3.3125
3
[]
no_license
package day21_String_Manipulation_Part3; public class STring_Substring { public static void main(String[] args) { String sentence = "Java String Manipulation is fun!"; System.out.println(sentence.substring(2)); System.out.println(sentence.substring(5, 11)); System.out.println(sentence.length()); System.out.println(sentence.substring(5, sentence.length()-5));//5,27==>27 is not include String chars = "{{}}"; String word = "AUTOMATION"; String newWord = chars.substring(0,2).concat(word).concat(chars.substring(2)); System.out.println(newWord); System.out.println(word.toLowerCase()); } }
true
2f44fb4b632e506f68dba7b6fffc862415528116
Java
TencentCloud/tencentcloud-sdk-java-intl-en
/src/main/java/com/tencentcloudapi/mdl/v20200326/models/Scte35SettingsInfo.java
UTF-8
2,506
1.921875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.mdl.v20200326.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class Scte35SettingsInfo extends AbstractModel{ /** * Whether to pass through SCTE-35 information. Valid values: NO_PASSTHROUGH/PASSTHROUGH. Default value: NO_PASSTHROUGH. */ @SerializedName("Behavior") @Expose private String Behavior; /** * Get Whether to pass through SCTE-35 information. Valid values: NO_PASSTHROUGH/PASSTHROUGH. Default value: NO_PASSTHROUGH. * @return Behavior Whether to pass through SCTE-35 information. Valid values: NO_PASSTHROUGH/PASSTHROUGH. Default value: NO_PASSTHROUGH. */ public String getBehavior() { return this.Behavior; } /** * Set Whether to pass through SCTE-35 information. Valid values: NO_PASSTHROUGH/PASSTHROUGH. Default value: NO_PASSTHROUGH. * @param Behavior Whether to pass through SCTE-35 information. Valid values: NO_PASSTHROUGH/PASSTHROUGH. Default value: NO_PASSTHROUGH. */ public void setBehavior(String Behavior) { this.Behavior = Behavior; } public Scte35SettingsInfo() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public Scte35SettingsInfo(Scte35SettingsInfo source) { if (source.Behavior != null) { this.Behavior = new String(source.Behavior); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Behavior", this.Behavior); } }
true
6080195c50a55189ef81b97d43333436c8ab5941
Java
SimonHu1993/SpringbootZuul
/core_simon/src/main/java/com/ simonhu/common/IPWhiteUtil.java
UTF-8
1,643
2.21875
2
[]
no_license
package com.simonhu.common; import com.simonhu.common.exception.IpNoAccessException; import com.simonhu.util.IpUtil; import com.simonhu.web.merchant.service.MerchantService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.List; import java.util.Map; /** * @Author: SimonHu * @Date: 2019/8/23 13:55 * @Description: */ @Service public class IPWhiteUtil { private static final Logger logger = LoggerFactory.getLogger(IPWhiteUtil.class); @Autowired private MerchantService merchantService; public boolean isAccess(HttpServletRequest request) { String ip = IpUtil.getIpAddr(request); logger.info("------------您的ip地址:{}----------------------------" ,ip); if (StringUtils.isEmpty(ip)) { throw new IpNoAccessException("获取不到ip"); } else { Map result = merchantService.sysConfigInfo(Constants.CONFIG_IP); if(result == null || result.isEmpty() || "0".equals(String.valueOf(result.get("value1")))){ return true; } String ipString = String.valueOf(result.get("value4")); String[] ipList = ipString.split(","); List<String> list = Arrays.asList(ipList); if (list.contains(ip)) { return true; } throw new IpNoAccessException("ip不在白名单内:::" + ip); } } }
true
ee3f896fb093c5ac7f12055bfe862d6d4485bcc9
Java
openid-certification/conformance-suite
/src/main/java/net/openid/conformance/condition/client/GenerateRS256ClientJWKs.java
UTF-8
698
2.046875
2
[ "MIT" ]
permissive
package net.openid.conformance.condition.client; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.gen.JWKGenerator; import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; import net.openid.conformance.condition.PostEnvironment; import net.openid.conformance.testmodule.Environment; public class GenerateRS256ClientJWKs extends AbstractGenerateClientJWKs { @Override @PostEnvironment(required = {"client_jwks", "client_public_jwks" }) public Environment evaluate(Environment env) { JWKGenerator<RSAKey> generator = new RSAKeyGenerator(DEFAULT_KEY_SIZE) .algorithm(JWSAlgorithm.RS256); return generateClientJWKs(env, generator); } }
true
7bb317d1bc756387ebd370fb015eb692241d43b3
Java
1553002/PTTKHTTT-15CLC-Elearning
/app/src/main/java/com/example/congcanh/elearningproject/adapter/ChooseLessonCustomDialogAdapter.java
UTF-8
2,197
2.65625
3
[]
no_license
package com.example.congcanh.elearningproject.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.congcanh.elearningproject.R; import com.example.congcanh.elearningproject.model.TopicEntity; /** * Created by CongCanh on 4/13/2018. */ public class ChooseLessonCustomDialogAdapter extends BaseAdapter { String[] levels = new String[]{"Lesson 1", "Lesson 2", "Lesson 3", "Quiz"}; LayoutInflater layoutInflater; TopicEntity topicEntity; public ChooseLessonCustomDialogAdapter(Context context, TopicEntity topicEntity) { this.layoutInflater = LayoutInflater.from(context); this.topicEntity = topicEntity; } //Hàm quyết định item nào được enable @Override public boolean isEnabled(int position){ if (position <= topicEntity.getCurrent_level() || levels[position]=="Quiz"){ return true; } return false; } @Override public int getCount() { return levels.length; } @Override public Object getItem(int position) { return levels[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null){ convertView = layoutInflater.inflate(R.layout.choose_lesson_listview_row, null); holder = new ViewHolder(); holder.lesson = (TextView)convertView.findViewById(R.id.tw_lesson_title); holder.status = (TextView)convertView.findViewById(R.id.tw_status); convertView.setTag(holder); }else{ holder = (ViewHolder)convertView.getTag(); } holder.lesson.setText(levels[position]); if (position < topicEntity.getCurrent_level()){ holder.status.setText("Finished"); } return convertView; } static class ViewHolder{ TextView lesson; TextView status; } }
true
9481b43998ae10970498d580b54ea0b48a24ae56
Java
neredumelliprasad/POC
/application/src/main/java/com/eunice/sap/hana/model/DataConstructionContext.java
UTF-8
565
1.9375
2
[]
no_license
package com.eunice.sap.hana.model; /** * Created by roychoud on 18 Dec 2019. */ import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.productmaster.Product; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * History: * <ul> * <li> 18 Dec 2019 : roychoud - Created * </ul> * * @authors roychoud : Arunava Roy Choudhury * © 2019 HERE */ public class DataConstructionContext { private Map<String, Product> productMap = new ConcurrentHashMap<>(); public Map<String, Product> getProductMap() { return productMap; } }
true
655be29680f9606a9cdd59d5b83e3a87a6b37472
Java
google-code/chartmechanic
/ds/src/com/bayareasoftware/chartengine/ds/StreamOutput.java
UTF-8
6,108
2.671875
3
[]
no_license
/* * Copyright 2008-2010 Bay Area Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bayareasoftware.chartengine.ds; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import com.bayareasoftware.chartengine.model.DataType; import com.bayareasoftware.chartengine.model.Metadata; import com.bayareasoftware.chartengine.model.StringUtil; import com.bayareasoftware.chartengine.util.DateUtil; /** * StreamOutput outputs DataStreams into Writers in a textual format. * It outputs the header of the DataStream first, then each row, with each column * value separated by a COLUMN_DELIMITER (default is comma), and each row by a ROW_DELIMITER * (default is newline). With the default settings, the output looks a CSV format * * the output uses the format strings in the metadata when columns have format strings * * Subclasses should override outputHeader(), outputRow(), outputFooter() accordingly * */ public class StreamOutput { protected DataStream stream; protected Metadata metadata; protected int columnCount; protected Writer out; protected DateFormat defaultDateFmt; protected DecimalFormat defaultDecimalFmt; protected String columnDelimiter = ","; protected String rowDelimiter = "\n"; protected String defaultDateFormat = "yyyy-MM-dd"; protected String defaultNumberFormat = "###.##"; public StreamOutput(DataStream stream, Writer out) { this.stream = stream; this.out = out; this.metadata = stream.getMetadata(); columnCount = metadata.getColumnCount(); defaultDateFmt = new SimpleDateFormat(defaultDateFormat); defaultDecimalFmt = new DecimalFormat(defaultNumberFormat); } /** * run the stream up until the end * @return number of rows produced * @throws Exception */ public int runStream() throws Exception { return runStream(-1); } /** * run the stream up to maxRows number of rows * @param maxRows - if negative, runs to end of stream * @throws Exception * @return number of rows produced */ public int runStream(int maxRows) throws Exception { outputHeader(); if (maxRows < 0) maxRows = Integer.MAX_VALUE; int r = 0; while (stream.next() && r < maxRows) { outputRow(); r++; } outputFooter(); out.flush(); return r; } protected void outputRow() throws Exception { for (int i = 1; i <= columnCount; i++) { if (metadata.getColumnType(i) != DataType.IGNORE) { outputAtom(i); if (i < columnCount) { out.write(columnDelimiter); } } } out.write(rowDelimiter); } protected void outputAtom(int index) throws Exception { int dataType = metadata.getColumnType(index); switch (dataType) { case DataType.BOOLEAN: Boolean b = stream.getBoolean(index); if (b != null) { if (b) { out.write("true"); } else { out.write("false"); } } break; case DataType.INTEGER: Integer i = stream.getInt(index); if (i != null) { out.write(String.valueOf(i)); } break; case DataType.DOUBLE: Double d = stream.getDouble(index); if (d != null) { String fmt = StringUtil.trim(metadata.getColumnFormat(index)); DecimalFormat decFmt; if (fmt != null) decFmt = new DecimalFormat(fmt); else decFmt = defaultDecimalFmt; out.write(decFmt.format(d)); } break; case DataType.STRING: String s = stream.getString(index); if (s != null) { out.write(s); } break; case DataType.DATE: Date date = stream.getDate(index); if (date != null) { DateFormat dateFmt = defaultDateFmt; String fmt = StringUtil.trim(metadata.getColumnFormat(index)); if (fmt != null && !fmt.equals(Metadata.INTERNAL_DATE_FORMAT)) { dateFmt = DateUtil.createDateFormat(fmt); // dateFmt = new SimpleDateFormat(fmt); } String val = dateFmt.format(date); out.write(val); } break; } } protected void outputHeader() throws IOException { for (int i = 1; i <= columnCount; i++) { String name = metadata.getColumnName(i); if (name != null) out.write(name); else out.write(""); if (i < columnCount) { out.write(columnDelimiter); } } out.write(rowDelimiter); } // subclass can override this to do something at the end of the stream protected void outputFooter() throws IOException { } // close the stream and the writer public void close() throws IOException { if (stream != null) stream.close(); if (out !=null) { out.close(); } } }
true
a576e08803c52c66fe10bfb7cbffcfe1ead87eb7
Java
enricopersiani/gef
/org.eclipse.draw2d.examples/src/org/eclipse/draw2d/examples/graph/CompoundGraphTests.java
UTF-8
14,803
2.21875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2005, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.draw2d.examples.graph; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.draw2d.graph.CompoundDirectedGraph; import org.eclipse.draw2d.graph.CompoundDirectedGraphLayout; import org.eclipse.draw2d.graph.Edge; import org.eclipse.draw2d.graph.EdgeList; import org.eclipse.draw2d.graph.Node; import org.eclipse.draw2d.graph.NodeList; import org.eclipse.draw2d.graph.Subgraph; /** * A collection of compound graph tests. * * @author hudsonr * @since 2.1 */ public class CompoundGraphTests { public static CompoundDirectedGraph aaaapull(int direction) { Subgraph s1, s2; Node a, b, e, j, m, n, y; Node r, t; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); s1 = new Subgraph("Subgraph 1"); s2 = new Subgraph("Subgraph 2"); nodes.add(r = new Node("r", s2)); nodes.add(t = new Node("t", s2)); nodes.add(a = new Node("a", s1)); nodes.add(b = new Node("b", s1)); nodes.add(e = new Node("e", s1)); nodes.add(j = new Node("j", s1)); nodes.add(m = new Node("m", s1)); edges.add(new Edge(a, b)); edges.add(new Edge(b, e)); edges.add(new Edge(e, j)); edges.add(new Edge(m, t)); edges.add(new Edge(j, r)); edges.add(new Edge(a, r)); edges.add(new Edge(s1, s2)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; graph.nodes.add(s1); graph.nodes.add(s2); new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph aaaflowEditor(int direction) { Subgraph diagram, flow, subflow1, subflow2; Node a1, a2, a3; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); nodes.add(diagram = new Subgraph("Editor")); nodes.add(flow = new Subgraph("Flow", diagram)); nodes.add(subflow1 = new Subgraph("Sub1", flow)); nodes.add(subflow2 = new Subgraph("Sub2", flow)); nodes.add(a1 = new Node("a1", diagram)); nodes.add(a2 = new Node("a2", subflow1)); nodes.add(a3 = new Node("a3", subflow2)); a1.width = a2.width = a3.width = 200; a1.outgoingOffset = 1; edges.add(new Edge(a1, flow)); edges.add(new Edge(a1, a2)); edges.add(new Edge(a2, a3)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph chains(int direction) { Subgraph s1, s2, s3, sb; Node nx, n0, n1, n2, n3, n4, n5, n6, na, nb; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); nodes.add(s1 = new Subgraph("S1")); nodes.add(s2 = new Subgraph("S2")); nodes.add(s3 = new Subgraph("S3")); nodes.add(sb = new Subgraph("SB")); s1.setPadding(new Insets(10)); s1.innerPadding = new Insets(1); s1.insets = new Insets(9); edges.add(new Edge(s1, s2)); edges.add(new Edge(s1, sb)); edges.add(new Edge(sb, s3)); edges.add(new Edge(s2, s3)); nodes.add(n0 = new Node("0", s1)); nodes.add(nx = new Node("x", s1)); nodes.add(n1 = new Node("1", s1)); nodes.add(n2 = new Node("2", s1)); edges.add(new Edge(nx, n2)); edges.add(new Edge(n0, n2)); edges.add(new Edge(n1, n2)); nodes.add(n3 = new Node("3", s2)); nodes.add(n4 = new Node("4", s2)); edges.add(new Edge(n3, n4)); nodes.add(n5 = new Node("5", s3)); nodes.add(n6 = new Node("6", s3)); edges.add(new Edge(n5, n6)); nodes.add(na = new Node("a", sb)); nodes.add(nb = new Node("b", sb)); edges.add(new Edge(na, nb)); n1.width = 60; n2.width = na.width = 70; n3.width = 100; n5.width = n6.width = 64; n4.width = 150; CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph flowChart(int direction) { NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); Subgraph diagram, s1, s2, s3, s4, s5, s6, s7, s8; nodes.add(diagram = new Subgraph("diagram")); nodes.add(s1 = new Subgraph("s1", diagram)); nodes.add(s2 = new Subgraph("s2", s1)); nodes.add(s3 = new Subgraph("s3", s1)); nodes.add(s4 = new Subgraph("s4", s1)); nodes.add(s5 = new Subgraph("s5", s1)); nodes.add(s6 = new Subgraph("s6", s1)); nodes.add(s7 = new Subgraph("s7", s1)); nodes.add(s8 = new Subgraph("s8", s1)); Node outer1, outer2, outer3; nodes.add(outer1 = new Node("asdf", diagram)); nodes.add(outer2 = new Node("asfasdf", diagram)); nodes.add(outer3 = new Node("a3", diagram)); edges.add(new Edge(s3, s6)); edges.add(new Edge(s4, s7)); edges.add(new Edge(s6, s8)); edges.add(new Edge(outer1, outer3)); edges.add(new Edge(outer3, s1)); edges.add(new Edge(outer2, s1)); Node s2a, s2b, s2c; nodes.add(s2a = new Node("BMW", s2)); nodes.add(s2b = new Node("Hawking", s2)); nodes.add(s2c = new Node("Smurfy", s2)); edges.add(new Edge(s2a, s2b)); edges.add(new Edge(s2a, s2c)); Node s3a, s3b; nodes.add(s3a = new Node("Jammin", s3)); nodes.add(s3b = new Node("This is it", s3)); edges.add(new Edge(s3a, s3b)); nodes.add(new Node("catDog", s4)); Node s5a, s5b; nodes.add(s5a = new Node("a1", s5)); nodes.add(s5b = new Node("a2", s5)); edges.add(new Edge(s5a, s5b)); Node s6a, s6b, s6c; nodes.add(s6a = new Node("Hoop it up", s6)); nodes.add(s6b = new Node("Streeball", s6)); nodes.add(s6c = new Node("Downtown", s6)); edges.add(new Edge(s6b, s6c)); edges.add(new Edge(s6a, s6b)); Node s7a, s7b; nodes.add(s7a = new Node("Thing 1", s7)); nodes.add(s7b = new Node("Thing 2", s7)); edges.add(new Edge(s7a, s7b)); Node s8a, s8b, s8c, s8d, s8e; nodes.add(s8a = new Node("a1", s8)); nodes.add(s8b = new Node("a2", s8)); nodes.add(s8c = new Node("a3", s8)); nodes.add(s8d = new Node("a4", s8)); nodes.add(s8e = new Node("a5", s8)); edges.add(new Edge(s8a, s8c)); edges.add(new Edge(s8a, s8d)); edges.add(new Edge(s8b, s8c)); edges.add(new Edge(s8b, s8e)); edges.add(new Edge(s8c, s8e)); Node inner1, inner2, inner3, inner4, inner5, inner6, inner7, inner8, inner9, inner10, inner11, inner12, inner13, inner14, inner15, inner16; nodes.add(inner1 = new Node("buckyball", s1)); nodes.add(inner2 = new Node("d", s1)); nodes.add(inner3 = new Node("cheese", s1)); nodes.add(inner4 = new Node("dingleberry", s1)); nodes.add(inner5 = new Node("dinosaur", s1)); nodes.add(inner6 = new Node("foobar", s1)); nodes.add(inner7 = new Node("t30", s1)); nodes.add(inner8 = new Node("a21", s1)); nodes.add(inner9 = new Node("katarina", s1)); nodes.add(inner10 = new Node("zig zag", s1)); nodes.add(inner11 = new Node("a16", s1)); nodes.add(inner12 = new Node("a23", s1)); nodes.add(inner13 = new Node("a17", s1)); nodes.add(inner14 = new Node("a20", s1)); nodes.add(inner15 = new Node("a19", s1)); nodes.add(inner16 = new Node("a24", s1)); edges.add(new Edge(inner1, inner3)); edges.add(new Edge(inner2, inner4)); edges.add(new Edge(inner2, inner3)); edges.add(new Edge(inner3, inner5)); edges.add(new Edge(inner4, inner5)); edges.add(new Edge(inner4, inner6)); edges.add(new Edge(inner6, s6)); edges.add(new Edge(inner5, inner7)); edges.add(new Edge(inner7, inner8)); edges.add(new Edge(inner8, s5)); edges.add(new Edge(s3, inner9)); edges.add(new Edge(s4, inner9)); edges.add(new Edge(inner9, inner10)); edges.add(new Edge(s7, inner11)); edges.add(new Edge(s7, inner12)); edges.add(new Edge(inner11, inner13)); edges.add(new Edge(inner11, inner14)); edges.add(new Edge(inner11, inner15)); edges.add(new Edge(inner12, inner15)); edges.add(new Edge(inner12, inner16)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph flowEditor1(int direction) { Subgraph diagram, flow; Node a1, a2, a4, a5, a6, a7, a8, x, y; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); nodes.add(diagram = new Subgraph("Editor")); nodes.add(flow = new Subgraph("Flow", diagram)); nodes.add(a1 = new Node("a1", diagram)); nodes.add(a2 = new Node("a2", diagram)); nodes.add(a4 = new Node("a4", diagram)); nodes.add(a5 = new Node("a5", diagram)); nodes.add(a6 = new Node("a6", diagram)); nodes.add(a7 = new Node("a7", diagram)); nodes.add(a8 = new Node("a8", diagram)); edges.add(new Edge(a1, a2)); edges.add(new Edge(a2, a4)); edges.add(new Edge(a2, a5)); edges.add(new Edge(a2, a6)); edges.add(new Edge(a6, flow)); nodes.add(x = new Node("x", flow)); nodes.add(y = new Node("y", flow)); edges.add(new Edge(x, y)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph flowEditor2(int direction) { Subgraph diagram, flow; Node a1, a2, a3, a4; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); nodes.add(diagram = new Subgraph("Editor")); nodes.add(flow = new Subgraph("Flow", diagram)); nodes.add(a1 = new Node("a1", diagram)); nodes.add(a2 = new Node("a2", diagram)); nodes.add(a3 = new Node("a3", flow)); nodes.add(a4 = new Node("a4", flow)); edges.add(new Edge(a1, a2)); edges.add(new Edge(a2, a4)); edges.add(new Edge(a3, a2)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph ShortestPassCase(int direction) { NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); Subgraph p = new Subgraph("parent"); nodes.add(p); Node a = new Node("a", p); nodes.add(a); Node b = new Node("b", p); nodes.add(b); Node c = new Node("c", p); nodes.add(c); Node d = new Node("d", p); nodes.add(d); Node e = new Node("e", p); nodes.add(e); edges.add(new Edge(a, d)); edges.add(new Edge(a, c)); edges.add(new Edge(b, c)); edges.add(new Edge(b, d)); edges.add(new Edge(b, e)); edges.add(new Edge(c, d)); edges.add(new Edge(c, e)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph tangledSubgraphs(int direction) { Subgraph A, B, C, D; Node a1, a2, b1, b2, c1, c2, d1, d2; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); nodes.add(A = new Subgraph("Subgraph A")); nodes.add(B = new Subgraph("Subgraph B")); nodes.add(C = new Subgraph("Subgraph C")); nodes.add(D = new Subgraph("Subgraph D")); // C.rowOrder = 2; // B.rowOrder = 3; nodes.add(a1 = new Node("a1", A)); nodes.add(a2 = new Node("a2", A)); edges.add(new Edge(a1, a2)); nodes.add(b1 = new Node("b1", B)); nodes.add(b2 = new Node("b2", B)); edges.add(new Edge(b1, b2)); nodes.add(c1 = new Node("c1", C)); nodes.add(c2 = new Node("c2", C)); edges.add(new Edge(c1, c2)); nodes.add(d1 = new Node("d1", D)); nodes.add(d2 = new Node("d2", D)); edges.add(new Edge(d1, d2)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; edges.add(new Edge(a1, d2)); edges.add(new Edge(d1, c2)); edges.add(new Edge(d1, b2)); new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph test1(int direction) { Subgraph s1, s2; Node n1, n2, n3, n4, n5, n6, n7; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); s1 = new Subgraph("Subgraph 1"); s2 = new Subgraph("Subgraph 2"); nodes.add(n1 = new Node("1", s1)); nodes.add(n2 = new Node("2", s1)); nodes.add(n3 = new Node("3", s1)); nodes.add(n4 = new Node("4", s2)); nodes.add(n5 = new Node("5", s2)); nodes.add(n6 = new Node("6", s2)); nodes.add(n7 = new Node("7", s2)); n1.width = 60; n2.width = 70; n3.width = 100; n5.width = n6.width = 64; n7.width = n4.width = 90; edges.add(new Edge(n1, n3)); edges.add(new Edge(n2, n3)); edges.add(new Edge(n4, n5)); edges.add(new Edge(n4, n6)); edges.add(new Edge(n6, n7)); edges.add(new Edge(n5, n7)); edges.add(new Edge(n2, n5)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; graph.nodes.add(s1); graph.nodes.add(s2); new CompoundDirectedGraphLayout().visit(graph); return graph; } public static CompoundDirectedGraph test2(int direction) { Subgraph s1, s2, s1_1; Node n1, n2, n3, n4, n5, n6, n7, n8; NodeList nodes = new NodeList(); EdgeList edges = new EdgeList(); s1 = new Subgraph("Subgraph 1"); s2 = new Subgraph("Subgraph 2"); s1_1 = new Subgraph("Subgraph 1.1", s1); nodes.add(s1); nodes.add(s2); nodes.add(s1_1); nodes.add(n1 = new Node("1", s1)); nodes.add(n2 = new Node("2", s1)); nodes.add(n3 = new Node("3", s1)); nodes.add(n4 = new Node("4", s2)); nodes.add(n5 = new Node("5", s2)); nodes.add(n6 = new Node("6", s2)); nodes.add(n7 = new Node("7", s2)); nodes.add(n8 = new Node("8", s1_1)); n8.width = 80; n1.width = 60; n2.width = 70; n3.width = 100; n5.width = n6.width = 64; n7.width = n4.width = 90; edges.add(new Edge(n1, n2)); edges.add(new Edge(n2, n3)); // edges.add(new Edge(n1, n3)); edges.add(new Edge(n1, n8)); edges.add(new Edge(n1, n5)); edges.add(new Edge(n8, n3)); edges.add(new Edge(n4, n5)); edges.add(new Edge(n4, n6)); edges.add(new Edge(n6, n7)); edges.add(new Edge(n5, n7)); edges.add(new Edge(n2, n5)); CompoundDirectedGraph graph = new CompoundDirectedGraph(); graph.setDirection(direction); graph.nodes = nodes; graph.edges = edges; new CompoundDirectedGraphLayout().visit(graph); return graph; } }
true
879f73724388f4345af008d59bf65cebfe347965
Java
leiyuxin/SpringInAction
/studyspringdemo/src/main/java/org/leiyuxin/exercise/studyspringdemo/chapter1/Knight.java
UTF-8
377
1.8125
2
[]
no_license
package org.leiyuxin.exercise.studyspringdemo.chapter1; import org.springframework.beans.factory.BeanFactory; import com.mysql.cj.jdbc.Driver; /*import org.springframework.jdbc.core.JdbcTemplate;*/ public interface Knight { public default void embarkOnQuest() { System.out.println("default knight"); /*new JdbcTemplate().queryForObject(sql, rowMapper, args);*/ } }
true
4f80665f9c08e45f565103c9b89cb636bd789b07
Java
CUSTEAM/stis
/src/model/stmd_info.java
UTF-8
2,489
2.078125
2
[]
no_license
package model; public class stmd_info { private String student_no, AborigineCode, editime, AborigineCode_f, AborigineCode_m, FirstCollegeStd, Education_f, Education_m, AborigineListen, AborigineSpeak, AborigineRead, AborigineWrite, Hometown; public String getHometown() { return Hometown; } public void setHometown(String hometown) { Hometown = hometown; } public String getAborigineListen() { return AborigineListen; } public void setAborigineListen(String aborigineListen) { AborigineListen = aborigineListen; } public String getAborigineSpeak() { return AborigineSpeak; } public void setAborigineSpeak(String aborigineSpeak) { AborigineSpeak = aborigineSpeak; } public String getAborigineRead() { return AborigineRead; } public void setAborigineRead(String aborigineRead) { AborigineRead = aborigineRead; } public String getAborigineWrite() { return AborigineWrite; } public void setAborigineWrite(String aborigineWrite) { AborigineWrite = aborigineWrite; } private Integer Oid; public String getStudent_no() { return student_no; } public void setStudent_no(String student_no) { this.student_no = student_no; } public String getAborigineCode() { return AborigineCode; } public void setAborigineCode(String aborigineCode) { AborigineCode = aborigineCode; } public String getEditime() { return editime; } public void setEditime(String editime) { this.editime = editime; } public String getAborigineCode_f() { return AborigineCode_f; } public void setAborigineCode_f(String aborigineCode_f) { AborigineCode_f = aborigineCode_f; } public String getAborigineCode_m() { return AborigineCode_m; } public void setAborigineCode_m(String aborigineCode_m) { AborigineCode_m = aborigineCode_m; } public String getFirstCollegeStd() { return FirstCollegeStd; } public void setFirstCollegeStd(String firstCollegeStd) { FirstCollegeStd = firstCollegeStd; } public String getEducation_f() { return Education_f; } public void setEducation_f(String education_f) { Education_f = education_f; } public String getEducation_m() { return Education_m; } public void setEducation_m(String education_m) { Education_m = education_m; } public Integer getOid() { return Oid; } public void setOid(Integer oid) { Oid = oid; } }
true
fce419332b8326530fd0fbfc36b560f13720f5bb
Java
zhuguangyuan/designPattern
/java_basic/4_javaGC/WeakHashMapTest.java
UTF-8
2,244
3.609375
4
[]
no_license
package main.java; import java.util.WeakHashMap; /** * @Author: zhuguangyuan * @DateTime: 2018-07-24 12:49:56 * @Descrition: 弱引用测试 */ class CrazyKey { String name; public CrazyKey(String name){ this.name = name; } public int hashCode(){ return name.hashCode(); } public boolean equals(Object obj){ if (obj == null) { return true; } if (obj != null && (obj.getClass() == CrazyKey.class)) { return name.equals(((CrazyKey)obj).name); } return false; } public String toString(){ return "CrazyKey[name=" + name + "]"; } } public class WeakHashMapTest { public static void main(String[] args) throws InterruptedException { // 强引用map指向堆内的一个HashMap类型的map, // map中通过key映射到String,String类型的实例value11作为弱引用引用堆内的String对象 // 当垃圾回收的时候,只有弱引用指向的堆内对象会被回收 // 同时对应的弱引用对象也会被回收? /** * --- 运行垃圾回收前 --- * { CrazyKey[name=key9]=value910, * CrazyKey[name=key7]=value710, * CrazyKey[name=key8]=value810, * CrazyKey[name=key1]=value110, * CrazyKey[name=key2]=value210, * CrazyKey[name=key0]=value010, * CrazyKey[name=key5]=value510, * CrazyKey[name=key6]=value610, * CrazyKey[name=key3]=value310, * CrazyKey[name=key4]=value410 * } * value210 * --- 运行垃圾回收后 --- * {} * null */ WeakHashMap<CrazyKey,String> map = new WeakHashMap<CrazyKey,String>(); for (int i=0; i<10; i++) { map.put( new CrazyKey("key"+i), "value"+i+10 ); } System.out.println("--- 运行垃圾回收前 ---"); System.out.println(map); System.out.println(map.get(new CrazyKey("key2"))); System.gc(); Thread.sleep(50); System.out.println("--- 运行垃圾回收后 ---"); System.out.println(map); System.out.println(map.get(new CrazyKey("key2"))); } }
true
8c1a457eb095dc504b5c45b3f8b76e730990135d
Java
sbsteacher/2020_srping
/first/src/com/kita/first/level3/Monitor.java
UTF-8
354
2.921875
3
[]
no_license
package com.kita.first.level3; public class Monitor { static String brand; int inch; void printInfo() { System.out.printf("brand: %s, inch: %d\n" , this.brand, this.inch); } void printInch() { System.out.println(brand); System.out.println(inch); } static void printBrand() { System.out.println(brand); } }
true
c2769ea77038f4ce26d5f605e9b9c75e6cfc51d6
Java
lawalgren/CSCI310-final
/app/src/main/java/com/example/lucas/whogoesthere/EditGroup.java
UTF-8
5,171
2.234375
2
[]
no_license
package com.example.lucas.whogoesthere; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Text; import java.io.IOException; import butterknife.BindView; import butterknife.ButterKnife; import okhttp3.Call; import okhttp3.Callback; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class EditGroup extends AppCompatActivity { @BindView(R.id.cancel_button) Button cancel_button; @BindView(R.id.save_button) Button save_button; @BindView(R.id.groupnamefield) TextView groupnamefield; String username; String password; String groupname; String newgroupname; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_group); getSupportActionBar().setTitle("Edit Group"); ButterKnife.bind(this); Intent intent = getIntent(); username = intent.getStringExtra("username"); password = intent.getStringExtra("password"); groupname = intent.getStringExtra("groupname"); groupnamefield.setText(groupname); save_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { newgroupname = groupnamefield.getText().toString(); try { HttpUrl.Builder urlBuilder = HttpUrl.parse("http://adm-store.com/AttendanceDB/update_group.php").newBuilder(); urlBuilder.addQueryParameter("username", username); urlBuilder.addQueryParameter("password", password); urlBuilder.addQueryParameter("groupname", groupname); urlBuilder.addQueryParameter("newgroupname", newgroupname); String built = urlBuilder.build().toString(); doGetRequest(built); } catch (IOException e) { e.printStackTrace(); } } }); cancel_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_editgroup, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.delete) { try { HttpUrl.Builder urlBuilder = HttpUrl.parse("http://adm-store.com/AttendanceDB/remove_group.php").newBuilder(); urlBuilder.addQueryParameter("username", username); urlBuilder.addQueryParameter("password", password); urlBuilder.addQueryParameter("groupname", groupname); String built = urlBuilder.build().toString(); doGetRequest(built); } catch (IOException e) { e.printStackTrace(); } } return true; } OkHttpClient client = new OkHttpClient(); void doGetRequest(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); client.newCall(request) .enqueue(new Callback() { @Override public void onFailure(final Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { } }); } @Override public void onResponse(Call call, final Response response) throws IOException { runOnUiThread(new Runnable() { public void run() { String resp = null; try { resp = response.body().string(); processResults(resp); } catch (IOException e) { e.printStackTrace(); } } }); } }); } void processResults(String resp) { try { JSONObject obj = new JSONObject(resp); int success = obj.getInt("success"); String message = obj.getString("message"); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); if(success == 1) { finish(); } } catch (JSONException e) { e.printStackTrace(); } } }
true
8287667b1f9e2342a7538ea59154f4d34de41500
Java
TonPaes/exercicio_consultorio
/consult/src/test/java/com/consult/consult/unit/service/TurnServiceTest.java
UTF-8
934
2.03125
2
[]
no_license
package com.consult.consult.unit.service; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Date; import com.consult.consult.dto.AllPatientsByDayResponseDTO; import com.consult.consult.service.TurnService; import com.consult.consult.service.TurnServiceImpl; import com.consult.consult.unit.mocks.Mocks; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class TurnServiceTest { TurnService turnService = new TurnServiceImpl(); @Test void contextLoads(){ } @Test void listAllPatientsAllDaysAllDentists(){ AllPatientsByDayResponseDTO mokedResponse = Mocks.getAllPatientsByDayResponseDTO(); Date mockDate = new Date(1624393063); AllPatientsByDayResponseDTO response = turnService.allPatientsByDate(mockDate); assertTrue(response.equals(mokedResponse)); } }
true
013f64d3f22260312a3d53098b2bfe0faacd1069
Java
JJong84/week2
/app/src/main/java/firstTabHelper/PostPerson.java
UTF-8
2,559
2.90625
3
[]
no_license
package firstTabHelper; import android.os.AsyncTask; import android.util.Log; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import Contact.Person; /** * AsyncTask를 이용하여 REST POST콜을 통해 JSON을 입력하는 클래스. */ public class PostPerson { private Person person; public void postPerson(Person person) { this.person = person; new PostTask().execute("http://52.231.68.146:8080/api/contacts"); } // AsyncTask를 inner class로 구현 private class PostTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { Log.d("REST POST", params[0]); try { return POST(params[0]); } catch (IOException e) { return "Unable to retreive data. URL may be invalid."; } } } private String POST(String myurl) throws IOException { InputStream inputStream = null; String returnString = ""; JSONObject json = new JSONObject(); int length = 30000; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.connect(); json.accumulate("name", person.getName()); Log.d("namee",person.getPhone()); json.accumulate("phone", person.getPhone()); json.accumulate("email", person.getEmail()); json.accumulate("address", person.getAddress()); json.accumulate("profile", person.getPhoto()); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(json.toString()); writer.flush(); writer.close(); int response = conn.getResponseCode(); Log.d("REST POST", "The response is : " + response); } catch (Exception e) { Log.e("REST POST", "Error : " + e.getMessage()); } finally { if (inputStream != null) inputStream.close(); } return returnString; } }
true
b2c014fa3747a8718b5eb0d7414a495b9cdc9047
Java
LeszekOtkala/Cucumber
/src/test/java/GL/Cucumber/runners/PageStructure.java
UTF-8
567
1.617188
2
[]
no_license
package GL.Cucumber.runners; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features="classpath:GL/Cucumber/features/PageStructure.feature", glue = {"GL/Cucumber/stepDefinitions"}, // tu szuka step definitions; strict=true, dryRun=false //,tags= {"@RunNow"} //,tags= {"@Positive"}//or //, tags= {"@Positive", "@Negative"}//and //tags= {"@Positive,@Negative"} //or //tags= {"~@Positive", "@Negative"}//and ) public class PageStructure { }
true
e1d61fd2179f061b07f7ada20f599b776da26847
Java
radasilviu/heimdall-backend
/auth-server/src/main/java/com/antonio/authserver/service/AuthService.java
UTF-8
8,784
2.109375
2
[]
no_license
package com.antonio.authserver.service; import com.antonio.authserver.dto.AppUserDto; import com.antonio.authserver.entity.AppUser; import com.antonio.authserver.model.Code; import com.antonio.authserver.model.CustomException; import com.antonio.authserver.model.JwtObject; import com.antonio.authserver.model.LoginCredential; import com.antonio.authserver.repository.AppUserRepository; import com.antonio.authserver.request.ClientLoginRequest; import com.antonio.authserver.utils.SecurityConstants; import io.jsonwebtoken.Claims; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.*; @Service @Transactional public class AuthService { private BCryptPasswordEncoder passwordEncoder; private ClientService clientService; private UserService userService; private JwtService jwtService; private Environment env; private AppUserRepository appUserRepository; private EmailService emailService; @Autowired public AuthService(BCryptPasswordEncoder passwordEncoder, ClientService clientService, UserService userService, JwtService jwtService, Environment env, AppUserRepository appUserRepository, EmailService emailService) { this.passwordEncoder = passwordEncoder; this.clientService = clientService; this.userService = userService; this.jwtService = jwtService; this.env = env; this.appUserRepository = appUserRepository; this.emailService = emailService; } public Code getCode(ClientLoginRequest clientLoginRequest) { clientService.getClientBySecretAndNameWithRealm(clientLoginRequest.getRealm(),clientLoginRequest.getClientId(), clientLoginRequest.getClientSecret()); final AppUserDto user = userService.findByUsernameAndPasswordAndRealm(clientLoginRequest.getUsername(), clientLoginRequest.getPassword(), clientLoginRequest.getRealm()); Code code = clientService.generateCode(user); saveUserWithNewCodeValue(user, code); return code; } private void saveUserWithNewCodeValue(AppUserDto user, Code code) { user.setCode(code.getCode()); userService.update(user); } public JwtObject login(LoginCredential loginCredential) { String code = loginCredential.getClientCode(); verifyClientCode(code); Claims claims = jwtService.decodeJWT(code); final AppUserDto user = userService.getUserByUsername(claims.getIssuer()); long tokenExpirationTime = jwtService.getTokenExpirationTime(); long refreshTokenExpirationTime = jwtService.getRefreshTokenExpirationTime(); final String accessToken = jwtService.createAccessToken(user, tokenExpirationTime, new ArrayList<>(), SecurityConstants.TOKEN_SECRET); final String refreshToken = jwtService.createRefreshToken(refreshTokenExpirationTime, SecurityConstants.TOKEN_SECRET); final JwtObject jwtObject = new JwtObject(user.getUsername(), accessToken, refreshToken, tokenExpirationTime, refreshTokenExpirationTime, user.getIdentityProvider().getProvider()); setJwtToUserAndSave(user, accessToken, refreshToken); return jwtObject; } private void setJwtToUserAndSave(AppUserDto userDto, String token, String refreshToken) { userDto.setToken(token); userDto.setRefreshToken(refreshToken); userService.update(userDto); } private void verifyClientCode(String clientCode) { userService.verifyUserCode(clientCode); } public void logout(JwtObject jwtObject) { // if log out has been called, token need to be updated even on error occurs final AppUserDto appUserDto = userService.getUserByUsername(jwtObject.getUsername()); updateNewTokensToUser(appUserDto, null, null); if (verifyIfUserSessionExpired(jwtObject.getToken_expire_time(), jwtObject.getRefresh_token_expire_time())) { throw new CustomException("Your session has been expired, please log in again.", HttpStatus.UNAUTHORIZED); } } private boolean verifyIfUserSessionExpired(long accessTokenExpirationTime, long refreshTokenExpirationTime) { final long currentTime = System.currentTimeMillis(); return (currentTime > accessTokenExpirationTime && currentTime > refreshTokenExpirationTime); } public JwtObject generateNewAccessToken(JwtObject refreshToken) { final AppUserDto appUserDto = userService.findUserByRefreshToken(refreshToken.getRefresh_token()); JwtObject jwtObject = createNewJWtObject(appUserDto); updateNewTokensToUser(appUserDto, jwtObject.getAccess_token(), jwtObject.getRefresh_token()); return jwtObject; } private void updateNewTokensToUser(AppUserDto appUserDto, String accessToken, String refreshToken) { appUserDto.setToken(accessToken); appUserDto.setRefreshToken(refreshToken); userService.update(appUserDto); } private JwtObject createNewJWtObject(AppUserDto appUserDto) { long tokenExpirationTime = jwtService.getTokenExpirationTime(); long refreshTokenExpirationTime = jwtService.getRefreshTokenExpirationTime(); final String accessToken = generateAccessToken(appUserDto); final String refreshToken = generateRefreshToken(); JwtObject jwtObject = new JwtObject(appUserDto.getUsername(), accessToken, refreshToken, tokenExpirationTime, refreshTokenExpirationTime, appUserDto.getIdentityProvider().getProvider()); return jwtObject; } private String generateRefreshToken() { long expirationTime = System.currentTimeMillis() + SecurityConstants.TOKEN_EXPIRATION_TIME; final String accessToken = jwtService.createRefreshToken(expirationTime, SecurityConstants.TOKEN_SECRET); return accessToken; } private String generateAccessToken(AppUserDto appUserDto) { final String issuer = appUserDto.getUsername(); long expirationTime = jwtService.getTokenExpirationTime(); String accessToken = jwtService.createAccessToken(appUserDto, expirationTime, new ArrayList<>(), SecurityConstants.TOKEN_SECRET); return accessToken; } public void sendForgotPasswordEmail(String email) { Optional<AppUser> user = appUserRepository.findByEmail(email); if (user != null) { String forgotPasswordCode = generateRandomString(); user.get().setForgotPasswordCode(forgotPasswordCode); appUserRepository.save(user.get()); Map<String, Object> model = new HashMap<>(); model.put("email", user.get().getEmail()); model.put("forgotPasswordCode", user.get().getForgotPasswordCode()); model.put("clientFrontedURL", env.getProperty("clientFrontedURL")); emailService.sendEmail("forgot_password.ftl", model, user.get().getEmail(), "Forgot password", this.env.getProperty("mail.from")); } } private String generateRandomString() { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); return generatedString; } public void changePassword(String password, String confirmPassword, String email, String forgotPasswordCode) { if (!password.equals(confirmPassword)) { throw new CustomException("Passwords do not match", HttpStatus.BAD_REQUEST); } Optional<AppUser> user = appUserRepository.findByEmailAndForgotPasswordCode(email, forgotPasswordCode); if (!user.isPresent()) { throw new CustomException("Code invalid or wrong code for user", HttpStatus.BAD_REQUEST); } user.get().setPassword(passwordEncoder.encode(password)); appUserRepository.save(user.get()); } public JwtObject profileLogin(String username, String password, String realm) { AppUserDto user = userService.findByUsernameAndRealmName(username, realm); JwtObject jwtObject = createNewJWtObject(user); return jwtObject; } }
true
30cb86a5daf6c0e9d16e1f8ef44a070c90f9c98f
Java
qihouying/thinkMind
/src/main/java/com/qhy/practice/a20190215/pow_50/Solution.java
UTF-8
761
3.46875
3
[]
no_license
package com.qhy.practice.a20190215.pow_50; /** * Created by dream on 2019/2/17. */ public class Solution { public double myPow(double x, int n) { return n < 0 ? 1.0/(n == Integer.MIN_VALUE ? recurse(x, -(n+1)) : recurse(x, -n)) : recurse(x, n); } public double recurse(double x, int n) { double result = 1; if (0 == n) { return result; } result = recurse(x, n>>1); if (n % 2 == 1) { result = result * result * x; } else { result = result * result; } return result; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.myPow(2.0, 2)); } }
true
ce40637d0a7dfbfc47c2967f11a908522c5b7af2
Java
joshsoftware/OnCoT-Email-Service
/src/main/java/com/josh/emailFunctionality/Exception/NoEmailAccountsRegisteredException.java
UTF-8
299
2.015625
2
[]
no_license
package com.josh.emailFunctionality.Exception; @SuppressWarnings("serial") public class NoEmailAccountsRegisteredException extends RuntimeException { public NoEmailAccountsRegisteredException(String message) { super(message); } public NoEmailAccountsRegisteredException() { super(); } }
true
759798e852f2f5de9d5fef271967d5f5d80ff5e4
Java
llaine/xml-project
/src/main/java/com/miagebdx/domain/User.java
UTF-8
4,971
2.390625
2
[]
no_license
package com.miagebdx.domain; import com.miagebdx.interfaces.IUser; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * gs-actuator-service * * @author llaine * @package com.miagebdx.domain */ public class User implements IUser { private Long id; private String firstname; private String lastname; private String password; private String email; private String birthdayDate; private List<User> friends; private List<Group> groups; public User(String firstname, String lastname, String password, String email, String birthdayDate) { this.firstname = firstname; this.lastname = lastname; this.password = password; this.email = email; this.birthdayDate = birthdayDate; this.friends = new ArrayList<>(); this.groups = new ArrayList<>(); } /* Empty constructor */ public User(){ } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBirthdayDate() { return birthdayDate; } public void setBirthdayDate(String birthdayDate) { this.birthdayDate = birthdayDate; } public List<User> getFriends() { return friends; } public void setFriends(List<User> friends) { this.friends = friends; } public void addFriend(User u){ this.friends.add(u); } public List<Group> getGroups() { return groups; } public void setGroups(List<Group> groups) { this.groups = groups; } @Override public String toString() { return "User{" + "id=" + id + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", birthdayDate='" + birthdayDate + '\'' + ", friends=" + friends + ", groups=" + groups + '}'; } @Override public String getUniqueFileName(){ return "user-" + this.getId() + ".xml"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (birthdayDate != null ? !birthdayDate.equals(user.birthdayDate) : user.birthdayDate != null) return false; if (email != null ? !email.equals(user.email) : user.email != null) return false; if (firstname != null ? !firstname.equals(user.firstname) : user.firstname != null) return false; if (friends != null ? !friends.equals(user.friends) : user.friends != null) return false; if (groups != null ? !groups.equals(user.groups) : user.groups != null) return false; if (id != null ? !id.equals(user.id) : user.id != null) return false; if (lastname != null ? !lastname.equals(user.lastname) : user.lastname != null) return false; if (password != null ? !password.equals(user.password) : user.password != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (firstname != null ? firstname.hashCode() : 0); result = 31 * result + (lastname != null ? lastname.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (birthdayDate != null ? birthdayDate.hashCode() : 0); result = 31 * result + (friends != null ? friends.hashCode() : 0); result = 31 * result + (groups != null ? groups.hashCode() : 0); return result; } /** * get a specific group, lambda style expression! * @param id * @return */ public Optional<Group> getGroup(Long id){ return Optional.ofNullable( groups.stream() .filter(group -> group.getId().equals(id)) .findAny() ).orElse(null); } @Override public void addFriends(User user) { this.friends.add(user); } @Override public void addGroup(Group group) { this.groups.add(group); } }
true
247bfe1769a5841339eaf245bbfcbaa4cdf03698
Java
maptopixel/metaworkflows-wps
/src/main/java/org/n52/wps/demo/ExtensionTest.java
UTF-8
1,347
2.59375
3
[ "Apache-2.0" ]
permissive
package org.n52.wps.demo; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.n52.wps.io.data.IData; import org.n52.wps.io.data.binding.literal.LiteralStringBinding; import org.n52.wps.server.AbstractSelfDescribingAlgorithm; import org.n52.wps.server.ExceptionReport; /** * Simple mockup algorithm doing nothing special. * * @author matthes rieke * */ public class ExtensionTest extends AbstractSelfDescribingAlgorithm { static final String INPUT = "inputString"; static final String OUTPUT = "resultOutput"; public Class<?> getInputDataType(String identifier) { if (identifier.equals(INPUT)) { return LiteralStringBinding.class; } return null; } public Class<?> getOutputDataType(String identifier) { if (identifier.equals(OUTPUT)) { return LiteralStringBinding.class; } return null; } public Map<String, IData> run(Map<String, List<IData>> data) throws ExceptionReport { Map<String,IData> result = new HashMap<String, IData>(); System.out.println("Jules test algo"); result.put(OUTPUT, data.get(INPUT).get(0)); return result; } @Override public List<String> getInputIdentifiers() { return Collections.singletonList(INPUT); } @Override public List<String> getOutputIdentifiers() { return Collections.singletonList(OUTPUT); } }
true
c9d07ec1492bdeed3276e087e51120fa3cbc0dd9
Java
AY2021S1-CS2103T-T15-1/tp
/src/main/java/seedu/address/model/HairStyleX.java
UTF-8
11,155
2.59375
3
[ "MIT" ]
permissive
package seedu.address.model; import static java.util.Objects.requireNonNull; import java.util.List; import java.util.Objects; import javafx.collections.ObservableList; import seedu.address.logic.commandshortcut.CommandShortcutSet; import seedu.address.model.appointment.Appointment; import seedu.address.model.appointment.AppointmentId; import seedu.address.model.appointment.UniqueAppointmentList; import seedu.address.model.person.Person; import seedu.address.model.person.client.Client; import seedu.address.model.person.client.ClientId; import seedu.address.model.person.client.UniqueClientList; import seedu.address.model.person.hairdresser.Hairdresser; import seedu.address.model.person.hairdresser.HairdresserId; import seedu.address.model.person.hairdresser.UniqueHairdresserList; /** * Wraps all data at the hairStyleX level * Duplicates are not allowed (by .isSamePerson comparison) */ public class HairStyleX implements ReadOnlyHairStyleX { private final UniqueClientList clients; private final UniqueHairdresserList hairdressers; private final UniqueAppointmentList appointments; private final IdCounter idCounter; private final CommandShortcutSet commandShortcutSet; /* * The 'unusual' code block below is a non-static initialization block, sometimes used to avoid duplication * between constructors. See https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html * * Note that non-static init blocks are not recommended to use. There are other ways to avoid duplication * among constructors. */ { clients = new UniqueClientList(); hairdressers = new UniqueHairdresserList(); appointments = new UniqueAppointmentList(); idCounter = IdCounter.getInstance(); commandShortcutSet = CommandShortcutSet.getInstance(); } public HairStyleX() {} /** * Creates an HairStyleX using the Persons in the {@code toBeCopied} */ public HairStyleX(ReadOnlyHairStyleX toBeCopied) { this(); resetData(toBeCopied); } //// list overwrite operations /** * Replaces the content of the idCounter with {@code idCounter}. * {@code appointments} must not contain duplicate entities. */ public void setIdCounter(IdCounter idCounter) { this.idCounter.setCurrentMaxClientId(idCounter.getCurrentMaxClientId()); this.idCounter.setCurrentMaxHairdresserId(idCounter.getCurrentMaxHairdresserId()); this.idCounter.setCurrentMaxAppointmentId(idCounter.getCurrentMaxAppointmentId()); } public void setCommandAliasSet(CommandShortcutSet aliasSet) { this.commandShortcutSet.setUpAliasSet(aliasSet); } /** * Resets the existing data of this {@code HairStyleX} with {@code newData}. */ public void resetData(ReadOnlyHairStyleX newData) { requireNonNull(newData); setHairdressers(newData.getHairdresserList()); setClients(newData.getClientList()); setHairdressers(newData.getHairdresserList()); setAppointments(newData.getAppointmentList()); setIdCounter(newData.getIdCounter()); } /** * Returns true if a person with the same identity as any * {@code hairdresser} or {@code client} exists in the hairStyleX. */ public boolean hasPerson(Person person) { requireNonNull(person); return hairdressers.containsPerson(person) || clients.containsPerson(person); } //===============hairdresser-level operations============= /** * Returns true if a hairdresser with the same identity as {@code hairdresser} exists in the hairStyleX. */ public boolean hasHairdresser(Hairdresser hairdresser) { requireNonNull(hairdresser); return hairdressers.contains(hairdresser); } /** * Adds a hairdresser to the hairStyleX. * The hairdresser must not already exist in the hairStyleX. */ public void addHairdresser(Hairdresser p) { hairdressers.add(p); } /** * Replaces the given hairdresser {@code target} in the list with {@code editedHairdresser}. * {@code target} must exist in the hairStyleX. * The hairdresser identity of {@code editedHairdresser} must not be the same as * another existing hairdresser in the hairStyleX. */ public void setHairdresser(Hairdresser target, Hairdresser editedHairdresser) { requireNonNull(editedHairdresser); hairdressers.setHairdresser(target, editedHairdresser); } /** * Replaces the contents of the hairdresser list with {@code hairdressers}. * {@code hairdressers} must not contain duplicate persons. */ public void setHairdressers(List<Hairdresser> hairdressers) { this.hairdressers.setHairdressers(hairdressers); } /** * Removes {@code key} from this {@code HairStyleX}. * {@code key} must exist in the hairStyleX. */ public void removeHairdresser(Hairdresser key) { hairdressers.remove(key); } //============client level operations================= /** * Replaces the contents of the client list with {@code clients}. * {@code clients} must not contain duplicate clients. */ public void setClients(List<Client> clients) { this.clients.setClients(clients); } /** * Returns true if a client with the same identity as {@code client} exists in the hairStyleX. */ public boolean hasClient(Client client) { requireNonNull(client); return clients.contains(client); } /** * Adds a client to the hairStyleX. * The client must not already exist in the hairStyleX. */ public void addClient(Client p) { clients.add(p); } /** * Replaces the given client {@code client} in the list with {@code editedClient}. * {@code target} must exist in the hairStyleX. * The client identity of {@code editedClient} must not be the same as another existing client in the hairStyleX. */ public void setClient(Client target, Client editedClient) { requireNonNull(editedClient); clients.setClient(target, editedClient); } /** * Removes {@code key} from this {@code HairStyleX}. * {@code key} must exist in the hairStyleX. */ public void removeClient(Client key) { clients.remove(key); } //// util methods /** * Return object Client with given id */ public Client getClientById(ClientId clientId) { requireNonNull(clientId); return clients.findClientById(clientId); } /** * Return object Hairdresser with given id */ Hairdresser getHairdresserById(HairdresserId hairdresserId) { requireNonNull(hairdresserId); return hairdressers.findHairdresserById(hairdresserId); } /** * Return object Appointment with given id */ Appointment getAppointmentById(AppointmentId appointmentId) { requireNonNull(appointmentId); return appointments.findAppointmentById(appointmentId); } @Override public ObservableList<Client> getClientList() { return clients.asUnmodifiableObservableList(); } // ================Appointment level operations ============== /** * Replaces the contents of the appointment list with {@code appointments}. * {@code appointment} must not contain duplicate persons. */ public void setAppointments(List<Appointment> appointments) { this.appointments.setAppointments(appointments); } /** * Removes {@code key} from this {@code HairStyleX}. * {@code key} must exist in the hairStyleX. */ public void removeAppointment(Appointment key) { appointments.remove(key); } /** * When patient is modified, update patient info in appointment */ public void updateAppointmentWhenClientIsUpdated(ClientId clientId, Client editedClient) { requireNonNull(clientId); appointments.updateClient(clientId, editedClient); } /** * Returns true if a duplicate {@code appointment} exists in HairStyleX. */ public boolean hasAppointment(Appointment appointment) { requireNonNull(appointment); return appointments.contains(appointment); } /** * Adds an appointment. * The appointment must not already exist. */ public void addAppointment(Appointment appointment) { appointments.add(appointment); } /** * Replaces the given appointment {@code target} in the list with {@code changedAppointment}. * {@code target} must exist in HairStyleX. * The new appointment must not be a duplicate of an existing appointment in HairStyleX. */ public void setAppointment(Appointment target, Appointment changedAppointment) { requireNonNull(changedAppointment); appointments.setAppointment(target, changedAppointment); } @Override public ObservableList<Appointment> getAppointmentList() { return appointments.asUnmodifiableObservableList(); } /** * Set client in appointments to null when the client with the id is deleted */ public void updateAppointmentWhenClientDeleted(ClientId clientId) { requireNonNull(clientId); appointments.deleteClient(clientId); } /** * Set hairdresser in appointments to null when the hairdresser with the id is deleted */ public void updateAppointmentWhenHairdresserDeleted(HairdresserId hairdresserId) { requireNonNull(hairdresserId); appointments.deleteHairdresser(hairdresserId); } /** * When hairdresser is modified, update hairdresser info in appointment */ public void updateAppointmentWhenHairdresserIsUpdated(HairdresserId hairdresserId, Hairdresser editedHairdresser) { requireNonNull(hairdresserId); appointments.updateHairdresser(hairdresserId, editedHairdresser); } //// util methods @Override public String toString() { return clients.asUnmodifiableObservableList().size() + " clients"; // TODO: refine later } @Override public ObservableList<Hairdresser> getHairdresserList() { return hairdressers.asUnmodifiableObservableList(); } @Override public IdCounter getIdCounter() { return idCounter; } @Override public CommandShortcutSet getCommandAliasSet() { return commandShortcutSet; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof HairStyleX // instanceof handles nulls && clients.equals(((HairStyleX) other).clients) && hairdressers.equals(((HairStyleX) other).hairdressers) && appointments.equals(((HairStyleX) other).appointments) && idCounter.equals(((HairStyleX) other).idCounter)); } @Override public int hashCode() { return Objects.hash(hairdressers, appointments, idCounter, clients); } }
true
c0853844f51c08415168a39313ad8000f5bb9ab3
Java
ha271923/leetcode
/app/src/main/java/com/cspirat/MissingRanges.java
UTF-8
1,481
3.59375
4
[ "MIT" ]
permissive
package com.cspirat; import java.util.ArrayList; import java.util.List; /** * Project Name : Leetcode * Package Name : leetcode * File Name : MissingRanges * Creator : Edward * Date : Sep, 2017 * Description : 163. Missing Ranges */ public class MissingRanges { /** * Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], * return its missing ranges. For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. [2147483647] 0 2147483647 ["0->2147483646"] ["0->2147483646","-2147483648->2147483647"] time : O(n) space : O(1) * @param nums * @param lower * @param upper * @return */ public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> res = new ArrayList<>(); long alower = (long)lower, aupper = (long)upper; for (int num : nums) { if (num == alower) { alower++; } else if (alower < num) { if (alower + 1 == num) { res.add(String.valueOf(alower)); } else { res.add(alower + "->" + (num - 1)); } alower = (long)num + 1; } } if (alower == aupper) res.add(String.valueOf(alower)); else if (alower < aupper) res.add(alower + "->" + aupper); return res; } }
true
6ed88d7dd5f6d777b67bb2edffd86396fcf87fb7
Java
Egorman7/Mobile2
/app/src/main/java/app/and/mobile2/api/IRedditApi.java
UTF-8
337
1.875
2
[]
no_license
package app.and.mobile2.api; import app.and.mobile2.models.RedditDataModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface IRedditApi { @GET("r/puppy.json?raw_json=1/") Call<RedditDataModel> getPuppiesModel(@Query("after") String after, @Query("limit") int limit); }
true
21e99cfb0882ebfefc0d9bfc50541fac4585a9d5
Java
EdLittle/hushfinal
/src/GUI/FieldPanel.java
UTF-8
4,688
2.5625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * FieldPanel.java * * Created on Jan 27, 2012, 2:07:29 AM */ package GUI; import java.awt.CardLayout; import javax.swing.JPanel; /** * * @author FREAK */ public class FieldPanel extends javax.swing.JPanel { private String newUsername; static JPanel[] panels; int number; /** Creates new form FieldPanel */ public FieldPanel() { initComponents(); } public FieldPanel(int number){ initComponents(); this.number = number; } public static void setStaticFields(JPanel[] panels){ FieldPanel.panels = panels; } /** 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() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/med/add.png"))); // NOI18N jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jLabel1MouseEntered(evt); } }); add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 30, -1, -1)); jTextField1.setFont(new java.awt.Font("Century Gothic", 2, 24)); jTextField1.setText("Name here..."); jTextField1.setPreferredSize(new java.awt.Dimension(141, 48)); jTextField1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTextField1MouseClicked(evt); } }); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField1KeyPressed(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { jTextField1KeyTyped(evt); } }); add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 30, 200, -1)); }// </editor-fold>//GEN-END:initComponents private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jLabel1MouseClicked private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextField1MouseClicked // TODO add your handling code here: jTextField1.setText(""); }//GEN-LAST:event_jTextField1MouseClicked private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped // TODO add your handling code here: }//GEN-LAST:event_jTextField1KeyTyped private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed // TODO add your handling code here: int keyCode = evt.getKeyCode(); if(keyCode == 10){ newUsername = jTextField1.getText(); LoginPanel.setUsername(newUsername, this.number); CardLayout cardLayout = (CardLayout)panels[this.number].getLayout(); cardLayout.show(panels[this.number], "card3"); } }//GEN-LAST:event_jTextField1KeyPressed private void jLabel1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseEntered // TODO add your handling code here: }//GEN-LAST:event_jLabel1MouseEntered // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
true
97494d7924319bb6e4f3890bbd305dc466923412
Java
TerenceG-cn/University-course-experiment
/算法分析与设计课程/src/分治法与递归/GoldBullion.java
WINDOWS-1252
1,059
3.078125
3
[]
no_license
package ηݹ; import java.util.Scanner; public class GoldBullion { private final static int N = 5; static void maxmin(int i, int j, float max[], float min[], float a[]) { int mid; float[] lmax = {0}, rmax = {0}, lmin = {0}, rmin = {0}; if (i == j) { min[0] = max[0] = a[i]; } else if (i == j - 1) { max[0] = a[i] > a[j] ? a[i] : a[j]; min[0] = a[i] > a[j] ? a[j] : a[i]; } else { mid = (i + j) / 2;//mid=(i+2j)/3 maxmin(i, mid, lmax, lmin, a); maxmin(mid, j, rmax, rmin, a); max[0] = (lmax[0] > rmax[0]) ? lmax[0] : rmax[0]; min[0] = (lmin[0] < rmin[0]) ? lmin[0] : rmin[0]; } } public static void main(String[] args) { int i; float[] a = new float[N]; float[] max= {Float.MIN_VALUE}; float[] min= {Float.MAX_VALUE}; Scanner scanner = new Scanner(System.in); System.out.printf("array a=?"); for (i = 0; i < N; i++) { a[i] = scanner.nextFloat(); } maxmin(0, N - 1, max, min, a); System.out.println("max="+max[0]+",min="+min[0]); } }
true
15398a0da22984c5e14607e1dc39dc92403e335f
Java
zfan40/musixise-backend
/src/main/java/musixise/web/rest/admin/WorkListFollowResource.java
UTF-8
6,850
2.296875
2
[]
no_license
package musixise.web.rest; import com.codahale.metrics.annotation.Timed; import musixise.domain.WorkListFollow; import musixise.repository.WorkListFollowRepository; import musixise.repository.search.WorkListFollowSearchRepository; import musixise.web.rest.util.HeaderUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.inject.Inject; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.elasticsearch.index.query.QueryBuilders.*; /** * REST controller for managing WorkListFollow. */ @RestController @RequestMapping("/api") public class WorkListFollowResource { private final Logger log = LoggerFactory.getLogger(WorkListFollowResource.class); @Inject private WorkListFollowRepository workListFollowRepository; @Inject private WorkListFollowSearchRepository workListFollowSearchRepository; /** * POST /work-list-follows : Create a new workListFollow. * * @param workListFollow the workListFollow to create * @return the ResponseEntity with status 201 (Created) and with body the new workListFollow, or with status 400 (Bad Request) if the workListFollow has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @RequestMapping(value = "/work-list-follows", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<WorkListFollow> createWorkListFollow(@Valid @RequestBody WorkListFollow workListFollow) throws URISyntaxException { log.debug("REST request to save WorkListFollow : {}", workListFollow); if (workListFollow.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("workListFollow", "idexists", "A new workListFollow cannot already have an ID")).body(null); } WorkListFollow result = workListFollowRepository.save(workListFollow); workListFollowSearchRepository.save(result); return ResponseEntity.created(new URI("/api/work-list-follows/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert("workListFollow", result.getId().toString())) .body(result); } /** * PUT /work-list-follows : Updates an existing workListFollow. * * @param workListFollow the workListFollow to update * @return the ResponseEntity with status 200 (OK) and with body the updated workListFollow, * or with status 400 (Bad Request) if the workListFollow is not valid, * or with status 500 (Internal Server Error) if the workListFollow couldnt be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @RequestMapping(value = "/work-list-follows", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<WorkListFollow> updateWorkListFollow(@Valid @RequestBody WorkListFollow workListFollow) throws URISyntaxException { log.debug("REST request to update WorkListFollow : {}", workListFollow); if (workListFollow.getId() == null) { return createWorkListFollow(workListFollow); } WorkListFollow result = workListFollowRepository.save(workListFollow); workListFollowSearchRepository.save(result); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert("workListFollow", workListFollow.getId().toString())) .body(result); } /** * GET /work-list-follows : get all the workListFollows. * * @return the ResponseEntity with status 200 (OK) and the list of workListFollows in body */ @RequestMapping(value = "/work-list-follows", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<WorkListFollow> getAllWorkListFollows() { log.debug("REST request to get all WorkListFollows"); List<WorkListFollow> workListFollows = workListFollowRepository.findAll(); return workListFollows; } /** * GET /work-list-follows/:id : get the "id" workListFollow. * * @param id the id of the workListFollow to retrieve * @return the ResponseEntity with status 200 (OK) and with body the workListFollow, or with status 404 (Not Found) */ @RequestMapping(value = "/work-list-follows/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<WorkListFollow> getWorkListFollow(@PathVariable Long id) { log.debug("REST request to get WorkListFollow : {}", id); WorkListFollow workListFollow = workListFollowRepository.findOne(id); return Optional.ofNullable(workListFollow) .map(result -> new ResponseEntity<>( result, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } /** * DELETE /work-list-follows/:id : delete the "id" workListFollow. * * @param id the id of the workListFollow to delete * @return the ResponseEntity with status 200 (OK) */ @RequestMapping(value = "/work-list-follows/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<Void> deleteWorkListFollow(@PathVariable Long id) { log.debug("REST request to delete WorkListFollow : {}", id); workListFollowRepository.delete(id); workListFollowSearchRepository.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("workListFollow", id.toString())).build(); } /** * SEARCH /_search/work-list-follows?query=:query : search for the workListFollow corresponding * to the query. * * @param query the query of the workListFollow search * @return the result of the search */ @RequestMapping(value = "/_search/work-list-follows", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<WorkListFollow> searchWorkListFollows(@RequestParam String query) { log.debug("REST request to search WorkListFollows for query {}", query); return StreamSupport .stream(workListFollowSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } }
true
81791fae48262eb87459f6c583d665e9ea71281f
Java
LaughingAndroid/base
/base/src/main/java/com/kibey/android/lib/BasePlugin.java
UTF-8
2,812
1.914063
2
[]
no_license
package com.kibey.android.lib; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.kibey.android.app.IContext; import com.kibey.proxy.ui.IToolbar; import java.util.List; /** * by liyihang * blog http://sijienet.com/ */ public abstract class BasePlugin implements PluginBaseInterface { protected static String TAG; protected IContext mContext; protected IContext getContext() { return mContext; } public FragmentActivity getActivity() { return mContext.getActivity(); } protected String mPluginName; @Override public ViewGroup onCreate(Bundle savedInstanceState, IContext activity, String pluginName) { TAG = getClass().getName(); this.mContext = activity; this.mPluginName = pluginName; ViewGroup view = (ViewGroup) PluginApkManager.inflate(mPluginName, getLayoutId(contentLayoutRes()), null); onViewCreated(view); return view; } public void onViewCreated(View view) { } @Override public void onDestroy() { } @Override public void onStart() { } @Override public void onResume() { } @Override public void onPause() { } @Override public void onStop() { } @Override public void onRestart() { } @Override public void onNewIntent(Intent intent) { } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { } @Override public boolean onBackPressed() { return false; } @Override public boolean onTouchEvent(MotionEvent event) { return false; } @Override public void onSaveInstanceState(Bundle outState) { } @Override public int getToolbarFlags() { return IToolbar.FLAG_NONE; } @Override public void setupToolbar(IToolbar toolbar) { } @Override public int getStatusBarColor() { return Color.WHITE; } @Override public void setData(int page, List data) { } @Override public RecyclerView.LayoutManager buildLayoutManager() { return new LinearLayoutManager(getActivity()); } @Override public boolean isTranslucentStatus() { return true; } @Override public String contentLayoutRes() { return "layout_base_list"; } public int getLayoutId(String name) { return PluginApkManager.getPluginApp(mPluginName).getResources().getIdentifier(name, "layout", mPluginName); } }
true
eaceccf4f2e6c284f3205170178a2eda17a44c5c
Java
jerlosam/b-cms-integration
/src/test/java/io/crazy88/beatrix/e2e/clients/ProfileSearchClient.java
UTF-8
921
1.828125
2
[]
no_license
package io.crazy88.beatrix.e2e.clients; import com.fasterxml.jackson.annotation.JsonProperty; import io.crazy88.beatrix.e2e.clients.dto.ProfileSearchResponse; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import static org.springframework.web.bind.annotation.RequestMethod.GET; @FeignClient(url = "${feign.profileSearch.url}", name = "profileSearch") public interface ProfileSearchClient { @JsonProperty("items") @RequestMapping(value = "v1/profiles", method = GET) ProfileSearchResponse searchProfile(@RequestHeader(AUTHORIZATION) String auth, @RequestParam("free_text") String searchCriteria); }
true
f967cefea0ac7a49d7273189366e2915bfc0050c
Java
vandongkyd/GitBuyer
/data/src/main/java/com/fernandocejas/android10/restrofit/enity/buyer/UserEntityResponse_Buyer.java
UTF-8
777
1.960938
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.fernandocejas.android10.restrofit.enity.buyer; import android.support.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; /** * Created by vandongluong on 3/12/18. */ @AutoValue public abstract class UserEntityResponse_Buyer { @SerializedName("status") public abstract boolean status(); @SerializedName("message") @Nullable public abstract String message(); @SerializedName("data") @Nullable public abstract UserEntity_Buyer data(); public static TypeAdapter<UserEntityResponse_Buyer> typeAdapter(Gson gson) { return new AutoValue_UserEntityResponse_Buyer.GsonTypeAdapter(gson); } }
true
b16260c36d3385db846fb9cee006f2cc2a99d41f
Java
CS-537-Spring-2016/ROVER_07
/src/swarmBots/ROVER_07.java
UTF-8
13,888
2.375
2
[]
no_license
package swarmBots; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import common.Coord; import common.MapTile; import common.ScanMap; import enums.RoverName; import enums.Science; import enums.Terrain; import rover07Util.Communications.ScienceInfo; import rover07Util.*; import rover07Util.Pathfinding.DStarLite; import rover07Util.Pathfinding.MapCell; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * The seed that this program is built on is a chat program example found here: * http://cs.lmu.edu/~ray/notes/javanetexamples/ Many thanks to the authors for * publishing their code examples */ public class ROVER_07 { // connection settings private final String ROVER_NAME = "ROVER_07"; private final String SERVER_ADDRESS; private final int PORT_ADDRESS = 9537; private Query q; private RoverComms comms; /** * Constructors */ public ROVER_07(String serverAddress) { System.out.println("ROVER_07 rover object constructed"); SERVER_ADDRESS = serverAddress; } /** * Connects to the server then enters the processing loop. */ private void run() throws IOException { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Make connection and initialize streams Socket socket = new Socket(SERVER_ADDRESS, PORT_ADDRESS); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); q = new Query(in, out, gson); // Set up rover communications thread try { comms = new RoverComms(RoverName.getEnum(ROVER_NAME)); } catch (IOException e) { comms = null; System.err.println("Failed to initialize rover connection"); e.printStackTrace(); } // Process all messages from server, wait until server requests Rover ID name while (true) { String line = in.readLine(); if (line.startsWith("SUBMITNAME")) { // This sets the name of this instance of a swarmBot for identifying the thread to the server out.println(ROVER_NAME); break; } } // Enter main loop try { mainLoop(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } try { socket.close(); } catch (Exception e) { System.err.println("Failed to close socket"); e.printStackTrace(); } if (comms != null) comms.close(); } /** * Main rover logic */ private void mainLoop() throws IOException, InterruptedException { ArrayList<String> equipment; Coord startLoc; Coord targetLoc; Coord currentLoc; Coord goal; DStarLite pf = null; List<MapCell> path = null; Set<WorldMapCell> roverCells = new HashSet<>(); int failures = 0; /** * Get initial values that won't change */ // get EQUIPMENT equipment = q.getEquipment(); System.out.println(ROVER_NAME + " equipment list results " + equipment + "\n"); // get START_LOC startLoc = q.getLoc(Query.LocType.START); System.out.println(ROVER_NAME + " START_LOC " + startLoc); // get TARGET_LOC targetLoc = q.getLoc(Query.LocType.TARGET); System.out.println(ROVER_NAME + " TARGET_LOC " + targetLoc); // build WorldMap WorldMap worldMap = new WorldMap(targetLoc.xpos + 10, targetLoc.ypos + 10); // build GoalPicker final GoalPicker goalPicker = new GoalPicker(); goalPicker.addDefault(worldMap.getCell(targetLoc)); // target corner goalPicker.addDefault(worldMap.getCell(startLoc.xpos, targetLoc.ypos)); // top right corner goalPicker.addDefault(worldMap.getCell(targetLoc.xpos, startLoc.ypos)); // bottom left corner goal = targetLoc; // initial goal while (true) { if (comms != null) { Set<ScienceInfo> commsData = comms.getScience(); if (commsData != null) { for (ScienceInfo info : commsData) { System.out.println("received data from other rover: " + info.getTerrain() + " " + info.getScience() + " " + info.getCoord()); // get cell from world map WorldMapCell cell = worldMap.getCell(info.getCoord()); if (cell == null) continue; // update tile MapTile tile = cell.getTile(); if (tile == null) { tile = new MapTile(info.getTerrain(), info.getScience(), 0, false); cell.setTile(tile); // if we had to generate a new tile, we need to check if it's traversable for pf if (tile.getTerrain() == Terrain.NONE || tile.getTerrain() == Terrain.ROCK) { cell.setBlocked(true); if (pf != null) pf.markChangedCell(cell); } } else { tile.setSciecne(info.getScience()); } // add to goalpicker goalPicker.addCell(worldMap.getCell(info.getCoord())); } } } // **** do a LOC **** currentLoc = q.getLoc(); System.out.println("ROVER_07 current location: " + currentLoc); // ***** do a SCAN ***** //System.out.println("ROVER_07 sending SCAN request"); ScanMap scanMap = q.getScan(); //scanMap.debugPrintMap(); boolean replan = false; { // check if we need to grow world map int extentX = 0; int extentY = 0; final int scanSize = scanMap.getEdgeSize(); final MapTile[][] map = scanMap.getScanMap(); for (int x = 0; x < scanSize; x++) { for (int y = 0; y < scanSize; y++) { if (x <= extentX && y <= extentY) continue; final MapTile tile = map[x][y]; if (tile.getTerrain() != Terrain.NONE) { extentX = Math.max(x, extentX); extentY = Math.max(y, extentY); } } } final int maxX = currentLoc.xpos - (scanSize >> 1) + extentX; final int maxY = currentLoc.ypos - (scanSize >> 1) + extentY; final int growX = Math.max(maxX - worldMap.getWidth(), 0); final int growY = Math.max(maxY - worldMap.getHeight(), 0); if (growX + growY > 0) { worldMap.grow(growX, growY); if (pf != null) pf = new DStarLite(worldMap, worldMap.getCell(currentLoc), worldMap.getCell(goal)); replan = true; } } // merge terrain/science changes Set<WorldMapCell> changes = worldMap.updateMap(currentLoc, scanMap); for (WorldMapCell cell : changes) { final MapTile tile = cell.getTile(); //System.out.println("learned " + cell.getCoord() + " is " + // tile.getTerrain().getTerString() + tile.getScience().getSciString()); // check not traversable if (tile.getTerrain() == Terrain.NONE || tile.getTerrain() == Terrain.ROCK) { cell.setBlocked(true); if (pf != null) pf.markChangedCell(cell); replan = true; } // communicate science if (tile.getScience() != Science.NONE) { goalPicker.addCell(cell); if (comms != null) { comms.sendScience(new ScienceInfo(tile.getTerrain(), tile.getScience(), cell.getCoord())); } } } // mark rover cells as blocked { // unblock last set for (WorldMapCell cell : roverCells) { cell.setBlocked(false); if (pf != null) pf.markChangedCell(cell); replan = true; } roverCells.clear(); // block new set final int scanSize = scanMap.getEdgeSize(); final MapTile[][] scanTiles = scanMap.getScanMap(); final int radius = scanSize >> 1; final int startX = currentLoc.xpos - radius; final int startY = currentLoc.ypos - radius; for (int dx = 0; dx < scanSize; dx++) { for (int dy = 0; dy < scanSize; dy++) { if (dx == radius && dy == radius) continue; // don't block our own spot if (scanTiles[dx][dy].getHasRover()) { WorldMapCell cell = worldMap.getCell(startX + dx, startY + dy); if (cell == null || cell.isBlocked()) continue; cell.setBlocked(true); roverCells.add(cell); if (pf != null) pf.markChangedCell(cell); replan = true; } } } } // ***** do a GATHER ***** q.doGather(); { // unmark any gatherable science at this loc MapTile tile = worldMap.getCell(currentLoc).getTile(); Terrain terr = tile.getTerrain(); if (terr != Terrain.ROCK && terr != Terrain.GRAVEL) { tile.setSciecne(Science.NONE); } } // ***** move ***** Coord bestGoal = goalPicker.getClosestGoal(currentLoc); if (bestGoal == null) { // TODO perform clustering to find least discovered areas? bestGoal = targetLoc; } if (!bestGoal.equals(goal)) { System.out.println("best goal -> " + bestGoal); goal = bestGoal; failures = 0; pf = null; } // if pf is null, we need to make a new instance of D*Lite if (pf == null) { pf = new DStarLite(worldMap, worldMap.getCell(currentLoc), worldMap.getCell(goal)); replan = true; } // if replan is true, we need to (re)calculate a path if (replan) { pf.updateStart(worldMap.getCell(currentLoc)); pf.solve(); path = pf.getPath(); } if (path.isEmpty()) { ++failures; if (failures >= 5) { goalPicker.removeGoal(worldMap.getCell(goal)); } } else { MapCell next; while (true) { if (path.isEmpty()) { next = null; break; } next = path.get(0); if (currentLoc.xpos == next.getX() && currentLoc.ypos == next.getY()) { path.remove(0); } else { break; } } if (next != null) { if (next.getX() == currentLoc.xpos + 1) { q.doMove("E"); } else if (next.getY() == currentLoc.ypos + 1) { q.doMove("S"); } else if (next.getX() == currentLoc.xpos - 1) { q.doMove("W"); } else if (next.getY() == currentLoc.ypos - 1) { q.doMove("N"); } else { System.err.println("Can't find which way to move: " + "(" + currentLoc.xpos + "," + currentLoc.ypos + ") -> " + "(" + next.getX() + "," + next.getY() + ")"); pf = null; } failures = 0; } else { System.err.println("Nowhere left to go?"); } } // repeat Thread.sleep(200); //System.out.println("ROVER_07 ------------ bottom process control --------------"); } } // ################ Support Methods ########################### /** * Runs the client */ public static void main(String[] args) throws Exception { ROVER_07 client; if (args.length > 0) { client = new ROVER_07(args[0]); } else { client = new ROVER_07("localhost"); } client.run(); } }
true
f0ed514b4e3c01e36193361f05b8ddfc34d28a81
Java
prandzio99/University-Classes
/OOP-Java-UniLabs/02-FVAT/InvoiceTest.java
UTF-8
3,628
2.78125
3
[]
no_license
import org.junit.*; import java.time.LocalDate; import java.util.*; public class InvoiceTest { final Person client = new Person("Jan Nowak", "Aleja Grunwaldzka 189/14, Gdansk", "123-456-78-90", "17 2039 5474 0000 3111 0127 3051"); final Person seller = new Person("Castorama", "Aleja Grunwaldzka 262, Gdansk", "010-243-16-07", "53 2343 7801 0000 1031 0251 1171"); static final String TESTDATE = "2020-01-04"; static final List<Item> TESTITEMS = Arrays.asList(new Item("Drabina", 1, 99.0, 0.23), new Item("Sekator", 1, 29.9, 0.23), new Item("Przedłużacz", 2, 24.5, 0.23)); @Test public void testGetItems() { Invoice invoice = new Invoice(client, seller); ArrayList<Item> items = new ArrayList<>(); Assert.assertEquals(invoice.getItems(), items); } @Test public void testAddItem() { Invoice invoice = new Invoice(client, seller); ArrayList<Item> items = new ArrayList<>(); Item item = TESTITEMS[0]; invoice.addItem(item); items.add(item); Assert.assertEquals(invoice.getItems(), items); } @Test public void testGetClient() { Invoice invoice = new Invoice(client, seller); Assert.assertEquals(invoice.getClient(), client); } @Test public void testSetClient() { Invoice invoice = new Invoice(client, seller); Person client2 = new Person("Marek Kowalski", "Zamenhofa 5/7, Gdansk", "132-461-77-91", "21 0936 7002 0000 3441 0124 2115"); invoice.setClient(client2); Assert.assertEquals(invoice.getClient(), client2); } @Test public void testSellTime() { Invoice invoice = new Invoice(client, seller); invoice.setSellTime(LocalDate.parse(TESTDATE)); Assert.assertEquals(invoice.getSellTime(), LocalDate.parse(TESTDATE)); } @Test public void testPaymentTime() { Invoice invoice = new Invoice(client, seller); invoice.setPaymentTime(LocalDate.parse(TESTDATE)); Assert.assertEquals(invoice.getPaymentTime(), LocalDate.parse(TESTDATE)); } @Test public void testGetSum() { Invoice invoice = new Invoice(client, seller); Item item1 = TESTITEMS[1]; Item item2 = TESTITEMS[2]; invoice.addItem(item1); invoice.addItem(item2); Assert.assertEquals(invoice.getSum(), 97.047, 0.001); } @Test public void testGetInvoiceNumber() { Invoice invoice = new Invoice(client, seller); Invoice invoice2 = new Invoice(client, seller); Assert.assertEquals(invoice2.getInvoiceNumber(), invoice.getInvoiceNumber() + 1); } @Test public void testRemoveItem() { Invoice invoice = new Invoice(client, seller); Item item1 = TESTITEMS[1]; Item item2 = TESTITEMS[2]; invoice.addItem(item1); invoice.addItem(item2); invoice.removeItem("Sekator"); Assert.assertEquals(invoice.getItems().size(), 1); } @Test public void testEditItem() { Invoice invoice = new Invoice(client, seller); Item item = TESTITEMS[1]; Item item2 = new Item("Sekator", 1, 24.9, 0.23); invoice.addItem(item); invoice.editItem(item, item2); Assert.assertEquals(invoice.getItem("Sekator"), item2); } @Test public void testGetItem() { Invoice invoice = new Invoice(client, seller); Item item = TESTITEMS[1]; invoice.addItem(item); Assert.assertEquals(invoice.getItem("Pepsi"), item); } }
true
dabd9fb44a4528f0e1e9ff55918ed2fb76e4d416
Java
jamiepngg/cs2030-1920
/labs/lab_7/Main2.java
UTF-8
389
2.796875
3
[]
no_license
import java.util.stream.Stream; class Main { static int gcd(int m, int n) { return Stream .iterate(new Pair<>(Math.max(m, n), Math.min(m, n)), pair -> pair.n != 0, p -> new Pair<>(p.n, p.m % p.n)) .reduce((p1, p2) -> p2) .get() .n; } }
true
0190c227aaacd108a6f0778923fb7a78dd3a4950
Java
ragnel/transactions-essentials
/public/transactions-jms/src/main/java/com/atomikos/jms/internal/AtomikosJmsMessageProducerWrapper.java
UTF-8
9,679
2.15625
2
[]
no_license
/** * Copyright (C) 2000-2023 Atomikos <info@atomikos.com> * * LICENSE CONDITIONS * * See http://www.atomikos.com/Main/WhichLicenseApplies for details. */ package com.atomikos.jms.internal; import javax.jms.CompletionListener; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageProducer; import com.atomikos.datasource.xa.session.SessionHandleState; import com.atomikos.logging.Logger; import com.atomikos.logging.LoggerFactory; class AtomikosJmsMessageProducerWrapper extends ConsumerProducerSupport implements MessageProducer { private static final Logger LOGGER = LoggerFactory.createLogger(AtomikosJmsMessageProducerWrapper.class); private MessageProducer delegate; AtomikosJmsMessageProducerWrapper(MessageProducer delegate, SessionHandleState state) { super(state); this.delegate = delegate; } public void send(Message msg) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( message )..."); } enlist(); delegate.send(msg); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } public void close() throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": close..."); } delegate.close(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": close done."); } } public int getDeliveryMode() throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": getDeliveryMode()..."); } int ret = delegate.getDeliveryMode(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": getDeliveryMode() returning " + ret); } return ret; } public Destination getDestination() throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": getDestination()..."); } Destination ret = delegate.getDestination(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": getDestination() returning " + ret); } return ret; } public boolean getDisableMessageID() throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": getDisableMessageID()..."); } boolean ret = delegate.getDisableMessageID(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": getDisableMessageID() returning " + ret); } return ret; } public boolean getDisableMessageTimestamp() throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": getDisableMessageTimestamp()..."); } boolean ret = delegate.getDisableMessageTimestamp(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": getDisableMessageTimestamp() returning " + ret); } return ret; } public int getPriority() throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": getPriority()..."); } int ret = delegate.getPriority(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": getPriority() returning " + ret); } return ret; } public long getTimeToLive() throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": getTimeToLive()..."); } long ret = delegate.getTimeToLive(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": getTimeToLive() returning " + ret); } return ret; } public void send(Destination dest, Message msg) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( destination , message )..."); } enlist(); delegate.send(dest, msg); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } public void send(Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( message , deliveryMode , priority , timeToLive )..."); } enlist(); delegate.send(msg, deliveryMode, priority, timeToLive); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } public void send(Destination dest, Message msg, int deliveryMode, int priority, long timeToLive) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( destination , message , deliveryMode , priority , timeToLive )..."); } enlist(); delegate.send(dest, msg, deliveryMode, priority, timeToLive); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } public void setDeliveryMode(int mode) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": setDeliveryMode ( " + mode + " )..."); } delegate.setDeliveryMode(mode); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": setDeliveryMode done."); } } public void setDisableMessageID(boolean mode) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": setDisableMessageID ( " + mode + " )..."); } delegate.setDisableMessageID(mode); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": setDisableMessageID done."); } } public void setDisableMessageTimestamp(boolean mode) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": setDisableMessageTimestamp ( " + mode + " )..."); } delegate.setDisableMessageTimestamp(mode); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": setDisableMessageTimestamp done."); } } public void setPriority(int pty) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": setPriority ( " + pty + " )..."); } delegate.setPriority(pty); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": setPriority done."); } } public void setTimeToLive(long ttl) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": setTimeToLive ( " + ttl + " )..."); } delegate.setTimeToLive(ttl); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": setTimeToLive done."); } } public String toString() { return "atomikosJmsMessageProducerWrapper for " + delegate; } @Override public void setDeliveryDelay(long deliveryDelay) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": setDeliveryDelay ( " + deliveryDelay + " )..."); } delegate.setDeliveryDelay(deliveryDelay); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": setDeliveryDelay done."); } } @Override public long getDeliveryDelay() throws JMSException { long ret = 0; if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": getDeliveryDelay()..."); } ret = delegate.getDeliveryDelay(); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": getDeliveryDelay() returning " + ret); } return ret; } @Override public void send(Message message, CompletionListener completionListener) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( message , completionListener )..." ); } enlist(); delegate.send(message, completionListener); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } @Override public void send(Message message, int deliveryMode, int priority, long timeToLive, CompletionListener completionListener) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( message , deliveryMode , priority , timeToLive , completionListener)..."); } enlist(); delegate.send(message, deliveryMode, priority, timeToLive, completionListener); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } @Override public void send(Destination destination, Message message, CompletionListener completionListener) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( destination , message , completionListener "); } enlist(); delegate.send(destination, message, completionListener); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } @Override public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive, CompletionListener completionListener) throws JMSException { if (LOGGER.isDebugEnabled()) { LOGGER.logDebug(this + ": send ( destination , message , deliveryMode , priority , timeToLive , completionListener )..."); } enlist(); delegate.send(destination, message, deliveryMode, priority, timeToLive, completionListener); if (LOGGER.isTraceEnabled()) { LOGGER.logTrace(this + ": send done."); } } }
true
d71c9bbfecb9c0416db7cebce68f963d59817499
Java
Bagusnanda90/javaproject
/Project/bean/com/dimata/harisma/form/clinic/CtrlMedicalType.java
UTF-8
6,901
2.171875
2
[]
no_license
/* * Ctrl Name : CtrlMedicalType.java * Created on : [date] [time] AM/PM * * @author : [authorName] * @version : [version] */ /******************************************************************* * Class Description : [project description ... ] * Imput Parameters : [input parameter ...] * Output : [output ...] *******************************************************************/ package com.dimata.harisma.form.clinic; /* java package */ import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /* dimata package */ import com.dimata.util.*; import com.dimata.util.lang.*; /* qdep package */ import com.dimata.qdep.system.*; import com.dimata.qdep.form.*; import com.dimata.qdep.db.*; /* project package */ //import com.dimata.harisma.db.*; import com.dimata.harisma.entity.clinic.*; public class CtrlMedicalType extends Control implements I_Language { public static int RSLT_OK = 0; public static int RSLT_UNKNOWN_ERROR = 1; public static int RSLT_EST_CODE_EXIST = 2; public static int RSLT_FORM_INCOMPLETE = 3; public static String[][] resultText = { {"Berhasil", "Tidak dapat diproses", "Medical Type sudah ada", "Data tidak lengkap"}, {"Succes", "Can not process", "Medical Type already exist", "Data incomplete"} }; private int start; private String msgString; private MedicalType medicalType; private PstMedicalType pstMedicalType; private FrmMedicalType frmMedicalType; int language = LANGUAGE_FOREIGN; public CtrlMedicalType(HttpServletRequest request){ msgString = ""; medicalType = new MedicalType(); try{ pstMedicalType = new PstMedicalType(0); }catch(Exception e){;} frmMedicalType = new FrmMedicalType(request, medicalType); } private String getSystemMessage(int msgCode){ switch (msgCode){ case I_DBExceptionInfo.MULTIPLE_ID : this.frmMedicalType.addError(frmMedicalType.FRM_FIELD_MEDICAL_TYPE_ID, resultText[language][RSLT_EST_CODE_EXIST] ); return resultText[language][RSLT_EST_CODE_EXIST]; default: return resultText[language][RSLT_UNKNOWN_ERROR]; } } private int getControlMsgId(int msgCode){ switch (msgCode){ case I_DBExceptionInfo.MULTIPLE_ID : return RSLT_EST_CODE_EXIST; default: return RSLT_UNKNOWN_ERROR; } } public int getLanguage(){ return language; } public void setLanguage(int language){ this.language = language; } public MedicalType getMedicalType() { return medicalType; } public FrmMedicalType getForm() { return frmMedicalType; } public String getMessage(){ return msgString; } public int getStart() { return start; } public int action(int cmd , long oidMedicalType){ msgString = ""; int excCode = I_DBExceptionInfo.NO_EXCEPTION; int rsCode = RSLT_OK; switch(cmd){ case Command.ADD : break; case Command.SAVE : if(oidMedicalType != 0){ try{ medicalType = PstMedicalType.fetchExc(oidMedicalType); //medicalType.setOID(oidMedicalType); }catch(Exception exc){ } } System.out.println("\nmedicalType oid : "+medicalType.getOID()); frmMedicalType.requestEntityObject(medicalType); if(frmMedicalType.errorSize()>0) { msgString = FRMMessage.getMsg(FRMMessage.MSG_INCOMPLATE); return RSLT_FORM_INCOMPLETE ; } String whereClause = "("+PstMedicalType.fieldNames[PstMedicalType.FLD_TYPE_CODE]+" = '"+medicalType.getTypeCode()+"'"+ " AND "+PstMedicalType.fieldNames[PstMedicalType.FLD_TYPE_NAME]+" = '"+medicalType.getTypeName()+"')"+ " AND "+PstMedicalType.fieldNames[PstMedicalType.FLD_MEDICAL_TYPE_ID]+" <> "+oidMedicalType; System.out.println("\n\n whereClause : "+whereClause); Vector lists = PstMedicalType.list(0,0,whereClause,""); System.out.println("lists : "+lists); if(lists != null && lists.size()>0){ System.out.println("already exist bo....\n"); msgString = resultText[language][RSLT_EST_CODE_EXIST]; return RSLT_EST_CODE_EXIST; } if(medicalType.getOID()==0){ try{ System.out.println("\ninsert : medicalType.getOID() : "+medicalType.getOID()); long oid = pstMedicalType.insertExc(this.medicalType); }catch(DBException dbexc){ excCode = dbexc.getErrorCode(); msgString = getSystemMessage(excCode); return getControlMsgId(excCode); }catch (Exception exc){ msgString = getSystemMessage(I_DBExceptionInfo.UNKNOWN); return getControlMsgId(I_DBExceptionInfo.UNKNOWN); } }else{ try { long oid = pstMedicalType.updateExc(this.medicalType); }catch (DBException dbexc){ excCode = dbexc.getErrorCode(); msgString = getSystemMessage(excCode); }catch (Exception exc){ msgString = getSystemMessage(I_DBExceptionInfo.UNKNOWN); } } break; case Command.EDIT : if (oidMedicalType != 0) { try { medicalType = PstMedicalType.fetchExc(oidMedicalType); } catch (DBException dbexc){ excCode = dbexc.getErrorCode(); msgString = getSystemMessage(excCode); } catch (Exception exc){ msgString = getSystemMessage(I_DBExceptionInfo.UNKNOWN); } } break; case Command.ASK : if (oidMedicalType != 0) { try { medicalType = PstMedicalType.fetchExc(oidMedicalType); } catch (DBException dbexc){ excCode = dbexc.getErrorCode(); msgString = getSystemMessage(excCode); } catch (Exception exc){ msgString = getSystemMessage(I_DBExceptionInfo.UNKNOWN); } } break; case Command.DELETE : if (oidMedicalType != 0){ try{ long oid = PstMedicalType.deleteExc(oidMedicalType); if(oid!=0){ msgString = FRMMessage.getMessage(FRMMessage.MSG_DELETED); excCode = RSLT_OK; }else{ msgString = FRMMessage.getMessage(FRMMessage.ERR_DELETED); excCode = RSLT_FORM_INCOMPLETE; } }catch(DBException dbexc){ excCode = dbexc.getErrorCode(); msgString = getSystemMessage(excCode); }catch(Exception exc){ msgString = getSystemMessage(I_DBExceptionInfo.UNKNOWN); } } break; default : } return rsCode; } }
true
8d87a3ea9dabc7294712bd65e2b84cdb46f94118
Java
yurgenMU/InformationalSystem
/src/main/java/controllers/ContractController.java
UTF-8
2,834
2.234375
2
[]
no_license
package controllers; import model.Contract; import model.Option; import model.Tariff; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import service.ContractService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Set; @Controller public class ContractController { @Autowired private ContractService contractService; public ContractService getContractService() { return contractService; } public void setContractService(ContractService contractService) { this.contractService = contractService; } @GetMapping(value = "contracts/new") public String getCreatePage(@RequestParam("clientId") int clientId, Model model, HttpServletRequest req) { model.addAttribute("client", contractService.getClientService().get(clientId)); model.addAttribute("tariffs", contractService.getTariffService().getAll()); HttpSession session = req.getSession(); return "newContract"; } @GetMapping(value = "contracts/saveNew") public String createNewContract(@RequestParam("clientId") int clientId, Model model, HttpServletRequest req) { HttpSession session = req.getSession(); contractService.addNewContractModel(session, clientId); return "redirect:/"; } @GetMapping(value = "contracts/generatePhoneNumber") @ResponseBody public String generateNumber(HttpServletRequest req){ String number = contractService.generateNumber(); HttpSession session = req.getSession(); session.setAttribute("phone", number); return number; } @GetMapping(value = "contracts/addTariffToBasket") // @ResponseStatus(value = HttpStatus.OK) @ResponseBody public String addTariffToBasket(@RequestParam("tariff") String tariff, HttpServletRequest req){ // contractService.setContractTariff(tariff, req.getSession()); HttpSession session = req.getSession(); Tariff tariff1 = contractService.getTariffService().getByName(tariff); Set<Option> actual = tariff1.getOptions(); session.setAttribute("tariff", tariff1); session.setAttribute("actual", actual); session.setAttribute("other", contractService.getOptionService().getCompatibleOptions(actual)); return "OK"; } @GetMapping(value = "contracts/addPhoneToBasket") @ResponseStatus(value = HttpStatus.OK) public void addOptionToBasket(@ModelAttribute("phone") String phone, HttpServletRequest req){ HttpSession session = req.getSession(); session.setAttribute("phone", phone); } }
true
a3228fbfd3663b48efd152b65d187b109914bcd6
Java
zhengsiyun/maven_carrent
/src/main/java/com/zsy/bus/controller/CheckController.java
UTF-8
2,009
2.203125
2
[]
no_license
package com.zsy.bus.controller; import java.util.Date; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.zsy.bus.domain.Check; import com.zsy.bus.domain.Rent; import com.zsy.bus.service.CheckService; import com.zsy.bus.service.RentService; import com.zsy.bus.vo.CheckVo; import com.zsy.bus.vo.RentVo; import com.zsy.sys.constast.SysConstast; import com.zsy.sys.utils.DataGridView; import com.zsy.sys.utils.ResultObj; @RestController @RequestMapping("check") public class CheckController { @Autowired private CheckService checkService; @Autowired private RentService rentService; /** * 根据出租单号查询出租单信息 */ @RequestMapping("checkRentExist") public Rent checkRentExist(String rentid) { Rent rent = rentService.queryRentByRentId(rentid); return rent; } /** * 根据出租单号加载检查单的数据 */ @RequestMapping("initCheckFormData") public Map<String, Object> initCheckFormData(String rentid){ return checkService.initCheckFormData(rentid); } @RequestMapping("saveCheck") public ResultObj saveCheck(CheckVo checkVo) { try { //设置创建时间 checkVo.setCreatetime(new Date()); //设置归还状态 checkService.addRent(checkVo); return ResultObj.ADD_SUCCESS; } catch (Exception e) { e.printStackTrace(); return ResultObj.ADD_ERROR; } } //全查询 @RequestMapping("loadAllCheck") public DataGridView loadAllCheck(CheckVo checkVo) { return checkService.queryAllCheck(checkVo); } //修改检查单 @RequestMapping("updateCheck") public ResultObj updateCheck(CheckVo checkVo) { try { checkService.updateCheck(checkVo); return ResultObj.UPDATE_SUCCESS; } catch (Exception e) { e.printStackTrace(); return ResultObj.UPDATE_ERROR; } } }
true
c1d43a355a46084369d13166708ebb7929953415
Java
purker/MethodDemosGit
/MethodDemos/src/mapping/ReferenceSetPublicationWorker.java
UTF-8
369
2.328125
2
[]
no_license
package mapping; import java.util.List; import mapping.result.Publication; import mapping.result.Reference; public class ReferenceSetPublicationWorker extends Worker { @Override public void doWork(Publication publication) { List<Reference> references = publication.getReferences(); for(Reference r : references) { r.setPublication(publication); } } }
true
b9336977c5ebaca396aaf207604f0dbb024f10ed
Java
lemon-piepie/design-mode
/factorymode/src/com/company/factorymode/abstractfactory/DrinkProduct.java
UTF-8
115
2.203125
2
[]
no_license
package com.company.factorymode.abstractfactory; public interface DrinkProduct { public void createDrink(); }
true
fbec0447399539bd62528fbb0d2fb7085f12781a
Java
samutayuga/samkuberop
/src/main/java/com/samutup/crd/content/config/ContentConstant.java
UTF-8
340
1.898438
2
[]
no_license
package com.samutup.crd.content.config; public enum ContentConstant { SERVER_CONFIG("server_config", "server_config"); final public String configVal; final public String cofigKey; ContentConstant(String configKey, String configValue) { this.cofigKey = configKey; this.configVal = configValue; } }
true
78e12f45c81e07662ff5c447644eae24a51a90b7
Java
ntrp/quarkus-native-lambda-demo
/src/main/java/org/qantic/quarkus/lambda/LambdaRuntime.java
UTF-8
1,504
2.21875
2
[]
no_license
package org.qantic.quarkus.lambda; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import org.eclipse.microprofile.rest.client.RestClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.Response; import java.net.MalformedURLException; import java.net.URL; public class LambdaRuntime { public static final Logger log = LoggerFactory.getLogger(LambdaRuntime.class); public static final String HEADER_REQUEST_ID = "lambda-runtime-aws-request-id"; public static void main(String[] args) throws MalformedURLException { String lambdaRuntimeApi = System.getenv("AWS_LAMBDA_RUNTIME_API"); log.info(lambdaRuntimeApi); LambdaAPIClient apiClient = RestClientBuilder.newBuilder() .baseUrl(new URL(lambdaRuntimeApi)) .build(LambdaAPIClient.class); while (true) { String requestId = "init"; try { Response next = apiClient.next(); requestId = next.getHeaderString(HEADER_REQUEST_ID); apiClient.respond(requestId, process(next)); } catch (RuntimeException r) { apiClient.error(requestId, r.getMessage()); } } } private static APIGatewayProxyResponseEvent process(Response next) { return new APIGatewayProxyResponseEvent() .withStatusCode(200) .withBody("{\"status\":\"ok\"}"); } }
true
8039061fd4aae6a107860d2c1d5f693329b64ee4
Java
ifwonderland/fudosaninvestor
/src/main/java/com/fudosaninvestor/fudosan/location/exception/AmbiguousAddressException.java
UTF-8
304
2.125
2
[]
no_license
package com.fudosaninvestor.fudosan.location.exception; /** * Multiple address matching given input exception. * <p/> * Created by Shaochen Huang on 11/8/15. */ public class AmbiguousAddressException extends Exception { public AmbiguousAddressException(String message) { super(message); } }
true