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
ccc579a3ee61827c865aab4acb486aacaeaef74a
Java
WanNJ/BuffetANA
/BUFF/BuffClient/src/main/java/gui/ChartController/chart/UpDownLineChart.java
UTF-8
4,013
3.0625
3
[]
no_license
package gui.ChartController.chart; import javafx.collections.ObservableList; import javafx.scene.chart.*; import vo.LongPeiceVO; /** * Created by wshwbluebird on 2017/3/7. */ /** * K 线图 */ public class UpDownLineChart extends LineChart<String, Number> { //TODO 这里参照学长代码进行设计 以后要修改为自己的 private static final int Height=800; private static final int Width=1000; /** * Constructs a XYChart given the two axes. The initial content for the chart * plot background and plot area that includes vertical and horizontal grid * lines and fills, are added. * * @param stringAxis X Axis for this XY chart * @param numberAxis Y Axis for this XY chart */ public UpDownLineChart(Axis<String> stringAxis, Axis<Number> numberAxis) { super(stringAxis, numberAxis); setAnimated(false); stringAxis.setAnimated(false); numberAxis.setAnimated(false); } /** * 直接用序列好的数据初始化 * @param xAxis * @param yAxis * @param data */ public UpDownLineChart(Axis<String> xAxis, Axis<Number> yAxis, ObservableList<Series<String, Number>> data) { this(xAxis, yAxis); setData(data); } /** * 建立线性 * @param ups * @param downs * @return */ public static UpDownLineChart createChart(ObservableList<LongPeiceVO> ups, ObservableList<LongPeiceVO> downs){ double max= Math.max(getMax(ups),getMax(downs)); //获取图像最小值 double min = Math.max(getMin(ups),getMin(downs)); // 参考学长的代码 计算间距 double gap=(max-min)/10; double HpixelPerValue=20; //X轴 final CategoryAxis xAxis = new CategoryAxis (); //Y轴 final NumberAxis yAxis = new NumberAxis(min-gap,max+gap*2,gap); final UpDownLineChart upDownLineChart= new UpDownLineChart(xAxis,yAxis); xAxis.setLabel("Day"); yAxis.setLabel("NUM"); // 加载传过来的数据序列 XYChart.Series<String,Number> seriesUp = new XYChart.Series<String,Number>(); seriesUp.setName("上涨股票"); for (int i=0; i< ups.size(); i++) { LongPeiceVO vo = ups.get(i); seriesUp.getData().add( new XYChart.Data<String,Number> (vo.localDate.toString(),vo.amount)); } XYChart.Series<String,Number> seriesDown = new XYChart.Series<String,Number>(); seriesDown.setName("下跌股票"); for (int i=0; i< downs.size(); i++) { LongPeiceVO vo = downs.get(i); seriesDown.getData().add( new XYChart.Data<String,Number> (vo.localDate.toString(),vo.amount)); } upDownLineChart.getData().addAll(seriesUp,seriesDown); //System.out.println("datasize: "+data.size()); double curWidth = HpixelPerValue*ups .size(); if(curWidth<Width){ curWidth=Width; } upDownLineChart.setPrefSize(curWidth,Height*0.95); return upDownLineChart; } /** * 获取图像最低点 * @param longPeiceVOs * @return 返回股票信息最低值的最小值 */ private static long getMin(ObservableList<LongPeiceVO> longPeiceVOs) { long min = 10000; for (LongPeiceVO temp : longPeiceVOs) { long tempMin = temp.amount; if (tempMin < min) { min = tempMin; } } return 0; } /** * 获取图像最高点 * @param longPeiceVOs * @return 返回股票信息的最高值的最大值 */ private static long getMax(ObservableList<LongPeiceVO> longPeiceVOs) { long max = 0; for (LongPeiceVO temp : longPeiceVOs) { long tempMax = temp.amount; if (tempMax > max) { max = tempMax; } } return max; } }
true
2c0c2c07f5bd1af3c530a6eb0d18be5979335a57
Java
brunopicinin/mobe
/mobe/src/br/com/mobe/core/processor/primitive/CalendarProcessor.java
UTF-8
766
2.546875
3
[]
no_license
package br.com.mobe.core.processor.primitive; import java.util.Calendar; import android.content.ContentValues; import android.database.Cursor; import br.com.mobe.core.processor.TimeProcessor; public class CalendarProcessor extends TimeProcessor { @Override public void putIn(ContentValues values, String key, Object value) { values.put(key, ((Calendar) value).getTimeInMillis()); } @Override public Object getFrom(Cursor cursor, int columnIndex) { long l = cursor.getLong(columnIndex); Calendar calendar = null; if (l != 0) { calendar = Calendar.getInstance(); calendar.setTimeInMillis(l); } return calendar; } @Override public String valueToString(Object value) { return String.valueOf(((Calendar) value).getTimeInMillis()); } }
true
eae5ebf8ef520b20862bdf946f41f7ee388c025b
Java
kayartaya-vinod/java-jwt-demo
/jwt-demo/src/main/java/co/vinod/demo/dto/User.java
UTF-8
147
1.625
2
[]
no_license
package co.vinod.demo.dto; import lombok.Data; @Data public class User { private String email; private String password; // md5 or bcrypt }
true
09a9b9294c25c2bec71eb3d41a96dd08195d5a39
Java
sebobr/dontpaytheferryman
/splitter/src/test/java/splitter/KeyValueAcceptor.java
UTF-8
225
2.109375
2
[ "MIT", "Apache-2.0" ]
permissive
package splitter; import java.io.IOException; public interface KeyValueAcceptor<K, V> { public void write(K k, V v) throws IOException, InterruptedException; public void close() throws IOException, InterruptedException; }
true
d3cd4acae40ed34b44ef57786140ee09f5a793ad
Java
achung4/MySQLProject
/src/OnlineTransaction.java
UTF-8
17,201
2.890625
3
[]
no_license
/* TODO System - Delivery Days, cannot purchase nothing; System will inform the customer after commit the number of days it will take to receive the goods (estimated based on outstanding/max orders). */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DecimalFormat; import java.util.ArrayList; import java.sql.Date; public class OnlineTransaction { public Connection con; public branch b; public BufferedReader in = new BufferedReader(new InputStreamReader( System.in)); public OnlineTransaction(Connection c, branch br) { con = c; b = br; } public void startTransaction() { welcome(); } public void welcome() { int choice; boolean quit = false; try { // disable auto commit mode con.setAutoCommit(false); while (!quit) { System.out .print("\n\nYou wanted to make an online transaction? \n"); System.out.print("1. Login\n"); System.out.print("2. Register\n"); System.out.print("3. Back\n>> "); choice = Integer.parseInt(in.readLine()); System.out.println(" "); switch (choice) { case 1: login(); break; case 2: register(); break; case 3: b.showMenu(); default: System.out.println("Wrong format, please try again."); } } con.close(); in.close(); System.out.println("\nGood Bye!\n\n"); System.exit(0); } catch (IOException e) { System.out.println("IOException!"); try { con.close(); System.exit(-1); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); } } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); } } public void register() throws IOException { String cid = "CHECK YOUR CID"; String password, name, address, phone; PreparedStatement ps; Statement stmt; ResultSet rs, rs_id; ArrayList<String> ids = new ArrayList<String>(); boolean correctFormat = false, cidAvailable = false; System.out .print("\nPlease choose a customer ID, the following customer IDs are taken:\n"); try { con.setAutoCommit(false); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT cid FROM Customer"); b.displayEnumTable(rs); stmt.close(); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); } ids.clear(); try { con.setAutoCommit(false); stmt = con.createStatement(); rs_id = stmt.executeQuery("SELECT cid FROM Customer"); // put all existing cid into arraylist while (rs_id.next()) { ids.add(rs_id.getString(1)); } stmt.close(); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); } // Checks for correct format and cid availability while (!correctFormat || !cidAvailable) { System.out.print("\n\nType your desired 4-character ID: "); cid = in.readLine(); if (!ids.contains(cid)) { cidAvailable = true; } else { cidAvailable = false; System.out .println("This CID is not available, please try again."); } if (cid.length() == 4) { correctFormat = true; } else { correctFormat = false; System.out .println("Incorrect format. We're looking for a 4-character id."); } } try { con.setAutoCommit(false); ps = con.prepareStatement("INSERT INTO Customer VALUES (?,?,?,?,?)"); ps.setString(1, cid); System.out.print("\nPassword: "); password = in.readLine(); ps.setString(2, password); System.out.print("\nName: "); name = in.readLine(); ps.setString(3, name); System.out.print("\nAddress: "); address = in.readLine(); ps.setString(4, address); System.out.print("\nPhone: "); phone = in.readLine(); ps.setString(5, phone); ps.executeUpdate(); // commit work con.commit(); ps.close(); System.out.println("Registration Successful!\n" + cid + " is now on the database"); } catch (IOException e) { System.out.println("IOException!"); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); try { // undo the insert con.rollback(); } catch (SQLException ex2) { System.out.println("Message: " + ex2.getMessage()); System.exit(-1); } } b.showMenu(); } public void login() { String cid, password; PreparedStatement ps; ResultSet rs; int rowNumber = 0; String name = null; boolean correctLogin = false; try { while (!correctLogin) { con.setAutoCommit(false); ps = con.prepareStatement("SELECT * FROM Customer WHERE cid = ? AND password = ?"); System.out .print("\nPlease type your unique 4-digit customer ID: "); cid = in.readLine(); ps.setString(1, cid); System.out.print("\nPlease type your password: "); password = in.readLine(); ps.setString(2, password); rs = ps.executeQuery(); // commit work con.commit(); while (rs.next()) { name = rs.getString(3); rowNumber++; } if (rowNumber == 1) { ArrayList<CartItem> wishList = new ArrayList<CartItem>(); customerView(cid, wishList, name.trim()); correctLogin = true; ps.close(); } else { System.out.println("Wrong login, please try again"); } } } catch (IOException e) { System.out.println("IOException!"); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); try { // undo the insert con.rollback(); } catch (SQLException ex2) { System.out.println("Message: " + ex2.getMessage()); System.exit(-1); } } } public void customerView(String cid, ArrayList<CartItem> wishList, String name) throws IOException { boolean quit = false; int choice = 0; double total = 0; DecimalFormat money = new DecimalFormat("$0.00"); while (!quit) { System.out.print("\n\nWelcome, " + name + "!\n"); System.out .print("\nYou have the following items in your virtual cart:\n\n"); System.out.printf("%-20s", "UPC"); System.out.printf("%-20s", "TITLE"); System.out.printf("%-20s", "QUANTITY"); System.out.printf("%-20s", "SELLPRICE"); System.out.printf("%-20s", "TOTAL PRICE"); System.out.println(); for (int i = 0; i < 100; i++) { System.out.printf("-"); } System.out.println(); total = 0; for (CartItem c : wishList) { total = total + c.quantity * c.price; } for (CartItem c : wishList) { System.out.printf("%-20s", c.upc); System.out.printf("%-20s", c.title); System.out.printf("%-20s", c.quantity); System.out.printf("%-20s", money.format(c.price)); System.out.print(money.format(c.quantity * c.price)); System.out.println(); } System.out.println("\nYOUR GRAND TOTAL: " + money.format(total)); if (wishList.size() == 0) { System.out.printf("\nYou have nothing in your virtual cart..."); } System.out.print("\n\nWhat do you want to do? \n"); System.out.print("1. Buy an item\n"); System.out.print("2. Commit to all purchase\n"); System.out.print("3. Leave without saving\n>> "); try { choice = Integer.parseInt(in.readLine()); } catch (NumberFormatException e) { e.printStackTrace(); System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } System.out.println(" "); switch (choice) { case 1: itemSelection(cid, wishList); break; case 2: if (!wishList.isEmpty()) { commit(cid, wishList); wishList.clear(); } else { System.out.println("You have no items to purchase!"); } break; case 3: b.showMenu(); default: System.out.println("Wrong format, please try again."); } } } public void commit(String cid, ArrayList<CartItem> wishList) { String cardNo, expiryDate; int receiptID = 0; PreparedStatement ps; Statement stmt; ResultSet rs; Long time = System.currentTimeMillis(); java.sql.Date now = new java.sql.Date(time); Date[] deliveryAndExpectedDates = deliveryAndExpected(now); // Make the Purchase data point try { con.setAutoCommit(false); System.out .println("You have chosen to commit all the items in your virtual cart."); System.out.println("Please enter your credit card number: "); cardNo = in.readLine(); System.out.println("Please enter your card's expiry date: "); expiryDate = in.readLine(); System.out.println("Perfect. Processing your purchase now..."); ps = con.prepareStatement("INSERT INTO Purchase VALUES(receiptCounter.nextVal, CURRENT_TIMESTAMP, ?, ?, ?, ?, ?)"); ps.setString(1, cid); ps.setString(2, cardNo); ps.setString(3, expiryDate); ps.setDate(4, deliveryAndExpectedDates[0]); ps.setDate(5, deliveryAndExpectedDates[1]); ps.executeUpdate(); // commit work con.commit(); ps.close(); System.out .println("Credit card authenticated!\nProceeding to committing your purchases...\n"); } catch (IOException e) { System.out.println("IOException!"); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); try { // undo the insert con.rollback(); } catch (SQLException ex2) { System.out.println("Message: " + ex2.getMessage()); System.exit(-1); } } // Retrieve ReceiptID try { stmt = con.createStatement(); rs = stmt.executeQuery("SELECT max(receiptID) FROM Purchase"); while (rs.next()) { receiptID = Integer.parseInt(rs.getString(1)); } System.out.println("receiptID retrieval Successful, receiptID = " + receiptID); // close the statement; // the ResultSet will also be closed stmt.close(); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); } // Register all the items in virtual cart try { for (CartItem c : wishList) { con.setAutoCommit(false); ps = con.prepareStatement("INSERT INTO PurchaseItem VALUES (?,?,?)"); ps.setInt(1, receiptID); ps.setString(2, c.upc); ps.setInt(3, c.quantity); ps.executeUpdate(); System.out.println("Added UPC#" + c.upc); // commit work con.commit(); ps.close(); con.setAutoCommit(false); ps = con.prepareStatement("UPDATE Item SET quantity = quantity - ? WHERE Item.upc = ?"); ps.setInt(1, c.quantity); ps.setString(2, c.upc); ps.executeUpdate(); con.commit(); ps.close(); } } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); try { // undo the insert con.rollback(); } catch (SQLException ex2) { System.out.println("Message: " + ex2.getMessage()); System.exit(-1); } } } public void itemSelection(String cid, ArrayList<CartItem> wishList) throws IOException { String title, category, name, upc, response, quantityString, selectionString; CartItem c; String query = "SELECT i.upc, i.title, i.category, i.quantity, l.name, i.sellprice FROM Item I, LeadSinger L WHERE i.upc=l.upc AND i.quantity > 0"; int selection, quantity = 0, quantityLimit = 0, rowCount = 0; Statement stmt; boolean proceed = false, sameSong = false; ResultSet rs, rsCheck, rsCart; try { con.setAutoCommit(false); while (!proceed || sameSong) { stmt = con.createStatement(); System.out.println("\nLet's look for your item..."); System.out .println("Please enter the item title, leave it blank to check everything."); title = in.readLine(); if (!title.isEmpty()) { query = query.concat(" AND i.title = '" + title + "'"); } System.out .println("Please enter the item category, leave it blank to check everything."); category = in.readLine(); if (!category.isEmpty()) { query = query .concat(" AND i.category = '" + category + "'"); } System.out .println("Please enter the artist name, leave it blank to check everything."); name = in.readLine(); if (!name.isEmpty()) { query = query.concat(" AND l.name = '" + name + "'"); } quantity = 0; while (quantity < 1) { System.out .println("Please enter the quantity, leave it blank to default to 1."); quantityString = in.readLine(); if (quantityString.isEmpty()) { quantity = 1; } else { quantity = Integer.parseInt(quantityString); } } rsCheck = stmt.executeQuery(query); while (rsCheck.next()) { rowCount++; } if (rowCount == 0) { System.out.println("\nNo matches found, please try again."); proceed = false; return; } else { proceed = true; } stmt = con.createStatement(); rs = stmt.executeQuery(query); b.displayEnumTable(rs); System.out .println("\n\nI have listed all the items that match your query,\nplease enter the choice# that you want to buy, leave it blank to default to the first choice:"); selectionString = in.readLine(); if (selectionString.isEmpty()) { selection = 1; } else { selection = Integer.parseInt(selectionString); } rsCart = stmt.executeQuery(query); c = rsToCartItem(rsCart, selection); upc = c.upc; title = c.title; quantityLimit = c.quantity; // Make sure this item is not already on the list sameSong = false; for (CartItem c1 : wishList) { if (c1.upc.equals(upc)) { System.out .println("You CANNOT buy the same item twice, please try again."); sameSong = true; break; } } if (!sameSong) { // We know everything, time to put the order in the cart if (quantityLimit < quantity) { System.out.println("There is only " + quantityLimit + " availble, is that okay? (y/n)"); response = in.readLine(); System.out.println("Your reponse was " + response); if (response.equalsIgnoreCase("y")) { System.out .println("Great! You have placed an order for " + quantityLimit + " copies."); wishList.add(c); proceed = true; } else { proceed = false; } } else { // changing c.quantity to become the desired quantity c.quantity = quantity; wishList.add(c); System.out.println("Selection successful!"); System.out .println("You have added another item to your cart"); proceed = true; } } else { break; } } } catch (IOException e) { System.out.println("IOException!"); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); try { // undo the insert con.rollback(); } catch (SQLException ex2) { System.out.println("Message: " + ex2.getMessage()); System.exit(-1); } } } // given the rs and choice, returns the CartItem public CartItem rsToCartItem(ResultSet rs, int choice) throws SQLException { CartItem c = new CartItem("7704", "Recovery", 20, 19.99); int index = 0; while (rs.next()) { index++; if (index == choice) { c.upc = rs.getString(1); c.title = rs.getString(2); c.quantity = Integer.parseInt(rs.getString(4)); c.price = Double.parseDouble(rs.getString(6)); } } if (choice > index) { System.out .println("ERROR - your choice exceed the size of the RS!"); System.out.println("You wanted " + choice); System.out.println("Your index is " + index); } return c; } // Returns an array consisting of the delivery date and expected date // Only 10 deliveries are allowed per day. public Date[] deliveryAndExpected(Date d) { ResultSet rs; int deliveryNumber = 0, limit = 3; PreparedStatement ps; Date[] result = new Date[2]; Date deliveryDate = d; Date deliveryDateAddOne = new Date(deliveryDate.getTime() + 86400000); Date expected = new Date(deliveryDate.getTime() + 86400000 * 5); result[0] = deliveryDate; result[1] = expected; System.out.println("\nChecking if your purchases can be delivered on " + deliveryDate + "..."); try { con.setAutoCommit(false); ps = con.prepareStatement("select count(*) FROM Purchase WHERE deliveredDate > ? AND deliveredDate <= ?"); ps.setDate(1, deliveryDate); ps.setDate(2, deliveryDateAddOne); rs = ps.executeQuery(); while (rs.next()) { deliveryNumber = Integer.parseInt(rs.getString(1)); } con.commit(); } catch (SQLException ex) { System.out.println("Message: " + ex.getMessage()); try { // undo the insert con.rollback(); } catch (SQLException ex2) { System.out.println("Message: " + ex2.getMessage()); System.exit(-1); } } System.out.println("On " + deliveryDate + ", there are currently " + deliveryNumber + " deliveries."); if (deliveryNumber < limit) { System.out .println("Therefore, your purchase can be delivered on that date."); System.out.println("\nYou can expect your purchase to arrive on " + expected + ".\n"); return result; } else { System.out .println("Therefore, your purchase CANNOT be delivered on that date (MAX = " + limit + ")..."); result = deliveryAndExpected(deliveryDateAddOne); return result; } } }
true
6f0989e5fd42c60ac39de4657a09596266eaa584
Java
tujasiri/BriefReqVerify
/src/main/java/com/sample/ProcessTest.java
UTF-8
3,263
2.234375
2
[]
no_license
package com.sample; import com.sample.BriefVerify; import com.sample.MyWorkItemHandler; import org.jbpm.workflow.instance.WorkflowRuntimeException; import org.jbpm.test.JbpmJUnitBaseTestCase; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.logger.KieRuntimeLogger; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.runtime.process.ProcessRuntime; import org.kie.api.runtime.process.WorkItem; import org.kie.api.runtime.process.WorkItemHandler; import org.kie.internal.io.ResourceFactory; import org.kie.internal.utils.KieHelper; /** * This is a sample file to test a process. */ public class ProcessTest extends JbpmJUnitBaseTestCase { @Test public void testProcess() { //RuntimeManager manager = createRuntimeManager("sample.bpmn"); /* RuntimeManager manager = createRuntimeManager("briefverify2.bpmn"); RuntimeEngine engine = getRuntimeEngine(null); KieSession ksession = engine.getKieSession(); */ KieHelper kieHelper = new KieHelper(); KieBase kbase = kieHelper.addResource(ResourceFactory .newClassPathResource("briefverify2.bpmn")) .build(); KieSession ksession = kbase.newKieSession(); KieRuntimeLogger logger = KieServices.Factory.get().getLoggers() .newThreadedFileLogger(ksession, "src/main/resources/mylogfile", 1000); // do something with the ksession here //TestWorkItemHandler testHandler = getTestWorkItemHandler(); try{ ksession.getWorkItemManager().registerWorkItemHandler("Service Task", new MyWorkItemHandler()); //ksession.getWorkItemManager().registerWorkItemHandler("Hello", testHandler); } catch (Exception ex){ System.err.println("WorkitemHandler==>"+ex.toString()); } System.out.println("before process instance start"); System.out.println("Session ID ==>"+ksession.getId()); try{ ProcessInstance processInstance = ksession.startProcess("com.sample.bpmn.ServiceProcess"); } catch(WorkflowRuntimeException e){ System.err.println("processInstance Exception ==>"+e.toString()); } /* WorkItem wi = testHandler.getWorkItem(); System.out.println("workitem info.name==>"+wi.getName()); System.out.println("workitem info.id==>"+wi.getId()); System.out.println("workitem info.state==>"+wi.getState()); */ //System.out.println("Process state=="+processInstance.getState()); //ProcessInstance processInstance = ksession.startProcess("ServiceProcess"); System.out.println("process instance started"); //ProcessInstance processInstance = ksession.startProcess("com.sample.bpmn.briefreqverify"); // check whether the process instance has completed successfully:w /* assertProcessInstanceCompleted(processInstance.getId(), ksession); assertNodeTriggered(processInstance.getId(), "Hello"); */ /* manager.disposeRuntimeEngine(engine); manager.close(); */ ksession.dispose(); logger.close(); System.out.println("reached the end..."); } }
true
d63316544f89b9e78d1e7fbb67f342292f4a0955
Java
moutainhigh/second-hand
/second-product-center/src/main/java/com/example/product/center/model/SecondIntegralStrategy.java
UTF-8
8,465
2.046875
2
[]
no_license
package com.example.product.center.model; import java.io.Serializable; import java.time.LocalDateTime; public class SecondIntegralStrategy implements Serializable { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column second_integral_strategy.id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private Integer id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column second_integral_strategy.product_id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private Integer productId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column second_integral_strategy.integral_id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private Integer integralId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column second_integral_strategy.exempt_commission * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private Integer exemptCommission; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column second_integral_strategy.create_date * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private LocalDateTime createDate; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column second_integral_strategy.modify_date * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private LocalDateTime modifyDate; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column second_integral_strategy.is_deleted * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private Byte isDeleted; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table second_integral_strategy * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ private static final long serialVersionUID = 1L; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column second_integral_strategy.id * * @return the value of second_integral_strategy.id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column second_integral_strategy.id * * @param id the value for second_integral_strategy.id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column second_integral_strategy.product_id * * @return the value of second_integral_strategy.product_id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public Integer getProductId() { return productId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column second_integral_strategy.product_id * * @param productId the value for second_integral_strategy.product_id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public void setProductId(Integer productId) { this.productId = productId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column second_integral_strategy.integral_id * * @return the value of second_integral_strategy.integral_id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public Integer getIntegralId() { return integralId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column second_integral_strategy.integral_id * * @param integralId the value for second_integral_strategy.integral_id * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public void setIntegralId(Integer integralId) { this.integralId = integralId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column second_integral_strategy.exempt_commission * * @return the value of second_integral_strategy.exempt_commission * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public Integer getExemptCommission() { return exemptCommission; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column second_integral_strategy.exempt_commission * * @param exemptCommission the value for second_integral_strategy.exempt_commission * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public void setExemptCommission(Integer exemptCommission) { this.exemptCommission = exemptCommission; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column second_integral_strategy.create_date * * @return the value of second_integral_strategy.create_date * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public LocalDateTime getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column second_integral_strategy.create_date * * @param createDate the value for second_integral_strategy.create_date * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public void setCreateDate(LocalDateTime createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column second_integral_strategy.modify_date * * @return the value of second_integral_strategy.modify_date * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public LocalDateTime getModifyDate() { return modifyDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column second_integral_strategy.modify_date * * @param modifyDate the value for second_integral_strategy.modify_date * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public void setModifyDate(LocalDateTime modifyDate) { this.modifyDate = modifyDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column second_integral_strategy.is_deleted * * @return the value of second_integral_strategy.is_deleted * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public Byte getIsDeleted() { return isDeleted; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column second_integral_strategy.is_deleted * * @param isDeleted the value for second_integral_strategy.is_deleted * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table second_integral_strategy * * @mbg.generated Fri Sep 18 10:45:05 CST 2020 */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", integralId=").append(integralId); sb.append(", exemptCommission=").append(exemptCommission); sb.append(", createDate=").append(createDate); sb.append(", modifyDate=").append(modifyDate); sb.append(", isDeleted=").append(isDeleted); sb.append("]"); return sb.toString(); } }
true
3d6605b834e8beee04bd11f54c3fa630a367bc4c
Java
wilsonpeng3/Tools
/src/thread/MHThreadFactory.java
UTF-8
1,448
2.5625
3
[]
no_license
/* * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package thread; import java.util.concurrent.atomic.AtomicInteger; /** * Created by PC on 2014/9/1. */ public class MHThreadFactory implements java.util.concurrent.ThreadFactory { private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public MHThreadFactory(String threadPoolName) { if (threadPoolName == null || "".equals(threadPoolName)) { threadPoolName = "DefaultPoolName"; } SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = threadPoolName + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }
true
1d68d017e121a83215b6cf66eadc36dfd494208d
Java
shizuan/ZooKeepAndDubbo
/ZooKeeper/src/main/java/com/zuanshi/zooKeeper_watch/PathChildrenCache_监听指定节点的子节点变化情况.java
UTF-8
4,576
2.828125
3
[]
no_license
package com.zuanshi.zooKeeper_watch; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; public class PathChildrenCache_监听指定节点的子节点变化情况 { public static void main(String[] args) throws Exception { /** * RetryPolicy: 失败的重试策略的公共接口 * ExponentialBackoffRetry是 公共接口的其中一个实现类 * 参数1: 初始化sleep的时间,用于计算之后的每次重试的sleep时间 * 参数2:最大重试次数 * 参数3(可以省略):最大sleep时间,如果上述的当前sleep计算出来比这个大,那么sleep用这个时间 */ RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); //创建客户端框架获取连接CuratorFramework.newClient(). /** * 参数1:连接的ip地址和端口号 * 参数2:会话超时时间,单位毫秒 * 参数3:连接超时时间,单位毫秒 * 参数4:失败重试策略 */ CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 3000, 1000, retryPolicy); //启动客户端 client.start(); System.out.println("客户端启动了"); //变化情况包括 1.新增子节点 2.子节点数据变更 3.子节点删除 //创建节点数据监听对象 true 能够获取到节点的数据内容 false 无法取到数据内容 PathChildrenCache childrenCache = new PathChildrenCache(client, "/app", true); //启动监听 /** * NORMAL: 普通启动方式, 在启动时缓存子节点数据 * POST_INITIALIZED_EVENT:在启动时缓存子节点数据,提示初始化 * BUILD_INITIAL_CACHE: 在启动时什么都不会输出 * 在官方解释中说是因为这种模式会在start执行执行之前先执行rebuild的方法,而rebuild的方法不会发出任何事件通知。 */ childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); //监听的回调函数 childrenCache.getListenable().addListener(new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception { //当发生子节点添加后执行该方法:PathChildrenCacheEvent.Type.CHILD_ADDED if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { System.out.println("添加了子节点"); System.out.println("添加的节点为:"+event.getData().getPath()); System.out.println("添加的数据为:"+new String(event.getData().getData())); }else if(event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED){ System.out.println("删除了子节点"); System.out.println("删除的节点为:"+event.getData().getPath()); System.out.println("删除的数据为:"+new String(event.getData().getData())); }else if(event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED){ System.out.println("修改了子节点"); System.out.println("修改的节点为:"+event.getData().getPath()); System.out.println("修改的数据为:"+new String(event.getData().getData())); }else if(event.getType() == PathChildrenCacheEvent.Type.INITIALIZED){ System.out.println("初始化了"); }else if(event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED){ System.out.println("连接失效时执行"); }else if(event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED){ System.out.println("连接时执行"); }else if(event.getType() == PathChildrenCacheEvent.Type.CONNECTION_LOST){ System.out.println("连接失效后,等一会执行"); } } }); System.in.read(); client.close(); } }
true
1479d42c09b1bae64d22ea15bd2862d0d605979c
Java
yuzongjian/fbsys
/src/main/java/com/buoy/job/JobWind.java
UTF-8
3,855
2.328125
2
[]
no_license
package com.buoy.job; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import com.buoy.entity.Wind; import com.buoy.service.JobService; import com.buoy.service.LastTimeService; import com.buoy.util.AccessDBUtil; /** * 风 * @author Howard * 2017年3月6日 */ public class JobWind implements Job{ protected static Logger logger = Logger.getLogger(JobWind.class); @Autowired private JobService jobServiceImpl; @Autowired private LastTimeService lastTimeImpl; @Override public void execute(JobExecutionContext context) throws JobExecutionException { List<Wind> winds = new ArrayList<>(); Connection connection = null; Statement st = null; ResultSet rt = null; ResultSet rt2 = null; String lastTime = lastTimeImpl.selectByBuoyName("wind"); logger.info("查找最新海风数据!上次最新时间:"+lastTime); try { connection = AccessDBUtil.getConnection(); st = connection.createStatement(); rt2 = st.executeQuery("select count(*) from TabFENG1 where 日期时间 > \'"+lastTime+"\' ORDER BY 日期时间 desc "); int totalCount = 0; while(rt2.next()) { totalCount = rt2.getInt(1); } String buoy = null; String newTime = null; int resultCount = 0; String sql = null; int page = (totalCount + 1000 - 1) /1000; for (int i = 0 ; i < page; i ++ ) { if (i == 0) { sql = "select * from TabFENG1 where 日期时间 > \'"+lastTime+"\' ORDER BY 日期时间 , 浮标号 limit 0,1000"; }else { sql = "select * from TabFENG1 where (日期时间 > \'"+lastTime+"\') OR ( 日期时间 = \'"+lastTime+"\' AND 浮标号 > \'"+buoy+"\' ) ORDER BY 日期时间 , 浮标号 limit 0,1000"; } rt = st.executeQuery(sql); while(rt.next()){ String buoyId = rt.getString("浮标号"); String date = rt.getString("日期时间"); String speed_max = rt.getString("最大风速"); String speed_maxto = rt.getString("最大风速的风向"); String speed_maxtime = rt.getString("最大风速时间"); String speed_ji = rt.getString("极大风速"); String speed_jito = rt.getString("极大风速的风向"); String speed_jitime = rt.getString("极大风速时间"); String speed_ten = rt.getString("十分钟平均风速"); String speed_tento = rt.getString("十分钟平均风向"); String to_instant = rt.getString("瞬时风向"); String speed_instant = rt.getString("瞬时风速"); Wind w = new Wind(); w.setDate(date); w.setWindBuoyid(buoyId); w.setWindSpeedMax(speed_max); w.setWindSpeedMaxto(speed_maxto); w.setWindSpeedMaxtime(speed_maxtime); w.setWindSpeedJi(speed_ji); w.setWindSpeedJito(speed_jito); w.setWindSpeedJitime(speed_jitime); w.setWindSpeedTen(speed_ten); w.setWindSpeedTento(speed_tento); w.setWindSpeedInstant(speed_instant); w.setWindToInstant(to_instant); winds.add(w); } if (winds.size() > 0) { newTime = winds.get(winds.size() - 1).getDate(); buoy = winds.get(winds.size() - 1).getWindBuoyid(); } lastTime = newTime; int result_ = jobServiceImpl.addWindList(winds); resultCount+=result_; lastTimeImpl.updateWithDate(newTime, "wind"); winds.clear(); } logger.info("添加海风数据"+totalCount+"条,最新时间:"+newTime); } catch (ClassNotFoundException | SQLException e) { logger.info("接收海风数据出现异常"); e.printStackTrace(); } finally{ AccessDBUtil.closeConnection(connection, st, rt); } } }
true
c3aa261bc30f926d53b108e0ed8df0e05741829d
Java
Pace17881/PriceCheck
/PriceCheck/src/datatypes/ProductInvalidationListener.java
UTF-8
1,006
2.765625
3
[]
no_license
package datatypes; import java.util.ArrayList; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import ui.controller.BaseViewController; public class ProductInvalidationListener implements InvalidationListener { ArrayList<BaseViewController> baseViewControllerList = new ArrayList<>(); @Override public void invalidated(Observable observable) { for (BaseViewController bvc : baseViewControllerList) { bvc.update(); } } public ProductInvalidationListener() { baseViewControllerList = new ArrayList<>(); } public void addViewController(BaseViewController bvc) { baseViewControllerList.add(bvc); System.out.println(bvc + " added"); } public void removeViewController(BaseViewController bvc) { baseViewControllerList.remove(bvc); System.out.println(bvc + " removed"); } @Override public String toString() { return "ProductInvalidationListener: count: " + baseViewControllerList.size(); } }
true
f365e794b8e3efe4c368354138271685fc44606e
Java
rommeliusAlejandro/tours-of-heroes-service
/src/main/java/com/learning/heroesservice/command/businesslogic/DeleteHeroBusinessLogic.java
UTF-8
1,391
2.25
2
[]
no_license
package com.learning.heroesservice.command.businesslogic; import com.learning.heroesservice.command.CreateHeroCommand; import com.learning.heroesservice.command.DeleteHeroCommand; import com.learning.heroesservice.command.SendHeroWSCommand; import com.learning.heroesservice.framework.businesslogic.BusinessLogic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS) @Component public class DeleteHeroBusinessLogic implements BusinessLogic { @Autowired private SendHeroWSCommand sendHeroWSCommand; private DeleteHeroCommand deleteHeroCommand; private SendHeroWSCommand getSendHeroWSCommand() { return sendHeroWSCommand; } private DeleteHeroCommand getDeleteHeroCommand() { return deleteHeroCommand; } public void setDeleteHeroCommand(DeleteHeroCommand deleteHeroCommand) { this.deleteHeroCommand = deleteHeroCommand; } @Override public void doWork() { getDeleteHeroCommand().execute(); getSendHeroWSCommand().setHero(getDeleteHeroCommand().getHero()); getSendHeroWSCommand().setCommand("DELETE"); getSendHeroWSCommand().execute(); } }
true
666e554ba552d8d2bc43bf4558012fa13391840e
Java
TungNT-2810/Sida
/DemoSourceTree/app/src/main/java/com/zyuternity/demosourcetree/JSONCustomerHistoryList.java
UTF-8
356
1.875
2
[]
no_license
package com.zyuternity.demosourcetree; import java.util.List; /** * Created by ZYuTernity on 7/22/2016. */ public class JSONCustomerHistoryList { private List<JSONCustomerHistoryItem> d; public List<JSONCustomerHistoryItem> getD() { return d; } public void setD(List<JSONCustomerHistoryItem> d) { this.d = d; } }
true
ef8d640232471f88edb770c2094173004c49abb7
Java
OksiBlack/learning-property-and-config-utils
/config-utils-core/src/main/java/org/learning/core/config/patterns/factory/factories/ConfigurationFactory.java
UTF-8
199
1.6875
2
[]
no_license
package org.learning.core.config.patterns.factory.factories; public abstract class ConfigurationFactory { public abstract PropertiesConfiguration getConfiguration(ConfigurationSource source); }
true
ccbd4ef858dce4dc73b27ff25fd3eb57e9b332e0
Java
moritz-w/Sportvereins-Verwaltung-Semester5
/Sportvereinsverwaltung/domain/src/main/java/at/fhv/sportsclub/entity/tournament/EncounterEntity.java
UTF-8
566
1.835938
2
[]
no_license
package at.fhv.sportsclub.entity.tournament; import at.fhv.sportsclub.entity.CommonEntity; import lombok.Data; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import java.time.LocalDate; import java.time.LocalTime; public @Data class EncounterEntity implements CommonEntity { private String id; private LocalDate date; private int time; private ObjectId homeTeam; private ObjectId guestTeam; private int homePoints; private int guestPoints; }
true
adc179108b351e1efa5b84e55e67223e94a3c594
Java
jwyming/CTCBFunding
/src/com/eds/ctcb/dao/priv/UserRoleDaoImpl.java
UTF-8
594
2.234375
2
[]
no_license
package com.eds.ctcb.dao.priv; import java.util.List; import com.eds.ctcb.bean.QryBean; import com.eds.ctcb.dao.BaseDaoImpl; import com.eds.ctcb.db.Role; public class UserRoleDaoImpl extends BaseDaoImpl implements UserRoleDao { public Role getRoleByUserId(Long userId){ Role role = null; QryBean qryBean = new QryBean( "select t.role from UserRole as t where t.user.id=?", new Object[]{userId}); List tempList = this.qryInList(qryBean); if(tempList!=null && tempList.size()==1 && tempList.get(0) instanceof Role){ role =(Role)(tempList.get(0)); } return role; } }
true
bb58002f3c5e503ac80bfee2e7ab6a6f7ae8a84d
Java
OliverKramer02/Cy_3
/Cy_3/src/org/apache/commons/math3/analysis/TrivariateFunction.java
UTF-8
388
2.125
2
[]
no_license
package org.apache.commons.math3.analysis; public abstract interface TrivariateFunction { public abstract double value(double paramDouble1, double paramDouble2, double paramDouble3); } /* Location: C:\Users\Olli\Desktop\NetworkPrioritizer-1.01.jar * Qualified Name: org.apache.commons.math3.analysis.TrivariateFunction * JD-Core Version: 0.7.0.1 */
true
dfe81bcf7fd9ee2d2020d9c9ed8bf2ae74ac1aca
Java
yonashail/BookApp
/src/com/company/bookk.java
UTF-8
1,505
3.140625
3
[]
no_license
package com.company; public class bookk { private String title; private String author; private String description; private double price; private boolean isInStock; protected static int count = 0; public bookk(){ title= ""; author=""; description=""; price=0; } @Override public String toString() { return "title: " + title + "\n" + "author " + author + "\n" + "Description: " + description + "\n" + "Price: " + this.getFormattedPrice() + "\n"; } private String getFormattedPrice() { return String.format("$%f", price); // Use the NumberFormat class to format the price to 2 decimal places } public static int getCount() { return count; } public static void setCount(int count) { bookk.count = count; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPrice() { return getFormattedPrice(); } public void setPrice(int price) { this.price = price; } }
true
ccec7815d28434d0cd9e76d9fb85b64208568448
Java
alexfr8/and-weatherapp
/app/src/main/java/com/personal/weatherapp/weatherapp/UI/Adapter/ForecastListAdapter.java
UTF-8
3,024
2.40625
2
[ "Apache-2.0" ]
permissive
package com.personal.weatherapp.weatherapp.UI.Adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.personal.weatherapp.weatherapp.Networking.Model.Forecast; import com.personal.weatherapp.weatherapp.R; import com.personal.weatherapp.weatherapp.Utils.Constants; import com.personal.weatherapp.weatherapp.Utils.DateUtils; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; public class ForecastListAdapter extends RecyclerView.Adapter<ForecastListAdapter.ForecastViewHolder> { private ArrayList<Forecast> mForecast = new ArrayList<>(); private Context mContext; public ForecastListAdapter(Context context, List<Forecast> forecasts) { mContext = context; mForecast.addAll(forecasts); } @Override public ForecastListAdapter.ForecastViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_weather, parent, false); ForecastViewHolder viewHolder = new ForecastViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(ForecastListAdapter.ForecastViewHolder holder, int position) { holder.bindRestaurant(mForecast.get(position)); } @Override public int getItemCount() { return mForecast.size(); } public class ForecastViewHolder extends RecyclerView.ViewHolder { ImageView mRestaurantImageView; TextView txtDate; TextView txtDesc; TextView txtTemp; ImageView imgWeather; private Context mContext; public ForecastViewHolder(View itemView) { super(itemView); mContext = itemView.getContext(); txtDate = (TextView) itemView.findViewById(R.id.txtDate); txtDesc = (TextView) itemView.findViewById(R.id.txtDesc); txtTemp = (TextView) itemView.findViewById(R.id.txtTemp); imgWeather = (ImageView) itemView.findViewById(R.id.imgWeather); } public void bindRestaurant(Forecast forecast) { txtDate.setText(DateUtils.stringBadFormedDateToGoodFormat(forecast.getDtTxt())); txtDesc.setText(forecast.getWeather().get(0).getDescription()); txtTemp.setText("Min: "+forecast.getMain().getTempMin() + "º \nMax: " + forecast.getMain().getTempMax() + "º"); //GlideApp.with(this).load(Constants.getOpenWeatherIconUrl() + forecast.getWeather().get(0).getIcon()+Constants.getIconExt()).into(imgWeather); Glide.with(mContext) .load(Constants.getOpenWeatherIconUrl() + forecast.getWeather().get(0).getIcon() + Constants.getIconExt()) .into(imgWeather); } } }
true
d60ddbc985837daa4cd77a6e7b6135eace8a22ce
Java
Aricelio/ProgressBible
/app/src/main/java/developer/celio/com/br/progressbible/ListaHistoricos.java
UTF-8
3,000
2.1875
2
[]
no_license
package developer.celio.com.br.progressbible; import android.app.ActionBar; import android.app.Activity; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ExpandableListView; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import developer.celio.com.br.DataAccess.HistoricoDAO; import developer.celio.com.br.DataAccess.LivroDAO; import developer.celio.com.br.DomainModel.Historico; import developer.celio.com.br.DomainModel.Livro; public class ListaHistoricos extends Activity { private ListView lstListaHistoricos; private ArrayAdapter<Historico> adapter; private int adapterLayout = android.R.layout.simple_list_item_1; private List<Historico> listaHistorico = new ArrayList<Historico>(); private HistoricoDAO histDAO = new HistoricoDAO(this); private static int ID_LIVRO; Livro livro = new Livro(); LivroDAO livroDAO = new LivroDAO(this); private static String STR_NOME; // Método onCreate.............................................................................. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_historicos); lstListaHistoricos = (ListView) findViewById(R.id.lstHistoricoLeitura); STR_NOME = this.getIntent().getExtras().getString("Nome"); livro = livroDAO.filtrar(STR_NOME); // Pega os dados do livro aberto ID_LIVRO = Integer.parseInt(livro.getId().toString()); // Configuração para o botão voltar do Icone ActionBar ab = getActionBar(); ab.setDisplayHomeAsUpEnabled(true); } // Método para Carregar a lista de Históricos do livro que foi aberto.......................... private void carregarLista(){ listaHistorico = histDAO.listar(ID_LIVRO); this.adapter = new ArrayAdapter<Historico>(this, adapterLayout, listaHistorico); this.lstListaHistoricos.setAdapter(adapter); } // Método onResume.............................................................................. @Override protected void onResume(){ super.onResume(); this.carregarLista(); } // Método onCreateOptionsMenu................................................................... @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_lista_historicos, menu); return true; } // Método onOptionsItemSelected................................................................. @Override public boolean onOptionsItemSelected(MenuItem item) { // Se foi pressionado o botão Voltar finaliza a Activity if(item.getItemId() == android.R.id.home){ finish(); } return super.onOptionsItemSelected(item); } }
true
70c458d7414ee0142ebcf93b0891e84f5a1eb60c
Java
linhui123/jhhsProject
/app/src/main/java/com/jhhscm/platform/fragment/aftersale/SaveBusAction.java
UTF-8
774
2.03125
2
[]
no_license
package com.jhhscm.platform.fragment.aftersale; import android.content.Context; import com.jhhscm.platform.http.AHttpService; import com.jhhscm.platform.http.ApiService; import com.jhhscm.platform.http.bean.BaseEntity; import com.jhhscm.platform.http.bean.NetBean; import retrofit2.Call; public class SaveBusAction extends AHttpService<BaseEntity> { private NetBean netBean; public static SaveBusAction newInstance(Context context, NetBean netBean) { return new SaveBusAction(context, netBean); } public SaveBusAction(Context context, NetBean netBean) { super(context); this.netBean = netBean; } @Override protected Call newRetrofitCall(ApiService apiService) { return apiService.saveBus(netBean); } }
true
c9d749b577e95da1d12a6d269d9e6b3bdd8130da
Java
BurakAydemir-tr/Hrms_Project
/hrms/src/main/java/kodlamaio/hrms/entities/concretes/School.java
UTF-8
1,261
2.125
2
[]
no_license
package kodlamaio.hrms.entities.concretes; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty.Access; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @Data @AllArgsConstructor @NoArgsConstructor @Table(name="schools") public class School { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private int id; @ManyToOne() @JoinColumn(name="resume_id") @JsonProperty(access = Access.WRITE_ONLY) private Resume resume; @ManyToOne() //@JsonProperty(access = Access.WRITE_ONLY) @JoinColumn(name = "graduate_id", referencedColumnName = "id") private EduGraduate eduGraduate;; @Column(name="school_name") private String schoolName; @Column(name="department") private String department; @Column(name="started_date") private Date startedDate; @Column(name="ended_date") private Date endedDate; }
true
73d5b07f219efd3a75e5ac188b0c9ae544dbfe2d
Java
thepembeweb/udasecurity-parent
/SecurityService/src/main/java/com/udacity/securityservice/application/ImagePanel.java
UTF-8
3,315
2.875
3
[ "MIT" ]
permissive
package com.udacity.securityservice.application; import com.udacity.securityservice.data.AlarmStatus; import com.udacity.securityservice.service.SecurityService; import com.udacity.image.service.StyleService; import net.miginfocom.swing.MigLayout; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; /** Panel containing the 'camera' output. Allows users to 'refresh' the camera * by uploading their own picture, and 'scan' the picture, sending it for image analysis */ public class ImagePanel extends JPanel implements StatusListener { private SecurityService securityService; private JLabel cameraHeader; private JLabel cameraLabel; private BufferedImage currentCameraImage; private int IMAGE_WIDTH = 300; private int IMAGE_HEIGHT = 225; public ImagePanel(SecurityService securityService) { super(); setLayout(new MigLayout()); this.securityService = securityService; securityService.addStatusListener(this); cameraHeader = new JLabel("Camera Feed"); cameraHeader.setFont(StyleService.HEADING_FONT); cameraLabel = new JLabel(); cameraLabel.setBackground(Color.WHITE); cameraLabel.setPreferredSize(new Dimension(IMAGE_WIDTH, IMAGE_HEIGHT)); cameraLabel.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY)); //button allowing users to select a file to be the current camera image JButton addPictureButton = new JButton("Refresh Camera"); addPictureButton.addActionListener(e -> { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setDialogTitle("Select Picture"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if(chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) { return; } try { currentCameraImage = ImageIO.read(chooser.getSelectedFile()); Image tmp = new ImageIcon(currentCameraImage).getImage(); cameraLabel.setIcon(new ImageIcon(tmp.getScaledInstance(IMAGE_WIDTH, IMAGE_HEIGHT, Image.SCALE_SMOOTH))); } catch (IOException |NullPointerException ioe) { JOptionPane.showMessageDialog(null, "Invalid image selected."); } repaint(); }); //button that sends the image to the image service JButton scanPictureButton = new JButton("Scan Picture"); scanPictureButton.addActionListener(e -> { securityService.processImage(currentCameraImage); }); add(cameraHeader, "span 3, wrap"); add(cameraLabel, "span 3, wrap"); add(addPictureButton); add(scanPictureButton); } @Override public void notify(AlarmStatus status) { //no behavior necessary } @Override public void catDetected(boolean catDetected) { if(catDetected) { cameraHeader.setText("DANGER - CAT DETECTED"); } else { cameraHeader.setText("Camera Feed - No Cats Detected"); } } @Override public void sensorStatusChanged() { //no behavior necessary } }
true
ef0f2b1a7bf69ef9d05c10e541ca890f15350964
Java
vipinkumarr89/java_practise
/src/main/java/Collections/ArrayListDemo.java
UTF-8
1,145
3.578125
4
[]
no_license
package Collections; import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<>( ); System.out.println("Enter into array list"); arrayList.add( "Vipin" ); arrayList.add( "Varun" ); arrayList.add( "Vipin" ); arrayList.add( "Varun" ); System.out.println("Arraylist size: " +arrayList.size()); System.out.println(arrayList); arrayList.add( "Renu" ); System.out.println(arrayList); System.out.println("At second position: "+arrayList.get(2)); System.out.println("Change 2nd position with Arun"); arrayList.set( 2,"Arun" ); System.out.println("At second position: "+arrayList.get(2)); System.out.println("Remove 2nd position"); arrayList.remove( 2 ); System.out.println("At second position: "+arrayList.get(2)); System.out.println("Complete list: "+arrayList ); System.out.println("remove all vipin"); arrayList.remove( "Vipin" ); System.out.println("Complete list: "+arrayList ); } }
true
e8c29c2f3a45c2db524859d5f7f477940a98b193
Java
shaliniv10498/ExchangeProducts
/src/main/java/com/shalini/verma/manager/impl/ProductsManagerImpl.java
UTF-8
1,197
2.125
2
[]
no_license
package com.shalini.verma.manager.impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import com.shalini.verma.dao.ProductsDao; import com.shalini.verma.manager.ProductsManager; import com.shalini.verma.model.ExchangeOrderPojo; import com.shalini.verma.model.Products; @Service public class ProductsManagerImpl implements ProductsManager{ @Autowired private ProductsDao daoObject; @Override public boolean saveOrUpdateProductsIntoProducts(Products productObj) { return daoObject.save(productObj) !=null;// TODO Auto-generated method stub } @Override public List<Products> fetchListOfProducts(int pageNo, int size) { List<Products> productList = new ArrayList<>(); PageRequest pageable = PageRequest.of(pageNo, size); Page<Products> paginatedProducts= daoObject.findAll(pageable); // TODO Auto-generated method stub if(paginatedProducts.hasContent()) { return paginatedProducts.getContent(); } else { return productList; } } }
true
1f61706f290304802fb3a4c04fa95bb742aecd43
Java
sapardo10/parcial-pruebas
/sources/de/danoeh/antennapod/receiver/SPAReceiver.java
UTF-8
2,731
2.15625
2
[]
no_license
package de.danoeh.antennapod.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import de.danoeh.antennapod.core.ClientConfig; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.storage.DownloadRequestException; import de.danoeh.antennapod.core.storage.DownloadRequester; import de.danoeh.antennapod.debug.R; import java.util.Arrays; public class SPAReceiver extends BroadcastReceiver { public static final String ACTION_SP_APPS_QUERY_FEEDS = "de.danoeh.antennapdsp.intent.SP_APPS_QUERY_FEEDS"; private static final String ACTION_SP_APPS_QUERY_FEEDS_REPSONSE = "de.danoeh.antennapdsp.intent.SP_APPS_QUERY_FEEDS_RESPONSE"; private static final String ACTION_SP_APPS_QUERY_FEEDS_REPSONSE_FEEDS_EXTRA = "feeds"; private static final String TAG = "SPAReceiver"; public void onReceive(Context context, Intent intent) { if (TextUtils.equals(intent.getAction(), ACTION_SP_APPS_QUERY_FEEDS_REPSONSE)) { Log.d(TAG, "Received SP_APPS_QUERY_RESPONSE"); if (intent.hasExtra(ACTION_SP_APPS_QUERY_FEEDS_REPSONSE_FEEDS_EXTRA)) { String[] feedUrls = intent.getStringArrayExtra(ACTION_SP_APPS_QUERY_FEEDS_REPSONSE_FEEDS_EXTRA); if (feedUrls == null) { Log.e(TAG, "Received invalid SP_APPS_QUERY_REPSONSE: extra was null"); return; } String str = TAG; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Received feeds list: "); stringBuilder.append(Arrays.toString(feedUrls)); Log.d(str, stringBuilder.toString()); ClientConfig.initialize(context); for (String url : feedUrls) { try { DownloadRequester.getInstance().downloadFeed(context, new Feed(url, null)); } catch (DownloadRequestException e) { String str2 = TAG; StringBuilder stringBuilder2 = new StringBuilder(); stringBuilder2.append("Error while trying to add feed "); stringBuilder2.append(url); Log.e(str2, stringBuilder2.toString()); e.printStackTrace(); } } Toast.makeText(context, R.string.sp_apps_importing_feeds_msg, 1).show(); return; } Log.e(TAG, "Received invalid SP_APPS_QUERY_RESPONSE: Contains no extra"); } } }
true
dfb7220d145bc391022159a2894c83ef157ecbb6
Java
Itay2805/Perl6-Native-Compiler
/Perl6 Compiler/src/com/itay/perl6/compiler/subs/SubsLookupTable.java
UTF-8
1,007
2.8125
3
[ "Apache-2.0" ]
permissive
package com.itay.perl6.compiler.subs; import java.util.HashMap; public class SubsLookupTable { private static HashMap<Integer, HashMap<String, Subroutine>> table = new HashMap<>(); private static int block; static { table.put(0, new HashMap<>()); } public static int pushBlock() { block++; table.put(block, new HashMap<>()); return block; } public static void popBlock() { table.remove(block); block--; } public static int getBlock() { return block; } public static Subroutine get(String name) { return get(name, block); } private static Subroutine get(String name, int block) { if(!table.get(block).containsKey(name)) { if(block - 1 >= 0) { return get(name, block - 1); } System.out.println("VariableLookupTable.get()"); System.err.println("Could not find variable: " + name); System.exit(1); } return table.get(block).get(name); } public static HashMap<Integer, HashMap<String, Subroutine>> getTable() { return table; } }
true
76ecf7185ecbebc7f8bee5590a5782b305bda4e9
Java
kingjakeu/Allkill-core
/src/main/java/com/kingjakeu/allkillcore/domain/propertry/dao/PropertyRepository.java
UTF-8
826
1.757813
2
[]
no_license
package com.kingjakeu.allkillcore.domain.propertry.dao; import com.kingjakeu.allkillcore.domain.course.domain.CourseLikeHistory; import com.kingjakeu.allkillcore.domain.propertry.domain.Property; import org.springframework.data.jpa.repository.JpaRepository; /** * <b> </b> * * @author jakeyoo * @version 0.1 : 최초작성 * <hr> * <pre> * * description * * <b>History:</b> * ==================================================================== * 버전 : 작성일 : 작성자 : 작성내역 * -------------------------------------------------------------------- * 0.1 2020/02/19 jakeyoo 최초작성 * ==================================================================== * </pre> * @date 2020/02/19 */ public interface PropertyRepository extends JpaRepository<Property, String> { }
true
8d1718355eab25b23c6b56ed483665416ebc29c8
Java
Slavick-Vinnitskyi/WebPoject
/src/main/java/model/entity/Assignment.java
UTF-8
2,495
2.84375
3
[]
no_license
package model.entity; import java.time.LocalDate; public class Assignment { public enum Status { assigned, applied } private int id; private LocalDate date; private Route route; private Status status; private User driver; private Car bus; public Assignment(LocalDate date, Route route) { this.date = date; this.route = route; } public Assignment() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public User getDriver() { return driver; } public void setDriver(User driver) { this.driver = driver; } public Car getBus() { return bus; } public void setBus(Car bus) { this.bus = bus; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public Route getRoute() { return route; } public void setRoute(Route route) { this.route = route; } // @Override // public String toString() { // return "Assignment{" + // "id=" + id + // ", date=" + date + // ", route=" + route + // ", status=" + status + // ", driver=" + driver + // ", bus=" + bus + // '}'; // } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Assignment that = (Assignment) o; return date.equals(that.date) && route.equals(that.route) && status == that.status; } // // @Override // public int hashCode() { // int result = date.hashCode(); // result = 31 * result + (route != null ? route.hashCode() : 0); // result = 31 * result + status.hashCode(); // result = 31 * result + (driver != null ? driver.hashCode() : 0); // result = 31 * result + (bus != null ? bus.hashCode() : 0); // return result; // } } class A{ public static void main(String[] args) { System.out.println(new Assignment().hashCode()); System.out.println(new Assignment()); System.out.println(Integer.toHexString(1711574013)); } }
true
6cd177d393c22ac1880c45fbed70f17f2a485fa9
Java
zranko/XWS_BSEP
/XWS_BSEP/src/main/java/app/service/FakturaStavkeService.java
UTF-8
1,062
2.328125
2
[]
no_license
package app.service; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import app.model.FakturaStavke; import app.repo.FakturaStavkeRepo; @Service public class FakturaStavkeService { @Autowired private FakturaStavkeRepo fsRepo; public FakturaStavkeService() { // TODO Auto-generated constructor stub } public ArrayList<FakturaStavke> getAllByFaktura(int fakturaId) { ArrayList<FakturaStavke> fs = new ArrayList<>(); fsRepo.findByMaticnaFaktura_Id(fakturaId).forEach(fs::add); return fs; } public FakturaStavke getOneById(int fakturaId, int rednibroj) { FakturaStavke fs = fsRepo.findByMaticnaFaktura_IdAndRednibroj(fakturaId, rednibroj); return fs; } public FakturaStavke addNew(FakturaStavke fs) { return fsRepo.save(fs); } public FakturaStavke editFakturaStavke(FakturaStavke fs) { return fsRepo.save(fs); } public void deleteStavka(int rednibroj) { fsRepo.delete(rednibroj); } }
true
3ee6060464dca2b77f2bdae56f93df56a83d14af
Java
serviceshuios/-git-reference-java-lyon-worspace
/workspaceWebServiceSoap/UnMarshall/src/presentation/Lanceur.java
UTF-8
512
2.5
2
[]
no_license
package presentation; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import metier.Compte; public class Lanceur { public static void main(String[] args) throws Exception { System.out.println("initialisation du Contexte JAXB"); JAXBContext context = JAXBContext.newInstance(Compte.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Compte cp = (Compte) unmarshaller.unmarshal(new File("comptes.xml")); System.out.println(cp); } }
true
f7b4eb77e44b9953725c60ed36bdc954489c2b1b
Java
cward-dev/dissent-capstone
/dissent/src/main/java/capstone/dissent/data/PostRepository.java
UTF-8
550
2.078125
2
[]
no_license
package capstone.dissent.data; import capstone.dissent.models.Post; import java.time.LocalDateTime; import java.util.List; public interface PostRepository { public List<Post> findAll(); public Post findById(String postId); public List<Post> findByArticleId(String articleId); public List<Post> findByUserId(String userId); public List<Post> findByTimestampRange(LocalDateTime start, LocalDateTime end); public Post add(Post post); public boolean edit(Post post); public boolean deleteById(String postId); }
true
f39e2172c5ea1c724281f705b96c0aaa29e2ac7e
Java
codeaudit/variationanalysis
/framework/src/main/java/org/campagnelab/dl/framework/mappers/processing/TwoDimensionalRemoveMaskLabelMapper.java
UTF-8
6,863
2.546875
3
[ "Apache-2.0" ]
permissive
package org.campagnelab.dl.framework.mappers.processing; import org.campagnelab.dl.framework.mappers.LabelMapper; import org.campagnelab.dl.framework.mappers.MappedDimensions; import org.nd4j.linalg.api.ndarray.INDArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * Label mapper that takes in a label mapper that maps two-dimensional labels, and removes masked elements in * between non-masked elements. * For example, if a label mapper maps the following sequences, with '-' representing elements that would be masked: * - ACTGACTAC * - ACT-AC-A- * - AC--A---- * The TwoDimensionalRemoveMaskLabelMapper will map these equivalently to * - ACTGACTAC * - ACTACA--- * - ACA------ * Created by joshuacohen on 12/13/16. */ public class TwoDimensionalRemoveMaskLabelMapper<RecordType> implements LabelMapper<RecordType> { static private Logger LOG = LoggerFactory.getLogger(TwoDimensionalRemoveMaskLabelMapper.class); private LabelMapper<RecordType> delegate; private MappedDimensions dim; private HashSet<RecordType> normalizedCalled; private HashMap<RecordType, ArrayList<Bounds>> boundsMap; private int labelsPerTimeStep; private int numTimeSteps; private int startIndex; private int[] mapperIndices = new int[]{0, 0, 0}; private int[] maskerIndices = new int[]{0, 0}; /** * Creates a new label mapper from an existing 2D label mapper, where masked elements are removed * starting from position 0 * @param delegate Delegate two-dimensional label mapper */ public TwoDimensionalRemoveMaskLabelMapper(LabelMapper<RecordType> delegate) { this(delegate, 0); } /** * Creates a new label mapper from an existing 2D label mapper, where masked elements are removed * starting from position startIndex * @param delegate Delegate two-dimensional label mapper * @param startIndex starting position of where to start removing masked elements */ public TwoDimensionalRemoveMaskLabelMapper(LabelMapper<RecordType> delegate, int startIndex) { dim = delegate.dimensions(); if (dim.numDimensions() != 2) { throw new RuntimeException("Delegate mapper must be two dimensional"); } labelsPerTimeStep = dim.numElements(1); numTimeSteps = dim.numElements(2); this.delegate = delegate; this.startIndex = startIndex; boundsMap = new HashMap<>(); normalizedCalled = new HashSet<>(); } @Override public int numberOfLabels() { return delegate.numberOfLabels(); } @Override public MappedDimensions dimensions() { return delegate.dimensions(); } @Override public void prepareToNormalize(RecordType record, int indexOfRecord) { if (indexOfRecord == -1) { LOG.warn("prepareToNormalize should be called before mapping/masking or calling produceLabel/isMasked"); } if (delegate.hasMask()) { boolean prevMasked = true; Bounds currBounds = new Bounds(); ArrayList<Bounds> boundsList = new ArrayList<>(); int prevBoundsIndex = -1; for (int i = startIndex; i < dim.numElements(2); i++) { int labelIndex = i * labelsPerTimeStep; if (delegate.isMasked(record, labelIndex)) { if (!prevMasked) { currBounds.setEnd(i); if (prevBoundsIndex >= 0) { currBounds.setShiftedSize(boundsList.get(prevBoundsIndex)); } boundsList.add(currBounds); prevBoundsIndex++; currBounds = new Bounds(); } prevMasked = true; } else { if (prevMasked) { currBounds.setStart(i); } prevMasked = false; } } boundsMap.put(record, boundsList); } normalizedCalled.add(record); } @Override public void mapLabels(RecordType record, INDArray inputs, int indexOfRecord) { mapperIndices[0] = indexOfRecord; for (int i = 0; i < dim.numElements(2); i++) { for (int j = 0; j < dim.numElements(1); j++) { int labelIndex = i * labelsPerTimeStep + j; mapperIndices[1] = j; mapperIndices[2] = i; inputs.putScalar(mapperIndices, produceLabel(record, labelIndex)); } } } @Override public boolean hasMask() { return true; } @Override public void maskLabels(RecordType record, INDArray mask, int indexOfRecord) { maskerIndices[0] = indexOfRecord; for (int i = 0; i < dim.numElements(2); i++) { int labelIndex = i * labelsPerTimeStep; maskerIndices[1] = i; mask.putScalar(maskerIndices, isMasked(record, labelIndex) ? 1F : 0F); } } @Override public boolean isMasked(RecordType record, int labelIndex) { if (!normalizedCalled.contains(record)) { prepareToNormalize(record, -1); } int timeStepIndex = labelIndex / labelsPerTimeStep; int timeStepLabelIndex = labelIndex % labelsPerTimeStep; ArrayList<Bounds> boundsList = boundsMap.get(record); int shiftSize = 0; for (Bounds bounds : boundsList) { if (bounds.contains(timeStepIndex)) { shiftSize += bounds.size(); } } int newTimeStepIndex = timeStepIndex + shiftSize; if (newTimeStepIndex < numTimeSteps) { int newLabelIndex = newTimeStepIndex * labelsPerTimeStep + timeStepLabelIndex; return delegate.isMasked(record, newLabelIndex); } return false; } @Override public float produceLabel(RecordType record, int labelIndex) { if (!normalizedCalled.contains(record)) { prepareToNormalize(record, -1); } int timeStepIndex = labelIndex / labelsPerTimeStep; int timeStepLabelIndex = labelIndex % labelsPerTimeStep; ArrayList<Bounds> boundsList = boundsMap.get(record); int shiftSize = 0; for (Bounds bounds : boundsList) { if (bounds.contains(timeStepIndex)) { shiftSize += bounds.size(); } } int newTimeStepIndex = timeStepIndex + shiftSize; if (newTimeStepIndex < numTimeSteps) { int newLabelIndex = newTimeStepIndex * labelsPerTimeStep + timeStepLabelIndex; return delegate.produceLabel(record, newLabelIndex); } return 0F; } }
true
209ce3ba13cbc9a70d7f7bc1cc9210a9286cb310
Java
momos95/auctionar
/src/main/java/com/spideo/mamadou/auctionar/beans/ActivityResponse.java
UTF-8
771
2.453125
2
[]
no_license
package com.spideo.mamadou.auctionar.beans; import com.spideo.mamadou.auctionar.entities.SEntity; /** * * @author Mamadou * * This bean is used in order to get sql request result from services to controller. * */ public class ActivityResponse { /** * allows to know if we did encounter problem while executing functional process */ private boolean error ; /** * corresponds to the entity that is returned by repositories actions */ private SEntity entity ; public ActivityResponse(){ error = true ; } public SEntity getEntity() { return entity; } public void setEntity(SEntity entity) { this.entity = entity; } public boolean hasError() { return error; } public void setError(boolean error) { this.error = error; } }
true
1ea69bb1351d90452c843f994fa4cd847b9124bf
Java
hhovsepy/hawkular-java-client
/src/main/java/org/hawkular/client/metrics/MetricsClientImpl.java
UTF-8
7,688
1.8125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hawkular.client.metrics; import java.net.URI; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.Response; import org.hawkular.client.BaseClient; import org.hawkular.client.RestFactory; import org.hawkular.client.metrics.model.AvailabilityDataPoint; import org.hawkular.client.metrics.model.CounterDataPoint; import org.hawkular.client.metrics.model.GaugeDataPoint; import org.hawkular.client.metrics.model.MetricDefinition; import org.hawkular.client.metrics.model.TenantParam; import org.hawkular.metrics.core.api.Tenant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Hawkular-Metrics client implementation * @author vnguyen * */ public class MetricsClientImpl extends BaseClient<MetricsRestApi> implements MetricsClient { //private static final Duration EIGHT_HOURS = Duration.ofHours(8); private static final Logger logger = LoggerFactory.getLogger(MetricsClientImpl.class); public MetricsClientImpl(URI endpointUri, String username, String password) throws Exception { super(endpointUri, username, password, new RestFactory<MetricsRestApi>(MetricsRestApi.class)); } @Override public List<TenantParam> getTenants() { List<TenantParam> list = restApi().getTenants(); return list == null ? new ArrayList<TenantParam>(0) : list; } @Override public boolean createTenant(Tenant tenant) { TenantParam param = new TenantParam(tenant); Response response = restApi().createTenant(param); try { if (response.getStatus() == 201) { logger.debug("Tenant[{}] created successfully, Location URI: {}", tenant.getId(), response.getLocation().toString()); return true; } else { logger.warn("Tenant[{}] creation failed, HTTP Status code: {}, Error message if any:{}", tenant.getId(), response.getStatus(), response.readEntity(String.class)); return false; } } finally { response.close(); } } @Override public void createGaugeMetric(String tenantId, MetricDefinition definition) { restApi().createGaugeMetric(tenantId, definition); } @Override public MetricDefinition getGaugeMetric(String tenantId, String metricId) { return restApi().getGaugeMetric(tenantId, metricId); } @Override public void addGaugeData(String tenantId, String metricId, List<GaugeDataPoint> data) { restApi().addGaugeData(tenantId, metricId, data); } @Override public List<GaugeDataPoint> getGaugeData(String tenantId, String metricId) { return restApi().getGaugeData(tenantId, metricId); } @Override public List<GaugeDataPoint> getGaugeData(String tenantId, String metricId, long startTime, long endTime) { logger.debug("getGaugeData(): tenant={}, metricId={}, startTime={}, endTime={}", tenantId, metricId, startTime, endTime); return restApi().getGaugeData(tenantId, metricId, startTime, endTime); } @Override public void createAvailabilityMetric(String tenantId, MetricDefinition metricDefinition) { restApi().createAvailability(tenantId, metricDefinition); } @Override public MetricDefinition getAvailabilityMetric(String tenantId, String metricId) { return restApi().getAvailabilityMetric(tenantId, metricId); } @Override public void addAvailabilityData(String tenantId, String metricId, List<AvailabilityDataPoint> data) { logger.debug("addAvailabilityData(): tenant={}, data={}",tenantId, metricId, data); restApi().addAvailabilityData(tenantId, metricId, data); } @Override public List<AvailabilityDataPoint> getAvailabilityData(String tenantId, String metricId) { logger.debug("getAvailabilityData: tenantId={}, metricId={}, data={}", tenantId, metricId); return restApi().getAvailabilityData(tenantId, metricId); } @Override public void createCounter(String tenantId, MetricDefinition metricDefinition) { logger.debug("createCounter: tenantId={}, metricDef={}", tenantId, metricDefinition); restApi().createCounter(tenantId, metricDefinition); } @Override public MetricDefinition getCounter(String tenantId, String metricId) { logger.debug("getCounter: tenantId={}, metricId={}", tenantId, metricId); return restApi().getCounter(tenantId, metricId); } @Override public void addCounterData(String tenantId, String metricId, List<CounterDataPoint> data) { logger.debug("addCounterData: tenantId={}, metricId={}, data={}", tenantId, metricId, data); restApi().addCounterData(tenantId, metricId, data); } @Override public List<CounterDataPoint> getCounterData(String tenantId, String metricId) { logger.debug("getCounterData: tenantId={}, metricId={}", tenantId, metricId); return restApi().getCounterData(tenantId, metricId); } @Override public List<MetricDefinition> findMetricDefinitions(String tenantId, String type, String tags) { logger.debug("metrics(); tenantId={}, type={}, tags={}", tenantId, type, tags); return restApi().metrics(tenantId, type, tags); } // @Override // public List<NumericData> getNumericMetricData(String tenantId, // String metricId, long startTime, long endTime) { // logger.debug("getNumericMetricData(): tenant={}, metric={}, start={}, end={}", // tenantId, metricId, startTime, endTime); // return restApi().getNumericMetricData(tenantId, metricId, startTime, endTime); // } // // @Override // public List<NumericData> getNumericMetricData(String tenantId, // String metricId) { // logger.debug("getNumericMetricData(): tenant={}, metric={}",tenantId, metricId); // long now = System.currentTimeMillis(); // long sometime = now - EIGHT_HOURS.toMillis(); // return this.getNumericMetricData(tenantId, metricId, sometime, now); // } // // @Override // public List<AggregateNumericData> getAggregateNumericDataByBuckets(String tenantId, // String metricId, // long startTime, // long endTime, // int buckets) { // logger.debug("getNumericMetricDataWithBuckets(): tenantId={}, metric={}, start={}, end={}, buckets={}", // tenantId, metricId, startTime, endTime, buckets); // return restApi().getAggregateNumericDataByBuckets(tenantId, metricId, startTime, endTime, buckets); // } // }
true
b8a151b93fa4a3a2f30b4889d516ad2e197f9ce0
Java
cmFodWx5YWRhdjEyMTA5/MyApplication3-finalone
/app/src/main/java/com/example/myapplication/MainActivity.java
UTF-8
1,936
2.078125
2
[]
no_license
package com.example.myapplication; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView mTextMessage; private static Fragment selectedFragment = null; private Intent intent; private CardView cardEmergency,cardNotification,cardFeedback,cardMyAct; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cardMyAct = findViewById(R.id.cardMyAct); cardFeedback = findViewById(R.id.cardFeedback); cardNotification = findViewById(R.id.cardNotification); cardEmergency = findViewById(R.id.cardEmergency); cardMyAct.setOnClickListener(this); cardFeedback.setOnClickListener(this); cardNotification.setOnClickListener(this); cardEmergency.setOnClickListener(this); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); } @Override public void onClick(View v) { Intent i; switch (v.getId()){ case R.id.cardEmergency:i=new Intent(this,activity_emergency.class);startActivity(i);break; case R.id.cardFeedback:i=new Intent(this,activity_my_feedbacks.class);startActivity(i);break; case R.id.cardNotification:i=new Intent(this,activity_notifications.class);startActivity(i);break; case R.id.cardMyAct:i=new Intent(this,ProfileActivity.class);startActivity(i);break; default:break; } } }
true
6672f4480e4da8145bcee7dcaf298a640788a802
Java
RobESCOM/SPEE
/src/main/java/mx/ipn/escom/spee/consulta/mapeo/Consulta.java
UTF-8
743
1.804688
2
[]
no_license
package mx.ipn.escom.spee.consulta.mapeo; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import mx.ipn.escom.spee.util.mapeo.Modelo; //@Entity //@Table(name="tcd04_consulta") public class Consulta implements Modelo, Serializable{ private static final long serialVersionUID = 1L; // @Id // @Column(name="id_consulta") // private Integer id_consulta; // // @Column(name="fh_consulta") // private Date fh_consulta; // // @Column(name="tx_hora") // private String tx_hora; // // @Column(name="tx_observaciones") // private String tx_observaciones; // // @OneToMany }
true
a66fee2fcdddc05a4738656ac6c4aa7a0520ff29
Java
CLethe/cloudDemoDetail
/product-service/src/main/java/com/example/productservice/ProductEndpoint.java
UTF-8
1,966
2.59375
3
[]
no_license
package com.example.productservice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/products") public class ProductEndpoint { protected Logger logger = LoggerFactory.getLogger(ProductEndpoint.class); @RequestMapping(method = RequestMethod.GET) public List<Product> list(){ return this.buildProducts(); } @RequestMapping(value = "/{itemCode}", method = RequestMethod.GET) public Product detail(@PathVariable String itemCode){ List<Product> products = this.buildProducts(); for (Product product : products) { if (product.getItemCode().equalsIgnoreCase(itemCode)) return product; } return null; } protected List<Product> buildProducts(){ List<Product> products = new ArrayList<>(); products.add(Product.builder().itemCode("item-1") .name("测试商品-1").bandName("ThisisBandName") .price(100).build()); products.add(Product.builder().itemCode("item-2") .name("测试商品-2").bandName("ThisisBandName") .price(200).build()); products.add(Product.builder().itemCode("item-3") .name("测试商品-3").bandName("ThisisBandName") .price(300).build()); products.add(Product.builder().itemCode("item-4") .name("测试商品-4").bandName("ThisisBandName") .price(400).build()); products.add(Product.builder().itemCode("item-5") .name("测试商品-5").bandName("ThisisBandName") .price(500).build()); return products; } }
true
bbd9a93a3d5b0e1708cb8fa38d1e332e2e0dcd38
Java
mperalta98/mperaltaUF2
/app/src/main/java/com/example/crisp/mperaltauf2/WelcomeActivity.java
UTF-8
1,942
2.046875
2
[]
no_license
package com.example.crisp.mperaltauf2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.support.annotation.NonNull; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.firebase.ui.auth.AuthUI; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class WelcomeActivity extends AppCompatActivity { TextView tvUsername; ImageView ivUserAvatar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); tvUsername = findViewById(R.id.username); ivUserAvatar = findViewById(R.id.useravatar); FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (firebaseUser != null) { tvUsername.setText(firebaseUser.getDisplayName()); Glide.with(this) .load(firebaseUser.getPhotoUrl().toString()) .into(ivUserAvatar); findViewById(R.id.sign_out).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AuthUI.getInstance() .signOut(WelcomeActivity.this) .addOnCompleteListener(new OnCompleteListener<Void>() { public void onComplete(@NonNull Task<Void> task) { startActivity(new Intent(WelcomeActivity.this, MainActivity.class)); finish(); } }); } }); } } }
true
6fb226359c8dbd9fce35abf34ccc484f00d7eaa9
Java
lamarios/sparknotation
/src/test/java/com/ftpix/sparknnotation/testapp/TestController.java
UTF-8
1,228
2.46875
2
[ "Apache-2.0" ]
permissive
package com.ftpix.sparknnotation.testapp; import com.ftpix.sparknnotation.annotations.*; import spark.Request; import spark.Response; @SparkController(name = "test") public class TestController { @SparkGet(value = "/hello/:value") public String helloWorld(@SparkParam(value = "value") String name) { return "Hello " + name + " !"; } @SparkGet(value = "/hello/:firstName/:lastName") public String helloFullName( @SparkParam(value = "firstName") String firstName, @SparkParam(value = "lastName") String lastName) { return "Hello " + firstName + " " + lastName + " !"; } @SparkPost(value = "/hello") public String helloPost( @SparkQueryParam(value = "value") String name ) { return "Hello " + name + " !"; } @SparkGet(value = "/testRequest/:value") public String testRequest(Request request, Response response) { response.header("test-header", "header"); return request.params("value"); } @SparkGet(value ="/testSplat/*/and/*") public String testSplat(@SparkSplat(value = 1) String secondSplat, @SparkSplat String firstSplat){ return firstSplat+" and "+secondSplat; } }
true
0c85ee5ec32c89901eb485eae19704e35d972672
Java
cai-peiyuan/arcgis-runtime-samples-android
/java/forestry-arcgis-app/src/main/java/com/bohaigaoke/forestry/model/OrganizationResource.java
UTF-8
784
2.046875
2
[ "Apache-2.0" ]
permissive
package com.bohaigaoke.forestry.model; import java.io.Serializable; public class OrganizationResource implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private int organizationid; private String tablename; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getOrganizationid() { return organizationid; } public void setOrganizationid(int organizationid) { this.organizationid = organizationid; } public String getTablename() { return tablename; } public void setTablename(String tablename) { this.tablename = tablename; } }
true
93e47d6cb82b99e2465c5ea32b3bd2143a89b2ef
Java
rashed21/etickit
/src/java/ticket/com/cinema/pojo/ShowOnCinemaAndSeats.java
UTF-8
2,614
2.3125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ticket.com.cinema.pojo; /** * * @author Emrul */ public class ShowOnCinemaAndSeats { private int showIdOnCinema; private int showIdOnHall; private String showDate; private int seatCata_1; private String allocated_1; private double price_1; private int seatCata_2; private String allocated_2; private double price_2; private int seatCata_3; private String allocated_3; private double price_3; public int getShowIdOnCinema() { return showIdOnCinema; } public void setShowIdOnCinema(int showIdOnCinema) { this.showIdOnCinema = showIdOnCinema; } public int getShowIdOnHall() { return showIdOnHall; } public void setShowIdOnHall(int showIdOnHall) { this.showIdOnHall = showIdOnHall; } public String getShowDate() { return showDate; } public void setShowDate(String showDate) { this.showDate = showDate; } public int getSeatCata_1() { return seatCata_1; } public void setSeatCata_1(int seatCata_1) { this.seatCata_1 = seatCata_1; } public String getAllocated_1() { return allocated_1; } public void setAllocated_1(String allocated_1) { this.allocated_1 = allocated_1; } public double getPrice_1() { return price_1; } public void setPrice_1(double price_1) { this.price_1 = price_1; } public int getSeatCata_2() { return seatCata_2; } public void setSeatCata_2(int seatCata_2) { this.seatCata_2 = seatCata_2; } public String getAllocated_2() { return allocated_2; } public void setAllocated_2(String allocated_2) { this.allocated_2 = allocated_2; } public double getPrice_2() { return price_2; } public void setPrice_2(double price_2) { this.price_2 = price_2; } public int getSeatCata_3() { return seatCata_3; } public void setSeatCata_3(int seatCata_3) { this.seatCata_3 = seatCata_3; } public String getAllocated_3() { return allocated_3; } public void setAllocated_3(String allocated_3) { this.allocated_3 = allocated_3; } public double getPrice_3() { return price_3; } public void setPrice_3(double price_3) { this.price_3 = price_3; } }
true
97af9490ce1e01457001ff8ea921d4f8041e2958
Java
saketp18/docapp
/ChatApp/app/src/main/java/com/lite/chatapp/models/Message.java
UTF-8
977
2.203125
2
[]
no_license
package com.lite.chatapp.models; import com.google.gson.annotations.SerializedName; public class Message { @SerializedName("success") private String success; @SerializedName("errorMessage") private String errorMessage; @SerializedName("message") private MessageBot message; public Message(String mSuccess, String mExternalId, MessageBot message) { this.success = mSuccess; this.errorMessage = mExternalId; this.message = message; } public MessageBot getMessage() { return message; } public void setMessage(MessageBot message) { this.message = message; } public String getmMessage() { return success; } public void setmMessage(String mMessage) { this.success = mMessage; } public String getmExternalId() { return errorMessage; } public void setmExternalId(String mExternalId) { this.errorMessage = mExternalId; } }
true
865fd1ff4cba6f64da2a316a851a599f47145be7
Java
adanli/egg-rpc
/src/main/java/org/egg/integration/erpc/serialize/packet/consumer/ConsumerRequestQueue.java
UTF-8
2,788
2.328125
2
[]
no_license
package org.egg.integration.erpc.serialize.packet.consumer; import org.egg.integration.erpc.annotation.Service; import org.egg.integration.erpc.component.proxy.RemoteCallProxyFactory; import org.egg.integration.erpc.constant.RequestQueue; import org.egg.integration.erpc.serialize.packet.Packet; import org.egg.integration.erpc.transport.Transport; import sun.nio.ch.Interruptible; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; @Service public class ConsumerRequestQueue { private boolean start = true; public static LinkedList<Packet> packets; public static Set<Thread> set = new HashSet<>(); public ConsumerRequestQueue() { packets = RequestQueue.queue(); consumer(); } private void consumer() { Transport transport = (Transport) RemoteCallProxyFactory.getBean("simpleTransport"); new Thread(new ConsumerRequest(transport)).start(); } public void stop() { start = false; } class ConsumerRequest implements Runnable { private Interruptible interruptor = null; private Packet packet; private Transport transport; public ConsumerRequest(Transport transport) { this.transport = transport; } @Override public void run() { while (start) { this.begin(); doConsumer(); this.end(); } } private void doConsumer() { while (packets.size() > 0) { synchronized (RequestQueue.REQUEST_QUEUE_LOCK) { packet = packets.pollLast(); // System.out.println("消费" + packet); transport.send(packet); packet = null; } } } private void begin() { if(interruptor == null) { interruptor = new Interruptible() { @Override public void interrupt(Thread thread) { // 如果出现问题,将当前packet放回 reimportPacket(packet); } }; } blockOn(interruptor); Thread me = Thread.currentThread(); if(me.isInterrupted()) { interruptor.interrupt(me); } } private void end() { blockOn(null); } private void reimportPacket(Packet packet) { if(packet != null) { RequestQueue.attach(packet); } } } private static void blockOn(Interruptible interrupt) { sun.misc.SharedSecrets.getJavaLangAccess().blockedOn(Thread.currentThread(), interrupt); } }
true
3122aba6d386ab969a33c324196e6b7493b67acc
Java
lishiliang-new/elastic-job-proj
/elastic-job-core-proj/elastic-job-core/src/main/java/com/lishiliang/loadbalance/RandomLoadBalance.java
UTF-8
1,898
2.78125
3
[]
no_license
package com.lishiliang.loadbalance; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author lisl * @version 1.0 * @desc : 带权重的随机策略 */ public class RandomLoadBalance extends AbstractClientLoadBalance { /** * * @param jobName * @param serversWeightMap 服务权重列表 * @param zkServerShadingItem 服务在zk中获取的分片列表 (一个服务可能获取多个分片) * @return 返回需要向下执行的zk分片 */ @Override public int doSelect(final String jobName, ConcurrentHashMap<String, Integer> serversWeightMap, Map<String, Set<Integer>> zkServerShadingItem) { //zk只有一个服务 直接返回该服务的一个分片 if (zkServerShadingItem.entrySet().size() == 1) { return zkServerShadingItem.values().stream().flatMap(Collection::stream).findFirst().get(); } //只有一个服务配置了权重 直接返回该服务的一个分片 if (serversWeightMap.entrySet().size() == 1) { return new ArrayList<Integer>(zkServerShadingItem.get(serversWeightMap.keys().nextElement())).get(0); } //权重和 int sumWeight = serversWeightMap.values().stream().reduce(Integer::sum).get(); //hashcode取模 获取一个随机数(对于多个job来说是随机的) int random = Math.abs(jobName.hashCode() % sumWeight); //定位的结果服务 String resultServer = null; for (Map.Entry<String, Integer> serversWeight : serversWeightMap.entrySet()) { if ((random -= serversWeight.getValue()) < 0) { resultServer = serversWeight.getKey(); break; } } //返回一个当前服务所获得的一个zk分片 return new ArrayList<Integer>(zkServerShadingItem.get(resultServer)).get(0); } }
true
6835d0f99d70682e8dad8e23166e1225ea301066
Java
zhaoyuasd/ContextBean
/src/com/context/test/bean/TBean.java
UTF-8
219
2
2
[]
no_license
package com.context.test.bean; public class TBean { private String showStr; public String getShowStr() { return showStr; } public void setShowStr(String showStr) { this.showStr = showStr; } }
true
3eebd993d5729fcddbe2b4a2b8d076ec6fe2b82d
Java
fkocak2505/androidLabProjects
/Dagger2Dev/app/src/main/java/com/example/dagger2dev/injector/AppComponent.java
UTF-8
280
1.742188
2
[]
no_license
package com.example.dagger2dev.injector; import com.example.dagger2dev.views.MainActivity; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = AppModule.class) public interface AppComponent { void inject(MainActivity mainActivity); }
true
660dc4f6ba58da068960f90db4c4201cee77947c
Java
Cheshir4/SBD
/WebTom2/src/java/MyClass/User.java
UTF-8
1,875
2.625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package MyClass; import java.util.Date; /** * * @author Feda */ public class User { String NickName; String FullName; String Date; String Email; String Password; String Token; public User(String NickName, String FullName, String Email, String Password, String Date) { this.NickName = NickName; this.FullName = FullName; this.Email = Email; this.Password = Password; this.Date = Date; } public User(String NickName, String FullName, String Email, String Password, String Date,String Token) { this.NickName = NickName; this.FullName = FullName; this.Email = Email; this.Password = Password; this.Date = Date; this.Token = Token; } public String getNickName() { return NickName; } public void setNickName(String NickName) { this.NickName = NickName; } public String getFullName() { return FullName; } public void setFullName(String FullName) { this.FullName = FullName; } public String getDate() { return Date; } public void setDate(String Date) { this.Date = Date; } public String getEmail() { return Email; } public void setEmail(String Email) { this.Email = Email; } public String getPassword() { return Password; } public void setPassword(String Password) { this.Password = Password; } public String getToken() { return Token; } public void setToken(String Token) { this.Token = Token; } }
true
ec652d0da77a26918c7b2f3cf3eeefffe19fd8db
Java
tanisha-garg/OnlineVegetableShopping
/src/main/java/com/cg/vegetable/mgmt/exceptions/InvalidTransactionModeException.java
UTF-8
190
1.898438
2
[]
no_license
package com.cg.vegetable.mgmt.exceptions; public class InvalidTransactionModeException extends RuntimeException{ public InvalidTransactionModeException(String msg) { super(msg); } }
true
718429d4cb0db467882946dd28c56f8ccf4d1c0c
Java
abhilash42-zz/CN_Lab
/classes.dex_source_from_JADX/io/fabric/sdk/android/services/p020b/C1470b.java
UTF-8
1,135
1.75
2
[]
no_license
package io.fabric.sdk.android.services.p020b; /* compiled from: AdvertisingInfo */ class C1470b { public final String f3689a; public final boolean f3690b; C1470b(String str, boolean z) { this.f3689a = str; this.f3690b = z; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } C1470b c1470b = (C1470b) obj; if (this.f3690b != c1470b.f3690b) { return false; } if (this.f3689a != null) { if (this.f3689a.equals(c1470b.f3689a)) { return true; } } else if (c1470b.f3689a == null) { return true; } return false; } public int hashCode() { int hashCode; int i = 0; if (this.f3689a != null) { hashCode = this.f3689a.hashCode(); } else { hashCode = 0; } hashCode *= 31; if (this.f3690b) { i = 1; } return hashCode + i; } }
true
ce3bb5a1efdacf4c7f365f4497f7df20295ae76f
Java
baohuy91/sonartypetalknotifier
/src/main/java/jp/co/atware/sonar/typetalknotifier/TypetalkPostProjectAnalysisTask.java
UTF-8
6,347
1.859375
2
[]
no_license
package jp.co.atware.sonar.typetalknotifier; import org.sonar.api.ce.posttask.PostProjectAnalysisTask; import org.sonar.api.ce.posttask.QualityGate; import org.sonar.api.ce.posttask.QualityGate.Condition; import org.sonar.api.config.Configuration; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.measures.MetricFinder; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import java.util.Arrays; import java.util.Optional; import static jp.co.atware.sonar.typetalknotifier.PluginProp.*; public class TypetalkPostProjectAnalysisTask implements PostProjectAnalysisTask { private static final Logger LOG = Loggers.get(TypetalkPostProjectAnalysisTask.class); private static final String TYPETALK_URL = "https://typetalk.com/api/v1"; private final TypetalkClient typetalkClient; private final Configuration configuration; // I18n can only get name of Core metrics. batch.MetricFinder is only inject in Scanner side. private final MetricFinder metricFinder; public TypetalkPostProjectAnalysisTask(Configuration configuration, MetricFinder metricFinder) { this(new TypetalkClient(TYPETALK_URL), configuration, metricFinder); } public TypetalkPostProjectAnalysisTask( TypetalkClient typetalkClient, Configuration configuration, MetricFinder metricFinder) { this.typetalkClient = typetalkClient; this.configuration = configuration; this.metricFinder = metricFinder; } @Override public void finished(ProjectAnalysis analysis) { final String projKey = analysis.getProject().getKey(); final Optional<Boolean> enabledOpt = configuration.getBoolean(ENABLED.value()); if (!enabledOpt.isPresent()) { LOG.error("Plugin param {} missing", ENABLED.value()); return; } LOG.info("Typetalk plugin enabled: {}", enabledOpt.get()); if (!enabledOpt.get()) { return; } final String msg = createMessage(analysis); final String[] projConfIdxes = configuration.getStringArray(PROJECT.value()); final Optional<String> projConfIdx = Arrays.stream(projConfIdxes).filter(idx -> configuration.get(getFieldProperty(PROJECT.value(), idx, PROJECT_KEY.value())) .map(projKey::equals) .orElse(false) ).findAny(); if (!projConfIdx.isPresent()) { LOG.info("No project id match project key: {}", projKey); return; } final String projIdx = projConfIdx.get(); final String ttTopicField = getFieldProperty(PROJECT.value(), projIdx, TYPETALK_TOPIC_ID.value()); final String typetalkTopicId = configuration.get(ttTopicField) .orElseThrow(() -> new RuntimeException("Missing " + TYPETALK_TOPIC_ID.value())); final String ttTokenField = getFieldProperty(PROJECT.value(), projIdx, TYPETALK_TOKEN.value()); final String typetalkToken = configuration.get(ttTokenField) .orElseThrow(() -> new RuntimeException("Missing " + TYPETALK_TOKEN.value())); LOG.info("TypetalkTopicId: {}", typetalkTopicId); typetalkClient.postMessage(msg, typetalkTopicId, typetalkToken); } private String getFieldProperty(String property, String idx, String field) { return String.format("%s.%s.%s", property, idx, field); } private String createMessage(ProjectAnalysis analysis) { final QualityGate qualityGate = analysis.getQualityGate(); final String projectName = analysis.getProject().getName(); String overallMsg = String.format("Project [%s](%s) analyzed.", projectName, getProjectUrl(analysis)); if (qualityGate == null) { return overallMsg; } overallMsg += String.format(" Quality gate status: `%s`%n", qualityGate.getStatus().toString()); return overallMsg + qualityGate.getConditions().stream() .map(this::makeConditionMessage) .reduce((str, m) -> String.join("\n", str, m)) .orElse("No conditions"); } private String getProjectUrl(ProjectAnalysis analysis) { return getSonarServerUrl() + "dashboard?id=" + analysis.getProject().getKey(); } private String makeConditionMessage(Condition condition) { String conditionName = condition.getMetricKey(); final Metric metric = metricFinder.findByKey(condition.getMetricKey()); if (metric != null) { conditionName = metric.getName(); } return String.format("> %s %s → `%s`%s", emoji(condition), conditionName, getConditionValue(condition), getThresholdDesc(condition)); } private String getThresholdDesc(Condition condition) { StringBuilder sb = new StringBuilder(); if (condition.getWarningThreshold() != null) { sb.append(", warning if ") .append(getOperator(condition)) .append(" ") .append(condition.getWarningThreshold()); if (isPercentageMetric(condition)) { sb.append("%"); } } if (condition.getErrorThreshold() != null) { sb.append(", error if ") .append(getOperator(condition)) .append(" ") .append(condition.getErrorThreshold()); if (isPercentageMetric(condition)) { sb.append("%"); } } return sb.toString(); } private String getConditionValue(Condition condition) { if (QualityGate.EvaluationStatus.NO_VALUE.equals(condition.getStatus())) { return condition.getStatus().name(); } if (isPercentageMetric(condition)) { return String.format("%.2f%%", Double.parseDouble(condition.getValue())); } else { return condition.getValue(); } } private String emoji(Condition condition) { switch (condition.getStatus()) { case NO_VALUE: return ":thinking_face:"; case OK: return ":smile:"; case WARN: return ":nauseated_face:"; case ERROR: return ":rage:"; default: return ""; } } private String getOperator(Condition condition) { switch (condition.getOperator()) { case EQUALS: return "=="; case LESS_THAN: return "<"; case GREATER_THAN: return ">"; case NOT_EQUALS: return "!="; default: return ""; } } private boolean isPercentageMetric(Condition condition) { switch (condition.getMetricKey()) { case CoreMetrics.NEW_COVERAGE_KEY: case CoreMetrics.NEW_SQALE_DEBT_RATIO_KEY: case CoreMetrics.COVERAGE_KEY: case CoreMetrics.NEW_DUPLICATED_LINES_KEY: return true; default: return false; } } private String getSonarServerUrl() { // TODO: inject server to get url instead return configuration.get("sonar.core.serverBaseURL") .map(u -> u.endsWith("/") ? u : u + "/") .orElse(null); } }
true
965bcfed76fa866d1e6089f50d9f9b3c44355e69
Java
sunmaio159/goods
/src/com/goods/controller/OrderController.java
GB18030
5,907
2.09375
2
[]
no_license
package com.goods.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.goods.entity.Cutomer; import com.goods.entity.Goods; import com.goods.entity.Order; import com.goods.entity.OrderInfo; import com.goods.entity.OrderName; import com.goods.entity.Orderetail; import com.goods.entity.OrderetailList; import com.goods.service.CutomerService; import com.goods.service.GoodsService; import com.goods.service.OrderService; import com.goods.service.OrderetailService; @Controller public class OrderController { @Resource private GoodsService goodsservice; @Resource private CutomerService cutomerService; @Resource private OrderService orderservice; @Resource private OrderetailService orderetailservice; @RequestMapping(value="/order/order.htm") public ModelAndView order(HttpServletRequest request,HttpSession session) throws Exception{ ModelAndView model = new ModelAndView("/addorder"); String userid = request.getParameter("id"); String bh=dateToStamp(); String time = time(); List<Cutomer> list = new ArrayList<Cutomer>(); list = cutomerService.CutomerList(userid); model.addObject("cutomer", list); model.addObject("userid", userid); model.addObject("orderid", bh); model.addObject("time", time); return model; } @SuppressWarnings("null") @RequestMapping(value="/order/saveorder.htm") public ModelAndView saveorder(Order order,HttpServletRequest request,HttpSession session) throws Exception{ ModelAndView model = new ModelAndView("/orderList"); String bh=order.getOrderid(); Order order1 = new Order(); order1 = orderservice.selectByOrderid(bh); //List<Cutomer> list = new ArrayList<Cutomer>(); String userid = request.getParameter("id"); List<OrderName> list = new ArrayList<OrderName>(); if(order1==null){ orderservice.save(order); /*list =cutomerService.selectCutomer(order.getCutomerid().toString()); model.addObject("cutomer",list); model.addObject("orderid",order.getOrderid()); model.addObject("time",order.getTimedate()); model.addObject("userid", order.getUserid());*/ model.addObject("list", list); model.addObject("msg","ӳɹ"); return model; }else{ /*list = cutomerService.selectCutomer(order1.getCutomerid().toString()); model.addObject("cutomer",list); model.addObject("orderid",order1.getOrderid()); model.addObject("time",order1.getTimedate()); model.addObject("userid", order1.getUserid());*/ orderservice.updateByOrderid(order1); list = orderservice.getorderlist(userid); model.addObject("msg","ӳɹ"); return model; } } @RequestMapping(value="/order/orderaddgoods.htm") public ModelAndView orderaddgoods(HttpServletRequest request,HttpSession session) throws Exception{ ModelAndView model = new ModelAndView("/ordergoods"); String userid = request.getParameter("id"); model.addObject("userid", userid); return model; } public static String dateToStamp(){ SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//ڸʽ String date = df.format(new Date()); return date; } public static String time(){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//ڸʽ String date = df.format(new Date()); return date; } @RequestMapping(value="/order/addGoodsToOrder.htm") public ModelAndView addGoodsToOrder(HttpServletRequest request,HttpSession session) throws Exception{ ModelAndView model = new ModelAndView("/addorder"); String goodslist = request.getParameter("goodslist"); String[] map =goodslist.split(","); List<Goods> list = new ArrayList<Goods>(); for(int i=0;i<map.length;i++){ Goods goods = goodsservice.getgoods(map[i]); list.add(goods); } model.addObject("goodslist", list); return model; } @RequestMapping(value="/order/saveOrderEtail.htm") public ModelAndView saveOrderEtail(OrderetailList orderetaillist,HttpServletRequest request,HttpSession session) throws Exception{ ModelAndView model = new ModelAndView("/orderList"); String userid = request.getParameter("id"); List<OrderName> list = new ArrayList<OrderName>(); for(Orderetail orderetail :orderetaillist.getOrderetaillist()){ orderetailservice.saveOrderetail(orderetail); } list = orderservice.getorderlist(userid); model.addObject("msg","ӳɹ"); model.addObject("list",list); return model; } @RequestMapping(value="/order/orderList.htm") public ModelAndView orderList(HttpServletRequest request,HttpSession session) throws Exception{ ModelAndView model = new ModelAndView("/orderList"); String userid = request.getParameter("id"); List<OrderName> list = new ArrayList<OrderName>(); list = orderservice.getorderlist(userid); model.addObject("list", list); return model; } @RequestMapping(value="/order/orderInfo.htm") public ModelAndView orderInfo(HttpServletRequest request,HttpSession session) throws Exception{ ModelAndView model = new ModelAndView("/OrderInfo"); String orderid = request.getParameter("orderid"); List<OrderInfo> list = new ArrayList<OrderInfo>(); OrderName order = new OrderName(); order = orderservice.selectOrderid(orderid); list=orderetailservice.getOrderetail(orderid); for(int i=0;i<list.size();i++){ Integer n = list.get(i).getNum(); Float danjia = list.get(i).getPrice(); Float money = n*danjia; list.get(i).setMoney(money); } //list = orderservice.getorderlist(userid); model.addObject("order", order); model.addObject("list", list); return model; } }
true
72afb2be2fef981d24cbce794451bcd6ba529851
Java
pangamdipti/CRUD-operations-with-SpringBoot
/src/main/java/com/springboot/task/Subject.java
UTF-8
1,048
2.375
2
[]
no_license
package com.springboot.task; import javax.persistence.*; import javax.validation.constraints.NotNull; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="subjects") public class Subject extends AuditModel{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @NotNull @Lob @Column(name="subject_name") private String subjectName; @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "student_id", nullable = false) @OnDelete(action = OnDeleteAction.CASCADE) @JsonIgnore private Student student; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } }
true
bb5b5052ec1f9e5da073fc779c1cb87526f22ed9
Java
MisterDeamon/btpj
/src/main/java/com/jack/security/webapp/SecurityUserController.java
UTF-8
10,317
1.953125
2
[]
no_license
package com.jack.security.webapp; import com.jack.security.pojo.SecurityRole; import com.jack.security.pojo.SecurityUser; import com.jack.security.service.SecurityUserRoleService; import com.jack.security.service.SecurityUserService; import com.jack.security.shiro.ShiroDbRealm; import com.jack.security.webapp.asyncDemo.LongTimeAsyncCallService; import com.jack.utils.Pager; import com.jack.utils.StringUtils; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.*; /** * Created by wajiangk on 9/6/2016. */ @Controller @RequestMapping(value = "/management/security/user") public class SecurityUserController extends BaseController{ @Autowired private SecurityUserService userService; @Autowired private SecurityUserRoleService userRoleService; @Autowired private LongTimeAsyncCallService longTimeAsyncCallService; private static final Logger log = Logger.getLogger(SecurityUserController.class); private static final String LIST = "management/security/user/list"; private static final String CREATE = "management/security/user/create"; private static final String MODIFY = "management/security/user/modify"; private static final String ROLESET = "management/security/user/roleSet"; @RequestMapping(value={"/list",""},method= {RequestMethod.GET,RequestMethod.POST}) @RequiresPermissions("User:view") public String LIST(Model model,SecurityUser user,SecurityRole searchRole,HttpServletRequest request){ log.info(request.getLocalAddr()); Pager<SecurityUser> pager = new Pager<SecurityUser>(); pager.setPageSize(10); setPageInfo(request,pager); List<SecurityRole> searchRoles=null; if(null!=searchRole.getRoleName()&&!"".equals(searchRole.getRoleName())){ searchRoles = new ArrayList<SecurityRole>(); searchRoles.add(searchRole); } user.setSroles(searchRoles); List<SecurityUser> userList = userService.findUserPage(user,pager); int total = userService.findUserCount(user,pager); //select user roles for(int i=0;i<userList.size();i++){ userList.get(i).setSroles(userService.findById(userList.get(i).getId()).getSroles()); } pager.setTotalCount(total); pager.setResult(userList); pager.setFirstandLastPn(); model.addAttribute("page", pager); model.addAttribute("userList", pager.getResult()); model.addAttribute("searchUser", user); model.addAttribute("searchRole", searchRole); return LIST; } /*@RequestMapping(value={"/list",""},method= {RequestMethod.GET,RequestMethod.POST}) @RequiresPermissions("User:view") public Callable<ModelAndView> LIST(SecurityUser user, SecurityRole searchRole, HttpServletRequest request){ }*/ /** * create User * @return */ @RequestMapping(value="/create",method = RequestMethod.GET) @RequiresPermissions("User:create") public String create(){ return CREATE; } /** * save create user form * @param request * @param user * @param file * @return */ @RequestMapping(value="/create",method = RequestMethod.POST,produces ="application/json;charset=UTF-8" ) @RequiresPermissions("User:create") public @ResponseBody String create(HttpServletRequest request, SecurityUser user, @RequestParam("file")MultipartFile file){ user.setUserName(StringUtils.encodeUTF8(user.getUserName())); Map<String,Object> map = new HashMap<String,Object>(); Subject subject = SecurityUtils.getSubject(); ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject.getPrincipal(); try { user.setPlainPasswd(request.getParameter("password")); userService.preCreate(user,shiroUser); userService.preUpdate(user,shiroUser); String fileName = uploadHeadPic(request, file, "/file/upload/headpic"); if (!fileName.equals("")) { user.setHeadPicPath(fileName); } userService.saveOrUpdate(user); map.put("success", true); map.put("msg", "用户创建成功"); }catch (Exception e){ map.put("success",false); e.printStackTrace(); } return getJsonResult(map); } /** * modify user * @param userId * @param model * @return */ @RequestMapping(value="/modify",method = RequestMethod.GET) @RequiresPermissions("User:modify") public String modify(@RequestParam("id") String userId,Model model) { model.addAttribute("user",userService.findById(userId)); return MODIFY; } /** * save modify user form * @param request * @param user * @param file * @return */ @RequestMapping(value="/modify",method = RequestMethod.POST,produces ="application/json;charset=UTF-8" ) @RequiresPermissions("User:modify") public @ResponseBody String modify(HttpServletRequest request, SecurityUser user, @RequestParam("file")MultipartFile file){ user.setUserName(StringUtils.encodeUTF8(user.getUserName())); Map<String,Object> map = new HashMap<String,Object>(); Subject subject = SecurityUtils.getSubject(); ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject.getPrincipal(); try { user.setPlainPasswd(request.getParameter("password")); userService.preUpdate(user,shiroUser); String fileName = uploadHeadPic(request, file, "/file/upload/headpic"); if (!fileName.equals("")) { user.setHeadPicPath(fileName); } userService.saveOrUpdate(user); map.put("success", true); map.put("msg", "用户修改成功"); }catch (Exception e){ map.put("success",false); e.printStackTrace(); } return getJsonResult(map); } public String uploadHeadPic(HttpServletRequest request,MultipartFile file,String savePath){ String fileName = ""; try{ if(file!=null&&!file.isEmpty()){ ServletContext sc = request.getSession().getServletContext(); String dir = sc.getRealPath(savePath); // 设定文件保存的目录 String orignFileName = file.getOriginalFilename(); fileName = StringUtils.getFormatDate_2() + "." + orignFileName.substring(orignFileName.lastIndexOf(".") + 1); FileUtils.writeByteArrayToFile(new File(dir,fileName),file.getBytes()); } } catch (IOException e) { e.printStackTrace(); } return fileName; } /** * delete user * @param userIds * @return */ @RequestMapping(value="/delete",method = RequestMethod.POST,produces ="application/json;charset=UTF-8" ) @RequiresPermissions("User:delete") public @ResponseBody String deleteUser(@RequestParam("ids")String[] userIds){ Map<String,Object> map = new HashMap<String,Object>(); try{ for(String id:userIds){ userService.remove(id); } map.put("success",true); map.put("msg","删除用户成功"); }catch (Exception e){ map.put("success",false); e.printStackTrace(); } return getJsonResult(map); } /** * change user account status * @param userId * @param status * @return */ @RequestMapping(value = "/changeAccountStatus",method=RequestMethod.GET,produces ="application/json;charset=UTF-8" ) public @ResponseBody String unlockAccount(@RequestParam("userId")String userId,@RequestParam("status") int status){ Map<String,Object> map= new HashMap<String,Object>(); try { map.put("success",true); if(status==0){ userService.lockAccount(userId); map.put("msg","锁定成功"); }else{ userService.relockAccount(userId); map.put("msg","解锁成功"); } }catch (Exception e){ map.put("success",false); e.printStackTrace(); } return getJsonResult(map); } /** * roleSet * @param userId * @param model * @return */ @RequestMapping(value = "/roleSet",method=RequestMethod.GET,produces ="application/json;charset=UTF-8" ) public String roleSet(@RequestParam("id")String userId,Model model){ SecurityUser tempUser = userService.findById(userId); List<SecurityRole> roles = userRoleService.findAll(); model.addAttribute("userRoleSet",tempUser); model.addAttribute("allRoles",roles); return ROLESET; } /** * roleSet * @param * @param * @return */ @RequestMapping(value = "/roleSet",method=RequestMethod.POST,produces ="application/json;charset=UTF-8" ) public @ResponseBody String roleSet(HttpServletRequest request,@RequestParam("userId") String userId){ String[] roleIds = request.getParameterValues("roleId"); Map<String,Object> map = new HashMap<String, Object>(); try{ SecurityUser temp = userService.findById(userId); List<SecurityRole> roles = temp.getSroles(); userService.setRole(userId,roleIds,roles); map.put("msg","角色分配成功!"); map.put("success",true); }catch (Exception e){ map.put("msg","角色分配失败!"); e.printStackTrace(); } return getJsonResult(map); } }
true
e71c6d6063236f8971b94e284c2671c9a76c1762
Java
codefaster/java
/pr/src/pr1/a07/NameComparator.java
UTF-8
367
2.4375
2
[]
no_license
package pr1.a07; import java.util.Comparator; import lernhilfe2012ws.objectPlay.*; public class NameComparator implements Comparator<Person> { public int compare(Person persObj1, Person persObj2) { String name1 = new String (persObj1.getNachname()); String name2 = new String (persObj2.getNachname()); return (name1.compareTo(name2)); } }
true
18778d79ef978b68119e942b8596e9f278679176
Java
desislava-hristova-ontotext/rdf4j
/core/sparqlbuilder/src/main/java/org/eclipse/rdf4j/sparqlbuilder/graphpattern/GraphPatternNotTriples.java
UTF-8
2,447
2.71875
3
[ "BSD-3-Clause", "MIT", "CPL-1.0", "JSON", "Apache-2.0", "EPL-1.0", "MPL-1.1", "Apache-1.1", "LicenseRef-scancode-generic-export-compliance" ]
permissive
package org.eclipse.rdf4j.sparqlbuilder.graphpattern; import org.eclipse.rdf4j.sparqlbuilder.constraint.Expression; public class GraphPatternNotTriples implements GraphPattern { GraphPattern gp; GraphPatternNotTriples() { this(new GroupGraphPattern()); } GraphPatternNotTriples(GraphPattern from) { this.gp = from; } /** * Like {@link GraphPattern#and(GraphPattern...)}, but mutates and returns this instance * * @param patterns the patterns to add * @return this */ @Override public GraphPatternNotTriples and(GraphPattern... patterns) { gp = gp.and(patterns); return this; } /** * Like {@link GraphPattern#union(GraphPattern...)}, but mutates and returns this instance * * @param patterns the patterns to add * @return this */ @Override public GraphPatternNotTriples union(GraphPattern... patterns) { gp = gp.union(patterns); return this; } /** * Like {@link GraphPattern#optional()}, but mutates and returns this instance * * @return this */ @Override public GraphPatternNotTriples optional() { gp = gp.optional(); return this; } /** * Like {@link GraphPattern#optional(boolean)}, but mutates and returns this instance * * @param isOptional if this graph pattern should be optional or not * @return this */ @Override public GraphPatternNotTriples optional(boolean isOptional) { gp = gp.optional(isOptional); return this; } /** * Like {@link GraphPattern#filter(Expression)}, but mutates and returns this instance * * @param constraint the filter constraint * @return this */ @Override public GraphPatternNotTriples filter(Expression<?> constraint) { gp = gp.filter(constraint); return this; } /** * Like {@link GraphPattern#minus(GraphPattern...)}, but mutates and returns this instance * * @param patterns the patterns to construct the <code>MINUS</code> graph pattern with * @return this */ @Override public GraphPatternNotTriples minus(GraphPattern... patterns) { gp = gp.minus(patterns); return this; } /** * Like {@link GraphPattern#from(GraphName)}, but mutates and returns this instance * * @param name the name to specify * @return this */ @Override public GraphPatternNotTriples from(GraphName name) { gp = gp.from(name); return this; } @Override public boolean isEmpty() { return gp.isEmpty(); } @Override public String getQueryString() { return gp.getQueryString(); } }
true
563ee31c78d8714e011039c32c6c8ff0b8f2f750
Java
sulfasTor/Duck-Hunt-Game
/CursorPanel.java
UTF-8
2,508
2.625
3
[]
no_license
import javax.swing.*; import javax.imageio.*; import java.io.*; import java.awt.image.BufferedImage; import java.awt.*; import java.util.LinkedList; import javax.sound.sampled.*; import sun.audio.*; public class CursorPanel{ private int x, y; private int gunNum = 0; private int imgWidth = 500; private int imgHeight = 500; private boolean reload=false; private Point punto = null; private SurfaceJeu sj; private BufferedImage arme = null; private BufferedImage vise = null; private String[] gunNames = {"HK-MP5", "COD-PeaceKeeper", "Shotgun", "Pistol", "Sniper Rifle", "AK-47"}; public CursorPanel(SurfaceJeu sj){ this.sj=sj; try{ vise = ImageIO.read(new File("media//sight.png")); } catch(IOException io){io.printStackTrace();} } public void setX(int a){x = a;} public void setY(int b){y = b;} public Point getPunto(){ return punto; } public String getGunName(){ return gunNames[gunNum]; //String nom=""; // switch(gunNum){ // case 0 : nom="HK-MP5"; break; // case 1 : nom="COD-PeaceKeeper"; break; // case 2 : nom="Shotgun"; break; // case 3 : nom="Pistol"; break; // case 4 : nom="Sniper Rifle"; break; // case 5 : nom= "AK-47"; break; // default: nom="";break; //} //return nom; } public int getGunIndex(){ return gunNum; } public int getShootRadio(){ if(gunNum!=2 & gunNum!=4) return 5; else if(gunNum==4) return 10; else return 20; } //Methode qui dit si une arme peut tirer en mode automatique public boolean isAutomatic(){ return gunNum!=2 && gunNum!=3 && gunNum!=4; } //Methodes qui obtient la coordonnes X et Y des positions d ela souris public void click(Point circle){ punto = circle; } //Methode qui change l'index de l'arme public void gunChange(){ if (gunNum==5) gunNum = 0; else gunNum++; } //Methode qui change l'orientation des armes public void gunOrientChange(){ int limite = sj.getWidth()/2; if (x>=limite){ imgWidth=-500; } else {imgWidth = 500;} } //Methode qui dessine les armes public void dessinerArme(Graphics g){ g.drawImage(vise, x - 25, y - 25, 50, 50, null); gunOrientChange(); try{ arme = ImageIO.read(new File("media//gun"+gunNum+".png")); } catch(IOException io){io.printStackTrace();} int yec = y; if (yec > sj.getHeight()/2) yec +=100; else yec = sj.getHeight()/2; g.drawImage(arme, x - imgWidth/2, yec,imgWidth, imgHeight, null); } }
true
3f7d40f84b2a18e1724693f5f9c58250bdb6ae8d
Java
DanielLoaiza/SimpleRedditReader
/app/src/main/java/com/dafelo/co/redditreader/subreddits/domain/SubReddit.java
UTF-8
5,592
2.09375
2
[]
no_license
package com.dafelo.co.redditreader.subreddits.domain; import com.dafelo.co.redditreader.main.domain.RedditObject; import org.parceler.Parcel; import java.util.List; /** * Created by root on 7/01/17. */ @Parcel public class SubReddit implements RedditObject { String bannerImg; String submitTextHtml; String id; String submitText; String displayName; String headerImg; String descriptionHtml; String title; String publicDescriptionHtml; String iconImg; String headerTitle; String description; Integer subscribers; String submitTextLabel; String lang; String name; Integer created; String url; Integer createdUtc; String publicDescription; String subredditType; public SubReddit() {} public SubReddit(String bannerImg, String submitTextHtml, String submitText, String displayName, String headerImg, String descriptionHtml, String title, String publicDescriptionHtml, String iconImg, String headerTitle, String description, Integer subscribers, String submitTextLabel, String lang, String name, Integer created, String url, Integer createdUtc, String publicDescription, String subredditType) { this.bannerImg = bannerImg; this.submitTextHtml = submitTextHtml; this.submitText = submitText; this.displayName = displayName; this.headerImg = headerImg; this.descriptionHtml = descriptionHtml; this.title = title; this.publicDescriptionHtml = publicDescriptionHtml; this.iconImg = iconImg; this.headerTitle = headerTitle; this.description = description; this.subscribers = subscribers; this.submitTextLabel = submitTextLabel; this.lang = lang; this.name = name; this.created = created; this.url = url; this.createdUtc = createdUtc; this.publicDescription = publicDescription; this.subredditType = subredditType; } public String getBannerImg() { return bannerImg; } public void setBannerImg(String bannerImg) { this.bannerImg = bannerImg; } public String getSubmitTextHtml() { return submitTextHtml; } public void setSubmitTextHtml(String submitTextHtml) { this.submitTextHtml = submitTextHtml; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSubmitText() { return submitText; } public void setSubmitText(String submitText) { this.submitText = submitText; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getHeaderImg() { return headerImg; } public void setHeaderImg(String headerImg) { this.headerImg = headerImg; } public String getDescriptionHtml() { return descriptionHtml; } public void setDescriptionHtml(String descriptionHtml) { this.descriptionHtml = descriptionHtml; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPublicDescriptionHtml() { return publicDescriptionHtml; } public void setPublicDescriptionHtml(String publicDescriptionHtml) { this.publicDescriptionHtml = publicDescriptionHtml; } public String getIconImg() { return iconImg; } public void setIconImg(String iconImg) { this.iconImg = iconImg; } public String getHeaderTitle() { return headerTitle; } public void setHeaderTitle(String headerTitle) { this.headerTitle = headerTitle; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getSubscribers() { return subscribers; } public void setSubscribers(Integer subscribers) { this.subscribers = subscribers; } public String getSubmitTextLabel() { return submitTextLabel; } public void setSubmitTextLabel(String submitTextLabel) { this.submitTextLabel = submitTextLabel; } public String getLang() { return lang; } public void setLang(String lang) { this.lang = lang; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCreated() { return created; } public void setCreated(Integer created) { this.created = created; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getCreatedUtc() { return createdUtc; } public void setCreatedUtc(Integer createdUtc) { this.createdUtc = createdUtc; } public String getPublicDescription() { return publicDescription; } public void setPublicDescription(String publicDescription) { this.publicDescription = publicDescription; } public String getSubredditType() { return subredditType; } public void setSubredditType(String subredditType) { this.subredditType = subredditType; } }
true
54ceb8e2bbc2a37fa4a7a7a164322e99fef50826
Java
1322739583/OmniList
/app/src/main/java/me/shouheng/omnilist/adapter/picker/ModelsPickerAdapter.java
UTF-8
1,964
2.15625
2
[]
no_license
package me.shouheng.omnilist.adapter.picker; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import java.util.List; import me.shouheng.omnilist.R; import me.shouheng.omnilist.model.Model; import me.shouheng.omnilist.model.tools.Selectable; import me.shouheng.omnilist.utils.ColorUtils; /** * Created by wangshouheng on 2017/10/5.*/ public class ModelsPickerAdapter<T extends Model & Selectable> extends BaseQuickAdapter<T, BaseViewHolder> { private int selectedColor = -1; @NonNull private ModelsPickerStrategy<T> modelsPickerStrategy; public ModelsPickerAdapter(@Nullable List<T> data, @NonNull ModelsPickerStrategy<T> modelsPickerStrategy) { super(R.layout.item_universal_icon_layout, data); this.modelsPickerStrategy = modelsPickerStrategy; } @Override protected void convert(BaseViewHolder helper, T item) { helper.setText(R.id.tv_title, modelsPickerStrategy.getTitle(item)); helper.setText(R.id.tv_sub_title, modelsPickerStrategy.getSubTitle(item)); helper.setVisible(R.id.iv_more, modelsPickerStrategy.shouldShowMore()); helper.setImageDrawable(R.id.iv_icon, modelsPickerStrategy.getIconDrawable(item)); if (modelsPickerStrategy.isMultiple() && item.isSelected()) { helper.itemView.setBackgroundColor(getSelectedColor()); } else { helper.itemView.setBackgroundColor(Color.TRANSPARENT); } } private int getSelectedColor() { if (selectedColor == -1) { selectedColor = ColorUtils.accentColor() + 536_870_912; } return selectedColor; } public void setModelsPickerStrategy(@NonNull ModelsPickerStrategy<T> modelsPickerStrategy) { this.modelsPickerStrategy = modelsPickerStrategy; } }
true
195517011c4168f64270cb060b61d778ea32616f
Java
ezelau95/TP2_ComplejidadComputacional
/src/polinomios/BinomioDeNewton.java
UTF-8
3,129
3.984375
4
[]
no_license
package polinomios; /*Falta revisar otras formas de obtener los coeficientes del desarrollo completo del binomio. * Técnicas con y sin memorización*/ public class BinomioDeNewton { // considerando la fórmula (ax+b)^n private int a; private int b; private int n; /** * Constructor con parametros * * @param a * <code>int</code> * @param b * <code>int</code> * @param n * <code>int</code> */ public BinomioDeNewton(int a, int b, int n) { this.a = a; this.b = b; this.n = n; } /** * Obtener el termino k del polinomio utilizando el calculo combinatorio * iterativo * * Complejidad * * @param k * <code>int</code> el termino a obtener * @return termino enviado como parametro */ public int terminoK(int k) { return (int) (Utilitario.combinatoria(n, k) * Math.pow(a, k) * Math.pow(b, n - k)); } /** * Obtener el termino k del polinomio utilizando el calculo combinatorio * recursivo * * Complejidad * * @param k * <code>int</code> el termino a obtener * @return termino enviado como parametro */ public int terminoKRecursivo(int k) { return (int) (Utilitario.combinatoriaRecursiva(n, k) * Math.pow(a, k) * Math.pow(b, n - k)); } /** * Obtener el termino k del polinomio utilizando el triangulo de Tartaglia * * Complejidad * * @param k * <code>int</code> el termino a obtener * @return termino enviado como parametro */ public int terminoKMejorado(int k) { return (int) (Utilitario.combinatoriaMejorada(n, k) * Math.pow(a, k) * Math.pow(b, n - k)); } /** * Obtener el polinomio del desarrollo completo de un binomio de newton, el * calculo combinatorio iterativo * * Complejidad * * @return polinomio resultante */ public Polinomio desarrolloCompleto() { double[] coeficientes = new double[n + 1]; for (int i = 0; i < coeficientes.length; i++) { coeficientes[i] = Utilitario.combinatoria(n, i) * Math.pow(a, n - i) * Math.pow(b, i); } return new Polinomio(coeficientes); } /** * Obtener el polinomio del desarrollo completo de un binomio de newton, el * calculo combinatorio recursivo * * Complejidad * * @return polinomio resultante */ public Polinomio desarrolloCompletoRecursivo() { double[] coeficientes = new double[n + 1]; for (int i = 0; i < coeficientes.length; i++) { coeficientes[i] = Utilitario.combinatoriaRecursiva(n, i) * Math.pow(a, n - i) * Math.pow(b, i); } return new Polinomio(coeficientes); } /** * Obtener el polinomio del desarrollo completo de un binomio de newton, el * calculo combinatorio mejorado con triangulo de tartaglia * * Complejidad * * @return polinomio resultante */ public Polinomio desarrolloCompletoMejorado() { double[] coeficientes = new double[n + 1]; for (int i = 0; i < coeficientes.length; i++) { coeficientes[i] = Utilitario.combinatoriaMejorada(n, i) * Math.pow(a, n - i) * Math.pow(b, i); } return new Polinomio(coeficientes); } /** * * @return n <code>int</code> */ public int getN() { return n; } }
true
0f0b3649c195c406537b0e4a99f79d60c28320d4
Java
phblr77/MyShop
/src/main/java/ru/geekbrains/shop/controllers/RestProductController.java
UTF-8
1,745
2.5
2
[]
no_license
package ru.geekbrains.shop.controllers; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ru.geekbrains.shop.model.Product; import ru.geekbrains.shop.services.ProductService; import ru.geekbrains.shop.utils.ProductNotFoundException; import java.util.List; @RestController @RequiredArgsConstructor @RequestMapping("/shop/") public class RestProductController { private final ProductService productService; //получение всех товаров [ GET .../app/products ] @GetMapping public List<Product> getAllProducts() { return productService.findAll(); } //создание нового товара [ POST .../app/products ] @PostMapping("/products/add") @ResponseStatus(HttpStatus.CREATED) public Product saveNewProduct(@RequestBody Product product) { if (product.getId() != null) { product.setId(null); } return productService.saveNewProduct(product); } //получение товара по id [ GET .../app/products/{id} ] @GetMapping("/products/{id}") public ResponseEntity<?> getOneProduct(@PathVariable Long id) { if (!productService.existsById(id)) { throw new ProductNotFoundException("Product not found, id: " + id); } return new ResponseEntity<>(productService.findById(id), HttpStatus.OK); } //удаление товара по id.[ GET .../app/products/delete/{id} ] @DeleteMapping("/products/{id}") public String deleteOneProduct(@PathVariable Long id) { productService.deleteById(id); return "OK"; } }
true
e7032114db3279267b6365090dc6a44e625b8b80
Java
MadMockers/mc-devs
/net/minecraft/server/BlockWorkbench.java
UTF-8
847
2.171875
2
[]
no_license
package net.minecraft.server; public class BlockWorkbench extends Block { protected BlockWorkbench(int paramInt) { super(paramInt, Material.WOOD); this.textureId = 59; a(CreativeModeTab.c); } public int a(int paramInt) { if (paramInt == 1) return this.textureId - 16; if (paramInt == 0) return Block.WOOD.a(0); if ((paramInt == 2) || (paramInt == 4)) return this.textureId + 1; return this.textureId; } public boolean interact(World paramWorld, int paramInt1, int paramInt2, int paramInt3, EntityHuman paramEntityHuman, int paramInt4, float paramFloat1, float paramFloat2, float paramFloat3) { if (paramWorld.isStatic) { return true; } paramEntityHuman.startCrafting(paramInt1, paramInt2, paramInt3); return true; } } /* * Qualified Name: net.minecraft.server.BlockWorkbench * JD-Core Version: 0.6.0 */
true
155447b0c4a24674663a584c527e1b30935ae65f
Java
Carla93/JavaPracticeHacktoberfest
/src/com/hacktoberfest/DiasDiferencia.java
ISO-8859-1
1,045
3.609375
4
[]
no_license
package com.hacktoberfest; import java.util.Scanner; public class DiasDiferencia { // Este programa calcula cuntos das de diferencia hay entre dos fechas public static void main(String[] args) { int d1, d2, m1, m2, a1, a2; int dif; Scanner sc = new Scanner(System.in); System.out.println("PRIMERA FECHA."); System.out.println("Introduzca el da:"); d1 = sc.nextInt(); System.out.println("Introduzca el mes en nmero:"); m1 = sc.nextInt(); System.out.println("Introduzca el ao:"); a1 = sc.nextInt(); System.out.println("SEGUNDA FECHA."); System.out.println("Introduzca el da:"); d2 = sc.nextInt(); System.out.println("Introduzca el mes en nmero:"); m2 = sc.nextInt(); System.out.println("Introduzca el ao:"); a2 = sc.nextInt(); dif = d2 - d1 + 30 * (m2 - m1) + 365 * (a2 - a1); if (dif < 0) { dif = dif * -1; System.out.println("La diferencia es de " + dif + " das."); } else System.out.println("La diferencia es de " + dif + " das."); sc.close(); } }
true
f49cd0c7a8ea8c04ff3f20730641a25c16516236
Java
SeungJuAhn0317/object-oriented_programming_1
/src/Project/Study_newstudy_modal.java
UTF-8
4,327
2.640625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Project; import java.awt.Font; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JTextField; /** * * @author 이혜주 */ public class Study_newstudy_modal extends JDialog{ public Study_newstudy_modal(Window parent) throws IOException{//, JLabel label, JLabel label2, JLabel label3, JLabel label4, JLabel label5 super(parent, "신규강좌등록",ModalityType.APPLICATION_MODAL); setSize(350,440); setLayout(null); setLocationRelativeTo(null); JLabel lb1 = new JLabel("강좌 번호"); lb1.setFont(new Font("굴림", Font.PLAIN, 15)); lb1.setBounds(60,40,150,50); // 위치 , 글자 크기 add(lb1); JTextField field1 = new JTextField(10); field1.setBounds(135,50,100,30); add(field1); JLabel lb2 = new JLabel("강좌 이름"); lb2.setFont(new Font("굴림", Font.PLAIN, 15)); lb2.setBounds(60,85,150,50); add(lb2); JTextField field2 = new JTextField(10); field2.setBounds(135,95,100,30); add(field2); JLabel lb3 = new JLabel("학 과"); lb3.setFont(new Font("굴림", Font.PLAIN, 15)); lb3.setBounds(60,125,150,50); add(lb3); String [] s = {"전산학과","전자공학과","화학공학과","기계공학과","항공우주학과"}; JComboBox<String> combo; combo = new JComboBox<String> (s); combo.setFont(new Font("굴림", Font.PLAIN, 15)); combo.setBounds(135,135,150,30); add(combo); JLabel lb4 = new JLabel("학점 수"); lb4.setFont(new Font("굴림", Font.PLAIN, 15)); lb4.setBounds(60,165,150,50); add(lb4); JTextField field4 = new JTextField(10); field4.setBounds(135,175,100,30); add(field4); JLabel lb5 = new JLabel("강좌 설명"); lb5.setFont(new Font("굴림", Font.PLAIN, 15)); lb5.setBounds(60,205,150,50); add(lb5); JTextArea field5 = new JTextArea(); field5.setBounds(135,225,150,60); add(field5); JButton b1 = new JButton("취소"); b1.setBounds(95,335,60,40); add(b1); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ //label.setText(field1.getText()); dispose(); } }); JButton b2 = new JButton("등록"); b2.setBounds(160,335,60,40); add(b2); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ee){ FileWriter reader; try { String filename = field2.getText(); reader = new FileWriter(filename+".txt"); // 텍스트 파일이 없으면 새로 생성함! } catch (IOException ex) { Logger.getLogger(Study_newstudy_modal.class.getName()).log(Level.SEVERE, null, ex); } JOptionPane.showMessageDialog(null,"등록 되었습니다."); Study_lecture sl = new Study_lecture(); String str1 = field1.getText(); String str2 = field2.getText(); String str3 = combo.getSelectedItem().toString(); String str4 = field4.getText(); String str5 = field5.getText(); sl.info(str1,str2,str3,str4,str5); dispose(); } }); } }
true
c6f5f7292ee4c72193c9d8dbf7197dbfb149492e
Java
victorSenia/list-war
/src/main/java/com/leo/test/list/war/config/SecurityConfig.java
UTF-8
2,782
2.015625
2
[]
no_license
package com.leo.test.list.war.config; import com.leo.test.list.war.model.Role; import com.leo.test.list.war.service.UserDetailsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(). antMatchers("/registration", "/login", "/js/**", "/css/**", "/favicon.ico").permitAll(). // antMatchers("/admin/**").hasRole("SUMERADMIN"). antMatchers("/**").hasRole("USER"). and().formLogin().loginPage("/login").failureUrl("/login?error").usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/youtube/list", true). and().logout().logoutSuccessUrl("/login?logout"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"). and().withUser("admin").password("admin_password").roles("ADMIN"); } @Autowired UserDetailsServiceImpl userDetailsServiceImpl; @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(bCryptPasswordEncoder()); provider.setUserDetailsService(userDetailsServiceImpl); return provider; } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(16); } @Bean public RoleHierarchy hierarchyImpl() { RoleHierarchyImpl hierarchyImpl = new RoleHierarchyImpl(); for (String string : Role.hierarchy()) hierarchyImpl.setHierarchy(string); return hierarchyImpl; } }
true
46be77212e52d8b1e6b9d8ded05a22730188f72a
Java
fengykeji/YQDandriod-
/app/src/main/java/com/ccsoft/yunqudao/bean/CityBean.java
UTF-8
1,477
2.390625
2
[]
no_license
package com.ccsoft.yunqudao.bean; import java.util.List; public class CityBean { /** * code : 200 * msg : 查询成功 * data : [{"city_name":"绵阳","city_code":"510700"}] */ private int code; private String msg; private List<DataBean> data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { @Override public String toString() { return "DataBean{" + "city_name='" + city_name + '\'' + ", city_code='" + city_code + '\'' + '}'; } /** * city_name : 绵阳 * city_code : 510700 */ private String city_name; private String city_code; public String getCity_name() { return city_name; } public void setCity_name(String city_name) { this.city_name = city_name; } public String getCity_code() { return city_code; } public void setCity_code(String city_code) { this.city_code = city_code; } } }
true
452e8c2992319151098e53c13a7ac980542101a6
Java
Darrenwdq/syGeneralFramework
/syGeneralFramework/src/main/java/com/sy/web/userInfo/dao/impl/UserDaoImpl.java
UTF-8
1,529
2.125
2
[]
no_license
package com.sy.web.userInfo.dao.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.sy.commons.persistence.dao.BaseDao; import com.sy.commons.persistence.dao.impl.EntityDaoSupport; import com.sy.commons.pojo.User; import com.sy.web.userInfo.dao.UserDao; /** * @Author:Darren * @Date:2016年12月26日 * @Version:1.0 * @Description:Dao实现类主要是放SQL语句的查询 */ @Repository public class UserDaoImpl extends EntityDaoSupport<User> implements UserDao,BaseDao { @Autowired private JdbcTemplate druidJDBCTemplate; /* public int queryUser(User user) { String sql = simpleSqlBuilder.getQueryAllSql(); Map<String, Object> map = druidJDBCTemplate.queryForMap("SELECT count(*) id FROM USER WHERE username ='" + user.getUsername() + "' AND PASSWORD ='" + user.getDescribe() + "'"); System.out.println(map.get("id")); return Integer.valueOf(map.get("id").toString()); }*/ public int queryUser(User user) { String sql = "SELECT count(*) id FROM USER WHERE username = ? AND PASSWORD = ?"; Object[] obj = {user.getUsername(), user.getDescribe() }; System.out.println(user.getUsername() + user.getDescribe()); // try { // List userList = search(sql, obj); // } catch (DaoAccessException e) { // e.printStackTrace(); // } return druidJDBCTemplate.queryForInt(sql, obj); } public int register() { System.out.println("这是注册!"); return 0; } }
true
d4b43d1bff2b04090f780759dbb2633661861a32
Java
muhammadaliyya19/3rd_Semester_Data-Structure-and-Algorithm
/src/Queue/Queue.java
UTF-8
1,160
3.515625
4
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Queue; /** * * @author asus */ public class Queue { public NodeQueue front = null; //inisialisasi awal null private NodeQueue rear = null; //inisialisasi awal null private NodeQueue kondektur = null; //inisialisasi awal null public int count = 0; public void enqueue(NodeQueue gerbong) { if (front == null) { front = gerbong; } else { rear.next = gerbong; //gerbong baru yang masuk } rear = gerbong; //karena kode nya sama antara if dan else, maka dikeluarkan saja count++; } public boolean isEmpty(){ if (front == null){ return true; } else { return false; } } public NodeQueue dequeue(){ kondektur = front; if (isEmpty() == false){ front = front.next; count--; return kondektur; } else { return null; } } }
true
13b66a3edda47e72cb9352a028cd551a4762fc9d
Java
jorge-luque/hb
/sources/p163cz/msebera/android/httpclient/impl/cookie/C5841d0.java
UTF-8
4,116
2.109375
2
[]
no_license
package p163cz.msebera.android.httpclient.impl.cookie; import java.util.Locale; import p163cz.msebera.android.httpclient.cookie.C5677a; import p163cz.msebera.android.httpclient.cookie.C5678b; import p163cz.msebera.android.httpclient.cookie.C5679c; import p163cz.msebera.android.httpclient.cookie.C5682f; import p163cz.msebera.android.httpclient.cookie.C5690m; import p163cz.msebera.android.httpclient.cookie.CookieRestrictionViolationException; import p163cz.msebera.android.httpclient.cookie.MalformedCookieException; import p163cz.msebera.android.httpclient.p187k0.C5886a; /* renamed from: cz.msebera.android.httpclient.impl.cookie.d0 */ /* compiled from: RFC2965DomainAttributeHandler */ public class C5841d0 implements C5678b { /* renamed from: a */ public String mo33121a() { return "domain"; } /* renamed from: a */ public void mo33132a(C5690m mVar, String str) throws MalformedCookieException { C5886a.m18894a(mVar, "Cookie"); if (str == null) { throw new MalformedCookieException("Missing value for domain attribute"); } else if (!str.trim().isEmpty()) { String lowerCase = str.toLowerCase(Locale.ROOT); if (!str.startsWith(".")) { lowerCase = '.' + lowerCase; } mVar.mo33161f(lowerCase); } else { throw new MalformedCookieException("Blank value for domain attribute"); } } /* renamed from: b */ public boolean mo33133b(C5679c cVar, C5682f fVar) { C5886a.m18894a(cVar, "Cookie"); C5886a.m18894a(fVar, "Cookie origin"); String lowerCase = fVar.mo33136a().toLowerCase(Locale.ROOT); String d = cVar.mo33127d(); if (mo33618a(lowerCase, d) && lowerCase.substring(0, lowerCase.length() - d.length()).indexOf(46) == -1) { return true; } return false; } /* renamed from: a */ public boolean mo33618a(String str, String str2) { return str.equals(str2) || (str2.startsWith(".") && str.endsWith(str2)); } /* renamed from: a */ public void mo33131a(C5679c cVar, C5682f fVar) throws MalformedCookieException { C5886a.m18894a(cVar, "Cookie"); C5886a.m18894a(fVar, "Cookie origin"); String lowerCase = fVar.mo33136a().toLowerCase(Locale.ROOT); if (cVar.mo33127d() != null) { String lowerCase2 = cVar.mo33127d().toLowerCase(Locale.ROOT); if (!(cVar instanceof C5677a) || !((C5677a) cVar).mo33120c("domain")) { if (!cVar.mo33127d().equals(lowerCase)) { throw new CookieRestrictionViolationException("Illegal domain attribute: \"" + cVar.mo33127d() + "\"." + "Domain of origin: \"" + lowerCase + "\""); } } else if (lowerCase2.startsWith(".")) { int indexOf = lowerCase2.indexOf(46, 1); if ((indexOf < 0 || indexOf == lowerCase2.length() - 1) && !lowerCase2.equals(".local")) { throw new CookieRestrictionViolationException("Domain attribute \"" + cVar.mo33127d() + "\" violates RFC 2965: the value contains no embedded dots " + "and the value is not .local"); } else if (!mo33618a(lowerCase, lowerCase2)) { throw new CookieRestrictionViolationException("Domain attribute \"" + cVar.mo33127d() + "\" violates RFC 2965: effective host name does not " + "domain-match domain attribute."); } else if (lowerCase.substring(0, lowerCase.length() - lowerCase2.length()).indexOf(46) != -1) { throw new CookieRestrictionViolationException("Domain attribute \"" + cVar.mo33127d() + "\" violates RFC 2965: " + "effective host minus domain may not contain any dots"); } } else { throw new CookieRestrictionViolationException("Domain attribute \"" + cVar.mo33127d() + "\" violates RFC 2109: domain must start with a dot"); } } else { throw new CookieRestrictionViolationException("Invalid cookie state: domain not specified"); } } }
true
7d041aeb924bcb1d49009a14cafc61eea78d5ae8
Java
LuisAntonioDeMelo/apliFinac
/projeto-spring-angular-gestao-financeira/gestao-financeira-server/src/main/java/com/tst/gestao/financeira/repository/TributacaoRepository.java
UTF-8
243
1.640625
2
[]
no_license
package com.tst.gestao.financeira.repository; import com.tst.gestao.financeira.modelo.Tributacao; import org.springframework.data.jpa.repository.JpaRepository; public interface TributacaoRepository extends JpaRepository<Tributacao,Long> { }
true
adcabcb1e43c64d3d13ad47ff687f61622b79729
Java
HanJaeWon621/starfield-admin
/src/test/java/kr/co/starfield/rest/controller/AKWD002RestControllerTest.java
UTF-8
6,272
1.914063
2
[]
no_license
package kr.co.starfield.rest.controller; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.transaction.annotation.Transactional; import kr.co.starfield.common.BaseException; import kr.co.starfield.common.StatusCode; import kr.co.starfield.model.RecommendTag; import kr.co.starfield.model.vo.SKWD002Vo; import kr.co.starfield.service.AKWD002Service; public class AKWD002RestControllerTest extends BaseTest { @Autowired AKWD002Service akwd002Service; RecommendTag recommendTag; @Override public void setup() throws Exception { recommendTag = new RecommendTag(); recommendTag.bcn_cd = "01"; recommendTag.tag_div = "a"; recommendTag.tag_nm = "tag"; recommendTag.sort_ord = 0; recommendTag.sts = 1; } /** * RecommendTag 등록 * @return */ @Test @Transactional public void testRegRecommendTag() throws Exception { mockMvc.perform(post("/admin/rest/" + recommendTag.bcn_cd + "/recommend/tags") .header("content-type", "application/json") .contentType(MediaType.APPLICATION_JSON) .characterEncoding("UTF-8") .content(new ObjectMapper().writeValueAsString(recommendTag))) .andDo(print()) .andExpect(handler().handlerType(AKWD002RestController.class)) .andExpect(handler().methodName("regRecommendTag")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(0)); } /** * RecommendTag 목록 조회 * @return */ @Test @Transactional public void testGetRecommendTagList() throws Exception { recommendTag.recm_tag_seq = akwd002Service.regRecommendTag(recommendTag.toVo()).extra; mockMvc.perform(get("/admin/rest/" + recommendTag.bcn_cd + "/recommend/tags") .header("content-type", "application/json") .contentType(MediaType.APPLICATION_JSON) .characterEncoding("UTF-8") .param("q", "tag_nm=tag") .param("offset", "0") .param("limit", "10")) .andDo(print()) .andExpect(handler().handlerType(AKWD002RestController.class)) .andExpect(handler().methodName("getRecommendTagList")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)); } /** * RecommendTag 상세 * @return */ @Test @Transactional public void testGetRecommendTag() throws Exception { recommendTag.recm_tag_seq = akwd002Service.regRecommendTag(recommendTag.toVo()).extra; mockMvc.perform(get("/admin/rest/" + recommendTag.bcn_cd + "/recommend/tags/" + recommendTag.recm_tag_seq) .header("content-type", "application/json") .contentType(MediaType.APPLICATION_JSON) .characterEncoding("UTF-8")) .andDo(print()) .andExpect(handler().handlerType(AKWD002RestController.class)) .andExpect(handler().methodName("getRecommendTag")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.bcn_cd").value("BCN001")); } /** * RecommendTag 수정 * @return */ @Test @Transactional public void testModifyRecommendTag() throws Exception { recommendTag.recm_tag_seq = akwd002Service.regRecommendTag(recommendTag.toVo()).extra; assertThat(akwd002Service.getRecommendTag(recommendTag.toVo()).recm_tag_seq, is(recommendTag.recm_tag_seq)); recommendTag.tag_nm = "tagName"; mockMvc.perform(put("/admin/rest/" + recommendTag.bcn_cd + "/recommend/tags/" + recommendTag.recm_tag_seq) .header("content-type", "application/json") .contentType(MediaType.APPLICATION_JSON) .characterEncoding("UTF-8") .content(new ObjectMapper().writeValueAsString(recommendTag))) .andDo(print()) .andExpect(handler().handlerType(AKWD002RestController.class)) .andExpect(handler().methodName("modifyRecommendTag")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(0)); assertThat(akwd002Service.getRecommendTag(recommendTag.toVo()).tag_nm, is(recommendTag.tag_nm)); } /** * RecommendTag 삭제 * @return */ @Test @Transactional public void testDeleteRecommendTag() throws Exception { recommendTag.recm_tag_seq = akwd002Service.regRecommendTag(recommendTag.toVo()).extra; assertThat(akwd002Service.getRecommendTag(recommendTag.toVo()).recm_tag_seq, is(recommendTag.recm_tag_seq)); mockMvc.perform(delete("/admin/rest/" + recommendTag.bcn_cd + "/recommend/tags/" + recommendTag.recm_tag_seq) .header("content-type", "application/json") .contentType(MediaType.APPLICATION_JSON) .characterEncoding("UTF-8")) .andDo(print()) .andExpect(handler().handlerType(AKWD002RestController.class)) .andExpect(handler().methodName("deleteRecommendTag")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(0)); SKWD002Vo vo = recommendTag.toVo(); vo.sts = StatusCode.Common.DELETE.getCode(); assertThat(akwd002Service.getRecommendTag(vo).sts, is(vo.sts)); } }
true
14586167685551317ba66d236afe5cdcf10c678b
Java
SSAwk/Object-Oriented-Programming-in-Java
/Project 3/BoxList.java
UTF-8
989
3.484375
3
[]
no_license
public abstract class BoxList { protected BoxNode first; protected BoxNode last; protected int length; public BoxList() { first = null; last = null; length = 0; } // Constructor public Box get(int x) { //Gets object from list if (x < 0 || x >= length) { return null; } if (x == length - 1) { return last.Data(); } BoxNode n = first; for (int i = 1; i <= x; i++) n = n.Next(); return n.Data(); } public int length() { //Returns length of list return length; } public void append(Box b) { BoxNode node = new BoxNode(b); if (first == null) { first = node; last = node; } else { last.next = node; last = node; } length++; } // Appends a box @Override public String toString() { String data = ""; BoxNode node = first; while (node != null) { data += node.data.toString() + "\n"; node = node.next; } return data; } // Override for toString; returns a string }
true
b190ecf891ad64842e837f974832d418de08b180
Java
liust15/test-Clothes-Mall
/src/main/java/com/liust/utils/EmptyUtils.java
UTF-8
281
2.0625
2
[]
no_license
package com.liust.utils; /** * @program: Clothes * @description: * @author: liust * @create: 2018-05-31 18:01 **/ public class EmptyUtils { public static boolean isEmpty(String s){ if (null==s||"".equals(s)) return true; return false; } }
true
3b34addb03e3d6aa679a4f736359e1ea55133325
Java
bristle-com/javalib
/src/com/bristle/javalib/net/http/ServletDebugger.java
UTF-8
6,655
2.515625
3
[]
no_license
// Copyright (C) 2005-2012 Bristle Software, Inc. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 1, or (at your option) // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc. package com.bristle.javalib.net.http; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // ServletDebugger /****************************************************************************** * This class contains utility routines for interacting with the HTTP protocol. *<pre> *<b>Usage:</b> * - The typical scenario for using this class is: * * - To enable the ServletDebugger for an HttpServlet, add the following * line of code to the top of the servlet's service() method: * if (ServletDebugger.intercept(this, request, response)) return; * This causes the ServletDebugger to examine the HTTP request, and * decide whether to take action. If so, it generates an HTTP response * (setting the content-type, writing to the response Writer, etc.) and * returns true. Returning true causes the calling servlet to return * to its caller without doing anything. * * - To activate an enabled ServletDebugger for an HTTP request, specify * the following HTTP parameter (typically in the URL string) * bristleDebug * * - To force activation of the ServletDebugger, even if the HTTP parameters * didn't request it: * ServletDebugger.invoke(this, request, response); * *?? Add other params that can cause other actions. *<b>Assumptions:</b> *<b>Effects:</b> * - Intercepts requests to a servlet, sending its own response to the * HTTP client while running in the original servlet's Session. Can * modify values of attributes in the Session, the ServletContext, * etc. ??Not yet?? *<b>Anticipated Changes:</b> *<b>Notes:</b> *<b>Implementation Notes:</b> *<b>Portability Issues:</b> *<b>Revision History:</b> * $Log$ *</pre> ******************************************************************************/ public class ServletDebugger { //-- //-- Class variables //-- //-- //-- Instance variables to support public properties //-- //-- //-- Internal instance variables //-- /************************************************************************** * Name of the HTTP parameter used to active the ServletDebugger. **************************************************************************/ public static final String strACTIVATION_PARAM_NAME = "bristleDebug"; /************************************************************************** * Examine the specified HTTP request, and decide whether to invoke the * "servlet debugger", returning true if invoked; false otherwise. * See invoke() for more details. *@param servlet The HttpServlet object defining the servlet. *@param request The HttpServletRequest object of the servlet. *@param response The HttpServletResponse object of the servlet. *@return true if invoked; false otherwise. *@throws IOException When an I/O error occurs during interaction * with the servlet, request, or response. **************************************************************************/ public static boolean intercept (HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) throws IOException { if (HttpUtil.getParamPresent(request, strACTIVATION_PARAM_NAME)) { invoke(servlet, request, response); return true; } return false; } /************************************************************************** * Invoke the "servlet debugger". For now, this simply means to write as an * XML stream to the HTTP client all information available to the servlet. * Format of XML is as shown in HttpUtil.writeInfoAvailableToServlet. *@param servlet The HttpServlet object defining the servlet. *@param request The HttpServletRequest object of the servlet. *@param response The HttpServletResponse object of the servlet. *@throws IOException When an I/O error occurs during interaction * with the servlet, request, or response. **************************************************************************/ public static void invoke (HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) throws IOException { HttpUtil.writeInfoAvailableToServlet(servlet, request, response); } /************************************************************************** * Each class contains a Tester inner class with a main() for easier * unit testing. To call main from the command line, use: * <pre> * java class$Tester *</pre> * where "class" is the name of the outer class. **************************************************************************/ public static class Tester { /********************************************************************** * Main testing method. *@param args Array of command line argument strings **********************************************************************/ public static void main(String[] args) { try { System.out.println("Begin tests..."); System.out.println("...End tests."); } catch (Throwable e) { System.out.println("Error in main(): "); e.printStackTrace(); } } } }
true
e2d038c59ce9c62270e1297e8b89b7b10537d1af
Java
patrickka09/homework16
/Person.java
UTF-8
183
1.921875
2
[]
no_license
package edu.dmacc.codedsm.hw16; public class Person implements TaskAssigner { @Override public void assignTasker() { System.out.println(" task from Person"); } }
true
67f38277fd201582afcd2b2b3097e395ba246b07
Java
JavaBasti0711er/TestMySkills
/TestMySkills/src/de/testmyskills/utils/ScoreboardAPI.java
UTF-8
9,492
2.078125
2
[]
no_license
package de.testmyskills.utils; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import de.testmyskills.Main; import net.minecraft.server.v1_8_R3.IScoreboardCriteria; import net.minecraft.server.v1_8_R3.Packet; import net.minecraft.server.v1_8_R3.PacketPlayOutScoreboardDisplayObjective; import net.minecraft.server.v1_8_R3.PacketPlayOutScoreboardObjective; import net.minecraft.server.v1_8_R3.PacketPlayOutScoreboardScore; import net.minecraft.server.v1_8_R3.Scoreboard; import net.minecraft.server.v1_8_R3.ScoreboardObjective; import net.minecraft.server.v1_8_R3.ScoreboardScore; public class ScoreboardAPI implements Listener { Main pl; public ScoreboardAPI(Main instance) { pl = instance; } @EventHandler public void onJoin(PlayerJoinEvent e) { Player p = e.getPlayer(); sendScoreboard(p); for (Player all : Bukkit.getOnlinePlayers()) { sendScoreboard(all); } } @EventHandler public void onQuit(PlayerQuitEvent e) { for(Player all : Bukkit.getOnlinePlayers()) { sendScoreboard(all); } } public static void sendScoreboard(Player p) { SetupScoreboard sm = Main.instance.setupScoreboard; String displayname = sm.getString("ScoreboardName"); String score1 = sm.getString("Score1"); String score2 = sm.getString("Score2"); String score3 = sm.getString("Score3"); String score4 = sm.getString("Score4"); String score5 = sm.getString("Score5"); String score6 = sm.getString("Score6"); String score7 = sm.getString("Score7"); String score8 = sm.getString("Score8"); String score9 = sm.getString("Score9"); String score10 = sm.getString("Score10"); String score11 = sm.getString("Score11"); String score12 = sm.getString("Score12"); String score13 = sm.getString("Score13"); String score14 = sm.getString("Score14"); String score15 = sm.getString("Score15"); boolean score1b = sm.getBoolean("Score1boolean"); boolean score2b = sm.getBoolean("Score2boolean"); boolean score3b = sm.getBoolean("Score3boolean"); boolean score4b = sm.getBoolean("Score4boolean"); boolean score5b = sm.getBoolean("Score5boolean"); boolean score6b = sm.getBoolean("Score6boolean"); boolean score7b = sm.getBoolean("Score7boolean"); boolean score8b = sm.getBoolean("Score8boolean"); boolean score9b = sm.getBoolean("Score9boolean"); boolean score10b = sm.getBoolean("Score10boolean"); boolean score11b = sm.getBoolean("Score11boolean"); boolean score12b = sm.getBoolean("Score12boolean"); boolean score13b = sm.getBoolean("Score13boolean"); boolean score14b = sm.getBoolean("Score14boolean"); boolean score15b = sm.getBoolean("Score15boolean"); Scoreboard board = new Scoreboard(); ScoreboardObjective obj = board.registerObjective("a", IScoreboardCriteria.b); obj.setDisplayName(displayname.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); PacketPlayOutScoreboardObjective createPacket = new PacketPlayOutScoreboardObjective(obj, 0); PacketPlayOutScoreboardObjective removePacket = new PacketPlayOutScoreboardObjective(obj, 1); PacketPlayOutScoreboardDisplayObjective display = new PacketPlayOutScoreboardDisplayObjective(1, obj); ScoreboardScore s1 = new ScoreboardScore(board, obj, score1.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s2 = new ScoreboardScore(board, obj, score2.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s3 = new ScoreboardScore(board, obj, score3.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s4 = new ScoreboardScore(board, obj, score4.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s5 = new ScoreboardScore(board, obj, score5.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s6 = new ScoreboardScore(board, obj, score6.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s7 = new ScoreboardScore(board, obj, score7.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s8 = new ScoreboardScore(board, obj, score8.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s9 = new ScoreboardScore(board, obj, score9.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s10 = new ScoreboardScore(board, obj, score10.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s11 = new ScoreboardScore(board, obj, score11.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s12 = new ScoreboardScore(board, obj, score12.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s13 = new ScoreboardScore(board, obj, score13.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s14 = new ScoreboardScore(board, obj, score14.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); ScoreboardScore s15 = new ScoreboardScore(board, obj, score15.replaceAll("%onlineplayers%", String.valueOf(Bukkit.getOnlinePlayers().size())) .replaceAll("%playername%", p.getName())); if (score1b == true) { s1.setScore(1); } if (score2b == true) { s2.setScore(2); } if (score3b == true) { s3.setScore(3); } if (score4b == true) { s4.setScore(4); } if (score5b == true) { s5.setScore(5); } if (score6b == true) { s6.setScore(6); } if (score7b == true) { s7.setScore(7); } if (score8b == true) { s8.setScore(8); } if (score9b == true) { s9.setScore(9); } if (score10b == true) { s10.setScore(10); } if (score11b == true) { s11.setScore(11); } if (score12b == true) { s12.setScore(12); } if (score13b == true) { s13.setScore(13); } if (score14b == true) { s14.setScore(14); } if (score15b == true) { s15.setScore(15); } PacketPlayOutScoreboardScore p1 = new PacketPlayOutScoreboardScore(s1); PacketPlayOutScoreboardScore p2 = new PacketPlayOutScoreboardScore(s2); PacketPlayOutScoreboardScore p3 = new PacketPlayOutScoreboardScore(s3); PacketPlayOutScoreboardScore p4 = new PacketPlayOutScoreboardScore(s4); PacketPlayOutScoreboardScore p5 = new PacketPlayOutScoreboardScore(s5); PacketPlayOutScoreboardScore p6 = new PacketPlayOutScoreboardScore(s6); PacketPlayOutScoreboardScore p7 = new PacketPlayOutScoreboardScore(s7); PacketPlayOutScoreboardScore p8 = new PacketPlayOutScoreboardScore(s8); PacketPlayOutScoreboardScore p9 = new PacketPlayOutScoreboardScore(s9); PacketPlayOutScoreboardScore p10 = new PacketPlayOutScoreboardScore(s10); PacketPlayOutScoreboardScore p11 = new PacketPlayOutScoreboardScore(s11); PacketPlayOutScoreboardScore p12 = new PacketPlayOutScoreboardScore(s12); PacketPlayOutScoreboardScore p13 = new PacketPlayOutScoreboardScore(s13); PacketPlayOutScoreboardScore p14 = new PacketPlayOutScoreboardScore(s14); PacketPlayOutScoreboardScore p15 = new PacketPlayOutScoreboardScore(s15); sendPacket(p, removePacket); sendPacket(p, createPacket); sendPacket(p, display); if (score1b == true) { sendPacket(p, p1); } if (score2b == true) { sendPacket(p, p2); } if (score3b == true) { sendPacket(p, p3); } if (score4b == true) { sendPacket(p, p4); } if (score5b == true) { sendPacket(p, p5); } if (score6b == true) { sendPacket(p, p6); } if (score7b == true) { sendPacket(p, p7); } if (score8b == true) { sendPacket(p, p8); } if (score9b == true) { sendPacket(p, p9); } if (score10b == true) { sendPacket(p, p10); } if (score11b == true) { sendPacket(p, p11); } if (score12b == true) { sendPacket(p, p12); } if (score13b == true) { sendPacket(p, p13); } if (score14b == true) { sendPacket(p, p14); } if (score15b == true) { sendPacket(p, p15); } } public static void sendPacket(Player p, Packet<?> packet) { ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet); } }
true
7527aa607e2d5147efeeaff8b2c503365140ba88
Java
Affirm/affirm-merchant-sdk-android
/affirm/src/main/java/com/affirm/android/model/CardDetails.java
UTF-8
1,798
2.1875
2
[ "BSD-3-Clause" ]
permissive
package com.affirm.android.model; import android.os.Parcelable; import androidx.annotation.Nullable; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; @AutoValue public abstract class CardDetails implements Parcelable { public static CardDetails.Builder builder() { return new AutoValue_CardDetails.Builder(); } public static TypeAdapter<CardDetails> typeAdapter(Gson gson) { return new AutoValue_CardDetails.GsonTypeAdapter(gson); } @Nullable @SerializedName("cardholder_name") public abstract String cardholderName(); @SerializedName("checkout_token") public abstract String checkoutToken(); @Nullable @SerializedName("cvv") public abstract String cvv(); @Nullable @SerializedName("expiration") public abstract String expiration(); @Nullable @SerializedName("number") public abstract String number(); @Nullable @SerializedName("callback_id") public abstract String callbackId(); @Nullable @SerializedName("id") public abstract String id(); @AutoValue.Builder public abstract static class Builder { public abstract CardDetails.Builder setCardholderName(String value); public abstract CardDetails.Builder setCheckoutToken(String value); public abstract CardDetails.Builder setCvv(String value); public abstract CardDetails.Builder setExpiration(String value); public abstract CardDetails.Builder setNumber(String value); public abstract CardDetails.Builder setCallbackId(String value); public abstract CardDetails.Builder setId(String value); public abstract CardDetails build(); } }
true
fb9005fbfdfe81b4c550360744ca60206662114b
Java
olgaalex/ipharm
/src/main/java/biol/ipharm/form/ShippingMethodForm.java
UTF-8
505
2.328125
2
[]
no_license
package biol.ipharm.form; import biol.ipharm.entity.enums.ShippingMethod; import javax.validation.constraints.NotNull; /** * * @author Olga */ public class ShippingMethodForm { @NotNull(message = "Выберите метод доставки") private ShippingMethod shippingMethod; public ShippingMethod getShippingMethod() { return shippingMethod; } public void setShippingMethod(ShippingMethod shippingMethod) { this.shippingMethod = shippingMethod; } }
true
917419a7530b34cf6677855aa9dc4273517fcd8d
Java
ht16519/springboot-aop-ip-limit
/src/main/java/com/xh/aop/config/BeanConfig.java
UTF-8
556
1.890625
2
[ "MIT" ]
permissive
package com.xh.aop.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; /** * @Name BeanConfig * @Description * @Author wen * @Date 2019-07-11 */ @Configuration public class BeanConfig { @Bean public ValueOperations<String, String> valueOperations(StringRedisTemplate stringRedisTemplate){ return stringRedisTemplate.opsForValue(); } }
true
e14f583abdda14c980e14739a44553c3e82af17f
Java
soerenmetje/HMM
/src/main/hmm/profil/viterbi/parallel/ThreadViterbi.java
UTF-8
4,138
2.875
3
[]
no_license
package main.hmm.profil.viterbi.parallel; import main.fastaparser.Sequence; import main.hmm.profil.ProfilHMM; import main.hmm.profil.viterbi.Viterbi; import main.hmm.profil.viterbi.ViterbiPath; import main.logger.Log; import java.util.Queue; /** * Thread {@link Thread}, der Sequnzen {@link Sequence} aus uebergebener Schlange abarbeitet. * Dabei wird fuer jede Sequenz anhand des uebergebenen Modells mittels des Viterbi-Algorithmus der maximierende Zustands-Pfad berechnet. * Der Score und der Zustands-Pfad der Sequenz wird dann mittles der Wrapper-Klasse {@link ViterbiPath} * zum uebergebenen Array an entsprechender Position hinzugefuegt. * * @author Soeren Metje */ class ThreadViterbi extends Thread { /** * Monitor, um Ausgabe zu synchronisieren */ private static final Object outputMonitor = new Object(); /** * Monitor, um die Bestimmung des Index der naechsten Sequenz zu synchronisieren */ private static final Object indexPollMonitor = new Object(); /** * RNAProfilHMM, welches zur Berechnung verwendet wird */ private final ProfilHMM model; /** * Schlange abzuarbeitender Sequenzen */ private final Queue<Sequence> sequenceQueue; /** * Initiale Anzahl der Sequnzen in Schlange */ private final int sequenzeQueueInitSize; /** * Threadsichere Liste zu der Ergebnisse hinzugefuegt werden */ private final ViterbiPath[] finishedPaths; /** * Konstruktor * * @param model zu verwendenes RNAProfilHMM * @param sequenceQueue abzuarbeitende Sequenzen * @param finishedPaths threadsichere Liste fuer Ergebnisse */ public ThreadViterbi(ProfilHMM model, Queue<Sequence> sequenceQueue, int sequenzeCount, ViterbiPath[] finishedPaths) { this.model = model; this.sequenceQueue = sequenceQueue; this.finishedPaths = finishedPaths; this.sequenzeQueueInitSize = sequenzeCount; } /** * Arbeitet Sequnzen {@link Sequence} aus uebergebener Schlange ab. * Dabei wird fuer jede Sequenz anhand des uebergebenen Modells mittels des Viterbi-Algorithmus der maximierende Zustands-Pfad berechnet. * Der Score und der Zustands-Pfad der Sequenz wird dann mittles der Wrapper-Klasse {@link ViterbiPath} * zum uebergebenen Array an entsprechender Position hinzugefuegt. */ @Override public void run() { Log.dLine(getName() + " started"); boolean running = true; while (running) { Sequence sequence = null; int index = 0; synchronized (indexPollMonitor) { running = !sequenceQueue.isEmpty(); if (running) { index = sequenzeQueueInitSize - sequenceQueue.size(); sequence = sequenceQueue.poll(); } } if (sequence != null) { ViterbiPath viterbiPath = null; long millis = System.currentTimeMillis(); // measure calc time try { viterbiPath = Viterbi.viterbi(model, sequence); } catch (IllegalArgumentException e) { Log.eLine("ERROR: Viterbi RNAProfilHMM failed! " + e.getMessage()); System.exit(1); } catch (OutOfMemoryError e) { Log.eLine("ERROR: Out of Memory " + e.getMessage() + ". Start with more Memory. (Argument -Xmx<Size>)"); System.exit(1); } millis = (System.currentTimeMillis() - millis); // calc time of viterbi float time = (float) millis / 1000; // in sec synchronized (outputMonitor) { Log.iLine(String.format("(%.2fsec) %s -----------------------------", time, sequence.getDescription())); Log.iLine(sequence.getNucleotideSequence()); Log.iLine(String.valueOf(viterbiPath.getStatePath())); Log.iLine(); } finishedPaths[index] = viterbiPath; } } } }
true
3e956b6063d9e9d5f34550ad274790fda8e6650c
Java
FedosovMax/knight-todo
/todocore/src/main/java/com/knighttodo/todocore/exception/DayNotFoundException.java
UTF-8
188
1.992188
2
[]
no_license
package com.knighttodo.todocore.exception; public class DayNotFoundException extends RuntimeException { public DayNotFoundException(String message) { super(message); } }
true
c691230d6362b6b0542636a68022892a23fd58ea
Java
riyadmuhammad/employee-salary
/employee-salary/src/main/java/com/brainstation/employeesalary/employee/repository/BasicSalaryLowestRangeRepository.java
UTF-8
317
1.695313
2
[]
no_license
package com.brainstation.employeesalary.employee.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.brainstation.employeesalary.employee.model.entity.BasicSalaryLowestRange; public interface BasicSalaryLowestRangeRepository extends JpaRepository<BasicSalaryLowestRange, Long>{ }
true
26919b1f9fb1c1e6aa58897b8231afdb3d29760b
Java
Mr-Anonim-377/Tim-scientific-portal_Back
/src/main/java/com/tim/scientific/portal/back/utils/ObjectUtils.java
UTF-8
4,321
2.53125
3
[ "MIT" ]
permissive
package com.tim.scientific.portal.back.utils; import com.tim.scientific.portal.back.controllers.common.handlers.exception.ApiException; import com.tim.scientific.portal.back.controllers.common.handlers.exception.NoSuchObjects; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; public class ObjectUtils { public Predicate<List<?>> isEmptyList() { return List::isEmpty; } public Predicate<Object> isEmpty() { return Objects::isNull; } public Predicate<List<?>> isNotEmptyList() { return objects -> !objects.isEmpty(); } public Predicate<Object> isNotEmpty() { return Objects::nonNull; } @FunctionalInterface public interface CheckedErrorFunction<T, R> { R apply(T t) throws Exception; } @FunctionalInterface public interface CheckedErrorSupplier<R> { R get() throws Exception; } @FunctionalInterface public interface CheckedErrorConsumer<T> { void accept(T t) throws Exception; } protected <T> void objectAssert(RuntimeException apiException, T actual, T expected) { if (!actual.equals(expected)) { throw apiException; } } protected <T> void objectAssert(RuntimeException apiException, Predicate<T> predicate, T t) { if (!predicate.test(t)) { throw apiException; } } // TODO Нужно подумать над ошибками и ассертами protected <T> T objectAssert(CheckedErrorFunction<T,T> function, Predicate<T> predicate, T t) { if (!predicate.test(t)) { try { return function.apply(t); } catch (Exception e) { e.printStackTrace(); } } return t; } protected <T, R> void objectAssert(RuntimeException apiException, BiPredicate<T, R> predicate, T actual, R expected) { if (!predicate.test(actual, expected)) { throw apiException; } } public void listAssert(List<?> list, Predicate<List<?>> predicate) { if (!predicate.test(list)) { throw new NoSuchObjects(); } } public void listAssert(List<?> list, Predicate<List<?>> predicate, ApiException e) { if (!predicate.test(list)) { throw e; } } protected <R> R applyByException(CheckedErrorSupplier<R> function, Map<? extends Throwable, ? extends ApiException> exceptionFields) { R applyResult = null; try { applyResult = function.get(); } catch (Throwable e) { throwCustomException(e, exceptionFields); } return applyResult; } protected <T, R> R applyByException(T t, CheckedErrorFunction<T, R> function, Map<? extends Throwable, ? extends ApiException> exceptionFields) { R applyResult = null; try { applyResult = function.apply(t); } catch (Throwable e) { throwCustomException(e, exceptionFields); } return applyResult; } protected <T> void applyByException(T t, CheckedErrorConsumer<T> consumer, Map<? extends Throwable, ? extends ApiException> exceptionFields) { try { consumer.accept(t); } catch (Throwable e) { throwCustomException(e, exceptionFields); } } private <T extends Throwable> void throwCustomException( T exception, Map<? extends Throwable, ? extends ApiException> exceptionFields) { try { Class<? extends Throwable> exceptionClass = exception.getClass(); for (Map.Entry<? extends Throwable, ? extends ApiException> entry : exceptionFields.entrySet()) { if (entry.getKey().getClass() == exceptionClass) { exception.printStackTrace(); throw entry.getValue(); } } throw exception; } catch (Throwable t) { t.printStackTrace(); throw new ApiException(t.getMessage(), t.getMessage()); } } }
true
3d81bbf6501e6a03bcd15bd33e35df59f506fcd2
Java
gani0004/New
/Testing/src/com/writeDatatoExcel/WriteDtaToExcelWorkbook.java
UTF-8
847
2.546875
3
[]
no_license
package com.writeDatatoExcel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class WriteDtaToExcelWorkbook { public static void main(String[] args) throws IOException { FileInputStream file=new FileInputStream("./src/com/ExcelFiles/Book1.xlsx"); XSSFWorkbook workbook=new XSSFWorkbook(file); XSSFSheet sheet=workbook.getSheet("Sheet1"); Row r=sheet.createRow(2); Cell c=r.createCell(3); c.setCellValue("Gani"); FileOutputStream file1=new FileOutputStream("./src/com/ExcelFiles/Book1.xlsx"); workbook.write(file1);//to save the file } }
true
8cc3a8a76081cce9843191e3f23c80c828b488aa
Java
PhotonBursted/TheLighterBot
/src/main/java/st/photonbur/Discord/Bot/lightbotv3/command/SetCategoryCommand.java
UTF-8
4,478
2.640625
3
[]
no_license
package st.photonbur.Discord.Bot.lightbotv3.command; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.entities.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import st.photonbur.Discord.Bot.lightbotv3.command.alias.CommandAliasCollectionBuilder; import st.photonbur.Discord.Bot.lightbotv3.controller.DiscordController; import st.photonbur.Discord.Bot.lightbotv3.main.LoggerUtils; import st.photonbur.Discord.Bot.lightbotv3.misc.Utils; import st.photonbur.Discord.Bot.lightbotv3.misc.menu.selector.SelectionEvent; import st.photonbur.Discord.Bot.lightbotv3.misc.menu.selector.Selector; import st.photonbur.Discord.Bot.lightbotv3.misc.menu.selector.SelectorBuilder; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; @AvailableCommand public class SetCategoryCommand extends Command implements Selector<Category> { private static final Logger log = LoggerFactory.getLogger(SetCategoryCommand.class); private Category c; private String search; public SetCategoryCommand() { super(new CommandAliasCollectionBuilder() .addAliasPart("setcat", "sc", "setcategory")); } @Override protected void execute() { if (input.size() < 1) { handleError("The category to set wasn't specified!"); return; } search = Utils.drainQueueToString(input); if (search.startsWith("cat:")) { List<Category> candidates = l.getBot().getCategoriesByName(String.join(":", Arrays.copyOfRange(search.split(":"), 1, search.split(":").length)), true); if (candidates.size() > 1) { LinkedHashMap<String, Category> candidateMap = new LinkedHashMap<>(); candidates.forEach(candidate -> candidateMap.put(String.format("%s (ID %s)", candidate.getName(), candidate.getId()), candidate)); new SelectorBuilder<>(this) .setOptionMap(candidateMap) .build(); return; } else if (candidates.size() == 1) { c = candidates.get(0); } else { c = null; } } else if (search.matches("[0-9]+")) { c = l.getBot().getCategoryById(search); } else { c = null; } performCategoryChange(); } @Override protected String getDescription() { return "Sets the default category to place new temporary channels into."; } @Override protected Permission[] getPermissionsRequired() { return new Permission[] { Permission.MANAGE_CHANNEL }; } @Override protected String getUsage() { return "{}setcat <searchTerm>\\n\" +\n" + " <searchTerm> can be any of:\n" + " - <search> - searches for a category ID.\n" + " This can also be `remove` or `null` to remove the default category.\n" + " - cat:<search> - searches for a category with the name of <search>"; } @Override public void onSelection(SelectionEvent<Category> selEv) { if (!selEv.selectionWasMade()) { handleError("The category change was cancelled."); return; } c = selEv.getSelectedOption(); performCategoryChange(); } private void performCategoryChange() { if (c == null && !search.equals("remove") && !search.equals("null")) { handleError("The category you specified couldn't be found!"); return; } if (c == null) { l.getChannelController().getCategories().removeByKeyStoring(ev.getGuild()); l.getDiscordController().sendMessage(ev, "Successfully removed the category to put new temporary channels in.", DiscordController.AUTOMATIC_REMOVAL_INTERVAL); LoggerUtils.logAndDelete(log, "Removed default category from " + ev.getGuild().getName()); } else { l.getChannelController().getCategories().putStoring(ev.getGuild(), c); l.getDiscordController().sendMessage(ev, "Successfully set category to put new temporary channels in to **" + c.getName() + "** (ID " + c.getId() + ")", DiscordController.AUTOMATIC_REMOVAL_INTERVAL); LoggerUtils.logAndDelete(log, "Set default category to " + c.getName() + " for " + ev.getGuild().getName()); } } }
true
44dd14ec380c7126ae1f2a015260ce603206f875
Java
jokanovicc/SpringMVCProjekat
/Knjizara/src/main/java/com/ftn/Knjizara/dao/impl/ListaZeljaDAOImpl.java
UTF-8
2,923
2.3125
2
[]
no_license
package com.ftn.Knjizara.dao.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.ftn.Knjizara.dao.KnjigaDAO2; import com.ftn.Knjizara.dao.KorisnikDAO; import com.ftn.Knjizara.dao.ListaZeljaDAO; import com.ftn.Knjizara.model.Knjiga; import com.ftn.Knjizara.model.Korisnik; import com.ftn.Knjizara.model.ListaZelja; @Repository public class ListaZeljaDAOImpl implements ListaZeljaDAO { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private KorisnikDAO korisnikDAO; @Autowired private KnjigaDAO2 knjigaDAO; private class ListaZeljaRowMapper implements RowMapper<ListaZelja> { @Override public ListaZelja mapRow(ResultSet rs, int rowNum) throws SQLException { int index = 1; Long id = rs.getLong(index++); String korisnickoIme = rs.getString(index++); Korisnik korisnik = korisnikDAO.findOne(korisnickoIme); Long knjigaId = rs.getLong(index++); Knjiga knjiga = knjigaDAO.findOne(knjigaId); ListaZelja listaZelja = new ListaZelja(id, knjiga, korisnik); return listaZelja; } } @Override public ListaZelja findOne(Long id) { String sql = "SELECT l.id,u.korisnickoIme, k.id FROM listazelja l " +"LEFT JOIN korisnici u on u.korisnickoIme = l.korisnik " +"LEFT JOIN knjige k on k.id = l.knjigaId " +"WHERE l.id = ? " +"ORDER BY l.id"; return jdbcTemplate.queryForObject(sql, new ListaZeljaRowMapper(), id); } @Override public List<ListaZelja> findAll() { String sql = "SELECT l.id,u.korisnickoIme, k.id FROM listazelja l " +"LEFT JOIN korisnici u on u.korisnickoIme = l.korisnicko " +"LEFT JOIN knjige k u on k.id = l.knjigaId " +"ORDER BY l.id"; return jdbcTemplate.query(sql, new ListaZeljaRowMapper()); } @Override public List<ListaZelja> izvuciKorisnikove(String korisnicko) { String sql = "SELECT l.id,u.korisnickoIme, k.id FROM listazelja l " +"LEFT JOIN korisnici u on u.korisnickoIme = l.korisnik " +"LEFT JOIN knjige k on k.id = l.knjigaId " +" WHERE u.korisnickoIme = ? "; return jdbcTemplate.query(sql, new ListaZeljaRowMapper(),korisnicko); } @Override public int save(ListaZelja listaZelja) { String sql = "INSERT INTO listazelja (korisnik,knjigaId) VALUES (?,?)"; return jdbcTemplate.update(sql,listaZelja.getKorisnik().getKorisnickoIme(),listaZelja.getKnjiga().getId()); } @Override public int update(ListaZelja listaZelja) { // TODO Auto-generated method stub return 0; } @Override public int delete(Long id) { String sql = "DELETE FROM listazelja WHERE id = ?"; return jdbcTemplate.update(sql, id); } }
true
e2ff00442183e208e20c153fb42c95c9ee65fce1
Java
kaoz36/RespaldoUniat
/AndroidStudioProjects/Ejemplos/TaxyMobile/android/proyect/TaxyMobile/src/com/jaguarlabs/taxymobile/Location.java
WINDOWS-1250
15,999
1.726563
2
[]
no_license
///** ************************************************************************* // * // * Copyright (c) 2013 by Jaguar Labs. // * Confidential and Proprietary // * All Rights Reserved // * // * This software is furnished under license and may be used and copied // * only in accordance with the terms of its license and with the // * inclusion of the above copyright notice. This software and any other // * copies thereof may not be provided or otherwise made available to any // * other party. No title to and/or ownership of the software is hereby // * transferred. // * // * The information in this software is subject to change without notice and // * should not be construed as a commitment by JaguarLabs. // * // * @(#)$Id: $ // * Last Revised By : efren campillo // * Last Checked In : $Date: $ // * Last Version : $Revision: $ // * // * Original Author : Julio Hernandez [email protected] // * Origin : SEnE -- march 13 @ 11:00 (PST) // * Notes : // * // ** *************************************************************************/ // //package com.jaguarlabs.taxymobile; // //import java.util.ArrayList; //import java.util.List; // //import android.app.AlertDialog; //import android.content.Context; //import android.content.DialogInterface; //import android.content.Intent; //import android.content.SharedPreferences; //import android.content.SharedPreferences.Editor; //import android.graphics.Typeface; //import android.graphics.drawable.Drawable; //import android.os.Bundle; //import android.util.Log; //import android.view.KeyEvent; //import android.view.LayoutInflater; //import android.view.MotionEvent; //import android.view.View; //import android.view.View.OnClickListener; //import android.view.View.OnTouchListener; //import android.view.Window; //import android.view.animation.Animation; //import android.view.animation.Animation.AnimationListener; //import android.view.animation.AnimationUtils; //import android.widget.EditText; //import android.widget.FrameLayout; //import android.widget.ImageButton; //import android.widget.ImageView; //import android.widget.LinearLayout; //import android.widget.RelativeLayout; //import android.widget.TextView; // ///** // * Location class // * activity for locate a device // ** */ // //public class Location extends MapActivity { // static Location mthis =null; // MapView mapa = null; // // double lat = 0; // double lon = 0; // // String comment = ""; // GPSlocalize gps; // // boolean _debug = true; // boolean _menulayout = false; // boolean _cancel = true; //// boolean _msj = false; // // Animation anim; // // AlertDialog nota = null; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // this.requestWindowFeature(Window.FEATURE_NO_TITLE); // mthis = this; // setContentView(R.layout.activity_location); // mapa = (MapView)findViewById(R.id.mapa); // mapa.setBuiltInZoomControls(true); // setButtons(); // GPSlocalize gps = new GPSlocalize(mthis); // if( gps.canGetLocation() ){ // updatePosition( gps.getLocation() ); // msjLocation(); // }else{ // gps.showSettingsAlert(); // } // // } // // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data){ // log("result","request:"+requestCode+" result:"+resultCode+" intent:"+data); // if( requestCode == 11 ){ // GPSlocalize gps = new GPSlocalize(mthis); // if( gps.canGetLocation() ){ // updatePosition(gps.getLocation()); // msjLocation(); // }else{ // gps.showSettingsAlert(); // } // } // } // // public void log(String tag, String msg) { // if( _debug ){ // Log.i(tag, msg); // } // } // // /* // * setButtons // * method for set buttons // * @receive // * @return void // */ // public void setButtons() { // final String url = TaxyMobile.base_url; // final ImageButton ok = (ImageButton)this.findViewById(R.id.imageButton1); // ok.setOnTouchListener(new OnTouchListener(){ // @Override // public boolean onTouch(View arg0, MotionEvent arg1) { // if( arg1.getAction() == MotionEvent.ACTION_DOWN ){ // ok.setImageResource( R.drawable.btn_ok_pressed ); // return true; // }else if( arg1.getAction() == MotionEvent.ACTION_UP ){ //// if( TaxyMobile.getConexion( url ) ){ // SharedPreferences pref = mthis.getPreferences(MODE_PRIVATE); // Editor e = pref.edit(); // e.putBoolean( "_stop", false ); // e.commit(); // log("_stop cambio", "_stop" + pref.getBoolean("_stop: ", true) ); // ok.setImageResource(R.drawable.btn_ok_normal); // if( TaxyMobile.mthis.findViewById(R.id.calltaxi) != null ){ // TaxyMobile.mthis.findViewById(R.id.calltaxi).setEnabled( true ); // Log.i("Paso", TaxyMobile.mthis.findViewById(R.id.calltaxi) + ""); // }else{ // Log.i("Ubiera Crashado", TaxyMobile.mthis.findViewById(R.id.calltaxi) + ""); // } // // Intent output = new Intent(); // output.putExtra( "location", lat + "," + lon ); // output.putExtra( "comment", comment ); // setResult(RESULT_OK, output); //// }else{ //// TaxyMobile.mthis.showAlertDialog("Error de conexin.", "Intenta mas tarde."); //// TaxyMobile.mthis.log("Error de conexin", "Intenta mas tarde"); //// } // mthis.finish(); // return true; // } // return false; // } // }); // // ImageButton back = (ImageButton)mthis.findViewById(R.id.back_button); // back.setOnClickListener(new OnClickListener(){ // @Override // public void onClick(View arg0) { // setResult(RESULT_CANCELED); // //gps.stopUsingGPS();//TODO: desactivate GPS- // TaxyMobile.mthis.findViewById(R.id.calltaxi).setEnabled( true ); // mthis.finish(); // } // // }); // // LinearLayout addcomment = (LinearLayout) mthis.findViewById(R.id.addnote); // addcomment.setOnClickListener(new OnClickListener(){ // @Override // public void onClick(View arg0) { // addComment(); // } // }); // // LinearLayout getUbicacion = (LinearLayout) mthis.findViewById(R.id.ubicacion); // getUbicacion.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // // TODO Auto-generated method stub // GPSlocalize gps = new GPSlocalize(mthis); // if( gps.canGetLocation() ){ // updatePosition( gps.getLocation() ); // msjLocation(); // }else{ // gps.showSettingsAlert(); // } // } // }); // // final ImageView buttonmenu = (ImageView)findViewById(R.id.btn_menu); // final LinearLayout layoutmenu = (LinearLayout)mthis.findViewById(R.id.menulayout); // buttonmenu.setOnClickListener(new OnClickListener(){ // @Override // public void onClick(View arg0) { // menu( layoutmenu, buttonmenu ); // } // }); // } // // /* // * addComment // * method for add comments // * @receive // * @return void // */ // public void addComment(){ // AlertDialog.Builder alertDialog = new AlertDialog.Builder(mthis); // alertDialog.setTitle("Nota"); // LayoutInflater inflater = mthis.getLayoutInflater(); // final View comment = inflater.inflate(R.layout.taxymobile_agregar_nota, null); // alertDialog.setView(comment); // alertDialog.setPositiveButton("Cancelar", new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog,int which) { // dialog.dismiss(); // } // }); // alertDialog.setNegativeButton("Agregar", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // EditText text=(EditText)comment.findViewById(R.id.editText1); // mthis.comment=text.getText().toString(); // } // }); // alertDialog.setCancelable( false ); // alertDialog.show(); // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // final LinearLayout layoutmenu = (LinearLayout)mthis.findViewById(R.id.menulayout); // switch( keyCode ){ // ////KeyBack // case 4: // if( _menulayout ){ // _menulayout = false; // Animation inmenu = AnimationUtils.loadAnimation(mthis, R.layout.animation_menu_out); // layoutmenu.startAnimation(inmenu); // layoutmenu.setVisibility(View.GONE); // }else{ // TaxyMobile.mthis.findViewById(R.id.calltaxi).setEnabled( true ); // mthis.finish(); // } // break; // ////Ajustes // case 82: // menu( layoutmenu, (ImageView)findViewById(R.id.btn_menu) ); // break; // } // return true; // } // // /* // * menu // * method for show the menu // * @receive // * LinearLayout layoutmenu // * @return void // */ // public void menu(final LinearLayout layoutmenu, final ImageView buttonmenu){ // final FrameLayout helptem = (FrameLayout) mthis.findViewById(R.id.helptem); // if( _menulayout ){ // _menulayout = false; // Animation inmenu = AnimationUtils.loadAnimation(mthis, R.layout.animation_menu_out); // inmenu.setAnimationListener(new AnimationListener() { // @Override // public void onAnimationStart(Animation animation) { // buttonmenu.setEnabled( false ); // } // @Override // public void onAnimationRepeat(Animation animation) { // } // @Override // public void onAnimationEnd(Animation animation) { // buttonmenu.setEnabled( true ); // helptem.setVisibility( View.GONE ); // } // }); // layoutmenu.startAnimation(inmenu); // // layoutmenu.setVisibility(View.GONE); // }else{ // _menulayout = true; // layoutmenu.setVisibility(View.VISIBLE); // Animation inmenu = AnimationUtils.loadAnimation(mthis, R.layout.animation_menu_in); // inmenu.setAnimationListener(new AnimationListener() { // @Override // public void onAnimationStart(Animation animation) { // buttonmenu.setEnabled( false ); // } // @Override // public void onAnimationRepeat(Animation animation) { // } // @Override // public void onAnimationEnd(Animation animation) { // buttonmenu.setEnabled( true ); // helptem.setVisibility( View.VISIBLE ); // } // }); // layoutmenu.startAnimation(inmenu); // // LinearLayout help = (LinearLayout) layoutmenu.findViewById(R.id.linear_help); // help.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // startHelp(); // Animation inmenu = AnimationUtils.loadAnimation(mthis, R.layout.animation_menu_out); // layoutmenu.startAnimation(inmenu); // layoutmenu.setVisibility(View.GONE); // helptem.setVisibility( View.GONE ); // _menulayout = false; // } // }); // // LinearLayout delete = (LinearLayout) mthis.findViewById(R.id.linear_deletedata); // delete.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { //// if( TaxyMobile.getConexion( mthis ) ){ // mthis.finish(); // TaxyMobile.mthis.clearApplicationData(); // //// } // // } // }); // // helptem.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // helptem.setVisibility( View.GONE ); // menu(layoutmenu, buttonmenu ); // } // }); // } // // loadfontCity( (TextView) mthis.findViewById(R.id.help) ); // loadfontCity( (TextView) mthis.findViewById(R.id.deletedata) ); // } // // /* // * msjLocation // * method for show the mesagge the GPS // * @receive // * @return void // */ // private void msjLocation(){ // nota = new AlertDialog.Builder(mthis).create(); // nota.setTitle("GPS localizando ubicacin."); // nota.setMessage("Esto puede tomar unos segundos, por favor espera..."); // nota.setButton("Aceptar", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // nota.cancel(); // } // }); // nota.show(); // } // // /* // * startHelp // * method for show help // * @receive // * @return void // */ // public void startHelp(){ // final RelativeLayout help = (RelativeLayout) mthis.findViewById(R.id.help_location); // anim = AnimationUtils.loadAnimation(mthis, R.anim.help_in); // anim.setAnimationListener(new AnimationListener() { // @Override // public void onAnimationStart(Animation animation) { // help.setVisibility(View.VISIBLE); // } // @Override // public void onAnimationRepeat(Animation animation) {} // @Override // public void onAnimationEnd(Animation animation) { // help.setOnTouchListener(new OnTouchListener() { // @Override // public boolean onTouch(View v, MotionEvent event) { // if( event.getAction() == MotionEvent.ACTION_DOWN ){ // return true; // }else if( event.getAction() == MotionEvent.ACTION_UP ){ // anim = AnimationUtils.loadAnimation(mthis, R.anim.help_out); // anim.setFillAfter(true); // anim.setAnimationListener(new AnimationListener() { // // @Override // public void onAnimationStart(Animation animation) {} // // @Override // public void onAnimationRepeat(Animation animation) {} // // @Override // public void onAnimationEnd(Animation animation) { // help.setVisibility( View.GONE ); // help.clearAnimation(); // } // }); // help.startAnimation(anim); // return true; // } // return false; // } // }); // help.clearAnimation(); // } // }); // anim.setFillAfter(true); // help.startAnimation(anim); // } // // public void updatePosition(android.location.Location location){ // if( location != null ){ // lat = location.getLatitude(); // lon = location.getLongitude(); // GeoPoint point = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6)); // OverlayItem overlayitem = new OverlayItem(point, "tittle", "message"); // mapa.getOverlays().clear(); // List<Overlay> mapOverlays = mapa.getOverlays(); // Drawable drawable = this.getResources().getDrawable(R.drawable.icon_location_green); // HelloOverlayItems itemizedoverlay = new HelloOverlayItems(drawable, this); // itemizedoverlay.addOverlay( overlayitem ); // mapOverlays.add( itemizedoverlay ); // mapa.getController().setCenter( point ); // mapa.getController().setZoom( 16 ); // } // } // @Override // protected boolean isRouteDisplayed() { // return false; // } // // /* // * loadfontCity // * method for load a font for aplication // * @receive // * TextView text // * @return void // */ // public void loadfontCity(TextView text){ // Typeface myFont = Typeface.createFromAsset(getAssets(), // "font/myriadpro_regular.otf"); // text.setTypeface(myFont); // } //} // //class HelloOverlayItems extends ItemizedOverlay{ // // private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>(); // Context mContext=null; // // public HelloOverlayItems(Drawable defaultMarker) { // super(boundCenterBottom(defaultMarker)); // } // public HelloOverlayItems(Drawable defaultMarker, Context context) { // super(boundCenterBottom(defaultMarker)); // mContext = context; // } // @Override // protected OverlayItem createItem(int i) { // return mOverlays.get(i); // } // // @Override // public int size() { // return mOverlays.size(); // } // public void addOverlay(OverlayItem overlay) { // mOverlays = new ArrayList<OverlayItem>(); // mOverlays.add(overlay); // populate(); // } // //}
true
79e7981e2597c6aac568258e44a5038e036bde4e
Java
rathoddilip/BooksWagonAndroidMobileAppUsingAppium
/src/main/java/com/appium/utility/ScreenshotTestImage.java
UTF-8
1,392
2.3125
2
[]
no_license
package com.appium.utility; import com.appium.base.BaseClass; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; public class ScreenshotTestImage extends BaseClass { public File sourceFile; String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()); String screenshotFilePath = "/home/arjun/Dilip/BooksWagonAppiumTestingProject/src/main/java/com/appium"; public void failed(String testMethodName) throws IOException { sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(sourceFile, new File(screenshotFilePath + "/testfailed/FAILED" + "_" + testMethodName + timeStamp + ".jpg")); } catch (IOException exception) { exception.printStackTrace(); } } public void success(String testMethodName) { sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(sourceFile, new File(screenshotFilePath + "/testsuccess/SUCCESS" + "_" + testMethodName + timeStamp + ".jpg")); } catch (IOException exception) { exception.printStackTrace(); } } }
true
2c9f45994fa553ad995eee97dfd3ccf649f29e59
Java
eurasia-insurance/oldies-kz-lib
/eelib/src/main/java/tech/lapsa/kz/taxpayer/validators/ValidTaxpayerNumberConstraintValidator.java
UTF-8
1,058
2.453125
2
[]
no_license
package tech.lapsa.kz.taxpayer.validators; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.ValidationException; import tech.lapsa.java.commons.function.MyObjects; import tech.lapsa.kz.taxpayer.TaxpayerNumber; public class ValidTaxpayerNumberConstraintValidator implements ConstraintValidator<ValidTaxpayerNumber, Object> { @Override public void initialize(final ValidTaxpayerNumber constraintAnnotation) { } @Override public boolean isValid(final Object value, final ConstraintValidatorContext cvc) { if (value == null) return true; TaxpayerNumber check; if (MyObjects.isA(value, String.class)) check = TaxpayerNumber.assertValid(MyObjects.requireA(value, String.class)); else if (MyObjects.isA(value, TaxpayerNumber.class)) check = MyObjects.requireA(value, TaxpayerNumber.class); else throw new ValidationException("Unknown type " + value.getClass()); if (TaxpayerNumber.nonValid(check)) return false; return true; } }
true
617f52bffb7f396747bffe07d91ec7a5b17367ea
Java
JavaFan1996/Java2
/Bank/src/banking/Bank.java
UTF-8
1,259
3.234375
3
[]
no_license
package banking; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * �������ж��� * * @author Think Pad */ public class Bank { private List<Customer> customers; private Bank() { customers = new ArrayList<>(); } private static Bank instance = new Bank(); public static Bank getBank() { return instance; } /** * @param firstName * @param lastName */ public void addCustomer(String firstName, String lastName) { Customer customer = new Customer(firstName, lastName); customers.add(customer); } /** * ���� ��ʾ customers �������ж��ٸ������� Customer ��������� * * @return */ public int getNumOfCustomers() { return customers.size(); } /** * ����ָ��������Ӧ�� Customer ���� * * @param index * @return */ public Customer getCustomer(int index) { return customers.get(index); } /** * * @return 获取cus list的迭代器 */ public Iterator<Customer> getCustomers(){ return customers.iterator(); } }
true
f91d45e70685f40d7bb791bc53f620cd1c0070ee
Java
anderfernandes/ProgrammingForTeens2017
/src/LeapYear/LeapYear.java
UTF-8
599
3.359375
3
[]
no_license
package LeapYear; import javax.swing.*; /** * Created by instructor on 7/12/2017. */ public class LeapYear { public static void main(String args[]){ String input = JOptionPane.showInputDialog(null, "Enter a year:"); int year = Integer.parseInt(input); if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) { JOptionPane.showMessageDialog(null, year + " is a leap year."); } else { JOptionPane.showMessageDialog(null, year + " is not a leap year."); } } }
true
230730a09bc46e19219ed9042690f268a3db3e44
Java
stachu540/HiRezAPI
/realm/src/main/java/hirez/realm/object/Talent.java
UTF-8
624
1.804688
2
[ "MIT" ]
permissive
package hirez.realm.object; import com.fasterxml.jackson.annotation.JsonProperty; import hirez.api.object.interfaces.ReturnedMessage; import lombok.Data; /** * @deprecated This endpoint is not exist */ @Data @Deprecated public class Talent implements ReturnedMessage { private final String categoryName; @JsonProperty("item_id") private final long id; private final long lootTableItemId; @JsonProperty("ret_msg") private final String returnedMessage; @JsonProperty("talent_description") private final String description; @JsonProperty("talent_name") private final String name; }
true
e4896af1fb10ebc8465d7e2c1967a8a04b0b00b3
Java
MichaelAntropov/medical-education
/src/main/java/me/hizencode/mededu/course/content/user/test/CourseUserTestEntity.java
UTF-8
1,729
2.1875
2
[ "MIT" ]
permissive
package me.hizencode.mededu.course.content.user.test; import javax.persistence.*; @Entity @IdClass(CourseUserTestId.class) @Table(name = "course_user_test") public class CourseUserTestEntity { @Id @Column(name = "user_id") private int userId; @Id @Column(name = "test_id") private int testId; @Column(name = "course_id") private int courseId; @Column(name = "completed") private int completed; @Column(name = "score") private int score; public CourseUserTestEntity() { } public CourseUserTestEntity(int userId, int testId, int courseId) { this.userId = userId; this.testId = testId; this.courseId = courseId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getTestId() { return testId; } public void setTestId(int testId) { this.testId = testId; } public int getCourseId() { return courseId; } public void setCourseId(int courseId) { this.courseId = courseId; } public int getCompleted() { return completed; } public void setCompleted(int completed) { this.completed = completed; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } @Override public String toString() { return "CourseUserTestEntity{" + "userId=" + userId + ", testId=" + testId + ", courseId=" + courseId + ", completed=" + completed + ", score=" + score + '}'; } }
true
8ab5031e80315c449ffa631a935c25d32afd9bf8
Java
MaxTran03/SRCS
/src/TME6/Server.java
UTF-8
1,205
2.234375
2
[]
no_license
package TME6; import java.util.Properties; import org.omg.CORBA.ORB; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContext; import org.omg.CosNaming.NamingContextHelper; import org.omg.PortableServer.POA; import org.omg.PortableServer.POAHelper; import TME6.cache.FileSystemPOA; public class Server { public static void main(String args[]) throws Exception { Properties props = new Properties(); props.put("org.omg.CORBA.ORBInitialPort", "1050"); props.put("org.omg.CORBA.ORBInitialHost", "localhost"); ORB orb = ORB.init(args, props); // Récupération RootPOA, conversions et activation org.omg.CORBA.Object rootobj = orb.resolve_initial_references("RootPOA"); POA poa = POAHelper.narrow(rootobj); poa.the_POAManager().activate(); org.omg.CORBA.Object ncobj = orb.resolve_initial_references("NameService"); NamingContext nc = NamingContextHelper.narrow(ncobj); FileSystemPOA servant = new FileSystemImpl(); org.omg.CORBA.Object obj = poa.servant_to_reference(servant); NameComponent[] names = new NameComponent[] { new NameComponent("Bob", "") }; nc.rebind(names, obj); // Traitement des requetes de clients orb.run(); } }
true
90b800cc9548c5c9024607f484d00516ddbad9f8
Java
ophielia/bank
/src/main/java/meg/bank/bus/repo/QuickGroupDetailRepository.java
UTF-8
748
1.953125
2
[]
no_license
package meg.bank.bus.repo; import java.util.List; import meg.bank.bus.dao.QuickGroup; import meg.bank.bus.dao.QuickGroupDetail; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface QuickGroupDetailRepository extends JpaRepository<QuickGroupDetail, Long>, JpaSpecificationExecutor<QuickGroupDetail> { @Query("select b from QuickGroupDetail b where b.quickgroup=:quickgroup") List<QuickGroupDetail> findByQuickGroup( @Param("quickgroup") QuickGroup quickgroup); }
true
3c9eca5e757c12e641d7f04e6bdb9cdabab029ab
Java
thedrycake/Legacy
/TempInCity/src/com/thedrycake/tempincity/persistence/DatabaseHelper.java
UTF-8
4,139
2.15625
2
[]
no_license
/* * Copyright (C) 2013 The Drycake Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thedrycake.tempincity.persistence; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.thedrycake.tempincity.provider.AppContract.TemperatureEntity; public final class DatabaseHelper extends SQLiteOpenHelper { public interface Tables { String TEMPERATURE = "temperature"; } private static final String DATABASE_NAME = "tempincity.db"; private static final int DATABASE_VERSION = 4; private static final String LOG_TAG = DatabaseHelper.class.getSimpleName(); private static DatabaseHelper sInstance = null; public static synchronized DatabaseHelper getInstance(Context context) { if (sInstance == null) { sInstance = new DatabaseHelper(context.getApplicationContext()); } return sInstance; } private DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.TEMPERATURE + " (" + TemperatureEntity.Columns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TemperatureEntity.Columns.CITY_NAME + " TEXT NOT NULL, " + TemperatureEntity.Columns.COUNTRY_CODE + " TEXT NOT NULL, " + TemperatureEntity.Columns.IMPL_TYPE + " TEXT NOT NULL, " + TemperatureEntity.Columns.IMPL_TYPE_ARGS + " TEXT, " + TemperatureEntity.Columns.TEMP + " REAL NOT NULL, " + TemperatureEntity.Columns.TEMP_DATE + " INTEGER NOT NULL, " + TemperatureEntity.Columns.CREATE_DATE + " INTEGER NOT NULL, " + TemperatureEntity.Columns.MODIFICATION_DATE + " INTEGER NOT NULL)"); db.execSQL(createIndexSql(Tables.TEMPERATURE, TemperatureEntity.Columns.CITY_NAME)); db.execSQL(createIndexSql(Tables.TEMPERATURE, TemperatureEntity.Columns.COUNTRY_CODE)); db.execSQL(createUniqueIndexSql(Tables.TEMPERATURE, TemperatureEntity.Columns.CITY_NAME, TemperatureEntity.Columns.COUNTRY_CODE)); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(LOG_TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + "city"); db.execSQL("DROP TABLE IF EXISTS " + Tables.TEMPERATURE); onCreate(db); } private static String createIndexSql(String tableName, String... columnNames) { return createIndexSql(false, tableName, columnNames); } private static String createUniqueIndexSql(String tableName, String... columnNames) { return createIndexSql(true, tableName, columnNames); } private static String createIndexSql(boolean unique, String tableName, String... columnNames) { String indexName = createIndexName(tableName, columnNames); StringBuilder sb = new StringBuilder(); sb.append("CREATE "); if (unique) { sb.append("UNIQUE "); } sb.append("INDEX "); sb.append("IF NOT EXISTS "); sb.append(indexName); sb.append(" ON "); sb.append(tableName); sb.append(" ("); for (int i = 0; i < columnNames.length; i++) { if (i > 0) { sb.append(", "); } sb.append(columnNames[i]); } sb.append(")"); return sb.toString(); } private static String createIndexName(String tableName, String... columnNames) { StringBuilder sb = new StringBuilder(); sb.append(tableName); sb.append("_"); for (String columnName : columnNames) { sb.append(columnName); sb.append("_"); } sb.append("idx"); return sb.toString(); } }
true
ce723d665ef0be3a91e267e13821d4bb8c998532
Java
GregGreenfield/Register
/Register/src/register/StudentDisplay.java
UTF-8
9,757
2.390625
2
[]
no_license
package register; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import register.Program.State; import javax.swing.SpringLayout; import javax.swing.JList; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Color; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JMenuBar; import java.awt.Font; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; public class StudentDisplay extends JFrame { private JPanel contentPane; private JList list, list_1, list_2; private DefaultListModel here = new DefaultListModel(); private DefaultListModel absent = new DefaultListModel(); private DefaultListModel more = new DefaultListModel(); private JTextField filename = new JTextField(), dir = new JTextField(); public StudentDisplay() { setTitle("Students"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 401, 516); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); JMenuItem mntmLogout = new JMenuItem("Logout"); mntmLogout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Program.changeState(State.Logout); } }); JMenuItem SaveMenu = new JMenuItem("Save"); SaveMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser c = new JFileChooser(); int rVal = c.showSaveDialog(null); if (rVal == JFileChooser.APPROVE_OPTION) { filename.setText(c.getSelectedFile().getName()); dir.setText(c.getCurrentDirectory().toString()); Program.saveFile(filename.getText(), dir.getText()); } if (rVal == JFileChooser.CANCEL_OPTION) { filename.setText("You pressed cancel"); dir.setText(""); } } }); mnFile.add(SaveMenu); mnFile.add(mntmLogout); JMenu mnHelp = new JMenu("Help"); menuBar.add(mnHelp); JMenuItem mntmInstruction = new JMenuItem("Instruction"); mntmInstruction.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFrame parent = new JFrame(); JOptionPane.showMessageDialog(parent, "Follow button prompts!!!"); } }); mnHelp.add(mntmInstruction); contentPane = new JPanel(); contentPane.setBackground(new Color(173, 216, 230)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); SpringLayout sl_contentPane = new SpringLayout(); contentPane.setLayout(sl_contentPane); JButton AbsentBtn = new JButton("Change to absent"); sl_contentPane.putConstraint(SpringLayout.WEST, AbsentBtn, 36, SpringLayout.WEST, contentPane); AbsentBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String selected = ""; try{ selected = list.getSelectedValue().toString(); }catch(Exception e){ System.out.println("Nothing selected!"); } if(!selected.isEmpty()) { absent.addElement(list.getSelectedValue()); here.remove(list.getSelectedIndex()); Program.changeStudentState(selected); } } }); contentPane.add(AbsentBtn); JButton AttendBtn = new JButton("Change to attened"); sl_contentPane.putConstraint(SpringLayout.NORTH, AttendBtn, 0, SpringLayout.NORTH, AbsentBtn); sl_contentPane.putConstraint(SpringLayout.EAST, AttendBtn, -42, SpringLayout.EAST, contentPane); AttendBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String selected = ""; try{ selected = list_1.getSelectedValue().toString(); }catch(Exception e){ System.out.println("Nothing selected!"); } if(!selected.isEmpty()) { here.addElement(list_1.getSelectedValue()); absent.remove(list_1.getSelectedIndex()); Program.changeStudentState(selected); } } }); contentPane.add(AttendBtn); JButton EnrolAndHere = new JButton("Add to enrolled & here"); sl_contentPane.putConstraint(SpringLayout.WEST, EnrolAndHere, 114, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, EnrolAndHere, -10, SpringLayout.SOUTH, contentPane); EnrolAndHere.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String selected = ""; try{ selected = list_2.getSelectedValue().toString(); }catch(Exception e){ System.out.println("Nothing selected!"); } if(!selected.isEmpty()) { here.addElement(list_2.getSelectedValue()); more.remove(list_2.getSelectedIndex()); Program.enrolStudent(selected); } } }); contentPane.add(EnrolAndHere); JLabel lblScannedIn = new JLabel("Scanned in"); sl_contentPane.putConstraint(SpringLayout.WEST, lblScannedIn, 55, SpringLayout.WEST, contentPane); lblScannedIn.setFont(new Font("Comic Sans MS", Font.PLAIN, 16)); contentPane.add(lblScannedIn); JLabel lblAbsent = new JLabel("Absent"); sl_contentPane.putConstraint(SpringLayout.NORTH, lblScannedIn, 0, SpringLayout.NORTH, lblAbsent); sl_contentPane.putConstraint(SpringLayout.EAST, lblAbsent, -87, SpringLayout.EAST, contentPane); lblAbsent.setFont(new Font("Comic Sans MS", Font.PLAIN, 16)); contentPane.add(lblAbsent); JLabel lblScannedInAnd = new JLabel("Scanned in and not enrolled"); sl_contentPane.putConstraint(SpringLayout.SOUTH, AbsentBtn, -17, SpringLayout.NORTH, lblScannedInAnd); sl_contentPane.putConstraint(SpringLayout.WEST, lblScannedInAnd, 80, SpringLayout.WEST, contentPane); lblScannedInAnd.setFont(new Font("Comic Sans MS", Font.PLAIN, 16)); contentPane.add(lblScannedInAnd); JScrollPane scrollPane = new JScrollPane(); sl_contentPane.putConstraint(SpringLayout.NORTH, scrollPane, 72, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, scrollPane, 21, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, scrollPane, -6, SpringLayout.NORTH, AbsentBtn); contentPane.add(scrollPane); list = new JList(here); list.setFont(new Font("Calibri", Font.PLAIN, 11)); list.setBackground(new Color(224, 255, 255)); scrollPane.setViewportView(list); sl_contentPane.putConstraint(SpringLayout.WEST, list, 165, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, list, -31, SpringLayout.NORTH, AbsentBtn); JScrollPane scrollPane_1 = new JScrollPane(); sl_contentPane.putConstraint(SpringLayout.EAST, scrollPane, -39, SpringLayout.WEST, scrollPane_1); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblAbsent, -17, SpringLayout.NORTH, scrollPane_1); sl_contentPane.putConstraint(SpringLayout.NORTH, scrollPane_1, 0, SpringLayout.NORTH, scrollPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, scrollPane_1, -6, SpringLayout.NORTH, AttendBtn); sl_contentPane.putConstraint(SpringLayout.WEST, scrollPane_1, 201, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, scrollPane_1, 0, SpringLayout.EAST, AttendBtn); contentPane.add(scrollPane_1); list_1 = new JList(absent); list_1.setFont(new Font("Calibri", Font.PLAIN, 11)); list_1.setBackground(new Color(224, 255, 255)); scrollPane_1.setViewportView(list_1); sl_contentPane.putConstraint(SpringLayout.WEST, list_1, 278, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, list_1, 0, SpringLayout.EAST, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, list_1, -31, SpringLayout.NORTH, AttendBtn); sl_contentPane.putConstraint(SpringLayout.NORTH, list_1, 17, SpringLayout.SOUTH, lblAbsent); sl_contentPane.putConstraint(SpringLayout.NORTH, list, 0, SpringLayout.NORTH, list_1); sl_contentPane.putConstraint(SpringLayout.EAST, list, -6, SpringLayout.WEST, list_1); JScrollPane scrollPane_2 = new JScrollPane(); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblScannedInAnd, -6, SpringLayout.NORTH, scrollPane_2); sl_contentPane.putConstraint(SpringLayout.WEST, scrollPane_2, 40, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, scrollPane_2, -57, SpringLayout.EAST, contentPane); sl_contentPane.putConstraint(SpringLayout.NORTH, scrollPane_2, 332, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, scrollPane_2, -6, SpringLayout.NORTH, EnrolAndHere); contentPane.add(scrollPane_2); list_2 = new JList(more); list_2.setFont(new Font("Calibri", Font.PLAIN, 11)); list_2.setBackground(new Color(224, 255, 255)); scrollPane_2.setViewportView(list_2); sl_contentPane.putConstraint(SpringLayout.NORTH, list_2, 349, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, list_2, 58, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, list_2, -69, SpringLayout.SOUTH, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, list_2, -44, SpringLayout.EAST, contentPane); } public void addToList(List ls){ for(int i = 0; i < ls.size(); i++){ if(((Student) ls.get(i)).isAttend()) here.addElement(((Student) ls.get(i)).getStudentID() + " " +((Student) ls.get(i)).getName()); else if (((Student) ls.get(i)).isEnrolled()) absent.addElement(((Student) ls.get(i)).getStudentID() + " " +((Student) ls.get(i)).getName()); else more.addElement(((Student) ls.get(i)).getStudentID() + " " +((Student) ls.get(i)).getName()); } } }
true
b79786bfe71bcc9b5c39382d2a2bcbdce6ae55e8
Java
nandantumu/tomighty
/tomighty-swing/src/main/java/org/tomighty/plugin/impl/DefaultPluginLoader.java
UTF-8
3,956
2.03125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2010-2012 Célio Cidral Junior, Dominik Obermaier. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tomighty.plugin.impl; import com.google.inject.Injector; import com.google.inject.Module; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tomighty.plugin.Plugin; import org.tomighty.plugin.PluginLoader; import org.tomighty.plugin.PluginPack; import org.tomighty.util.PluginPropertiesReader; import javax.inject.Inject; import java.net.URL; import java.net.URLClassLoader; public class DefaultPluginLoader implements PluginLoader { @Inject private Injector injector; @Inject private PluginPropertiesReader pluginPropertiesReader; private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public Plugin load(PluginPack pluginPack) { logger.info("Loading plugin {}", pluginPack); URLClassLoader classLoader = createClassLoader(pluginPack); Class<? extends Plugin> pluginClass = loadPluginClass(classLoader); Injector pluginInjector = createPluginInjector(classLoader); return pluginInjector.getInstance(pluginClass); } private Injector createPluginInjector(final URLClassLoader classLoader) { Class<? extends Module> guiceModule = getGuiceModule(classLoader); try { return injector.createChildInjector(guiceModule.newInstance()); } catch (InstantiationException e) { logger.error("Could not instantiate {}", guiceModule.getName()); } catch (IllegalAccessException e) { logger.error("Could not instantiate {}", guiceModule.getName()); } //If we cannot return a child injector, just use the standard parent injector for the plugin return injector; } private URLClassLoader createClassLoader(PluginPack pluginPack) { URL[] jars = pluginPack.jars(); for (URL jar : jars) logger.info("Loading jar {}", jar); return new URLClassLoader(jars); } private Class<? extends Plugin> loadPluginClass(ClassLoader classLoader) { String pluginClassName = pluginPropertiesReader.getPluginClassName(classLoader); logger.info("Loading plugin class {}", pluginClassName); try { return (Class<? extends Plugin>) classLoader.loadClass(pluginClassName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private Class<? extends Module> getGuiceModule(ClassLoader classLoader) { String guiceModuleClassName = pluginPropertiesReader.getGuiceModuleClassName(classLoader); if (guiceModuleClassName != null) { try { return (Class<? extends Module>) classLoader.loadClass(guiceModuleClassName); } catch (ClassNotFoundException e) { logger.warn("Binding Module Class {} class is not found.!", guiceModuleClassName); } catch (ClassCastException cce) { logger.warn("Binding Module {} class is not a Guice Module!", guiceModuleClassName); logger.debug("Actual Exception:", cce); } } else { logger.warn("No Guice Binding Module defined in the tomighty-plugin.properties file."); } logger.info("Using default Guice Binding Module for the plugin"); return DefaultModule.class; } }
true
cda561d30a100f1365c66f539f6cc379913c3d86
Java
yyj1204/junchenlun
/emperor/src/main/java/com/wktx/www/emperor/ui/view/staff/IStaffRenewalView.java
UTF-8
451
1.804688
2
[]
no_license
package com.wktx.www.emperor.ui.view.staff; import com.wktx.www.emperor.apiresult.recruit.hire.HireInfoData; import com.wktx.www.emperor.ui.view.IView; /** * Created by yyj on 2018/1/26. * 管理我的员工---续签界面 */ public interface IStaffRenewalView extends IView<HireInfoData> { /** * 获取续签时间 */ String getRenewalTime(); /** * 获取输入的提成方案 */ String getPushMoney(); }
true
1cb6811b85d151e974813be427fbbe870771e074
Java
SlaynAndKorpil/Chess
/framework/src/framework/javaInterfacing/Reactions/ShowPromotionReaction.java
UTF-8
452
2.359375
2
[ "MIT" ]
permissive
package framework.javaInterfacing.Reactions; import framework.IOEvents.IOEvent; import framework.IOEvents.ShowPromotion; import java.util.function.Consumer; public class ShowPromotionReaction extends JReaction<ShowPromotion> { public boolean isDefinedAt(IOEvent event) { return event.getClass() == ShowPromotion.class; } public ShowPromotionReaction(Consumer<ShowPromotion> reaction) { this.reaction = reaction; } }
true