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
20aa309a46b9b0a2c8b7d45530920fed9bb64bd2
Java
visonforcoding/wonfu-spring-boot-starter
/src/main/java/com/vison/wonfu/spring/boot/starter/config/Log.java
UTF-8
2,517
2.765625
3
[]
no_license
package com.vison.wonfu.spring.boot.starter.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author visonforcoding <visonforcoding@gmail.com> */ public class Log { private static String msgTraceNo; public static void setMsgTraceNo(String msgTraceNo) { Log.msgTraceNo = msgTraceNo; } public static StackTraceElement findCaller() { // 获取堆栈信息 StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); if (null == callStack) { return null; } // 最原始被调用的堆栈信息 StackTraceElement caller = null; // 日志类名称 String logClassName = Log.class.getName(); // 循环遍历到日志类标识 boolean isEachLogClass = false; // 遍历堆栈信息,获取出最原始被调用的方法信息 for (StackTraceElement s : callStack) { // 遍历到日志类 if (logClassName.equals(s.getClassName())) { isEachLogClass = true; } // 下一个非日志类的堆栈,就是最原始被调用的方法 if (isEachLogClass) { if (!logClassName.equals(s.getClassName())) { isEachLogClass = false; caller = s; break; } } } return caller; } private static Logger logger() { // 最原始被调用的堆栈对象 StackTraceElement caller = findCaller(); if (null == caller) { return LoggerFactory.getLogger(Log.class); } String callInfo = caller.getClassName() + "." + caller.getMethodName() + ":" + caller.getLineNumber(); Logger log = LoggerFactory.getLogger(callInfo); return log; } public static void debug(String msg, Object o) { logger().debug(String.format("%s %s", msg, o.toString())); } public static void debug(String msg) { logger().debug(String.format("%s", msg)); } public static void error(String msg, Object o) { logger().error(String.format("%s %s", msg, o.toString())); } public static void error(String msg) { logger().error(String.format("%s", msg)); } public static void info(String msg, Object o) { logger().info(String.format("%s %s", msg, o.toString())); } public static void info(String msg) { logger().info(String.format("%s", msg)); } }
true
f611cfda11237d71341e7c29ae93575a418f70dd
Java
VBurachenko/hotel-munich
/src/main/java/by/training/hotel/controller/command/impl/admin/CreationRoomFormOpenCommand.java
UTF-8
480
1.710938
2
[]
no_license
package by.training.hotel.controller.command.impl.admin; import by.training.hotel.controller.command.Command; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CreationRoomFormOpenCommand implements Command { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { } }
true
73724488fdbcf33b77db4fe0d12ce420be1c8302
Java
estet90/e-journal
/error-lib/src/main/java/ru/salix/ejournal/error/operation/OperationCode.java
UTF-8
130
1.703125
2
[]
no_license
package ru.salix.ejournal.error.operation; public interface OperationCode { String OTHER = "999"; String getCode(); }
true
c362741cb2becfb24b58c4190e39807f2d8e2977
Java
jorgeacf/libraries-java-examples
/finance/src/main/java/com/jorgefigueiredo/finance/data/parsers/TickerDataParser.java
UTF-8
881
2.84375
3
[]
no_license
package com.jorgefigueiredo.finance.data.parsers; import com.jorgefigueiredo.finance.data.entities.TickerData; public class TickerDataParser implements ITickerDataParser { private final String delimiter = ","; public TickerData parse(String input) { String[] inputSegments = input.split(delimiter); TickerData tickerData = null; try { String timestamp = inputSegments[0]; Double close = Double.parseDouble(inputSegments[1]); Double high = Double.parseDouble(inputSegments[2]); Double low = Double.parseDouble(inputSegments[3]); Double open = Double.parseDouble(inputSegments[4]); Integer volume = Integer.parseInt(inputSegments[5]); tickerData = new TickerData( timestamp, close, high, low, open, volume); } catch(Exception ex) { // Add log //throw ex; } return tickerData; } }
true
4867193b2f2b99e94bbf532c0b1a8b5ff2cfb4cf
Java
nik-lazer/java-learn
/training/advanced/src/main/java/lan/training/advanced/servlet/FormServlet.java
UTF-8
1,328
2.40625
2
[]
no_license
package lan.training.advanced.servlet; import lan.training.advanced.jetty.PageGenerator; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.logging.Logger; /** * getting form data in servlet * @author nik-lazer 26.12.2014 12:52 */ public class FormServlet extends HttpServlet { private static Logger log = Logger.getLogger(FormServlet.class.getName()); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(PageGenerator.createRefreshingFormPage(null)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getParameter("id"); response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); Integer id = PageGenerator.getId(param); if (id == null ) { id = PageGenerator.generateId(); log.info("Id for form generated ="+id); } response.getWriter().println(PageGenerator.createRefreshingFormPage(id)); } }
true
dcd70397c48aac1b094706762ab992aa45ca0813
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_da9ae53035fd3380260822723bb4763ebe3b50da/RecentSituationComparator/2_da9ae53035fd3380260822723bb4763ebe3b50da_RecentSituationComparator_t.java
UTF-8
1,299
2.34375
2
[]
no_license
package org.onebusaway.presentation.impl.service_alerts; import java.util.Comparator; import org.onebusaway.collections.CollectionsLibrary; import org.onebusaway.transit_data.model.service_alerts.SituationBean; import org.onebusaway.transit_data.model.service_alerts.SituationConsequenceBean; import org.onebusaway.transit_data.model.service_alerts.TimeRangeBean; public class RecentSituationComparator implements Comparator<SituationBean> { @Override public int compare(SituationBean o1, SituationBean o2) { long t1 = getTimeForSituation(o1); long t2 = getTimeForSituation(o2); return Double.compare(t1, t2); } private long getTimeForSituation(SituationBean bean) { TimeRangeBean window = bean.getPublicationWindow(); if (window != null && window.getFrom() != 0) return window.getFrom(); if (! CollectionsLibrary.isEmpty(bean.getConsequences())) { long t = Long.MAX_VALUE; for (SituationConsequenceBean consequence : bean.getConsequences()) { TimeRangeBean period = consequence.getPeriod(); if (period != null && period.getFrom() != 0) t = Math.min(t, period.getFrom()); } if (t != Long.MAX_VALUE) return t; } return bean.getCreationTime(); } }
true
d3578293f840b3298fa18d4afb95959a09830005
Java
IlahiniReddy/Data_Structures
/MiniGoogle/src/searchengine/spider/BreadthFirstSpider.java
UTF-8
2,659
2.953125
3
[]
no_license
/** * * Copyright: Copyright (c) 2004 Carnegie Mellon University * * This program is part of an implementation for the PARKR project which is * about developing a search engine using efficient Datastructures. * * Modified by Mahender on 12-10-2009 */ package searchengine.spider; import java.io.IOException; import java.net.*; import java.util.LinkedList; import java.util.Queue; import java.util.Vector; import searchengine.dictionary.ObjectIterator; import searchengine.element.PageElementInterface; import searchengine.element.PageHref; import searchengine.element.PageWord; import searchengine.indexer.Indexer; import searchengine.parser.PageLexer; import searchengine.url.URLFixer; import searchengine.url.URLTextReader; /** Web-crawling objects. Instances of this class will crawl a given * web site in breadth-first order. */ public class BreadthFirstSpider implements SpiderInterface { /** Create a new web spider. @param u The URL of the web site to crawl. @param i The initial web index object to extend. */ private Indexer i = null; private URL u; public BreadthFirstSpider (URL u, Indexer i) { this.u = u; this.i = i; } /** Crawl the web, up to a certain number of web pages. @param limit The maximum number of pages to crawl. */ @SuppressWarnings({ "rawtypes", "unused", "unchecked" }) public Indexer crawl (int limit) throws Exception { Queue<String> q = new LinkedList<String>(); q.add(u.toString()); int k = 0; while(!q.isEmpty() && k < limit) { k++; URLTextReader in = new URLTextReader(u); Vector<String> v = new Vector<String>(); PageLexer<PageElementInterface> elts = null; elts = new PageLexer<PageElementInterface>(in, u); int count = 0; while(elts.hasNext()) { count++; PageElementInterface elt = (PageElementInterface)elts.next(); if (elt instanceof PageWord) { v.addElement(elt.toString()); System.out.println("word: "+elt); } else if (elt instanceof PageHref) { q.add(elt.toString()); System.out.println("link: "+elt); } } i.addPage(u, new ObjectIterator(v)); String str = q.poll(); URL u1 = u; URLFixer urlf = new URLFixer(); u= urlf.fix(u1,str); //System.out.println(u); } return i; } /** Crawl the web, up to the default number of web pages. */ public Indexer crawl() throws Exception{ // This redirection may effect performance, but its OK !! System.out.println("Crawling: "+u.toString()); return crawl(crawlLimitDefault); } /** The maximum number of pages to crawl. */ public int crawlLimitDefault = 10; }
true
ce04eed12b88c343e214b4aa3002a60cca430919
Java
itcastphp/StudentManager
/StudentManage/src/com/qfedu/servlet/DeleteStudentBySid.java
UTF-8
1,398
2.390625
2
[]
no_license
package com.qfedu.servlet; import java.io.IOException; import java.sql.Connection; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qfedu.daoImp.StudentDaoImpl; import com.qfedu.serviceImp.FindStudentImp; import com.qfedu.serviceImp.RemoveStudentImp; import com.qfedu.util.Init; import com.qfedu.util.MySqlUtil; @WebServlet("/deleteStudentBySid") public class DeleteStudentBySid extends HttpServlet{ public void init(RemoveStudentImp removeStudentImp ) { Connection connection = MySqlUtil.getConnection(); StudentDaoImpl studentDaoImpl = new StudentDaoImpl(); studentDaoImpl.setConnection(connection); removeStudentImp.setStudentDao(studentDaoImpl); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RemoveStudentImp removeStudentImp = new RemoveStudentImp(); init(removeStudentImp); String queryString = req.getQueryString(); String sid=queryString.split("=")[1]; removeStudentImp.removeStudentBySid(sid); req.getRequestDispatcher("/index.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
true
202309beee38f4812f935669cf40226c5ca46f78
Java
andmy2002/zeus
/lcarus/src/main/java/cn/lcarus/admin/res/EcpmListVo.java
UTF-8
1,071
1.960938
2
[]
no_license
package cn.lcarus.admin.res; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.experimental.Accessors; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * @author xincheng * @date 2019-10-24 */ @Data @Accessors(chain = true) @ApiModel(value = "ecpm列表查询vo", description = "响应") public class EcpmListVo implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "主键id") private Long id; @ApiModelProperty(value = "触发日期 日期格式 yyyy-MM-dd") private String triggerDay; @ApiModelProperty(value = "状态{0:'待生效',1:'已生效'}") private Integer state; @ApiModelProperty(value = "ecpm值") private BigDecimal ecpm; @ApiModelProperty(value = "版本号") private Integer version; @ApiModelProperty(value = "创建时间") private Date createTime; @ApiModelProperty(value = "更新时间") private Date updateTime; }
true
904e2446f7923051a5b7542170e05effa972d664
Java
cj19990510/TravelCompanion
/src/cn/com/zx/travelcompanion/servlet/SelectUserInfoServlet.java
UTF-8
2,380
2.328125
2
[]
no_license
package cn.com.zx.travelcompanion.servlet; import java.io.IOException; import java.io.Writer; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.com.zx.travelcompanion.bean.UserInfoBean; import cn.com.zx.travelcompanion.dao.UserInfoDao; /** * 获取用户信息dai */ @WebServlet("/SelectUserInfoServlet") public class SelectUserInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SelectUserInfoServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Content-type", "text/html;;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); int userid=((UserInfoBean)request.getSession().getAttribute("userinfo")).getUserId(); String userName=((UserInfoBean)request.getSession().getAttribute("userinfo")).getUserName(); String userPassword=((UserInfoBean)request.getSession().getAttribute("userinfo")).getUserPassword(); UserInfoBean userinfobean=new UserInfoBean(); System.out.println("userid+"+userid+"userName+"+userName+"+userPassword"+userPassword); UserInfoDao userinfo=new UserInfoDao(); userinfobean=userinfo.getUserInfoByuserid(userid,userName,userPassword); System.out.println(userinfobean.toString()); if(userinfobean!=null){ HttpSession session=request.getSession(); session.setAttribute("userinfo", userinfobean); request.getRequestDispatcher("userinfo.html").forward(request,response); }else{ request.setAttribute("msg", "您还没有登录,请登录!"); request.getRequestDispatcher("userlogin.html").forward(request,response); } } }
true
8459bebc4acdf516642d9ff8fe3d3b6ade18c9ea
Java
rchmnsyh/tubes_pbo_tikepi
/src/View/PetugasJFrame.java
UTF-8
11,237
2.125
2
[ "MIT" ]
permissive
/* * 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 View; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import javax.swing.table.DefaultTableModel; /** * * @author ahmad */ public class PetugasJFrame extends javax.swing.JFrame { /** * Creates new form PetugasJFrame */ public PetugasJFrame() { initComponents(); CenteredFrame(this); } public void CenteredFrame(javax.swing.JFrame objFrame){ Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize(); int iCoordX = (objDimension.width - objFrame.getWidth()) / 2; int iCoordY = (objDimension.height - objFrame.getHeight()) / 2; objFrame.setLocation(iCoordX, iCoordY); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tbTiket = new javax.swing.JTable(); jLabel5 = new javax.swing.JLabel(); kodeTiket = new javax.swing.JFormattedTextField(); jLabel10 = new javax.swing.JLabel(); btVerifikasi = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(55, 65, 74)); jPanel2.setBackground(new java.awt.Color(31, 36, 42)); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Adobe Fan Heiti Std B", 0, 65)); // NOI18N jLabel1.setForeground(new java.awt.Color(96, 187, 34)); jLabel1.setText("Tikepi."); jLabel2.setFont(new java.awt.Font("Adobe Fan Heiti Std B", 0, 10)); // NOI18N jLabel2.setForeground(new java.awt.Color(96, 187, 34)); jLabel2.setText("Kalau bukan sekarang, kapan lagi?"); jLabel3.setFont(new java.awt.Font("Adobe Fan Heiti Std B", 0, 24)); // NOI18N jLabel3.setForeground(new java.awt.Color(96, 187, 34)); jLabel3.setText("Pesan Tiket Kereta Api"); jLabel4.setFont(new java.awt.Font("Adobe Fan Heiti Std B", 0, 10)); // NOI18N jLabel4.setForeground(new java.awt.Color(96, 187, 34)); jLabel4.setText("Kalau bukan tikepi, apa lagi?"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addComponent(jLabel1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); tbTiket.setAutoCreateRowSorter(true); tbTiket.setBackground(new java.awt.Color(55, 65, 74)); tbTiket.setForeground(new java.awt.Color(31, 36, 42)); tbTiket.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Kode ", "Nama Kereta", "Jam Berangkat", "Jam Tiba" } )); tbTiket.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbTiketMouseClicked(evt); } }); jScrollPane1.setViewportView(tbTiket); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel5.setForeground(new java.awt.Color(59, 107, 156)); jLabel5.setText("Verifikasi Tiket Penumpang"); kodeTiket.setEditable(false); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(59, 107, 156)); jLabel10.setText("Kode Tiket"); btVerifikasi.setText("Verifikasi"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 688, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(kodeTiket, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btVerifikasi))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(kodeTiket, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btVerifikasi)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tbTiketMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbTiketMouseClicked int row = tbTiket.getSelectedRow(); String value = tbTiket.getModel().getValueAt(row, 0).toString(); kodeTiket.setText(value); }//GEN-LAST:event_tbTiketMouseClicked /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btVerifikasi; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JFormattedTextField kodeTiket; private javax.swing.JTable tbTiket; // End of variables declaration//GEN-END:variables public void addActionListener(ActionListener x){ btVerifikasi.addActionListener(x); } public void addMouseAdapter(MouseAdapter x){ tbTiket.addMouseListener(x); } public javax.swing.JButton getBtVerifikasi() { return btVerifikasi; } public void setBtVerifikasi(javax.swing.JButton btVerifikasi) { this.btVerifikasi = btVerifikasi; } public String getKodeTiket() { return kodeTiket.getText(); } public void setKodeTiket(String kodeTiket) { this.kodeTiket.setText(kodeTiket); } public javax.swing.JTable getTbTiket() { return tbTiket; } public void setTbTiket(DefaultTableModel tbTiket) { this.tbTiket.setModel(tbTiket); } }
true
7e1a9f7b3d9558550fd9beb7163c09b04a697a21
Java
DomenikIrrgang/TacStarV2
/core/src/com/tacstargame/combat/ability/AbilityImpl.java
UTF-8
1,501
2.578125
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 com.tacstargame.combat.ability; import com.tacstargame.combat.eventbus.EventBusEvent; import com.tacstargame.combat.eventbus.EventBusImpl; import com.tacstargame.combat.eventbus.EventBusListener; /** * * @author Domenik Irrgang */ public abstract class AbilityImpl implements Ability, EventBusListener { private int remainingCooldown = 0; private int maxCooldown; public AbilityImpl(int maxCooldown) { this.maxCooldown = maxCooldown; EventBusImpl.getInstance().registerForEvent(this, EventBusEvent.COMBAT_STATE_CHANGED); } @Override public void OnEventFired(EventBusEvent busEvent, Object... args) { if (busEvent.equals(EventBusEvent.COMBAT_STATE_CHANGED) && remainingCooldown > 0 && !((Boolean) args[0])) { remainingCooldown -= 1; } } @Override public void setRemainingCooldown(int remainingCooldown) { this.remainingCooldown = remainingCooldown; } @Override public int getRemainingCooldown() { return remainingCooldown; } @Override public void setMaxCooldown(int maxCooldown) { this.maxCooldown = maxCooldown; } @Override public int getMaxCooldown() { return maxCooldown; } }
true
db7338d47b577c1616d7cac23076e8a53a904e76
Java
radko26/Sirma_ITT_TodoSPABack-end
/src/main/java/com/sirma/itt/taskmgr/model/TaskBuilder.java
UTF-8
669
2.546875
3
[]
no_license
package com.sirma.itt.taskmgr.model; /** * Builder class for {@link Task} * * @author radoslav */ public class TaskBuilder { Task task; public TaskBuilder() { task = new Task(); } public TaskBuilder setId(String id) { task.setId(id); return this; } public TaskBuilder setContent(String content) { task.setContent(content); return this; } public TaskBuilder setExpire(long expireDateInTimeStamp) { task.setExpire(expireDateInTimeStamp); return this; } public TaskBuilder setFinished(boolean finished) { task.setFinished(finished); return this; } public Task build() { return task; } }
true
8f75bbd06980ee787201d1f2c49f52c2fb73d6b8
Java
LHang-01/leetcode-Exercise
/src/jianZhiOffer/num10_Fibonacci/Fibonacci.java
UTF-8
1,223
4.09375
4
[]
no_license
package jianZhiOffer.num10_Fibonacci; /** * 剑指offer面试题10--斐波那契数列 * 现在要求输入一个整数n,请你输出斐波那契数列的第n项。 */ public class Fibonacci { //1.迭代,用三个变量,其中用两个变量存储n-1和n-2 public int fib11(int n) { if (n==0) return 0; if (n==1) return 1; int temp1 = 0; int temp2 = 1; int sum = 0; for (int i = 2 ; i<=n;i++){ sum = temp1+temp2; temp1 = temp2; temp2 = sum; } return sum; } //1.迭代,用两个变量,其中一个存储n-2,另一个存储即n-2,又是存的返回值。 // 推荐,时间复杂度O(n) public int fib12(int n) { if (n==0) return 0; if (n==1) return 1; int temp1 = 0; int sum = 1; for (int i = 2 ; i<=n;i++){ sum = temp1+sum; temp1 = sum-temp1; } return sum; } //2.递归,时空开销较大,不推荐。 public int fib2(int n) { if (n <= 0) { return 0; } if (n == 1) { return 1; } return fib2(n-1) +fib2(n-2); } }
true
a96e08f061218aef87f883a44d1f5f3136103c20
Java
Mabrollin/TennisstegeUserApp
/src/main/java/org/tennisstege/api/JPA/repository/RoleRepository.java
UTF-8
308
1.992188
2
[]
no_license
package org.tennisstege.api.JPA.repository; import java.util.Optional; import org.springframework.data.mongodb.repository.MongoRepository; import org.tennisstege.api.JPA.entitymodell.Role; public interface RoleRepository extends MongoRepository<Role, Long> { Optional<Role> findByName(String string); }
true
445978adf7a73fe5da006abf6da8830097de46a7
Java
brunaks/core-payroll
/internal/src/main/java/bmworks/core/payroll/masterdata/Employee.java
UTF-8
1,039
2.921875
3
[]
no_license
package bmworks.core.payroll.masterdata; import java.math.BigDecimal; public class Employee { private Name name; private String contractName; private Salary salary; public Employee(String firstName, String lastName, String contractName, String monthlyGrossSalary) { this.name = new Name(firstName, lastName); this.contractName = contractName; this.salary = new Salary(); this.salary.setMonthlyGrossSalary(new BigDecimal(monthlyGrossSalary)); } public static Employee fromInfo(EmployeeInfo employeeInfo) { return new Employee(employeeInfo.firstName, employeeInfo.lastName, employeeInfo.contractName, employeeInfo.monthlyGrossSalary); } public String getFullName() { return name.getFullName(); } public String getContractName() { return contractName; } public BigDecimal getMonthlyGrossSalary() { return salary.getGrossSalary(); } }
true
6956dfdf310a22d83b29ebe02c0866a60dd74b57
Java
batizty/jersey-scheduler
/src/main/java/com/weibo/datasys/base/MySqlConnector.java
UTF-8
2,102
2.453125
2
[ "Apache-2.0" ]
permissive
package com.weibo.datasys.base; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; /** * Created by tuoyu on 22/12/2016. */ public class MySqlConnector implements ServletContextListener { protected final Log logger = LogFactory.getLog(getClass()); public static Connection connection; private final String host = "10.77.136.64"; private final String port = "3306"; private final String username = "hadoop"; private final String password = "hadoop"; private final String database = "datasys_monitor"; private final String sql_url = "jdbc:mysql://" + host + ":" + port + "/" + database; private final String driver = "com.mysql.jdbc.Driver"; public void getConnection() { try { Class.forName(driver).newInstance(); connection = DriverManager.getConnection(sql_url, username, password); logger.info("Connect to " + sql_url + " OK"); } catch (Exception e) { logger.error("Init Connection to DB Error:".concat(e.getMessage())); e.printStackTrace(); } } @Override public void contextInitialized(ServletContextEvent event) { logger.info("ServletContextListener Start"); getConnection(); event.getServletContext().setAttribute("connection", connection); } @Override public void contextDestroyed(ServletContextEvent arg0) { logger.info("ServletContextListener destroyed"); try { if (connection != null) { connection.close(); logger.info("DB Connect close"); } Driver mySqlDriver = DriverManager.getDriver(sql_url); DriverManager.deregisterDriver(mySqlDriver); } catch (Exception se) { logger.error("Could not deregister driver:".concat(se.getMessage())); } } }
true
f57841e45aac51accfb8d28083cfbb8348a31346
Java
kinglee1982/ACG
/app/src/main/java/com/kcx/acg/views/activity/PictureViewerActivity.java
UTF-8
8,920
1.726563
2
[]
no_license
package com.kcx.acg.views.activity; import android.content.Intent; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckedTextView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.common.collect.Lists; import com.kcx.acg.R; import com.kcx.acg.api.GetProductInfoApi; import com.kcx.acg.base.BaseActivity; import com.kcx.acg.bean.GetProductInfoBean; import com.kcx.acg.bean.UserInfoBean; import com.kcx.acg.conf.Constants; import com.kcx.acg.https.HttpManager; import com.kcx.acg.https.RetryWhenNetworkException; import com.kcx.acg.impl.HttpOnNextListener; import com.kcx.acg.manager.AccountManager; import com.kcx.acg.views.adapter.ImageAdapter; import com.kcx.acg.views.adapter.PicturePagerAdapter; import com.kcx.acg.views.view.BottomDialog2; import com.kcx.acg.views.view.CustomToast; import com.kcx.acg.views.view.EcoGallery; import com.kcx.acg.views.view.EcoGalleryAdapterView; import com.monke.immerselayout.ImmerseFrameLayout; import java.util.List; import me.jessyan.autosize.internal.CancelAdapt; import static com.kcx.acg.views.view.BottomDialog2.SHOW_NOT_LOGIN_ACTION; import static com.kcx.acg.views.view.BottomDialog2.SHOW_OPEN_VIP_ACTION; /** */ public class PictureViewerActivity extends BaseActivity implements CancelAdapt { public static final String KEY_PIC_POSITION = "key_pic_position"; private View rootView; private ViewPager picViewPager; private EcoGallery ecoGallery; private ImageView backIv; private CheckedTextView hdvCtv; private LinearLayout hdvLayout; private LinearLayout ecoLayout; private ImmerseFrameLayout mainLayout; private TextView countTv; private TextView currnetPosTv; private int productID; private List<GetProductInfoBean.ReturnDataBean.DetailListBean> productList; private PicturePagerAdapter pagerAdapter; private ImageAdapter smallAdapter; private int currentPos = 1; private boolean mVisible = true; @Override public View setInitView() { rootView = LayoutInflater.from(this).inflate(R.layout.activity_picture_viewer, null); picViewPager = rootView.findViewById(R.id.pic_viewer_view_pager); ecoGallery = rootView.findViewById(R.id.pic_viewer_esc_gallery); backIv = rootView.findViewById(R.id.pic_viewer_back_iv); hdvCtv = rootView.findViewById(R.id.pic_viewer_hdv_ctv); hdvLayout = rootView.findViewById(R.id.pic_viewer_hdv_layout); ecoLayout = rootView.findViewById(R.id.pic_eco_gallery_layout); mainLayout = rootView.findViewById(R.id.pic_main_layout); countTv = rootView.findViewById(R.id.pic_viewer_count_tv); currnetPosTv = rootView.findViewById(R.id.pic_viewer_current_pos_tv); return rootView; } @Override public void setListener() { backIv.setOnClickListener(this); hdvLayout.setOnClickListener(this); pagerAdapter.setOnItemClickListener(new PicturePagerAdapter.OnItemClickListener() { @Override public void onItemClick(View view) { mVisible = !mVisible; if (mVisible) { ecoLayout.setVisibility(View.VISIBLE); } else { ecoLayout.setVisibility(View.GONE); } setVis(mVisible); } }); picViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { ecoGallery.setSelection(position, true); ecoGallery.setSelected(true); currnetPosTv.setText(position + 1 + ""); } @Override public void onPageScrollStateChanged(int state) { } }); ecoGallery.setOnItemSelectedListener(new EcoGalleryAdapterView.OnItemSelectedListener() { @Override public void onItemSelected(EcoGalleryAdapterView<?> parent, View view, int position, long id) { picViewPager.setCurrentItem(position, true); currnetPosTv.setText(position + 1 + ""); view.setAlpha(1); } @Override public void onNothingSelected(EcoGalleryAdapterView<?> parent) { } }); } public void setVis(boolean mVisible) { if (!mVisible) { //全屏 rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); } else { //非全屏 rootView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION ); } } @Override public void initData() { productID = getIntent().getIntExtra(PreviewActivity.KEY_PRODUCT_ID, 0); currentPos = getIntent().getIntExtra(KEY_PIC_POSITION, 1); getProductInfo(productID); productList = Lists.newArrayList(); pagerAdapter = new PicturePagerAdapter(this, productList); smallAdapter = new ImageAdapter(this, productList); picViewPager.setAdapter(pagerAdapter); ecoGallery.setAdapter(smallAdapter); ecoGallery.setUnselectedAlpha(1f); } public void getProductInfo(final int productID) { GetProductInfoApi getProductInfoApi = new GetProductInfoApi(this); getProductInfoApi.setProductID(productID); getProductInfoApi.setListener(new HttpOnNextListener<GetProductInfoBean>() { @Override public RetryWhenNetworkException.Wrapper onNext(GetProductInfoBean getProductInfoBean) { if (getProductInfoBean.getErrorCode() == 200) { productList.addAll(getProductInfoBean.getReturnData().getDetailList()); pagerAdapter.notifyDataSetChanged(); smallAdapter.notifyDataSetChanged(); countTv.setText(getProductInfoBean.getReturnData().getDetailList().size() + ""); picViewPager.setCurrentItem(currentPos, true); ecoGallery.setSelection(currentPos, true); } return null; } }); HttpManager.getInstance().doHttpDeal(this, getProductInfoApi); } BottomDialog2.Builder dialog2; @Override public void onClick(View view) { switch (view.getId()) { case R.id.pic_viewer_back_iv: finish(); break; case R.id.pic_viewer_hdv_layout: boolean isLogin = AccountManager.getInstances().isLogin(this, false); dialog2 = new BottomDialog2.Builder(this); dialog2.setLayoutId(R.layout.dialog_not_login_layout); if (!isLogin) { dialog2.showWhat(SHOW_NOT_LOGIN_ACTION, getString(R.string.not_login_waring_msg), getString(R.string.not_login_btn_msg1), getString(R.string.not_login_btn_msg2)).show(); } else { UserInfoBean.ReturnDataBean userInfo = AccountManager.getInstances().getUserInfo(this).getReturnData(); if (userInfo.getUserLevel() == 1) { dialog2.showWhat(SHOW_OPEN_VIP_ACTION, getString(R.string.not_login_open_vip_waring_msg), getString(R.string.not_login_open_vip_btn_msg), getString(R.string.not_login_btn_msg2)).show(); } else { if (!hdvCtv.isChecked()) { CustomToast.showToast(getString(R.string.pic_hdv_toast_msg)); pagerAdapter.setHdvMode(true); pagerAdapter.notifyDataSetChanged(); } hdvCtv.setChecked(!hdvCtv.isChecked()); } } dialog2.setOnNotLoginClickListener(new BottomDialog2.Builder.OnNotLoginClickListener() { @Override public void onBtnClick(View view, int showWhat) { Intent intent = new Intent(); intent.putExtra(Constants.KEY_IS_FINISH_CUR_ACTIVITY, true); if (showWhat == SHOW_NOT_LOGIN_ACTION) { intent.setClass(PictureViewerActivity.this, LoginActivity.class); } if (showWhat == SHOW_OPEN_VIP_ACTION) { intent.setClass(PictureViewerActivity.this, VipActivity.class); } startDDMActivity(intent, true); dialog2.dismiss(); } }); break; } } }
true
1806fd8e939c16b6b0e3e6d96dded554ec6304f0
Java
evandrosuzart/javaparaweb-exemploshibernate
/src/main/java/br/com/javaparaweb/capitulo3/crudannotations/ContatoCrudAnotations.java
UTF-8
1,258
2.796875
3
[]
no_license
package br.com.javaparaweb.capitulo3.crudannotations; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import br.com.javaparaweb.capitulo3.conexao.HibernateUtil; public class ContatoCrudAnotations { private Session sessao; public ContatoCrudAnotations(Session sessao) { this.sessao = sessao; } public void salvar(Contato contato) { sessao.save(contato); } public void atualizar(Contato contato) { sessao.update(contato); } public void excluir(Contato contato) { sessao.delete(contato); } public List<Contato> listar(){ Query consulta = sessao.createQuery("from Contato"); return consulta.list(); } public Contato buscaContato(int valor) { Query consulta = sessao.createQuery("from Contato where codigo = :parametro"); consulta.setInteger("parametro", valor); return (Contato) consulta.uniqueResult(); } public static void main(String[] arg) { Session sessao = HibernateUtil.getSessionfactory().openSession(); org.hibernate.Transaction transacao = sessao.beginTransaction(); ContatoCrudAnotations contatoCrud = new ContatoCrudAnotations(sessao); Contato contato= new Contato(); contato = contatoCrud.buscaContato(2); sessao.close(); } }
true
0ca448d08e3213d7b132b45653e459d1469a3796
Java
0rand/ICOnator-backend
/services/monitor/src/main/java/io/iconator/monitor/consumer/SetWalletAddressMessageConsumer.java
UTF-8
2,887
2.09375
2
[ "Apache-2.0" ]
permissive
package io.iconator.monitor.consumer; import com.fasterxml.jackson.databind.ObjectMapper; import io.iconator.commons.amqp.model.SetWalletAddressMessage; import io.iconator.monitor.BitcoinMonitor; import io.iconator.monitor.EthereumMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.ExchangeTypes; import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Optional; import static io.iconator.commons.amqp.model.constants.ExchangeConstants.ICONATOR_ENTRY_EXCHANGE; import static io.iconator.commons.amqp.model.constants.QueueConstants.ADDRESS_SET_WALLET_QUEUE; import static io.iconator.commons.amqp.model.constants.RoutingKeyConstants.ADDRESS_SET_WALLET_ROUTING_KEY; import static java.util.Optional.ofNullable; @Component public class SetWalletAddressMessageConsumer { private static final Logger LOG = LoggerFactory.getLogger(SetWalletAddressMessageConsumer.class); @Autowired private ObjectMapper objectMapper; @Autowired private EthereumMonitor ethereumMonitor; @Autowired private BitcoinMonitor bitcoinMonitor; @RabbitListener( bindings = @QueueBinding(value = @Queue(value = ADDRESS_SET_WALLET_QUEUE, autoDelete = "false"), exchange = @Exchange( value = ICONATOR_ENTRY_EXCHANGE, type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true", durable = "true" ), key = ADDRESS_SET_WALLET_ROUTING_KEY) ) public void receiveMessage(byte[] message) { LOG.debug("Received from consumer: " + new String(message)); SetWalletAddressMessage setWalletAddressMessage = null; try { setWalletAddressMessage = objectMapper.reader().forType(SetWalletAddressMessage.class).readValue(message); } catch (IOException e) { LOG.error("Message not valid."); } Optional<SetWalletAddressMessage> optionalSetWalletAddressMessage = ofNullable(setWalletAddressMessage); optionalSetWalletAddressMessage.ifPresent((m) -> { ofNullable(m.getInvestor()).ifPresent((investor) -> { long timestamp = investor.getCreationDate().getTime() / 1000L; bitcoinMonitor.addMonitoredAddress(investor.getPayInBitcoinAddress(), timestamp); ethereumMonitor.addMonitoredEtherAddress(investor.getPayInEtherAddress()); }); }); } }
true
a7ad9b677b86112afcc30da62ba31def5281588e
Java
project-dmart/grpc-spring
/normal-case/server2/src/main/java/dev/idion/server2/Server2Application.java
UTF-8
1,096
2.28125
2
[]
no_license
package dev.idion.server2; import dev.idion.grpc.HelloRequest; import dev.idion.grpc.HelloResponse; import dev.idion.grpc.HelloServiceGrpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class Server2Application { @GetMapping("/hi") public String hi() { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080).usePlaintext() .build(); HelloServiceGrpc.HelloServiceBlockingStub stub = HelloServiceGrpc.newBlockingStub(channel); HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder() .setFirstName("김") .setLastName("선동") .setAge(26) .build()); channel.shutdown(); return helloResponse.getGreeting(); } public static void main(String[] args) { SpringApplication.run(Server2Application.class, args); } }
true
3aacc977a6d2b2463b46bd600a433d6f38d56737
Java
kbatalin/UniversityProjects
/computer-graphics/Life/src/main/java/ru/nsu/fit/g14205/batalin/utils/observe/IObservable.java
UTF-8
303
2.109375
2
[]
no_license
package ru.nsu.fit.g14205.batalin.utils.observe; /** * Created by kir55rus on 27.02.17. */ public interface IObservable { int addObserver(IEvent event, IObserverHandler handler); void deleteObserver(IEvent event, int id); void notifyObservers(IEvent event); void deleteObservers(); }
true
d6267659e5d8aff2730fdb85363399332726e1c1
Java
MorganB69/P6-Site-Communautaire
/site/business/src/main/java/fr/mb/projet/contract/UserManager.java
UTF-8
570
2.21875
2
[]
no_license
package fr.mb.projet.contract; import fr.mb.projet.bean.user.Utilisateur; import fr.mb.projet.exception.FunctionalException; import fr.mb.projet.exception.NotFoundException; import fr.mb.projet.exception.TechnicalException; /** * Interface des managers des User * @author Morgan * */ public interface UserManager { public Utilisateur getUser (String login, String mdp) throws NotFoundException; public void insert(Utilisateur user) throws FunctionalException, TechnicalException; public Utilisateur getUserById(Integer id) throws NotFoundException ; }
true
2974ccb2a4355b314d586212a829b9bab8336473
Java
blentle/blentle-foundation
/src/main/java/top/blentle/foundation/review/gc/GcFinalizeTest.java
UTF-8
1,040
2.984375
3
[]
no_license
package top.blentle.foundation.review.gc; import java.io.Serializable; /** * Created by blentle on 2017/2/13. */ public class GcFinalizeTest implements Serializable { // /** // * n是自然数 // * 递归实现 // * @param n // * @return // */ // public static int fibonacci(int n) { // if (n == 0) // return 0; // if (n == 1 || n == 2) // return 1; // return fibonacci(n - 2) + fibonacci(n - 1); // } /** * n是自然数 * 非递归实现 * * @param n * @return */ public static int fibonacci(int n) { if (n == 0) return 0; if (n == 1 || n == 2) return 1; int a, b; int sum = 0; a = b = 1; //这里从2开始遍历 for (int i = 2; i < n; i++) { sum = a + b; a = b; b = sum; } return sum; } public static void main(String[] args) { System.err.println(fibonacci(50)); } }
true
39bda5a74b5c3a4105b1fb5550e0611208fdae88
Java
Solmi/Walala2019
/src/main/java/com/utf18/site/service/UserService.java
UTF-8
458
1.851563
2
[]
no_license
package com.utf18.site.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.utf18.site.dao.UserDAO; import com.utf18.site.vo.UserVO; @Service("userservice") public class UserService { @Autowired private UserDAO dao; public void insertUser(UserVO vo) { dao.insert(vo); } public UserVO getUserVO(UserVO vo) { return dao.getuservo(vo); } }
true
fa5a24d7c1495fe51f13276fd1c9eb91a3a0c4f2
Java
jrharbin-york/atlas-middleware
/middleware-java/src/moosmapping/HelmBehaviourStationKeep.java
UTF-8
642
2.0625
2
[]
no_license
package moosmapping; public class HelmBehaviourStationKeep extends MOOSBehaviour { public HelmBehaviourStationKeep(MOOSProcess parent) { super("BHV_StationKeep", parent); // TODO: pull out these radii properties to the constructor setProperty("name", "station-keep"); setProperty("pwt", 100); //setProperty("condition", "MODE==STATION_KEEPING"); setProperty("inner_radius", 5); setProperty("outer_radius", 10); setProperty("outer_speed", 1.0); setProperty("transit_speed", 1.3); setProperty("swing_time", 7); setProperty("hibernation_radius", 25); setProperty("visual_hints", "vertex_size=0, edge_color=blue"); } }
true
e49bfb4629d6c8c3fd228486e8ed6f5b2bdee7b1
Java
liveqmock/SMS-1
/2012/销售管理/代码/sesale/src/com/isoftstone/cjmodules/bean/versionDef/ParamOrbitBean.java
UTF-8
1,243
1.757813
2
[]
no_license
package com.isoftstone.cjmodules.bean.versionDef; import com.isoftstone.adapter.bean.BaseEntity; public class ParamOrbitBean extends BaseEntity{ private String OperatorID; private String OperatorName; private String Operation; private String AreaModulus; private String OperatingDate; private String Memo; public String getOperatorID() { return OperatorID; } public void setOperatorID(String operatorID) { OperatorID = operatorID; } public String getOperatorName() { return OperatorName; } public void setOperatorName(String operatorName) { OperatorName = operatorName; } public String getOperation() { return Operation; } public void setOperation(String operation) { Operation = operation; } public String getAreaModulus() { return AreaModulus; } public void setAreaModulus(String areaModulus) { AreaModulus = areaModulus; } public String getOperatingDate() { return OperatingDate; } public void setOperatingDate(String operatingDate) { OperatingDate = operatingDate; } public String getMemo() { return Memo; } public void setMemo(String memo) { Memo = memo; } }
true
7e925325f007fcffc0345b52f599221feaf5eb30
Java
Black-Hole/mc-dev
/net/minecraft/core/particles/VibrationParticleOption.java
UTF-8
3,665
2.125
2
[]
no_license
package net.minecraft.core.particles; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.Locale; import net.minecraft.core.BlockPosition; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.PacketDataSerializer; import net.minecraft.world.level.World; import net.minecraft.world.level.gameevent.BlockPositionSource; import net.minecraft.world.level.gameevent.PositionSource; import net.minecraft.world.level.gameevent.PositionSourceType; import net.minecraft.world.phys.Vec3D; public class VibrationParticleOption implements ParticleParam { public static final Codec<VibrationParticleOption> CODEC = RecordCodecBuilder.create((instance) -> { return instance.group(PositionSource.CODEC.fieldOf("destination").forGetter((vibrationparticleoption) -> { return vibrationparticleoption.destination; }), Codec.INT.fieldOf("arrival_in_ticks").forGetter((vibrationparticleoption) -> { return vibrationparticleoption.arrivalInTicks; })).apply(instance, VibrationParticleOption::new); }); public static final ParticleParam.a<VibrationParticleOption> DESERIALIZER = new ParticleParam.a<VibrationParticleOption>() { @Override public VibrationParticleOption fromCommand(Particle<VibrationParticleOption> particle, StringReader stringreader) throws CommandSyntaxException { stringreader.expect(' '); float f = (float) stringreader.readDouble(); stringreader.expect(' '); float f1 = (float) stringreader.readDouble(); stringreader.expect(' '); float f2 = (float) stringreader.readDouble(); stringreader.expect(' '); int i = stringreader.readInt(); BlockPosition blockposition = BlockPosition.containing((double) f, (double) f1, (double) f2); return new VibrationParticleOption(new BlockPositionSource(blockposition), i); } @Override public VibrationParticleOption fromNetwork(Particle<VibrationParticleOption> particle, PacketDataSerializer packetdataserializer) { PositionSource positionsource = PositionSourceType.fromNetwork(packetdataserializer); int i = packetdataserializer.readVarInt(); return new VibrationParticleOption(positionsource, i); } }; private final PositionSource destination; private final int arrivalInTicks; public VibrationParticleOption(PositionSource positionsource, int i) { this.destination = positionsource; this.arrivalInTicks = i; } @Override public void writeToNetwork(PacketDataSerializer packetdataserializer) { PositionSourceType.toNetwork(this.destination, packetdataserializer); packetdataserializer.writeVarInt(this.arrivalInTicks); } @Override public String writeToString() { Vec3D vec3d = (Vec3D) this.destination.getPosition((World) null).get(); double d0 = vec3d.x(); double d1 = vec3d.y(); double d2 = vec3d.z(); return String.format(Locale.ROOT, "%s %.2f %.2f %.2f %d", BuiltInRegistries.PARTICLE_TYPE.getKey(this.getType()), d0, d1, d2, this.arrivalInTicks); } @Override public Particle<VibrationParticleOption> getType() { return Particles.VIBRATION; } public PositionSource getDestination() { return this.destination; } public int getArrivalInTicks() { return this.arrivalInTicks; } }
true
c809e9b2f6d3b39659eefd36a74b54e9bce2716e
Java
easycodebox/easycode
/easycode-jdbc/src/main/java/com/easycodebox/jdbc/entity/AbstractCreateEntity.java
UTF-8
835
2.328125
2
[ "Apache-2.0" ]
permissive
package com.easycodebox.jdbc.entity; import javax.persistence.*; import java.util.Date; /** * @author WangXiaoJin * */ @MappedSuperclass public abstract class AbstractCreateEntity extends AbstractEntity implements CreateEntity { private String creator; private Date createTime; /********** 冗余字段 **************/ @Transient private String creatorName; @Override public String getCreator() { return creator; } @Override public void setCreator(String creator) { this.creator = creator; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreatorName() { return creatorName; } public void setCreatorName(String creatorName) { this.creatorName = creatorName; } }
true
047ca00445364fa4b7a761420b90c03cf60c7e3d
Java
colining/algorithms-master
/src/com/company2/HeapDemo.java
GB18030
690
2.84375
3
[]
no_license
package com.company2; import algorithms2.HeapSort; /** * Created by asus on 2016/11/30. */ public class HeapDemo { public static void main(String args[]){ HeapSort hs = new HeapSort(); int[] array = {87,45,78,32,17,65,53,9,122}; System.out.print("ѣ"); hs.toString(hs.buildMaxHeap(array)); System.out.print("\n"+"ɾѶԪأ"); hs.toString(hs.deleteMax(array)); System.out.print("\n"+"Ԫ63:"); hs.toString(hs.insertData(array, 63)); System.out.print("\n"+""); hs.toString(hs.heapSort(array)); hs.toString(hs.deleteDate(array,3)); } }
true
f293946dac7f82d2754b5df471f2c2f782c9c1a4
Java
Akaifox16/SuperZuck
/core/src/main/java/CPE200/proj/succ/model/item/FlourConverter.java
UTF-8
348
2.234375
2
[]
no_license
package CPE200.proj.succ.model.item; import CPE200.proj.succ.model.GameObjectType; import com.badlogic.gdx.graphics.Texture; public class FlourConverter extends ItemObject{ public FlourConverter(int i, int j) { super(i, j); super.texture = new Texture("converter.png"); super.type = GameObjectType.Converter; } }
true
555c1b4a7fc23b2fb97b4ecf4464d1e51af1b596
Java
jaismeen/MOOCTestLab
/testlab/src/main/java/org/mytestlab/service/StudentService.java
UTF-8
5,424
2.5625
3
[]
no_license
package org.mytestlab.service; import java.util.ArrayList; import org.mytestlab.domain.Answer; import org.mytestlab.domain.Assignment; import org.mytestlab.domain.Student; import org.mytestlab.repository.AnswerRepository; import org.mytestlab.repository.AssignmentRepository; import org.mytestlab.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.neo4j.conversion.EndResult; import org.springframework.stereotype.Service; @Service public class StudentService { @Autowired private StudentRepository studentRepository; @Autowired private AssignmentRepository assignmentRepository; @Autowired private AnswerRepository answerRepository; public String loadTestData() { String ret = ""; Student stu = new Student(); stu.setFirstName("Amy"); stu.setLastName("Johnson"); stu.setPassword("111"); stu.setUsername("0002"); studentRepository.save(stu); ret += getStudentInfo("0002"); stu = new Student(); stu.setFirstName("John"); stu.setLastName("Don"); stu.setPassword("111"); stu.setUsername("0003"); studentRepository.save(stu); ret += getStudentInfo("0003"); stu = new Student(); stu.setFirstName("Richard"); stu.setLastName("Lee"); stu.setPassword("111"); stu.setUsername("0004"); studentRepository.save(stu); ret += getStudentInfo("0004"); stu = new Student(); stu.setFirstName("Mary"); stu.setLastName("Kate"); stu.setPassword("111"); stu.setUsername("0005"); studentRepository.save(stu); ret += getStudentInfo("0005"); stu = new Student(); stu.setFirstName("Sam"); stu.setLastName("Washington"); stu.setPassword("111"); stu.setUsername("0006"); studentRepository.save(stu); ret += getStudentInfo("0006"); stu = new Student(); stu.setFirstName("Linda"); stu.setLastName("Wong"); stu.setPassword("111"); stu.setUsername("0007"); studentRepository.save(stu); ret += getStudentInfo("0007"); stu = new Student(); stu.setFirstName("Shawn"); stu.setLastName("Tran"); stu.setPassword("111"); stu.setUsername("0008"); studentRepository.save(stu); ret += getStudentInfo("0008"); stu = new Student(); stu.setFirstName("Alex"); stu.setLastName("Patel"); stu.setPassword("111"); stu.setUsername("0009"); studentRepository.save(stu); ret += getStudentInfo("0009"); System.out.println(ret); return ret; } private String getStudentInfo(String username) { Student stu = studentRepository.findByUsername(username); String ret = "Student username: "+stu.getUsername()+", password: "+stu.getPassword()+", name: "+stu.getFirstName()+" "+stu.getLastName()+"\n"; return ret; } public String getTestData() { Student newAmy = studentRepository.findByUsername("0002"); String ret = "New Amy's name: "+newAmy.getFirstName()+" "+newAmy.getLastName(); System.out.println(ret); return ret; } //Return error string if there is an error. Return empty string if there is no error. public String login(String username, String password) { String ret = ""; String errorMsg = "Please enter your Username and Password."; String errorMsg2 = "The username doesn't exist."; String errorMsg3 = "Wrong password!"; if (username == null || (username != null && username.isEmpty()) || password == null || (password != null && password.isEmpty())) { ret = errorMsg; return ret; } Student stu = studentRepository.findByUsername(username); if (stu == null) { //can't find username ret = errorMsg2; } else if (!stu.getPassword().equals(password)) { //password doesn't match ret = errorMsg3; } return ret; } public String submitAnswer(String username, String assignmentName, ArrayList<String> codeStrings, int cyclomaticNumber) { String ret = ""; String answerName = assignmentName+"_"+username; Student stu = studentRepository.findByUsername(username); Assignment assign = assignmentRepository.findByName(assignmentName); Answer ans = null; EndResult<Answer> anss = answerRepository.findAll(); for (Answer an : anss) { if (answerName.equals(an.getName())) { ans = an; break; } } if (stu == null) { ret = "Student doesn't exist!"; return ret; } if (assign == null) { ret = "Assignment doesn't exist!"; return ret; } if (ans == null) { ans = new Answer(answerName, stu, assign); ans.setCodeStrings(codeStrings); ans.setCyclomaticNumber(cyclomaticNumber); stu.addAnswer(ans); assign.addAnswer(ans); answerRepository.save(ans); studentRepository.save(stu); assignmentRepository.save(assign); } else { ret = "Resubmission is not allowed."; } return ret; } public void printAnswers(String username) { Student stu = studentRepository.findByUsername(username); for (Answer ans : stu.getAnswers()){ System.out.println("Assignment Name: "+ans.getAssignment().getName()); System.out.println("Code String"); for (int i = 0; i < ans.getCodeStrings().size(); i++) { System.out.println(ans.getCodeStrings().get(i)); } System.out.println("Code String Points"); for (int i = 0; i < ans.getCodeStringsPoints().size(); i++) { System.out.println(ans.getCodeStringsPoints().get(i)); } System.out.println("Cyclomatic Number: "+ans.getCyclomaticNumber()+", Points: "+ans.getCyclomaticNumberPoint()); } } }
true
81bea0ba70cad282720cd2bbb88660ec714b1ac3
Java
pomelo4/DevNews
/DevNews/app/src/main/java/com/pomelo/devnews/ui/fragment/iOSFragment.java
UTF-8
734
2.15625
2
[ "Apache-2.0" ]
permissive
package com.pomelo.devnews.ui.fragment; import com.pomelo.devnews.cache.iOSCacheUtil; import com.pomelo.devnews.model.MobileNews; import java.util.ArrayList; public class iOSFragment extends MobileNewsFragment { @Override MobileNews.MobileType RequestUrl() { return MobileNews.MobileType.ISO; } @Override void clearAllCache() { iOSCacheUtil.getInstance(getActivity()).clearAllCache(); } @Override void addResultCache(String cache, int page) { iOSCacheUtil.getInstance(getActivity()).addResultCache(cache, page); } @Override ArrayList<MobileNews> getCacheByPage(int page) { return iOSCacheUtil.getInstance(getActivity()).getCacheByPage(page); } }
true
28081e6425efb8700fadac56703ffaf8a390e79d
Java
FluffyJay1/ShadowStone
/src/main/java/server/card/cardset/standard/bloodwarlock/PrisonOfPain.java
UTF-8
3,765
2.34375
2
[]
no_license
package server.card.cardset.standard.bloodwarlock; import client.tooltip.Tooltip; import client.tooltip.TooltipAmulet; import client.ui.game.visualboardanimation.eventanimation.damage.EventAnimationDamageMagicHit; import org.newdawn.slick.geom.Vector2f; import server.ServerBoard; import server.ai.AI; import server.card.*; import server.card.effect.Effect; import server.card.effect.EffectStats; import server.card.effect.Stat; import server.card.target.TargetList; import server.event.Event; import server.resolver.DamageResolver; import server.resolver.DrawResolver; import server.resolver.Resolver; import server.resolver.meta.ResolverWithDescription; import server.resolver.util.ResolverQueue; import java.util.List; public class PrisonOfPain extends AmuletText { public static final String NAME = "Prison of Pain"; private static final String BATTLECRY_DESCRIPTION = "<b>Battlecry</b>: Deal 1 damage to your leader and draw a card."; private static final String ONTURNEND_DESCRIPTION = "At the end of your turn, deal 1 damage to your leader and draw a card."; public static final String DESCRIPTION = "<b>Countdown(2)</b>.\n" + BATTLECRY_DESCRIPTION + "\n" + ONTURNEND_DESCRIPTION; public static final ClassCraft CRAFT = ClassCraft.BLOODWARLOCK; public static final CardRarity RARITY = CardRarity.SILVER; public static final List<CardTrait> TRAITS = List.of(); public static final TooltipAmulet TOOLTIP = new TooltipAmulet(NAME, DESCRIPTION, "card/standard/prisonofpain.png", CRAFT, TRAITS, RARITY, 3, PrisonOfPain.class, new Vector2f(127, 211), 1.3, () -> List.of(Tooltip.COUNTDOWN, Tooltip.BATTLECRY), List.of()); @Override protected List<Effect> getSpecialEffects() { return List.of(new Effect(DESCRIPTION, EffectStats.builder() .set(Stat.COUNTDOWN, 2) .build()) { @Override public ResolverWithDescription battlecry(List<TargetList<?>> targetList) { Effect effect = this; return new ResolverWithDescription(BATTLECRY_DESCRIPTION, new Resolver(false) { @Override public void onResolve(ServerBoard b, ResolverQueue rq, List<Event> el) { owner.player.getLeader().ifPresent(l -> { this.resolve(b, rq, el, new DamageResolver(effect, l, 1, true, new EventAnimationDamageMagicHit().toString())); this.resolve(b, rq, el, new DrawResolver(owner.player, 1)); }); } }); } @Override public double getBattlecryValue(int refs) { return AI.VALUE_PER_CARD_IN_HAND; } @Override public ResolverWithDescription onTurnEndAllied() { Effect effect = this; return new ResolverWithDescription(ONTURNEND_DESCRIPTION, new Resolver(false) { @Override public void onResolve(ServerBoard b, ResolverQueue rq, List<Event> el) { owner.player.getLeader().ifPresent(l -> { this.resolve(b, rq, el, new DamageResolver(effect, l, 1, true, new EventAnimationDamageMagicHit().toString())); this.resolve(b, rq, el, new DrawResolver(owner.player, 1)); }); } }); } @Override public double getPresenceValue(int refs) { return AI.VALUE_PER_CARD_IN_HAND * 2; } }); } @Override public TooltipAmulet getTooltip() { return TOOLTIP; } }
true
d9a112279e62bb9ddf14a82c4509cb0aa9cf0432
Java
abesisu/comS227Projects
/hw4_skeleton/src/hw4/CallExpression.java
UTF-8
3,077
3.6875
4
[]
no_license
package hw4; import api.ArgList; import api.DefaultNode; import api.Expression; import api.Function; import api.Scope; import parser.ProgramNode; /** * Expression representing the value of a function call. All expressions * in the argument list are evaluated with respect to the current scope, * and the resulting values are associated with the corresponding parameter names in * a new "local" Scope. This local scope is used to evaluate the function body * (its BlockInstruction) and after that, the function return expression. * Variables in the current scope are not accessible during execution of the function * body. * The eval method of this call expression returns value of the function's * return expression. * <ul> * <li>There are two children; the first is the Function object, and the second * is the argument list. * <li>The getLabel() method returns the string "Call". * <li>The getText() method returns the getText() string of the Function * </ul> */ // Directly implements Expression in order to reduce potential confusion from inheriting from ExpressionReference. // Because of the different instance variables, constructor, getText, getChild, and complex eval method, I thought // it would be better to not use inheritance with this important class. public class CallExpression implements Expression { private Function f; private ArgList args; /** * Constructs a CallExpression for the given function and argument list. * @param f * the function to be called * @param args * the arguments to the function */ public CallExpression(Function f, ArgList args) { this.f = f; this.args = args; } @Override public String getLabel() { return "Call"; } @Override public String getText() { return f.getText(); } @Override public ProgramNode getChild(int i) { if (i == 0) { return f; } else if (i == 1) { return args; } else { return new DefaultNode("Invalid index " + i + " for type " + this.getClass().getName()); } } @Override public int getNumChildren() { return 2; } /** * The eval method of this call expression returns value * of the function's return expression * @param env * scope with which this expression is to be evaluated */ @Override public int eval(Scope env) { Scope scope = new Scope(); for (int i = 0; i < args.getNumChildren(); ++i) { // gets the value from the expression int value = ((Expression) args.getChild(i)).eval(env); // gets the corresponding name from the parameter list String name = f.getChild(0).getChild(i).getText(); // updates the local scope scope.put(name, value); } // BlockInstruction execution ((BlockInstruction) f.getChild(1)).execute(scope); // return expression value; return ((Expression) f.getChild(2)).eval(scope); } /** * Sets the Function object for this CallExpression * @param f * the function to be called */ public void setFunction(Function f) { this.f = f; } @Override public String toString() { return makeString(); } }
true
4521f3038747fb2517a588584396ef553c42ca1d
Java
cherkavi/java-code-example
/oracle_xml_vs_mongo/test/com/test/TestXml_MongoDB.java
UTF-8
785
1.804688
2
[]
no_license
package com.test; import com.mongodb.Mongo; import com.test.connection.OracleConnection; import com.test.store.IXmlSearcher; import com.test.store.mongo_additional_table.MongoKeyDecoratorXml; public class TestXml_MongoDB extends AbstractTestXml{ @Override protected void setUp() throws Exception { System.out.println("begin"); /** XPath to Leaf */ this.findXpath="/root/property_1"; this.connection=OracleConnection.getConnection("127.0.0.1", 1521, "XE", "SYSTEM", "root"); this.xmlInDatabase=new MongoKeyDecoratorXml( connection, "xml_table", "temp_sequence", new Mongo("127.0.0.1", 27017), "test_mongo", "root", "test_collection"); this.xmlSearcher=(IXmlSearcher) this.xmlInDatabase; } }
true
62cd7445a692456f68290a1823f0ee5442b6ea84
Java
mplescano/spring-ws-security-soap-example
/src/main/java/com/bernardomg/example/swss/main/config/WSServletsConfig.java
UTF-8
5,599
1.710938
2
[ "MIT" ]
permissive
package com.bernardomg.example.swss.main.config; import org.springframework.boot.autoconfigure.webservices.WebServicesProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.ws.transport.http.MessageDispatcherServlet; import com.bernardomg.example.swss.servlet.encryption.wss4j.WSEncryptionWss4jContext; import com.bernardomg.example.swss.servlet.encryption.xwss.WSEncryptionXwssContext; import com.bernardomg.example.swss.servlet.password.digest.wss4j.WSPasswordDigestWss4jContext; import com.bernardomg.example.swss.servlet.password.digest.xwss.WSPasswordDigestXwssContext; import com.bernardomg.example.swss.servlet.password.plain.wss4j.WSPasswordPlainWss4jContext; import com.bernardomg.example.swss.servlet.password.plain.xwss.WSPasswordPlainXwssContext; import com.bernardomg.example.swss.servlet.signature.wss4j.WSSignatureWss4jContext; import com.bernardomg.example.swss.servlet.signature.xwss.WSSignatureXwssContext; import com.bernardomg.example.swss.servlet.unsecure.WSUnsecureContext; @Configuration @EnableConfigurationProperties(WebServicesProperties.class) public class WSServletsConfig { @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsUnsecureServlet(WebServicesProperties properties) { String path = "/unsecure/*"; Class<WSUnsecureContext> classParam = WSUnsecureContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsPasswordPlainWss4jServlet(WebServicesProperties properties) { String path = "/password/plain/wss4j/*"; Class<WSPasswordPlainWss4jContext> classParam = WSPasswordPlainWss4jContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsPasswordDigestWss4jServlet(WebServicesProperties properties) { String path = "/password/digest/wss4j/*"; Class<WSPasswordDigestWss4jContext> classParam = WSPasswordDigestWss4jContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsSignatureWss4jServlet(WebServicesProperties properties) { String path = "/signature/wss4j/*"; Class<WSSignatureWss4jContext> classParam = WSSignatureWss4jContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsEncryptionWss4jServlet(WebServicesProperties properties) { String path = "/encryption/wss4j/*"; Class<WSEncryptionWss4jContext> classParam = WSEncryptionWss4jContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsPasswordPlainXwssServlet(WebServicesProperties properties) { String path = "/password/plain/xwss/*"; Class<WSPasswordPlainXwssContext> classParam = WSPasswordPlainXwssContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsPasswordDigestXwssServlet(WebServicesProperties properties) { String path = "/password/digest/xwss/*"; Class<WSPasswordDigestXwssContext> classParam = WSPasswordDigestXwssContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsSignatureXwssServlet(WebServicesProperties properties) { String path = "/signature/xwss/*"; Class<WSSignatureXwssContext> classParam = WSSignatureXwssContext.class; return buildServletRegistration(properties, path, classParam); } @Bean public ServletRegistrationBean<MessageDispatcherServlet> wsEncryptionXwssServlet(WebServicesProperties properties) { String path = "/encryption/xwss/*"; Class<WSEncryptionXwssContext> classParam = WSEncryptionXwssContext.class; return buildServletRegistration(properties, path, classParam); } private ServletRegistrationBean<MessageDispatcherServlet> buildServletRegistration( WebServicesProperties properties, String path, Class<?> classParam) { AnnotationConfigWebApplicationContext wsServletContext = new AnnotationConfigWebApplicationContext(); wsServletContext.register(classParam); MessageDispatcherServlet servlet = new MessageDispatcherServlet(wsServletContext); servlet.setTransformWsdlLocations(true); servlet.setTransformSchemaLocations(true); String urlMapping = (path.endsWith("/") ? path + "*" : (path.endsWith("/*") ? path : path + "/*")); ServletRegistrationBean<MessageDispatcherServlet> registration = new ServletRegistrationBean<>( servlet, urlMapping); WebServicesProperties.Servlet servletProperties = properties.getServlet(); registration.setLoadOnStartup(servletProperties.getLoadOnStartup()); servletProperties.getInit().forEach(registration::addInitParameter); registration.setName(classParam.getCanonicalName()); return registration; } }
true
d0d15ec087ca47ddaba8dab68ba8d12886a31b3b
Java
jindalshiva/CameraView
/cameraview/src/test/java/com/otaliastudios/cameraview/frame/FrameTest.java
UTF-8
3,308
2.5625
3
[ "MIT" ]
permissive
package com.otaliastudios.cameraview.frame; import android.graphics.ImageFormat; import com.otaliastudios.cameraview.size.Size; import org.junit.After; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class FrameTest { private FrameManager manager; @Before public void setUp() { manager = mock(FrameManager.class); } @After public void tearDown() { manager = null; } @Test public void testEquals() { Frame f1 = new Frame(manager); long time = 1000; f1.set(null, time, 90, null, ImageFormat.NV21); Frame f2 = new Frame(manager); f2.set(new byte[2], time, 0, new Size(10, 10), ImageFormat.NV21); assertEquals(f1, f2); f2.set(new byte[2], time + 1, 0, new Size(10, 10), ImageFormat.NV21); assertNotEquals(f1, f2); } @Test public void testReleaseThrows() { final Frame frame = new Frame(manager); frame.set(new byte[2], 1000, 90, new Size(10, 10), ImageFormat.NV21); frame.release(); verify(manager, times(1)).onFrameReleased(frame); assertThrows(new Runnable() { public void run() { frame.getTime(); }}); assertThrows(new Runnable() { public void run() { frame.getFormat(); }}); assertThrows(new Runnable() { public void run() { frame.getRotation(); }}); assertThrows(new Runnable() { public void run() { frame.getData(); }}); assertThrows(new Runnable() { public void run() { frame.getSize(); }}); } private void assertThrows(Runnable runnable) { try { runnable.run(); throw new IllegalStateException("Expected an exception but found none."); } catch (Exception e) { // All good } } @Test public void testReleaseManager() { Frame frame = new Frame(manager); assertNotNull(frame.mManager); frame.releaseManager(); assertNull(frame.mManager); } @Test public void testFreeze() { Frame frame = new Frame(manager); byte[] data = new byte[]{0, 1, 5, 0, 7, 3, 4, 5}; long time = 1000; int rotation = 90; Size size = new Size(10, 10); int format = ImageFormat.NV21; frame.set(data, time, rotation, size, format); Frame frozen = frame.freeze(); assertArrayEquals(data, frozen.getData()); assertEquals(time, frozen.getTime()); assertEquals(rotation, frozen.getRotation()); assertEquals(size, frozen.getSize()); // Mutate the first, ensure that frozen is not affected frame.set(new byte[]{3, 2, 1}, 50, 180, new Size(1, 1), ImageFormat.JPEG); assertArrayEquals(data, frozen.getData()); assertEquals(time, frozen.getTime()); assertEquals(rotation, frozen.getRotation()); assertEquals(size, frozen.getSize()); assertEquals(format, frozen.getFormat()); } }
true
3a0268b43a559c634b1f4d274a611cbc58177882
Java
AGswasthik/seleniumframework
/src/test/java/frameworkstc/propertiespagelogin.java
UTF-8
1,022
2.03125
2
[]
no_license
package frameworkstc; import java.io.IOException; import org.apache.logging.log4j.Logger; import org.testng.annotations.Test; import base.browserintilization; import pages.landingpage; import pages.loginpages; public class propertiespagelogin extends browserintilization { public static Logger log1=org.apache.logging.log4j.LogManager.getLogger(browserintilization.class.getName()); @Test public void proplogin() throws IOException { //String urls=prop.getProperty("url"); //String un=prop.getProperty("username"); // String pw=prop.getProperty("password"); //System.out.println("url"+urls+"user"+un+"pass"+pw); driver=openbrowser(); driver.get(prop.getProperty("url")); landingpage lp=new landingpage(driver); lp.login().click(); loginpages log=new loginpages(driver); log.username().sendKeys(prop.getProperty("username")); log.password().sendKeys(prop.getProperty("password")); log.loginclick().click(); log1.info("prop pass"); } public void closebrowser() { driver.close(); } }
true
bb4515333e5a4a0df39206b18d8eb9f068604c44
Java
Dariyn/Adventuregame
/Adventuregame/Userweaponchoice.java
UTF-8
888
3.5
4
[]
no_license
public class Userweaponchoice { private Scan choice; private String weapon; private Opponent enemy; public Userweaponchoice(Scan n,Opponent m) { choice = n; enemy = m; } public int weaponchoice() { System.out.println("Option 1: A sword, it is good for fighting against a crowd of enemies"); System.out.println("Option 2: An axe, it is good for fighting a huge enemy"); choice.parseOption(false); int result = choice.parseOption(true); if (result == 1) { System.out.println("Dolan: You have chosen a sword!"); weapon = "Sword"; enemy.opponentchoice(); return 0; } else { System.out.println("Dolan: You have chosen an axe!"); weapon = "Axe"; enemy.opponentchoice(); return 0; } } }
true
537a430f9964513aad637830d468882c897e4c78
Java
skalatskiyMindata/automation
/src/main/java/DammAutomationFramework/webElements/component/SpotItem.java
UTF-8
489
1.890625
2
[]
no_license
package DammAutomationFramework.webElements.component; import com.github.webdriverextensions.WebComponent; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class SpotItem extends WebComponent { @FindBy(css = ".av-container span") public WebElement location; @FindBy(css = ".reallyslow") public WebElement title; @FindBy(css = ".lafoto") public WebElement lafoto; @FindBy(css = ".favourite span") public WebElement favoriteIcon; }
true
5ad41a66c5ffe44b67acf05d4c3e6f92e54ff9e0
Java
CrBatista/broccoli
/broccoli-eureka-client-google/src/main/java/com/broccoli/GoogleClientApplication.java
UTF-8
643
1.695313
2
[]
no_license
package com.broccoli; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @EnableDiscoveryClient @SpringBootApplication @EnableResourceServer @EnableAutoConfiguration public class GoogleClientApplication { public static void main(String[] args) { SpringApplication.run(GoogleClientApplication.class, args); } }
true
bfc15b1f6306e1fdb852fbae47b57c938dfbb3a1
Java
zzf-ai/StudentInformationManageSystem
/StudentInformationManager/src/main/RegisterDialog.java
UTF-8
266
1.773438
2
[]
no_license
package main; import javax.swing.*; public class RegisterDialog extends JDialog { public JTextField idField=new JTextField(20); public JPasswordField passwordField=new JPasswordField(20); public JPasswordField confirmField=new JPasswordField(20); }
true
01e7ea79f256dcfe0dfff83c9030b80b4ff2511e
Java
zhaoyunnian-xb/dcdb
/src/main/java/com/bm/index/service/DcdbSjjcsxDcsxService.java
UTF-8
922
1.773438
2
[]
no_license
package com.bm.index.service; import com.bm.index.model.DcdbSjjcsxDcsx; import com.bm.index.model.DcdbSjjcsxDcsxnq; import java.util.List; public interface DcdbSjjcsxDcsxService { //查询分工列表 List<DcdbSjjcsxDcsx> selectByExample(DcdbSjjcsxDcsx example); //删除分工列表 int deleteByExample(DcdbSjjcsxDcsx example); //插入分工列表 int insert(DcdbSjjcsxDcsx record); DcdbSjjcsxDcsx selectById(DcdbSjjcsxDcsx example); //分工发起插入DCDB_SJJCSX_DCSXNQ表中 int insertDcsxnq(DcdbSjjcsxDcsxnq record); //更新发起状态 0,未发起(默认) 1,已发起 int updateIsfq(DcdbSjjcsxDcsx record); int updateIszz(DcdbSjjcsxDcsxnq record); //更新插入待办表 int updateDb(String wh, String cbbmmc, String cbbmid, String userid, String userName, String bllx, String lclx); }
true
77b338682a543100486e92dcb66015cebb83358d
Java
pabllo007/cca
/Cadastro/ContaCapitalCadastroEJB/src/main/java/br/com/sicoob/cca/cadastro/negocio/servicos/ejb/ConfiguracaoCapitalServicoEJB.java
UTF-8
6,284
2.0625
2
[]
no_license
package br.com.sicoob.cca.cadastro.negocio.servicos.ejb; import java.util.List; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import br.com.bancoob.excecao.BancoobException; import br.com.bancoob.negocio.dto.ConsultaDto; import br.com.bancoob.persistencia.annotations.Dao; import br.com.sicoob.cca.cadastro.negocio.dto.CondicaoEstatutariaDTO; import br.com.sicoob.cca.cadastro.negocio.excecao.CadastroContaCapitalException; import br.com.sicoob.cca.cadastro.negocio.excecao.CadastroContaCapitalNegocioException; import br.com.sicoob.cca.cadastro.negocio.servicos.interfaces.ConfiguracaoCapitalServicoLocal; import br.com.sicoob.cca.cadastro.negocio.servicos.interfaces.ConfiguracaoCapitalServicoRemote; import br.com.sicoob.cca.cadastro.persistencia.dao.ContaCapitalCadastroCrudDaoIF; import br.com.sicoob.cca.cadastro.persistencia.dao.ContaCapitalCadastroDaoFactory; import br.com.sicoob.cca.cadastro.persistencia.dao.interfaces.ConfiguracaoCapitalDao; import br.com.sicoob.cca.entidades.negocio.entidades.ConfiguracaoCapital; /** * EJB contendo servicos relacionados a ConfiguracaoCapital. */ @Stateless @Local(ConfiguracaoCapitalServicoLocal.class) @Remote(ConfiguracaoCapitalServicoRemote.class) public class ConfiguracaoCapitalServicoEJB extends ContaCapitalCadastroCrudServicoEJB<ConfiguracaoCapital> implements ConfiguracaoCapitalServicoLocal, ConfiguracaoCapitalServicoRemote { @SuppressWarnings("unused") @PersistenceContext(unitName = "emCCAEntidades") private EntityManager em; @Dao (entityManager = "em", fabrica = ContaCapitalCadastroDaoFactory.class) private ConfiguracaoCapitalDao configuracaoCapitalDao; /** * @see br.com.sicoob.cca.cadastro.negocio.servicos.ejb.ContaCapitalCadastroCrudServicoEJB#getDAO() */ @Override protected ContaCapitalCadastroCrudDaoIF<ConfiguracaoCapital> getDAO() { return configuracaoCapitalDao; } /** * @see br.com.sicoob.cca.cadastro.negocio.servicos.ConfiguracaoCapitalServico#incluirConfiguracaoCapital(br.com.sicoob.cca.entidades.negocio.entidades.ConfiguracaoCapital) */ public void incluirConfiguracaoCapital(ConfiguracaoCapital configuracaoCapital) throws BancoobException { try{ ConfiguracaoCapital configuracaoCapitalAlt = configuracaoCapitalDao.obter(configuracaoCapital.getId()); if(configuracaoCapitalAlt != null){ throw new CadastroContaCapitalNegocioException("MSG_013"); } configuracaoCapitalDao.incluir(configuracaoCapital); } catch (CadastroContaCapitalNegocioException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalNegocioException(e.getMessage()); } catch (BancoobException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalException("MSG_012"); } } /** * @see br.com.sicoob.cca.cadastro.negocio.servicos.ConfiguracaoCapitalServico#alterarConfiguracaoCapital(br.com.sicoob.cca.entidades.negocio.entidades.ConfiguracaoCapital) */ public void alterarConfiguracaoCapital(ConfiguracaoCapital configuracaoCapital) throws BancoobException { try{ configuracaoCapitalDao.alterar(configuracaoCapital); }catch (CadastroContaCapitalNegocioException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalNegocioException(e.getMessage()); }catch (BancoobException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalException("MSG_012"); } } /** * @see br.com.sicoob.cca.cadastro.negocio.servicos.ConfiguracaoCapitalServico#pesquisarProximoSeqConfiguracaoCapital() */ public Integer pesquisarProximoSeqConfiguracaoCapital() throws BancoobException { try{ Integer idConfiguracaoCapital = null; idConfiguracaoCapital = configuracaoCapitalDao.pesquisarProximoSeqConfiguracaoCapital(); return idConfiguracaoCapital; }catch (CadastroContaCapitalNegocioException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalNegocioException(e.getMessage()); }catch (BancoobException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalException("MSG_011"); } } /** * @see br.com.sicoob.cca.cadastro.negocio.servicos.ConfiguracaoCapitalServico#listarConfiguracaoCapital(br.com.bancoob.negocio.dto.ConsultaDto) */ public List<ConfiguracaoCapital> listarConfiguracaoCapital(ConsultaDto<ConfiguracaoCapital> consultaDTO) throws BancoobException { try{ List<ConfiguracaoCapital> lstConfiguracaoCapital = null; lstConfiguracaoCapital = configuracaoCapitalDao.listar(consultaDTO); return lstConfiguracaoCapital; }catch (CadastroContaCapitalNegocioException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalNegocioException(e.getMessage()); }catch (BancoobException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalException("MSG_011"); } } /** * @see br.com.sicoob.cca.cadastro.negocio.servicos.ConfiguracaoCapitalServico#obterConfiguracaoCapital(java.lang.Integer) */ public ConfiguracaoCapital obterConfiguracaoCapital(Integer idConfiguracaoCapital) throws BancoobException { try{ ConfiguracaoCapital configuracaoCapital = null; configuracaoCapital = configuracaoCapitalDao.obter(idConfiguracaoCapital); return configuracaoCapital; }catch (CadastroContaCapitalNegocioException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalNegocioException(e.getMessage()); }catch (BancoobException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalException("MSG_011"); } } /** * @see br.com.sicoob.cca.cadastro.negocio.servicos.ConfiguracaoCapitalServico#consultarConfiguracaoEstatutaria(java.lang.Integer) */ public List<CondicaoEstatutariaDTO> consultarConfiguracaoEstatutaria(Integer idInstituicao) throws BancoobException { try { return configuracaoCapitalDao.consultarConfiguracaoEstatutaria(idInstituicao); } catch (BancoobException e) { this.getLogger().erro(e, e.getMessage()); throw new CadastroContaCapitalException(e); } } }
true
d02aa19498f9b401708649d9bfc63dd6c827d173
Java
mjdr/DC_CNC
/Desktop_java/src/main/java/cnc/commands/Draw.java
UTF-8
594
2.734375
3
[]
no_license
package cnc.commands; import cnc.data.Package; public class Draw extends Command { private boolean value; public Draw(boolean value) { super(); this.value = value; } @Override public cnc.data.Package toPackage() { return value ? new cnc.data.Package(Package.TYPE_RELATIVE, (short) 0, (short) 0, (short) 1) : new cnc.data.Package(Package.TYPE_RELATIVE, (short) 0, (short) 0, (short) 0); } public boolean getValue() { return value; } @Override public String toString() { return "draw("+value+")"; } @Override public Draw copy() { return new Draw(value); } }
true
4d6bcfe7e05c26e47115b85a8dd125a015c28544
Java
guoshijiang/biwork_service
/src/main/java/com/biwork/mapper/AddCoinMapper.java
UTF-8
396
1.820313
2
[]
no_license
package com.biwork.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.biwork.entity.AddCoin; import com.biwork.vo.CoinInfoVo; public interface AddCoinMapper { List<AddCoin> queryCoinInfo(@Param("coinName")String coinName, @Param("coinMark")String coinMark, @Param("contractAddress")String contractAddress); List<CoinInfoVo> queryCoinInfoAll(); }
true
dcb61462de266e30823befb8961973a8961773ac
Java
edgeMonitoring/PlacementCalculator
/src/main/java/com/orange/holisticMonitoring/placement/inputs/Link.java
UTF-8
203
1.523438
2
[]
no_license
package com.orange.holisticMonitoring.placement.inputs; public class Link { public Integer id; public Integer headId; public Integer tailId; public Integer capability; public Integer latency; }
true
7c9cdca9ab12cb371a9191a589a78ae3d07c391d
Java
AAFC-BICoE/dina-base-api
/dina-base-api/src/test/java/ca/gc/aafc/dina/entity/InheritedSuperClass.java
UTF-8
337
1.960938
2
[ "MIT" ]
permissive
package ca.gc.aafc.dina.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.SuperBuilder; import javax.persistence.MappedSuperclass; @Getter @Setter @MappedSuperclass @NoArgsConstructor @SuperBuilder public abstract class InheritedSuperClass { private String Inherited; }
true
cde7a8e6f59ba7d92ea318a3aa512dbdc328e19a
Java
tosektosek/java-for-the-impatient-solutions
/src/com/company/r03_interfejsy_i_wyrazenia_lambda/solutions/s07/LuckySort.java
UTF-8
993
3.734375
4
[]
no_license
package com.company.r03_interfejsy_i_wyrazenia_lambda.solutions.s07; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @author Kamil */ public class LuckySort { public void luckySort(List<String> strings, Comparator<String> comp) { ArrayList<String> result = new ArrayList<>(strings); result.sort(comp); int i = 0; while (!result.equals(strings)){ Collections.shuffle(strings); i++; } System.out.println("Posortowano za " + i + " razem."); } public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("kamil"); list.add("Michal"); list.add("Zygmunt"); list.add("Anna"); list.add("Aniina"); list.add("barbra"); list.add("Nara"); LuckySort luckySort = new LuckySort(); luckySort.luckySort(list, (String::compareTo)); } }
true
8fb8fbb685344fc4920f250f247d2111580ab100
Java
QiyuZ/leetcode-practice
/921. Minimum Add to Make Parentheses Valid.java
UTF-8
708
3.578125
4
[]
no_license
class Solution { public int minAddToMakeValid(String S) { Stack<Character> stack = new Stack<>(); for (char c : S.toCharArray()) { if (c == '(') stack.push(c); else if (c == ')' && (!stack.isEmpty() && stack.peek() == '(')) stack.pop(); else stack.push(')'); } return stack.size(); } } public int minAddToMakeValid(String S) { int left = 0, right = 0; for (int i = 0; i < S.length; ++i) { if (S.charAt(i) == '(') right++; else if (S.charAt(i) == ')' && right > 0) right--; else left++; //right <= 0 说明)过多此时需要( } return left + right; }
true
6f5b50ba203a02a144db07d5cad9d85ed363481d
Java
ShivaKotha07/parallelprojectsall
/src/com/paytm/dao/Customerdao.java
UTF-8
543
1.960938
2
[]
no_license
package com.paytm.dao; import java.util.HashMap; import java.util.List; import com.paytm.model.Account; public interface Customerdao { public boolean createCustomer(Account c); public Account createLogin(String name, String pwd); public float getbalance(Account a); public float creditedbalance(Account a,float amt); public float removedbalance(Account a,float wamt); public float transferedbalance(Account a,float tamt,String phno); public HashMap<Float, String> getTransactions(Account a); public List<Account> getallacc(); }
true
56c1a4b9a399b4d676a78bc35ee954f8ee983520
Java
Taha-Hussain/Android-Scripts
/app/src/main/java/net/mk786110/ubit1/AddActivity.java
UTF-8
4,580
2.109375
2
[]
no_license
package net.mk786110.ubit1; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import net.mk786110.ubit1.Handler.DbHandler; import net.mk786110.ubit1.entity.Profile; import static java.sql.Types.NULL; public class AddActivity extends AppCompatActivity { public static Profile Editprofile; EditText name_edit_text, phone_edit_text, email_edit_text, gender_edit_text, hobby_edit_text, aboutme_edit_text, dateofbirth_edit_text, image_edit_text; Button editButton,insertButton; Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); context=this; name_edit_text = (EditText) findViewById(R.id.name_edit_text); phone_edit_text = (EditText) findViewById(R.id.phone_edit_text); email_edit_text = (EditText) findViewById(R.id.email_edit_text); gender_edit_text = (EditText) findViewById(R.id.gender_edit_text); hobby_edit_text = (EditText) findViewById(R.id.hobby_edit_text); aboutme_edit_text = (EditText) findViewById(R.id.aboutme_edit_text); dateofbirth_edit_text = (EditText) findViewById(R.id.dateofbirth_edit_text); image_edit_text = (EditText) findViewById(R.id.image_edit_text); editButton=(Button) findViewById(R.id.editbutton); insertButton=(Button) findViewById(R.id.insertbutton); if (Editprofile != null) { editButton.setVisibility(View.VISIBLE); insertButton.setVisibility(View.GONE); name_edit_text.setText(Editprofile.getName()); phone_edit_text.setText(Editprofile.getPhone()); hobby_edit_text.setText(Editprofile.getHobby()); gender_edit_text.setText(Editprofile.getGender()); aboutme_edit_text.setText(Editprofile.getAboutme()); email_edit_text.setText(Editprofile.getEmail()); dateofbirth_edit_text.setText(Editprofile.getDob()); } else { name_edit_text.setText(""); phone_edit_text.setText(""); hobby_edit_text.setText(""); gender_edit_text.setText(""); aboutme_edit_text.setText(""); email_edit_text.setText(""); dateofbirth_edit_text.setText(""); } editButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Profile profile = new Profile(); DbHandler dbHandler = new DbHandler(context); profile.setId(Editprofile.getId()); profile.setName(name_edit_text.getText().toString()); profile.setPhone(phone_edit_text.getText().toString()); profile.setEmail(email_edit_text.getText().toString()); profile.setGender(gender_edit_text.getText().toString()); profile.setHobby(hobby_edit_text.getText().toString()); profile.setAboutme(aboutme_edit_text.getText().toString()); profile.setDob(dateofbirth_edit_text.getText().toString()); dbHandler.updateProfile(profile); Intent intent =new Intent(context,MainActivity.class); startActivity(intent); } } ); } public void saveProfile(View view) { Profile profile = new Profile(); DbHandler dbHandler = new DbHandler(this); profile.setName(name_edit_text.getText().toString()); profile.setPhone(phone_edit_text.getText().toString()); profile.setEmail(email_edit_text.getText().toString()); profile.setGender(gender_edit_text.getText().toString()); profile.setHobby(hobby_edit_text.getText().toString()); profile.setAboutme(aboutme_edit_text.getText().toString()); profile.setDob(dateofbirth_edit_text.getText().toString()); long getID = dbHandler.registerProfile(profile); if (getID > 0) { Toast.makeText(this, "Profile Inserted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show(); } } /* public void onClickEdit(View view) { Button editButton=(Button) findViewById(R.id.editbutton); editButton.setVisibility(View.VISIBLE); }*/ }
true
496f462f2e7a48fae699913bf37d383685d10ad6
Java
Madhuri-Ramisetty/javapractice
/javatraining/src/garbagecollection/GarbageDemo.java
UTF-8
485
3.40625
3
[]
no_license
package garbagecollection; public class GarbageDemo { //finalize() is invoked each time before the object is garbage collected and used to perform cleanup processing public void finalize() { System.out.println("object is garbage collected"); } public static void main(String[] args) { GarbageDemo s1=new GarbageDemo(); GarbageDemo s2=new GarbageDemo(); s1=null; s2=null; System.gc();//gc() is to invoke garbage collector to perform cleanup process } }
true
5c76f0668ceb37e357a3b529db5dd976151daa22
Java
Turbots/red-vs-blue
/java-player-solution/src/main/java/io/pivotal/workshop/redvsblue/redplayer/Player.java
UTF-8
953
2.8125
3
[]
no_license
package io.pivotal.workshop.redvsblue.redplayer; public class Player { private Long id; private String name; private Long score; private Team team; public Player() { } public Player(Long id, String name, Long score, Team team) { this.id = id; this.name = name; this.score = score; this.team = team; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getScore() { return score; } public void setScore(Long score) { this.score = score; } public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } public boolean isTeam(Team team) { return this.team == team; } }
true
978861e6bcdc61c9e56df232ea2b1b137d162f31
Java
nwpu043814/wifimaster4.2.02
/WiFi万能钥匙dex1-dex2jar.jar.src/com/wifipay/wallet/common/rpc/RpcService.java
UTF-8
609
1.820313
2
[]
no_license
package com.wifipay.wallet.common.rpc; import com.wifipay.common.net.RpcFactory; public class RpcService { public static <T> T getBgRpcProxy(Class<T> paramClass) { return (T)RpcFactory.create(paramClass, WPRpcInvocationHandler.class, true); } public static <T> T getRpcProxy(Class<T> paramClass) { return (T)RpcFactory.create(paramClass, WPRpcInvocationHandler.class, false); } } /* Location: /Users/hanlian/Downloads/WiFi万能钥匙dex1-dex2jar.jar!/com/wifipay/wallet/common/rpc/RpcService.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
2a8c7a25272319af3759e39c904132ede21168a0
Java
kamiaki/mybatisplus
/src/main/java/com/aki/mybatisplus/MybatisplusApplication.java
UTF-8
663
1.828125
2
[]
no_license
package com.aki.mybatisplus; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.aki.mybatisplus.mapper") public class MybatisplusApplication { private static final Logger logger = LoggerFactory.getLogger(MybatisplusApplication.class); public static void main(String[] args) { SpringApplication.run(MybatisplusApplication.class, args); logger.info("========================启动完毕========================"); } }
true
1a031bd2c9fd4e0d19dfa4efc2d50dfeab2ba69d
Java
enterprisesoftwaresolutions/Building-Microservices-with-Micronaut
/Chapter09/micronaut-petclinic/pet-clinic-concierge/src/main/java/com/packtpub/micronaut/web/rest/client/petowner/VisitResourceClientController.java
UTF-8
1,354
2
2
[ "MIT" ]
permissive
package com.packtpub.micronaut.web.rest.client.petowner; import com.packtpub.micronaut.service.dto.petowner.VisitDTO; import io.micronaut.data.model.Pageable; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.annotation.*; import io.micronaut.tracing.annotation.NewSpan; import javax.inject.Inject; import java.util.List; import java.util.Optional; @Controller("/api") public class VisitResourceClientController { @Inject VisitResourceClient visitResourceClient; @NewSpan @Post("/visits") public HttpResponse<VisitDTO> createVisit(VisitDTO visitDTO) { return visitResourceClient.createVisit(visitDTO); } @NewSpan @Put("/visits") public HttpResponse<VisitDTO> updateVisit(VisitDTO visitDTO) { return visitResourceClient.updateVisit(visitDTO); } @NewSpan @Get("/visits") public HttpResponse<List<VisitDTO>> getAllVisits(HttpRequest request, Pageable pageable) { return visitResourceClient.getAllVisits(request, pageable); } @NewSpan @Get("/visits/{id}") public Optional<VisitDTO> getVisit(Long id) { return visitResourceClient.getVisit(id); } @NewSpan @Delete("/visits/{id}") public HttpResponse deleteVisit(Long id) { return visitResourceClient.deleteVisit(id); } }
true
8c8f2562b56a6d709b6d0813dcc66efe61c4ce62
Java
debop/hibernate-redis
/hibernate-redis-stresser/src/main/java/org/hibernate/stresser/persistence/config/DatabaseConfig.java
UTF-8
2,547
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017. Sunghyouk Bae <sunghyouk.bae@gmail.com> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.hibernate.stresser.persistence.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * @author Johno Crawford (johno@sulake.com) */ @Configuration @PropertySource("classpath:db.properties") public class DatabaseConfig { @Value("${db.url}") private String url; @Value("${db.driver}") private String driver; @Value("${db.user}") private String user; @Value("${db.password}") private String password; /** * "For maximum performance and responsiveness to spike demands, we recommend not setting this value and instead * allowing HikariCP to act as a fixed size connection pool." * * @see <a href="https://github.com/brettwooldridge/HikariCP/wiki/Configuration">https://github.com/brettwooldridge/HikariCP/wiki/Configuration</a> */ @Value("${db.minimumIdle:0}") private int minimumIdle; @Value("${db.maximumPoolSize:20}") private int maximumPoolSize; @Value("${db.idleTimeout:45}") private int idleTimeout; @Value("${db.connectionTimeout:12}") private int connectionTimeout; public String getUrl() { return url; } public String getDriver() { return driver; } public String getUser() { return user; } public String getPassword() { return password; } public int getMinimumIdle() { return minimumIdle; } public int getMaximumPoolSize() { return maximumPoolSize; } public int getIdleTimeout() { return idleTimeout; } public int getConnectionTimeout() { return connectionTimeout; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
true
b23b790f2be22806ed387087733a18e5d0752b51
Java
Team488/TeamXbot2020
/src/main/java/competition/subsystems/internalconveyor/commands/KickerViaTriggerCommand.java
UTF-8
939
2.1875
2
[]
no_license
package competition.subsystems.internalconveyor.commands; import com.google.inject.Inject; import competition.operator_interface.OperatorInterface; import competition.subsystems.internalconveyor.KickerSubsystem; import xbot.common.command.BaseCommand; import xbot.common.math.MathUtils; public class KickerViaTriggerCommand extends BaseCommand { final KickerSubsystem kicker; final OperatorInterface oi; @Inject public KickerViaTriggerCommand(KickerSubsystem kicker, OperatorInterface oi) { this.addRequirements(kicker); this.kicker = kicker; this.oi = oi; } @Override public void initialize() { log.info("Initializing"); } @Override public void execute() { double power = MathUtils.deadband(oi.operatorGamepad.getLeftTrigger(), oi.getJoystickDeadband()); power = MathUtils.constrainDouble(power, 0, 1); kicker.setPower(power); } }
true
29d96a3786978ebf44836de5934caf4760e0e0ef
Java
jordanywhite/SquaresInteractive
/src/resourceManagement/ResourceLoader.java
UTF-8
6,719
3.296875
3
[ "MIT" ]
permissive
package resourceManagement; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; /** * * * @author Caleb Piekstra * */ public class ResourceLoader { ArrayList<File> dirs = null; // A mapping of directory to hashmap of filename to file HashMap<String, HashMap<String, File>> files = null; public ResourceLoader() { // Initialize the file hash map files = new HashMap<String, HashMap<String, File>>(); // Use the file loader to populate an array list of directories FileLoader fileLoader = new FileLoader("res/xml/Textures.xml"); // Save the list of directory files dirs = fileLoader.getDirectories(); // Get the paths to all the directory files ArrayList<String> dirPaths = fileLoader.getFileDirectories(); // Go through each directory path for (String dir : dirPaths) { // Get the name of the directory by extracting the last portion of the file URL String group = GlobalHelper.getLastBitFromUrl(dir); // Create a hash map to hold key value pairs of <filename,file> HashMap<String, File> fileMap = new HashMap<String, File>(); // Using the file loader, get an array list of all files in the current directory (named group) ArrayList<File> fileGroup = fileLoader.createFileGroup(group, ".*"); // Get files of all types // Populate the <filename,file> hash map for (File f : fileGroup) { fileMap.put(f.getName(), f); } // If no files were mapped, continue onto the next directory if (fileMap.isEmpty()) continue; // Populate the <dirName,dirFiles> hash map files.put(group, fileMap); } // Print the number of loaded files to the console System.out.println("Loaded " + files.size() + " resource groups"); } public File getFile(String dir, String fileName) { // Look through all directories for (String key : files.keySet()) { // Check if this directory contains the file we want if (files.get(key).containsKey(fileName)) { // If it contains the file we want, return the file return files.get(key).get(fileName); } } // File not found return null; } public ArrayList<File> getAllFilesInDir(String dir) { // Holds the list of files in the directory ArrayList<File> filesInDir = new ArrayList<File>(); // Look for the directory if (files.containsKey(dir)) { // Get the fileName,File mapping for the directory HashMap<String, File> mapOfDir = files.get(dir); // Populate an array of all the files in the directory for (String fileName : mapOfDir.keySet()) { filesInDir.add(mapOfDir.get(fileName)); } } // Sort the files Collections.sort(filesInDir); // Return the array of files (empty if dir doesn't exist or no files in dir) return filesInDir; } public ArrayList<File> getAllFilesWithExten(String exten) { // Holds the files with the specified extension ArrayList<File> filesWithExten = new ArrayList<File>(); // Go through all directories for (String dirKey : files.keySet()) { // Get the map for the current dir HashMap<String, File> dirMap = files.get(dirKey); // Go through all files in the current dir for (String fileKey : dirMap.keySet()) { // If the file has the requested extension or we are using .* to indicate // a request for any file, then add the file to the array list if (fileKey.endsWith(exten) || exten.equals(".*")) { filesWithExten.add(dirMap.get(fileKey)); } } } // Sort the files Collections.sort(filesWithExten); // Return the list of files with the specified extension (empty if no files found) return filesWithExten; } public ArrayList<File> getAllFilesWithExtenExcluding(String exten, String[] exclude) { // First get all files that have the specified extension ArrayList<File> allFilesWithExten = getAllFilesWithExten(exten); // Go through and remove all files whose paths contain one of the excluded directories for (Iterator<File> fileIterator = allFilesWithExten.iterator(); fileIterator.hasNext();) { File file = fileIterator.next(); for (String excludedDir : exclude) { if (file.getAbsolutePath().contains(excludedDir)) { fileIterator.remove(); } } } // Sort the files Collections.sort(allFilesWithExten); // Return the files return allFilesWithExten; } public ArrayList<File> getAllFilesInDirWithExten(String dir, String exten) { // Get all files and we can filter out by extension ArrayList<File> allFilesInDir = getAllFilesInDir(dir); // .* indicates a request for files of any type if (exten.equals(".*")) { // If they want files of any type, return all files in the directory return allFilesInDir; } // Go through all files in the directory for (Iterator<File> fileIterator = allFilesInDir.iterator(); fileIterator.hasNext();) { File file = fileIterator.next(); // Check if the file does not have the proper extension if (!file.getName().endsWith(exten)) { // Remove it fileIterator.remove(); } } // Sort the files Collections.sort(allFilesInDir); // Return all files in the directory that had the specified extension (empty if none found) return allFilesInDir; } public ArrayList<File> getAllDirs() { // Return a copy of the list of all directory files return new ArrayList<File>(dirs); } public ArrayList<File> getAllDirsExcluding(String[] exclude) { // Get a copy of the list of all directory files ArrayList<File> dirs = getAllDirs(); // Go through the directory files for (Iterator<File> fileIterator = dirs.iterator(); fileIterator.hasNext();) { File file = fileIterator.next(); // Check the directory path against all excluded directories for (String excludedDir : exclude) { // If an excluded directory is somewhere in the current // directory's file path remove the file from the list if (file.getAbsolutePath().contains(excludedDir)) { fileIterator.remove(); } } } // Sort the files Collections.sort(dirs); // Return the list of directory files return dirs; } public ArrayList<File> getAllDirsInDir(String dir) { // Get a copy of the list of all directory files ArrayList<File> dirs = new ArrayList<File>();; // Go through the directory files for (File file : getAllDirs()) { // Get the parent dir String filePath = file.getAbsolutePath(); String parentDir = GlobalHelper.getNthSegmentFromURLEnd(filePath,1); // If an include directory is not somewhere in the current // directory's file path remove the file from the list if (parentDir.equals(dir)) { dirs.add(file); } } // Sort the files Collections.sort(dirs); // Return the list of directory files return dirs; } }
true
86866e57f5a7b465859b9d5f66ca39c41918e641
Java
rsobook/ms-friends
/src/main/java/si/fri/rsobook/service/FriendsBean.java
UTF-8
4,195
1.960938
2
[]
no_license
package si.fri.rsobook.service; import com.kumuluz.ee.discovery.annotations.DiscoverService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.microprofile.faulttolerance.CircuitBreaker; import org.eclipse.microprofile.faulttolerance.Fallback; import org.eclipse.microprofile.faulttolerance.Timeout; import si.fri.rsobook.config.FriendsConfigProperties; import si.fri.rsobook.core.api.ApiConfiguration; import si.fri.rsobook.core.api.ApiCore; import si.fri.rsobook.core.api.client.utility.QueryParamBuilder; import si.fri.rsobook.core.api.data.response.PagingResponse; import si.fri.rsobook.core.api.resource.base.CrudApiResource; import si.fri.rsobook.core.database.dto.Paging; import si.fri.rsobook.core.database.exceptions.BusinessLogicTransactionException; import si.fri.rsobook.core.model.User; import si.fri.rsobook.core.model.UserFriends; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.InternalServerErrorException; import java.net.URL; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.UUID; @RequestScoped public class FriendsBean { private static final Logger LOG = LogManager.getLogger("si.fri.rsobook.rest.FriendsResource"); @Inject private FriendsBean friendsBean; @Inject private FriendsConfigProperties friendsConfigProperties; @Inject private DatabaseService databaseService; @Inject @DiscoverService(value = "ms-user", version = "2.0.x", environment = "dev") private URL url; public List<User> getFriends(UUID id) { List<UUID> ids = getFriendsUUIDs(id); return friendsBean.getResolvedList(ids); } public List<UUID> getFriendsUUIDs(UUID id) { final UUID qId = id; try { Paging<UserFriends> friendsList = databaseService.getList(UserFriends.class, (p, cb, r) -> cb.equal(r.get("userId"), qId)); List<UUID> ids = new ArrayList<>(); for(UserFriends uf : friendsList.getItems()) { ids.add(uf.getFriendsId()); } return ids; } catch (BusinessLogicTransactionException e) { e.printStackTrace(); throw new InternalServerErrorException("Error", e); } } @CircuitBreaker(requestVolumeThreshold = 1) @Fallback(fallbackMethod = "getResolvedListFallback") @Timeout(value = 3, unit = ChronoUnit.SECONDS) public List<User> getResolvedList(List<UUID> ids) { StringBuilder sb = new StringBuilder(); sb.append("["); for(UUID id : ids){ sb.append(id.toString()); sb.append(","); } sb.append("]"); QueryParamBuilder queryParamBuilder = new QueryParamBuilder(); queryParamBuilder.addCond("id:in:" + sb.toString()); String host = friendsConfigProperties.getUserApiHost(); if(friendsConfigProperties.getUserApiHostDiscovery() && url != null) { host = url.toString(); } LOG.info(String.format("Using discovered host: %s", host)); ApiConfiguration config = new ApiConfiguration(String.format("%s/api/v1", host)); ApiCore apiCore = new ApiCore(config, null); CrudApiResource<User> resource = new CrudApiResource<>(apiCore, User.class); try { String query = queryParamBuilder.buildQuery(); PagingResponse<User> response = resource.get(query); if(response.isStatusValid()) { return response.getItems(); } else { throw new InternalServerErrorException("User service is not responding."); } } catch (Exception e) { e.printStackTrace(); throw new InternalServerErrorException("Error processing users.", e); } } public List<User> getResolvedListFallback(List<UUID> ids) { User user = new User(); user.setName("Chuck"); user.setSurname("Norris"); user.setEmail("chuck@norris.com"); List<User> userList = new ArrayList<>(); userList.add(user); return userList; } }
true
0e041ce9e8a3d7c86e3248356413a3fbd99484d0
Java
monyone/library_pandoc
/source/src/main/java/jp/monyone/library/Graph/OfflineLCATarjan_Include.java
UTF-8
1,888
2.84375
3
[]
no_license
package jp.monyone.library.Graph; import static jp.monyone.library.DataStructure.UnionFind_Include.UnionFind; public class OfflineLCATarjan_Include { // スパソあまな感じだけど、このままだと計算量がヤバい // us, vs のループがあるので O(クエリ数 * 木) になっちゃう // https://yukicoder.me/submissions/101078 のように後で直す //@start // DFS で 前順走査(preorder) で 一番近い親を探す. 部分木のマージに, UnionFind を使う . public static void dfs(int[] us, int[] vs, int[] lcas, int node, int parent, boolean[] visited, int[] ancestor, boolean[][] adj, UnionFind uf){ ancestor[uf.find(node)] = node; // 自分の祖先は自分. for(int next = 0; next < adj.length; next++){ if(next == parent){ continue; } if(!adj[node][next]){ continue; } dfs(us, vs, lcas, next, node, visited, ancestor, adj, uf); uf.union(node, next); // next以下のLCAを探索し終えたので, 部分木を併合. ancestor[uf.find(node)] = node; // 併合した祖先は自分(部分木内はもう終えてる) } visited[node] = true; for(int i = 0; i < us.length; i++){ int not_node = -1; // 片方が自分だった時のもう片方が欲しい if(us[i] == node){ not_node = vs[i]; } else if(vs[i] == node){ not_node = us[i]; } if(not_node >= 0 && visited[not_node]){ // 両方とも評価済みかのチェック lcas[i] = ancestor[uf.find(not_node)]; // 両方とも評価済みの場合は一度しかない. } } } // public static int[] offlineLCA(int[] us, int[] vs, boolean[][] adj){ final int n = adj.length; int[] lca_nodes = new int[us.length], ancestor = new int[n]; boolean[] visited = new boolean[n]; UnionFind uf = new UnionFind(n); dfs(us, vs, lca_nodes, 0, -1, visited, ancestor, adj, uf); return lca_nodes; } //@end }
true
aebaaceca28526d5881005af8919e349c5b673db
Java
digirati-co-uk/taxonomy-manager
/taxonomy-manager-rest-server/src/main/java/com/digirati/taxman/rest/server/taxonomy/identity/ConceptSchemeIdResolver.java
UTF-8
459
1.882813
2
[ "MIT", "Apache-2.0" ]
permissive
package com.digirati.taxman.rest.server.taxonomy.identity; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.core.UriInfo; @ApplicationScoped public class ConceptSchemeIdResolver extends AbstractIdResolver { @Inject UriInfo uriInfo; ConceptSchemeIdResolver() { super("/v0.1/concept-scheme/:id:"); } @Override protected UriInfo getUriInfo() { return uriInfo; } }
true
9e42c7075bbe18644622f67bd85fd5e285b4ad2d
Java
SurendraShukla/Java
/learning/src/main/me/surendra/learning/generics/GenericClass.java
UTF-8
390
3.015625
3
[]
no_license
package me.surendra.learning.generics; import java.util.ArrayList; /** * Generics provides Type Safety at compile. Provides Flexibility. */ class GenericClass<T> { // Method belongs to GenericMethodOnly Class so return <T> before return type is not required. public void createArray(T sample){ ArrayList<T> list = new ArrayList<T>(); list.add(sample); } }
true
054eb4b1fe6e7ace6aa359bfdc522249b9d5fc56
Java
demien666/dev-blog
/021-aop-logger/src/main/java/com/demien/aoplogging/TestService.java
UTF-8
358
2.03125
2
[]
no_license
package com.demien.aoplogging; public class TestService { private TestDao dao; public void setDao(TestDao dao) { this.dao = dao; } public void doServiceAction() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } dao.doDaoAction(); } }
true
465d5db04e4799145bef675cf24b594fe488fef3
Java
nisheeth84/prjs_sample
/aio-service/src/main/java/com/viettel/aio/rest/AIOQuestionRsServiceImpl.java
UTF-8
9,402
1.820313
2
[]
no_license
package com.viettel.aio.rest; import com.viettel.aio.business.AIOQuestionBusiness; import com.viettel.aio.business.CommonServiceAio; import com.viettel.aio.dto.AIOQuestionDTO; import com.viettel.aio.dto.AIOResponseForCkeditorDTO; import com.viettel.coms.business.UtilAttachDocumentBusinessImpl; import com.viettel.coms.dto.UtilAttachDocumentDTO; import com.viettel.erp.dto.DataListDTO; import com.viettel.ktts2.common.BusinessException; import com.viettel.ktts2.common.UEncrypt; import com.viettel.ktts2.common.UFile; import com.viettel.ktts2.common.UString; import com.viettel.ktts2.dto.KttsUserSession; import com.viettel.utils.ImageUtil; import com.viettel.wms.business.UserRoleBusinessImpl; import org.apache.commons.lang3.StringUtils; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import javax.activation.DataHandler; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.io.InputStream; import java.util.*; public class AIOQuestionRsServiceImpl implements AIOQuestionRsService { protected final Logger log = Logger.getLogger(AIOQuestionRsServiceImpl.class); private static final String ATTACHMENT_QUESTION_TYPE = "103"; private static final String BASE64_PREFFIX = "data:image/jpeg;base64,"; @Value("${folder_upload2}") private String folderUpload; @Value("${default_sub_folder_upload}") private String defaultSubFolderUpload; @Value("${allow.file.ext}") private String allowFileExt; @Value("${allow.folder.dir}") private String allowFolderDir; @Value("${input_image_sub_folder_upload}") private String input_image_sub_folder_upload; @Autowired private AIOQuestionBusiness aioQuestionBusiness; @Autowired private UtilAttachDocumentBusinessImpl attachmentBusiness; @Autowired private CommonServiceAio commonService; @Autowired private UserRoleBusinessImpl userRoleBusiness; @Context private HttpServletRequest request; private Response buildErrorResponse(String message) { return Response.ok().entity(Collections.singletonMap("error", message)).build(); } @Override public Response doSearch(AIOQuestionDTO obj) { DataListDTO data = new DataListDTO(); data.setData(aioQuestionBusiness.doSearch(obj)); data.setTotal(obj.getTotalRecord()); data.setSize(obj.getPageSize()); data.setStart(1); return Response.ok(data).build(); } @Override public Response remove(AIOQuestionDTO obj) { try { AIOQuestionDTO chkObj = (AIOQuestionDTO) aioQuestionBusiness.getOneById(obj.getQuestionId()); if (chkObj == null) { return this.buildErrorResponse("Bản ghi không tồn tại"); } if (chkObj.getStatus().equals(AIOQuestionDTO.STATUS_DELETED)) { return this.buildErrorResponse("Bản ghi đã bị thay đổi."); } KttsUserSession userSession = (KttsUserSession) request.getSession().getAttribute("kttsUserSession"); aioQuestionBusiness.remove(obj.getQuestionId(), userSession.getSysUserId()); return Response.ok(Response.Status.OK).build(); } catch (BusinessException e) { log.error(e); return this.buildErrorResponse(e.getMessage()); } catch (Exception e) { log.error(e); return this.buildErrorResponse("Có lỗi xảy ra!"); } } @Override public Response insertOrUpdate(AIOQuestionDTO obj) { try { KttsUserSession userSession = (KttsUserSession) request.getSession().getAttribute("kttsUserSession"); Long questionId = obj.getQuestionId(); if (questionId != null) { AIOQuestionDTO chkObj = (AIOQuestionDTO) aioQuestionBusiness.getOneById(questionId); if (chkObj == null) { return this.buildErrorResponse("Bản ghi không tồn tại"); } if (chkObj.getStatus().equals(AIOQuestionDTO.STATUS_DELETED)) { return this.buildErrorResponse("Bản ghi đã bị thay đổi."); } obj.setUpdatedUser(userSession.getSysUserId()); obj.setUpdatedDate(new Date()); aioQuestionBusiness.update(obj); } else { obj.setStatus(AIOQuestionDTO.STATUS_ACTICE); obj.setCreatedUser(userSession.getSysUserId()); obj.setCreatedDate(new Date()); questionId = aioQuestionBusiness.save(obj); } for (UtilAttachDocumentDTO img : obj.getImages()) { UtilAttachDocumentDTO ckImg = (UtilAttachDocumentDTO) attachmentBusiness.getOneById(img.getUtilAttachDocumentId()); ckImg.setObjectId(questionId); attachmentBusiness.update(ckImg); } return Response.ok(Response.Status.OK).build(); } catch (BusinessException e) { log.error(e); return this.buildErrorResponse(e.getMessage()); } catch (Exception e) { log.error(e); return this.buildErrorResponse("Có lỗi xảy ra!"); } } @Override public Response uploadImage(Attachment attachment) { AIOResponseForCkeditorDTO res = new AIOResponseForCkeditorDTO(); try { KttsUserSession userSession = userRoleBusiness.getUserSession(request); MultivaluedMap<String, String> map = attachment.getHeaders(); String fileName = UFile.getFileName(map); if (StringUtils.isEmpty(fileName)) { HashMap<String, String> err = new HashMap<>(); err.put("message", "File bị lỗi"); res.setError(err); res.setUploaded(0); return Response.ok(res).build(); } DataHandler dataHandler = attachment.getDataHandler(); if (!UString.isExtendAllowSave(fileName, allowFileExt)) { throw new BusinessException("File extension khong nam trong list duoc up load, file_name:" + fileName); } InputStream inputStream = dataHandler.getInputStream(); String filePath = UFile.writeToFileServerATTT2(inputStream, fileName, input_image_sub_folder_upload, folderUpload); UtilAttachDocumentDTO attachmentDTO = new UtilAttachDocumentDTO(); attachmentDTO.setCreatedDate(new Date()); attachmentDTO.setCreatedUserId(userSession.getSysUserId()); attachmentDTO.setCreatedUserName(userSession.getFullName()); attachmentDTO.setType(ATTACHMENT_QUESTION_TYPE); attachmentDTO.setFilePath(filePath); attachmentDTO.setName(fileName); String base64Image = ImageUtil.convertImageToBase64(folderUpload + filePath); attachmentDTO.setBase64String(base64Image); res.setAttachmentId(attachmentBusiness.save(attachmentDTO)); res.setUrl(BASE64_PREFFIX + base64Image); res.setFileName(fileName); res.setUploaded(1); return Response.ok(res).build(); } catch (Exception e) { HashMap<String, String> err = new HashMap<>(); err.put("message", e.getMessage()); res.setError(err); res.setUploaded(0); return Response.ok(res).build(); } } @Override public Response getImages(Long questionId) { try { List<UtilAttachDocumentDTO> dtos = commonService.getListAttachmentByIdAndType(questionId, ATTACHMENT_QUESTION_TYPE); for (UtilAttachDocumentDTO dto : dtos) { String base64Image = ImageUtil.convertImageToBase64(UEncrypt.decryptFileUploadPath(dto.getFilePath())); dto.setBase64String(BASE64_PREFFIX + base64Image); } return Response.ok(dtos).build(); } catch (Exception e) { log.error(e); return this.buildErrorResponse("Có lỗi xảy ra!"); } } @Override public Response importExcel(Attachment attachment) { try { String filePath = commonService.uploadToServer(attachment, request); List<AIOQuestionDTO> result = aioQuestionBusiness.doImportExcel(filePath); if (result != null && !result.isEmpty() && (result.get(0).getErrorList() == null || result.get(0).getErrorList().size() == 0)) { aioQuestionBusiness.saveList(result); return Response.ok(result).build(); } else if (result == null || result.isEmpty()) { return Response.ok().entity(Response.Status.NO_CONTENT).build(); } else { return Response.ok(result).build(); } } catch (BusinessException e) { log.error(e); return this.buildErrorResponse(e.getMessage()); } catch (Exception e) { log.error(e); return this.buildErrorResponse("Có lỗi xảy ra!"); } } }
true
0ce8fb165a9211c731e339b39c29a32089d80954
Java
aimms321/house
/house-biz/src/main/java/com/project/house/biz/service/RecommendService.java
UTF-8
2,190
2.3125
2
[]
no_license
package com.project.house.biz.service; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.project.house.common.model.House; import com.project.house.common.page.PageData; import com.project.house.common.page.PageParams; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service public class RecommendService { @Value("${spring.redis.host}") private String server; @Value("${spring.redis.password}") private String password; @Autowired private HouseService houseService; private static final String HOT_HOUSE_KEY = "hot_house"; public void increase(Long id) { Jedis jedis = new Jedis(server); jedis.auth(password); jedis.zincrby(HOT_HOUSE_KEY, 1.0D, id + ""); jedis.zremrangeByRank(HOT_HOUSE_KEY, 10, -1); jedis.close(); } public List<Long> getHot() { Jedis jedis = new Jedis(server); jedis.auth(password); Set<String> idSet = jedis.zrevrange(HOT_HOUSE_KEY, 0, -1); List<Long> ids = idSet.stream().map(Long::parseLong).collect(Collectors.toList()); return ids; } public List<House> getHotHouse(Integer size) { House query = new House(); List<Long> list = getHot(); list = list.subList(0, Math.min(size, list.size())); if (list.isEmpty()) { return Lists.newArrayList(); } query.setIds(list); List<House> houseList = houseService.queryHouse(query, PageParams.bulid(1, size)).getList(); final List<Long> order = list; Ordering<House> houseSort=Ordering.natural().onResultOf(hs-> { return order.indexOf(hs.getId()); }); return houseSort.sortedCopy(houseList); } public List<House> getLastest() { House query = new House(); query.setSort("time_desc"); return houseService.queryHouse(query, PageParams.bulid(1, 8)).getList(); } }
true
9421b08726548a7901f1973d44921d31489cc80d
Java
jep7453/SWEN-262-Group-B
/src/Command/PurchaseBook.java
UTF-8
1,743
3.375
3
[]
no_license
package Command; import Library.*; import java.lang.reflect.Array; import java.util.ArrayList; public class PurchaseBook implements Command { private int quantity; private ArrayList<Integer> books; private Library library; /** * Constructor for PurchaseBook commands * @param library * @param quantity amount of each book to buy * @param books list of books to buy by ID from previous BookStoreSearch */ public PurchaseBook(Library library, int quantity, ArrayList<Integer> books) { this.quantity = quantity; this.books = books; this.library=library; } /** * Command execute function * Adds books to the library catalog from the specified ID from the last BookStoreSearch */ public String execute() { ArrayList<Book> bookLibrary = new ArrayList<>(library.getBookCollection().values()); ArrayList<Book> bookStore = library.getStoreSearch(); ArrayList<Book> purchased= new ArrayList<Book>(); for(Integer book : books) { Book storeBook = bookStore.get(book-1); purchased.add(storeBook); storeBook.addCopies(quantity); if(!bookLibrary.contains(storeBook)) { library.getBookCollection().put(storeBook.getTitle(),storeBook); } } String returnSting ="purchase,success,"+purchased.size()+'\n'; System.out.println("purchase,success,"+purchased.size()); for(Book purchasedBook: purchased) { returnSting = returnSting + purchasedBook + "," + String.valueOf(quantity)+ '\n'; System.out.println(purchasedBook + "," + String.valueOf(quantity)); } return returnSting; } }
true
92355f60f6b9e18425550a0fd93ccb14fea23433
Java
lpppph/lp-demo
/lp-springboot-spel/src/main/java/com/cn/lp/domain/MathEx.java
UTF-8
16,460
3.546875
4
[ "Apache-2.0" ]
permissive
package com.cn.lp.domain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ThreadLocalRandom; /** * 数学工具类 */ public class MathEx { private static Logger LOGGER = LoggerFactory.getLogger(MathEx.class); /** * 转Int * * @param number * @return */ public static Integer toInt(final Number number) { return number.intValue(); } /** * 转Long * * @param number * @return */ public static Long toLong(final Number number) { return number.longValue(); } /** * 转Double * * @param number * @return */ public static Double toDouble(final Number number) { return number.doubleValue(); } /** * 转Float * * @param number * @return */ public static Float toFloat(final Number number) { return number.floatValue(); } /** * 转Byte * * @param number * @return */ public static Byte toByte(final Number number) { return number.byteValue(); } /** * a 的 b 次幂 * * @param a * @param b * @return */ public static int toPow(int a, int b) { return (int) Math.pow(a, b); } /** * 开平方根 * * @param a * @return */ public static int toSqrt(int a) { return (int) Math.sqrt(a); } /** * 获取 0 到 number - 1 的随机数 * * @param number * @return */ public static int rand(final int number) { return ThreadLocalRandom.current().nextInt(number); } private static class RandomItem implements Comparable<RandomItem> { private Object object; private int value; public RandomItem(Object object, int value) { this.object = object; this.value = value; } public Object getObject() { return this.object; } public int getValue() { return this.value; } @Override public int compareTo(RandomItem o) { return (this.value - o.getValue()) * -1; } @Override public String toString() { return this.object + ":" + this.value; } } /** * 抽签 (权重) * 参数: [权重1, 返回值1, 权重2, 返回值2, .... 权重n, 返回值n] 如[1,"a",2,"b"] * 在 权重为1的"a" 和 权重为2的"b" 的范围内进行抽签 * 返回抽中的"a"或"b" * * @param randomItemList 内容 * @return */ public static Object lot(List<Object> randomItemList) { List<RandomItem> itemList = new ArrayList<RandomItem>(); int number = 0; for (int index = 0; index < randomItemList.size(); index = index + 2) { Integer value = (Integer) randomItemList.get(index); Object object = randomItemList.get(index + 1); number += value; itemList.add(new RandomItem(object, number)); } int value = ThreadLocalRandom.current().nextInt(number); for (RandomItem item : itemList) { if (value < item.getValue()) { return item.getObject(); } } return null; } /** * 随机获取对象 * 参数: [100:"a", 200:"b"] * 抽中"a"的范围为 0-99 * 抽中"b"的范围为 100-199 * 返回抽中的"a"或"b" 若无对象抽中返回 null * * @param number 随机范围 * @param randomItemList 随机内容 * @return */ public static Object rand(final int number, List<Object> randomItemList) { return rand(number, randomItemList, null); } /** * 随机获取对象 * 参数: [100:"a", 200:"b"] * 抽中"a"的范围为 0-99 * 抽中"b"的范围为 100-199 * 返回抽中的"a"或"b" 若无对象抽中返回 defaultObject * * @param number 随机范围 * @param randomItemList 随机内容 * @param defaultObject 随机不到对象 返回的默认值 * @return */ public static Object rand(final int number, List<Object> randomItemList, Object defaultObject) { List<RandomItem> itemList = new ArrayList<RandomItem>(); for (int index = 0; index < randomItemList.size(); index = index + 2) { Integer value = (Integer) randomItemList.get(index); Object object = randomItemList.get(index + 1); itemList.add(new RandomItem(object, value)); } Collections.sort(itemList); int value = ThreadLocalRandom.current().nextInt(number); for (RandomItem item : itemList) { if (value < item.getValue()) { return item.getObject(); } } return defaultObject; } /** * 随机获取对象(存在Key重复问题) * 参数: [100:"a", 200:"b"] * 抽中"a"的范围为 0-99 * 抽中"b"的范围为 100-199 * 返回抽中的"a"或"b" 若无对象抽中返回 null * * @param number 随机范围 * @param randomMap 随机内容 * @return */ public static Object rand(final int number, Map<Integer, Object> randomMap) { return rand(number, randomMap, null); } /** * 随机获取对象(存在Key重复问题) * 参数: [100:"a", 200:"b"] * 抽中"a"的范围为 0-99 * 抽中"b"的范围为 100-199 * 返回抽中的"a"或"b" 若无对象抽中返回 defaultObject * * @param number 随机范围 * @param randomMap 随机内容 * @param defaultObject 随机不到对象 返回的默认值 * @return */ public static Object rand(final int number, Map<Integer, Object> randomMap, Object defaultObject) { int value = ThreadLocalRandom.current().nextInt(number); SortedMap<Integer, Object> sortedMap = new TreeMap<Integer, Object>(randomMap); for (Entry<Integer, Object> entry : sortedMap.entrySet()) { if (value < entry.getKey()) { return entry.getValue(); } } return defaultObject; } /** * @return 随机 from 到 to 范围的随机数 */ public static int rand(final int from, final int to) { if (to < from) { throw new IllegalArgumentException("to : " + to + " < " + "from : " + from); } return MathEx.rand((to - from) + 1) + from; } /** * 限制time次出num个数量的随机器 * * @param time 监控次数 * @param num 监控次数出现的num * @param prob 随机概率 * @param currentTime 当前次数 * @param currentNum 当前出现数量 * @return 是否出现 */ public static boolean randLimited(int time, int num, int prob, int currentTime, int currentNum) { return randLimited(time, num, prob, 0, currentTime, currentNum); } /** * 限制time次出num个数量的随机器 * * @param time 监控次数 * @param num 监控次数出现的num * @param timesProbsMap 随机概率列表 * @param currentTime 当前次数 * @param currentNum 当前出现数量 * @return 是否出现 */ public static boolean randLimited(int time, int num, Map<Integer, Integer> timesProbsMap, int currentTime, int currentNum) { return randLimited(time, num, timesProbsMap, 0, currentTime, currentNum); } /** * 限制time次出num个数量的随机器 * * @param time 监控次数 * @param num 监控次数出现的num * @param timesProbsMap n次的概率列表 {3:30, 9:20, 20:10000} 没伦监控第n次概率 * @param extra 额外次数 够监控次数后的额外次数 * @param currentTime 当前次数 * @param currentNum 当前出现数量 * @return 是否出现 */ public static boolean randLimited(int time, int num, Map<Integer, Integer> timesProbsMap, int extra, int currentTime, int currentNum) { int certainly = checkCertainly(time, num, extra, currentTime, currentNum); boolean drop = false; if (certainly == 0) { int moreTime = currentTime % time; Integer prob = null; SortedMap<Integer, Integer> sortedMap = null; if (timesProbsMap instanceof SortedMap) { sortedMap = (SortedMap<Integer, Integer>) timesProbsMap; } else { sortedMap = new TreeMap<Integer, Integer>(timesProbsMap); } for (Entry<Integer, Integer> entry : sortedMap.entrySet()) { if (moreTime < entry.getKey()) { prob = entry.getValue(); break; } } if (prob == null) { prob = sortedMap.lastKey(); } int randValue = rand(0, 10000); drop = randValue < prob; } else { drop = certainly > 0; } if (LOGGER.isDebugEnabled()) { } return drop; } /** * 限制time次出num个数量的随机器 * * @param time 监控次数 * @param num 监控次数出现的num * @param extra 额外次数 够监控次数后的额外次数 * @param currentTime 当前次数 * @param currentNum 当前出现数量 * @return 是否出现 */ private static int checkCertainly(int time, int num, int extra, int currentTime, int currentNum) { int validNum = ((currentTime / time) + 1) * num; int moreTime = currentTime % time; if (LOGGER.isDebugEnabled()) { } if (currentNum < validNum) { if (moreTime >= (time - num)) { return 1; } } else if (currentNum >= validNum + extra) { return -1; } return 0; } /** * 限制time次出num个数量的随机器 * * @param time 监控次数 * @param num 监控次数出现的num * @param prob 随机概率 * @param extra 额外次数 够监控次数后的额外次数 * @param currentTime 当前次数 * @param currentNum 当前出现数量 * @return 是否出现 */ public static boolean randLimited(int time, int num, int prob, int extra, int currentTime, int currentNum) { int certainly = checkCertainly(time, num, extra, currentTime, currentNum); boolean drop = false; if (certainly == 0) { int randValue = rand(0, 10000); drop = randValue < prob; } else { drop = certainly > 0; } if (LOGGER.isDebugEnabled()) { } return drop; } /** * 随机字符串 * * @param src * @param length * @return */ public static String randKey(String src, int length) { StringBuilder builder = new StringBuilder(length); ThreadLocalRandom random = ThreadLocalRandom.current(); for (int index = 0; index < length; index++) { int srcIndex = random.nextInt(src.length()); builder.append(src.charAt(srcIndex)); } return builder.toString(); } /** * 限制value的值在min和max之间, 如果value小于min,返回min。 如果value大于max,返回max,否则返回value * * @param value * @param minValue * @param maxValue * @return */ public static int clamp(int value, int minValue, int maxValue) { return Math.min(Math.max(minValue, value), maxValue); } public static int sumNum(int startNum, int endNum) { int sumNum = 0; for (int num = startNum; num <= endNum; num++) { sumNum = sumNum + num; } return sumNum; } public static void main(String[] args) { List<Integer> dataList = new ArrayList<>(); dataList.add(12); dataList.add(1); dataList.add(12); dataList.add(12); System.out.println(sumNum(0, 9)); System.out.println(compareBigger(1, 45, 22)); System.out.println(MathEx.class.getPackage().getName()); // final int timePerRound = 50; // final int allTime = 100; // int currentTime = 0; // int currentNum = 0; // Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // map.put(25, 500); // map.put(40, 3000); // map.put(50, 9000); // for (int index = 0; index < allTime; index++) { // boolean ok = false; // if (randLimited(timePerRound, 10, map, 0, currentTime, currentNum)) { // currentNum++; // ok = true; // } // System.out.println(currentTime + " 次 ==> " + (ok ? 'O' : 'X') + " = " + currentNum); // if (index % timePerRound == (timePerRound - 1)) { // System.out.println(currentTime + " 临界值 " + " = " + currentNum); // } // currentTime++; // } } /** * 是否是奇数 * * @param number * @return */ public static boolean isOddNumber(Number number) { return number.longValue() % 2 != 0; } /** * 是否是偶数 * * @param number * @return */ public static boolean isEvenNumber(Number number) { return number.longValue() % 2 == 0; } /** * 首尾比对 * * @param dataList 偶数队列 * @param index 从1开始,小于队列的一半 * @return 1 首大于尾, -1 首小于尾, 0 首等于尾 */ public static int foreAndAftAlignment(List<? extends Number> dataList, int index) { if (dataList == null || dataList.isEmpty() || isOddNumber(dataList.size())) { throw new RuntimeException("队列不能为空或者为奇数"); } if (index <= 0 || index > dataList.size() / 2) { throw new RuntimeException("序号超过边界"); } Number foreNum = dataList.get(index - 1); Number aftNum = dataList.get(dataList.size() - index); if (foreNum.doubleValue() > aftNum.doubleValue()) { return 1; } else if (foreNum.doubleValue() < aftNum.doubleValue()) { return -1; } else { return 0; } } /** * 顺位数量 * * @param dataList 数列 * @param digital 数位, 个位(1) 百位(2) * @return */ public static int sequenceNum(List<? extends Number> dataList, int digital) { int num = 1; int maxNum = 1; long nextSign = -1; for (Number data : dataList) { long sign = data.longValue() % (digital * 10); if (sign == nextSign) { num = num + 1; } else { if (num > maxNum) { maxNum = num; } num = 1; } nextSign = (sign + 1) % (digital * 10); } return num > maxNum ? num : maxNum; } /** * 重复数量 * * @param dataList * @return */ public static int duplicateNum(List<? extends Number> dataList) { Map<Number, Integer> dataMap = new HashMap<>(); int maxNum = 0; for (Number data : dataList) { Integer num = dataMap.get(data); if (num != null) { num = num + 1; } else { num = 0; } if (num > maxNum) { maxNum = num; } dataMap.put(data, num); } return maxNum; } public static boolean compareBigger(int startNum, int endNum, int targetNum) { int total = endNum - startNum + 1; int index = 1; for (int num = startNum; num <= endNum; num++) { if (targetNum == num) { if (index <= total / 2) { return false; } else { return true; } } index++; } throw new IllegalArgumentException(targetNum + "不在" + startNum + "和" + endNum + "之间"); } }
true
1932ee68ab8756f298ca6760e5896b35cbbce0bb
Java
opurie/TextTransformer
/src/main/java/pl/put/poznan/transformer/logic/WrapExpressionTransformer.java
UTF-8
1,750
2.90625
3
[]
no_license
package pl.put.poznan.transformer.logic; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class that replaces expressions with abbreviations */ public class WrapExpressionTransformer implements TextTransformerInterface { private final TextTransformerInterface decorator; public WrapExpressionTransformer(TextTransformerInterface decorator) { this.decorator = decorator; } private static final Map<String, String> expressionsMap = new HashMap<>() {{ put("na przykład", "np."); put("doktor", "dr"); put("magister", "mgr"); put("profesor", "prof."); put("inżynier", "inż."); put("dyrektor", "dyr"); put("pułkownik", "płk"); put("major", "mjr"); put("generał", "gen."); put("i tak dalej", "itd."); put("i tym podobne", "itp."); put("Szanowny Pan/Szanowna Pani", "Sz.P."); put("Szanowna Pani", "Sz.P."); put("Szanowny Pan", "Sz.P."); put("centymetrów", "cm"); put("ciąg dalszy nastąpi.", "c.d.n."); put("zaraz wracam", "zw"); put("w sumie", "wsm"); }}; /** * @param text string to be transformed * @return string with abbreviations */ @Override public String transform(String text) { text = decorator.transform(text); for (String exp : expressionsMap.keySet()) { String pat = "\\b" + exp + "\\b"; Pattern expPattern = Pattern.compile(pat, Pattern.CASE_INSENSITIVE); Matcher matcher = expPattern.matcher(text); text = matcher.replaceAll(expressionsMap.get(exp)); } return text; } }
true
bed3ad6c91ef85c521c961fe4a25be1ec7e9c9bb
Java
amandaatt/SiteBlog
/src/java/gerenciador/beans/Usuario.java
UTF-8
1,992
2.609375
3
[]
no_license
package gerenciador.beans; /** * * @author Amanda e Gabriel */ public class Usuario { private String nome; private String email; private String senha; private String nascimento; private String endereco; private String c; private String uf; private Boolean nivel; public Usuario(String email, String senha, String nascimento, String endereco, String uf, String cidade, Boolean nivel, String nome) { this.nome = nome; this.email = email; this.senha = senha; this.nascimento = nascimento; this.endereco = endereco; this.uf = uf; this.c = cidade; this.nivel = nivel; } public Usuario() { } public String getC() { return c; } public void setC(String cidade) { this.c= cidade; } public String getUf() { return uf; } public void setUf(String uf) { this.uf = uf; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getNascimento() { return nascimento; } public void setNascimento(String nascimento) { this.nascimento = nascimento; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public Boolean getNivel() { return nivel; } public void setNivel(Boolean nivel) { this.nivel = nivel; } public boolean validarSenha(String senha1, String senha2) { if(senha1.equals(senha2)){ return true; } return false; } }
true
3d7c23ffd74381003d743130fe531c4d0b6d0f1e
Java
BlackAce21/SendToSpawn
/src/com/blackace/sendtospawn/SendToSpawn.java
UTF-8
609
2.078125
2
[]
no_license
package com.blackace.sendtospawn; import com.blackace.sendtospawn.commands.CommandSendToSpawn; import com.blackace.sendtospawn.listeners.PlayerListener; import org.bukkit.plugin.java.JavaPlugin; /** * Created by Black Ace on 11/10/2015. */ public class SendToSpawn extends JavaPlugin { public static SendToSpawn instance; PlayerListener playerListener; @Override public void onEnable(){ instance = this; playerListener = new PlayerListener(); this.getCommand("sts").setExecutor(new CommandSendToSpawn()); } @Override public void onDisable(){ } }
true
e1589389dd46a7216002c9e7d85d99279c9cae4e
Java
ichinna/essentia
/secureutils/AES.java
UTF-8
5,668
3.0625
3
[]
no_license
import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.Key; import java.util.Arrays; import java.util.Base64; public class AES { private static final String algorithm = "AES/CBC/PKCS5Padding"; private static final String AES = "AES"; private static final String encoding = "UTF-8"; private static final int VERSION_SIZE = 1; private static final int IV_SIZE = 16; private static final byte VERSION_NO_IV = 0x02; private static final byte VERSION = 0x03; private static final String UTF_8 = "UTF-8"; private String encode64(byte[] binaryData) { return Base64.getEncoder().encodeToString(binaryData); } private byte[] decode64(String encoded) throws Exception { return Base64.getDecoder().decode(encoded.getBytes(UTF_8)); } /** * Return a byte array that holds Version(first byte), IV (1-16 bytes inclusive), and Encrypted data (rest of the * bytes) * @param cipher * @param data * @return * @throws SecurityException */ private byte[] encrypt(Cipher cipher, byte[] data) throws SecurityException { if (data == null) { return null; } byte[] iv = cipher.getIV(); int ivSize = IV_SIZE; byte version = VERSION; final int offset = VERSION_SIZE + ivSize; final int outputSize = cipher.getOutputSize(data.length); final byte[] output = new byte[outputSize + offset]; int length; try { cipher.doFinal(data, 0, data.length, output, offset); output[0] = version; if (ivSize > 0) { System.arraycopy(iv, 0, output, VERSION_SIZE, ivSize); } return output; } catch (SecurityException e) { throw e; } catch (Exception e) { throw new SecurityException(e); } } private Cipher encryptingCipher(final Key key) throws SecurityException { try { Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher; } catch (SecurityException e) { throw e; } catch (Exception e) { throw new SecurityException(e); } } private byte[] encrypt(Key key, byte[] data) throws SecurityException { return encrypt(encryptingCipher(key), data); } private String encryptString(Key key, String data) throws SecurityException { try { if (data == null) { return null; } if (data.isEmpty()) { return data; } return encode64(encrypt(key, data.getBytes(encoding))); } catch (Exception e) { throw new SecurityException(e); } } private Cipher decryptingCipher(final Key key, final byte[] iv) throws SecurityException { try { Cipher cipher = Cipher.getInstance(algorithm); if (iv == null) { cipher.init(Cipher.DECRYPT_MODE, key); } else { cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); } return cipher; } catch (SecurityException e) { throw e; } catch (Exception e) { throw new SecurityException(e); } } private byte[] rawDecrypt(Key key, byte[] encrypted) throws SecurityException { if (encrypted == null) { return null; } if (encrypted.length == 0) { return encrypted; } if (encrypted.length < VERSION_SIZE) { throw new IllegalArgumentException("given data has no version."); } int offset; if (encrypted[0] == VERSION) { offset = VERSION_SIZE + IV_SIZE; } else if (encrypted[0] == VERSION_NO_IV) { offset = VERSION_SIZE; } else { throw new IllegalArgumentException("Unknown version " + encrypted[0]); } if (encrypted.length <= offset) { throw new IllegalArgumentException("given data is incomplete"); } byte[] iv = offset == VERSION_SIZE ? null : Arrays.copyOfRange(encrypted, VERSION_SIZE, offset); try { final Cipher cipher; cipher = decryptingCipher(key, iv); return cipher.doFinal(encrypted, offset, encrypted.length - offset); } catch (SecurityException e) { throw e; } catch (Exception e) { throw new SecurityException(e); } } private String decryptOnlyString(Key key, String encrypted) throws SecurityException { try { if (encrypted == null) { return null; } if (encrypted.isEmpty()) { return encrypted; } return new String(rawDecrypt(key, decode64(encrypted)), encoding); } catch (Exception e) { throw new SecurityException(e); } } private String decryptString(Key key, String encrypted) throws SecurityException { try { return decryptOnlyString(key, encrypted); } catch (Exception e) { throw new RuntimeException("Failed to decrypt"); } } public static void main(String[] args) { try { String secret = "12345678901234567890123456789012"; String input = "testemail@ce.com|testCompanyAlias"; Key key = new SecretKeySpec(secret.getBytes(UTF_8), AES); AES aes = new AES(); String encrypted = aes.encryptString(key, input); String decrypted = aes.decryptString(key, encrypted); //Test System.out.println(input.equalsIgnoreCase(decrypted)); } catch (Exception e) { e.printStackTrace(); } } }
true
65ca041b88ab1c9ede7e80996abe81bc69589439
Java
nathantippy/GreenLightning
/greenlightning/src/main/java/com/javanut/LightningRod.java
UTF-8
823
1.96875
2
[ "BSD-3-Clause" ]
permissive
package com.javanut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.javanut.gl.api.ArgumentParser; import com.javanut.gl.api.GreenRuntime; import com.javanut.gl.test.ParallelClientLoadTester; import com.javanut.gl.test.ParallelClientLoadTesterConfig; import com.javanut.gl.test.ParallelClientLoadTesterPayload; public class LightningRod { static final Logger logger = LoggerFactory.getLogger(GreenLightning.class); public static void main(String[] args) { ArgumentParser parser = new ArgumentParser(args); ParallelClientLoadTesterConfig config = new ParallelClientLoadTesterConfig(parser); ParallelClientLoadTesterPayload payload = new ParallelClientLoadTesterPayload(parser); GreenRuntime.run(new ParallelClientLoadTester(config, payload), args); } }
true
65a2ba2eb62cdc0c55752b20f884d7f430c02a15
Java
WangYi0220/gx-community
/community-student/src/main/java/com/gx/community/controller/PostJobTabController.java
UTF-8
1,787
1.984375
2
[]
no_license
package com.gx.community.controller; import com.github.pagehelper.PageInfo; import com.gx.community.pojo.JobPost; import com.gx.community.service.PostJobTabService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author :WangYi * @date :Created in 2019/4/14 21:05 * @description:就业贴操作 * @modified By: */ @RestController @RequestMapping("/post/job") @Api(tags = "就业贴操作接口(xyy)") public class PostJobTabController { @Autowired private PostJobTabService postJobTabService; @ApiOperation("查询全部就业列表") @GetMapping("/get/{nextPage}") public PageInfo<Map<String,Object>> queryJobPost(@PathVariable("nextPage") int nextPage) { return postJobTabService.queryJobPost(nextPage); } @ApiOperation("帖子详情") @GetMapping("/get/job/post/{jobUUID}") public JobPost queryJobPostByJobUUID(@PathVariable("jobUUID") String jobUUID) { return postJobTabService.queryJobPostByJobUUID(jobUUID); } @ApiOperation("根据行业查询就业贴") @GetMapping("/get/industryID/job/post/{industryID}/{nextPage}") public PageInfo<Map<String,Object>> queryJobPostByIndustryID(@PathVariable("industryID") int industryID,@PathVariable("nextPage") int nextPage) { return postJobTabService.queryJobPostByIndustryID(industryID,nextPage); } @ApiOperation("模糊查询就业贴") @PostMapping("/get/like/job/post") public PageInfo<Map<String,Object>> queryJobPostLikePostName(String postName, int nextPage) { return postJobTabService.queryJobPostLikePostName(postName,nextPage); } }
true
16df7ca68ef13882c0fc222821c655d367dcf149
Java
cmpe272group26/funontherun
/funontherun/src/com/funontherun/entities/Concert.java
UTF-8
4,826
2.296875
2
[]
no_license
package com.funontherun.entities; import org.json.JSONArray; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; public class Concert implements Entitiy, Parcelable { private String title; private String artist; private String venue; private String address; private String StartDate; private String website; private double lattitude; private double longitude; public Concert() { } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public String getVenue() { return venue; } public void setVenue(String venue) { this.venue = venue; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getStartDate() { return StartDate; } public void setStartDate(String startDate) { StartDate = startDate; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public double getLattitude() { return lattitude; } public void setLattitude(double lattitude) { this.lattitude = lattitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } @Override public JSONObject serializeJSON() throws Exception { return null; } /** * Method used to deserialize json for Weather object */ @Override public void deserializeJSON(JSONObject jsonObject) throws Exception { this.setTitle(jsonObject.has("title") ? jsonObject.getString("title") : ""); StringBuffer artists = new StringBuffer(""); JSONObject artistObject = jsonObject.getJSONObject("artists"); if (artistObject.has("artist: [")) { JSONArray artistArray = artistObject.getJSONArray("artist"); for (int i = 0; i < artistArray.length(); i++) { artists.append(artistArray.getString(i) + ", "); } String artist = artists.toString().substring(0, artists.toString().length() - 2); this.setArtist(artist); } else { this.setArtist(artistObject.has("artist") ? artistObject.getString("artist") : ""); } JSONObject venueObject = jsonObject.getJSONObject("venue"); this.setVenue(venueObject.has("name") ? venueObject.getString("name") : ""); JSONObject locationObject = venueObject.getJSONObject("location"); JSONObject geoPointObject = locationObject.getJSONObject("geo:point"); this.setLattitude(geoPointObject.has("geo:lat") ? geoPointObject .getDouble("geo:lat") : -1); this.setLongitude(geoPointObject.has("geo:long") ? geoPointObject .getDouble("geo:long") : -1); String city = (locationObject.has("city") ? locationObject .getString("city") : ""); String country = (locationObject.has("country") ? locationObject .getString("country") : ""); String street = (locationObject.has("street") ? locationObject .getString("street") : ""); String postalCode = (locationObject.has("postalcode") ? locationObject .getString("postalcode") : ""); this.setAddress(street + ", " + city + ", " + postalCode + ", " + country); this.setWebsite(jsonObject.has("website") ? jsonObject .getString("website") : ""); this.setStartDate(jsonObject.has("startDate") ? jsonObject .getString("startDate") : ""); } /** * * @return creator */ public static Parcelable.Creator<Concert> getCreator() { return CREATOR; } private Concert(Parcel in) { readFromParcel(in); } @Override public int describeContents() { return 0; } /** * write Location Object to parcel */ @Override public void writeToParcel(Parcel out, int flags) { out.writeString(title); out.writeString(artist); out.writeString(venue); out.writeString(address); out.writeString(StartDate); out.writeString(website); out.writeDouble(lattitude); out.writeDouble(longitude); } /** * read Reason Object from Parcel * * @param in */ public void readFromParcel(Parcel in) { title = in.readString(); artist = in.readString(); venue = in.readString(); address = in.readString(); StartDate = in.readString(); website = in.readString(); lattitude = in.readDouble(); longitude = in.readDouble(); } public static final Parcelable.Creator<Concert> CREATOR = new Parcelable.Creator<Concert>() { public Concert createFromParcel(Parcel in) { return new Concert(in); } public Concert[] newArray(int size) { return new Concert[size]; } }; }
true
d19d7b213bb5a505bca00b15643a5da9433faa69
Java
heyanfeng22/designPattern
/observerPattern/src/main/java/com/observer/guavaObserver/Teacher.java
UTF-8
924
2.859375
3
[]
no_license
package com.observer.guavaObserver; import com.google.common.eventbus.Subscribe; import com.observer.jdkObserver.GPer; import java.util.Observable; import java.util.Observer; /** * @Autor : heyanfeng22 * @Description : * @Date:Create:in 2019/3/23 13:46 * @Modified By: */ public class Teacher { private GuavaGPer guavaGPer; private String name; public Teacher(GuavaGPer guavaGPer,String name) { this.guavaGPer = guavaGPer; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Subscribe public void update(Object arg) { Question question = (Question)arg; System.out.println(this.name +"你好,你收到问题\n 来自"+this.guavaGPer.getName()+",提问者是:"+question.getUsername()+",提问内容是:"+question.getContext()); } }
true
aae8f5e4982c61a5eaf1194875fb4b77e9278a31
Java
Akshay790/Testing
/MakeMyTrip.java
UTF-8
5,919
2.3125
2
[]
no_license
package webappliction; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class MakeMyTrip { public static void main (String[] args){ System.setProperty("webdriver.chrome.driver","F:\\Selenium\\chromedriver.exe");//launch browser WebDriver driver = new ChromeDriver();//crrate object driver.get("https://www.makemytrip.com"); //launch browser driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); driver.findElement(By.xpath("//*[@id='SW']/div[2]/div[1]/ul/li[6]/div/p")).click();//click on create account and login link driver.findElement(By.xpath("//*[@id='SW']/div[2]/div[2]/div[2]/section/div[2]/p/span[2]/a")).click();//click on create account driver.findElement(By.id("emailOrPhone")).sendKeys("akshaydesai790@gmail.com");//user name driver.findElement(By.id("password")).sendKeys("Akshaydesai790@"); driver.findElement(By.xpath("//*[@id='SW']/div[2]/div[2]/div[2]/section/form/div[2]/div/a")).click();//show password driver.findElement(By.cssSelector("#SW > div.landingContainer > div.headerOuter > div.modal.displayBlock.modalLogin.modalCreateAccount.personal > section > form > div.btnContainer.appendBottom25 > button")).click(); ////////////////////////////////////////////////////////////////////////////////////////// //LOGIN driver.findElement(By.xpath("//*[@id='SW']/div[2]/div[2]/div[2]/section/div[2]/p/span[2]/a")).click(); // driver.findElement(By.className("pushRight modalResetBtn font12 appendRight5")).click(); driver.findElement(By.linkText("Reset Password")).click(); //driver.findElement(By.name("resetEmailPass")).sendKeys("akshaydesai790@gmail.com"); //driver.findElement(By.xpath("//*[@id='SW']/div[2]/div[2]/div[2]/section/form/div[2]/button/span")).click(); driver.findElement(By.xpath("//*[@id='SW']/div[2]/div[2]/div[2]/section/p/a")).click(); driver.findElement(By.id("username")).sendKeys("akshaydesai790@gmail.com"); driver.findElement(By.id("password")).sendKeys("Akshaydesai790@"); driver.findElement(By.cssSelector("#SW > div.landingContainer > div.headerOuter > div.modal.displayBlock.modalLogin.dynHeight.personal > section > form > div.btnContainer.appendBottom25 > button > span")).click(); driver.findElement(By.linkText("Flights")).click(); driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[1]/label/span")).click(); WebElement menu =driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[1]/div[1]/div/div/div/input")); Actions actions = new Actions(driver);//move and select pune city from drop down menu actions.moveToElement(menu).perform(); driver.findElement(By.xpath("//*[@id='react-autowhatever-1-section-0-item-4']/div/div[1]/p[1]")).click(); WebElement menu1 = driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[2]/div[1]/div/div/div/input")); Actions actions2 = new Actions(driver); actions2.moveToElement(menu1).perform(); driver.findElement(By.xpath("//*[@id='react-autowhatever-1-section-0-item-17']/div/div[1]/p[2]")).click(); WebElement menu3 = driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[3]/div[1]/div/div/div/div[1]/div/div[1]/p/span[2]")); Actions actions3=new Actions(driver);//select date start actions3.moveToElement(menu3).perform(); driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[3]/div[1]/div/div/div/div[2]/div/div[2]/div[2]/div[3]/div[1]/div[7]/div/p[2]")).click(); driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[4]/div/label/span")).click(); WebElement menu4 = driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[3]/div[1]/div/div/div/div[2]/div/div[2]/div[2]/div[1]/div")); Actions actions4=new Actions(driver);//select return date driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[3]/div[1]/div/div/div/div[2]/div/div[2]/div[1]/div[3]/div[5]/div[2]/div/p")).click(); driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[5]/label/p[1]")).click(); WebElement Adults = driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[5]/div[1]/div/p[1]")); Actions actions5= new Actions(driver);//select Adults driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[5]/div[1]/div/ul[1]/li[3]")).click(); WebElement child =driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[5]/div[1]/div/div/div[1]/p")); Actions actions6= new Actions(driver); driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[5]/div[1]/div/div/div[1]/ul/li[1]")); WebElement TravelClass = driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[5]/div[1]/div/p[2]")); Actions actions7=new Actions(driver); driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[5]/div[1]/div/ul[2]/li[4]")).click(); driver.findElement(By.cssSelector("#root > div > div:nth-child(2) > div > div.fsw.widgetOpen > div.fsw_inner.interNational > div.fsw_inputBox.flightTravllers.inactiveWidget.activeWidget > div.travellers > button")).click(); driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[6]/label/span")).click(); Actions actions8= new Actions(driver);//select travelling for driver.findElement(By.xpath("//*[@id='root']/div/div[2]/div/div[2]/div[1]/div[6]/ul/li[3]")).click(); driver.findElement(By.cssSelector("#root > div > div:nth-child(2) > div > div.fsw > p > a")).click(); } }
true
fd139c75fca23fb908a2620deacfc54b7784a898
Java
AbrahamPena/CampusPathwaysFinal
/app/src/androidTest/java/com/example/kelvin/campuspathways/UITests.java
UTF-8
2,624
2.09375
2
[]
no_license
package com.example.kelvin.campuspathways; import android.support.test.filters.LargeTest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.view.View; import org.hamcrest.Matcher; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.Espresso.pressBack; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.matcher.ViewMatchers.withId; /** * Created by Kelvin on 4/22/2018. * Used for Instrumented tests of UI */ @RunWith(AndroidJUnit4.class) @LargeTest public class UITests { @Rule public ActivityTestRule<StartActivity> activityTestRule = new ActivityTestRule<>(StartActivity.class); //Test navigation to display screen from start @Test public void goToDisplayPaths() { onView(withId(R.id.btShowMap)) .perform(click()); } //Test navigation to discover screen from start @Test public void goToDiscoverPaths() { onView(withId(R.id.btTrackPath)) .perform(click()); } //Test navigation to node screen from start @Test public void goToNodes() { onView(withId(R.id.btNodesFromStart)) .perform(click()); } @Test public void testFullNavigation() { //Go to node screen and back to start onView(withId(R.id.btNodesFromStart)) .perform(click()); pressBack(); //Go to discover and back onView(withId(R.id.btTrackPath)) .perform(click()); pressBack(); //Go to display and back onView(withId(R.id.btShowMap)) .perform(click()); pressBack(); //From start, go to discover and then display and then back onView(withId(R.id.btTrackPath)) .perform(click()); onView(withId(R.id.btDisplayPathFromDiscover)) .perform(click()); onView(withId(R.id.btDiscoverPathFromDisplay)) .perform(click()); //Go to nodes from discover and back onView(withId(R.id.btNodesFromDiscover)) .perform(click()); pressBack(); //Go to display from discover onView(withId(R.id.btDisplayPathFromDiscover)) .perform(click()); //Go to nodes from display and back onView(withId(R.id.btNodesFromDisplay)) .perform(click()); pressBack(); } }
true
9122c44babee7b349b4c9461a4db3482a371b0d5
Java
kesperado/DoodleEliminate
/ProjectServerDemo/src/data/game/GameDataService.java
UTF-8
273
1.914063
2
[]
no_license
package data.game; import java.util.ArrayList; import po.GamePO; public interface GameDataService { public boolean initGame(ArrayList<GamePO> poList); public boolean recordGame(ArrayList<GamePO> poList); public ArrayList<GamePO> getGame(String id); }
true
8df081df4152d2b8344d9880d2ba58f7d1817c4d
Java
Mzheldin/javaEE
/src/main/java/beans/ProductBeanWS.java
UTF-8
1,672
2.3125
2
[]
no_license
package beans; import interceptors.LogInterceptor; import persist.Category; import persist.CategoryRepository; import persist.Product; import persist.ProductRepository; import services.ws.ProductServiceWS; import javax.ejb.EJB; import javax.interceptor.Interceptors; import javax.jws.WebService; import java.io.Serializable; import java.util.List; @WebService(endpointInterface = "services.ws.ProductServiceWS") public class ProductBeanWS implements Serializable, ProductServiceWS { @EJB private ProductRepository productRepository; @EJB private CategoryRepository categoryRepository; @Override @Interceptors({LogInterceptor.class}) public List<Product> getAllProducts() { return productRepository.getAllProducts(); } @Override @Interceptors({LogInterceptor.class}) public List<Product> getAllProductsByCategory(Category category) { return productRepository.getProductsByCategory(category); } @Override @Interceptors({LogInterceptor.class}) public Product getProductByName(String name) { return productRepository.findByName(name); } @Override @Interceptors({LogInterceptor.class}) public Product getProductById(Integer id) { return productRepository.findById(id); } @Override @Interceptors({LogInterceptor.class}) public Product addProduct(Product product) { return productRepository.merge(product); } @Override @Interceptors({LogInterceptor.class}) public void deleteProduct(Product product) { if (productRepository.existById(product.getId())) productRepository.deleteProduct(product); } }
true
aa9f399259c9a32e50a22f1393c28ccda07e67bf
Java
LarsEckart/java_playground
/src/main/java/lars/ooad/Wood.java
UTF-8
707
2.640625
3
[ "Apache-2.0" ]
permissive
package lars.ooad; public enum Wood { INDIAN_ROSEWOOD, BRAZILIAN_ROSEWOOD, MAHOGANY, MAPLE, COCOBOLO, CEDAR, ADIRONDACK, ALDER, SITKA; public String toString() { switch (this) { case INDIAN_ROSEWOOD: return "Indian Rosewood"; case BRAZILIAN_ROSEWOOD: return "Brazilian Rosewood"; case MAHOGANY: return "Mahogany"; case MAPLE: return "Maple"; case COCOBOLO: return "Cocobolo"; case CEDAR: return "Cedar"; case ADIRONDACK: return "Adirondack"; case ALDER: return "Alder"; case SITKA: return "Sitka"; default: return "unspecified"; } } }
true
c6ab7893ecb0dc3d1a0796571a1983cdbc10cc66
Java
supermao1013/study-demo
/dalomao-design-mode/src/main/java/com/dalomao/decorator/Display.java
UTF-8
643
3.125
3
[]
no_license
package com.dalomao.decorator; /** * <p>Package: com.dalomao.demo.decorator</p> * <p>Description:被装饰的对象的接口 </p> * <p>Copyright: Copyright (c) 2013</p> * <p>Company: TODO</p> * * @author maohw * @version 1.0 * @date 2018/12/4 **/ public abstract class Display { abstract int getColumns();//获取横向字符数 abstract int getRows();//获取纵向字符数 abstract String getRowText(int i);//获取第row行的字符串 /** * 显示所有字符 */ public final void show() { for (int i=0; i<getRows(); i++) { System.out.println(getRowText(i)); } } }
true
6367c71cb9ed1ca5931c73f1ad2c0f61377024d1
Java
mfkiwl/StepCounter-DeadReckoning
/app/src/main/java/com/example/stepcounter/observers/Subscriber.java
UTF-8
102
2.03125
2
[]
no_license
package com.example.stepcounter.observers; public interface Subscriber { public void update(); }
true
ffce93808386953476eac9cb66d5df904e09a163
Java
WFTinternship/EventManagement
/src/main/java/com/workfront/internship/event_management/dao/InvitationDAO.java
UTF-8
1,084
2.078125
2
[]
no_license
package com.workfront.internship.event_management.dao; import com.workfront.internship.event_management.exception.dao.DAOException; import com.workfront.internship.event_management.model.Invitation; import java.util.List; /** * Created by Hermine Turshujyan 7/8/16. */ public interface InvitationDAO { //insert invitation into db int addInvitation(Invitation invitation); void addInvitations(List<Invitation> invitation); //get records from db Invitation getInvitationById(int invitationId); List<Invitation> getAllInvitations() throws DAOException; List<Invitation> getInvitationsByEventId(int eventId); List<Invitation> getInvitationsByUserId(int userId); //update record in db boolean updateInvitation(Invitation invitation); boolean updateInvitationResponse(int eventId, int userId, int responseId); //delete records from db boolean deleteInvitation(int invitationId); void deleteInvitationsByEventId(int eventId); void deleteInvitationsByUserId(int userId); void deleteAllInvitations() throws DAOException; }
true
f09d218997a9a149511eac239eae7c0e2c3d010c
Java
opl-/Evaldor
/src/pl/noip/evaldor/command/CommandTp.java
UTF-8
2,304
2.4375
2
[]
no_license
package pl.noip.evaldor.command; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import pl.noip.evaldor.Evaldor; import pl.noip.evaldor.Messages; public class CommandTp implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { if (args.length == 1) { if (!(sender instanceof Player)) { sender.sendMessage(Messages.playerOnly); return true; } Player target = (Bukkit.getServer().getPlayer(args[0])); if (target == null) { sender.sendMessage(Messages.playerNotFound.replaceAll("\\{player\\}", args[0])); return true; } else { ((Player) sender).teleport(target.getLocation()); sender.sendMessage(Messages.tpTeleportedTo.replaceAll("\\{player\\}", Evaldor.getName(target))); return true; } } else if (args.length == 2) { Player target = (Bukkit.getServer().getPlayer(args[0])); Player target2 = (Bukkit.getServer().getPlayer(args[1])); if (target != null && target2 != null) { sender.getServer().getPlayer(args[0]).teleport(sender.getServer().getPlayer(args[1]).getLocation()); sender.sendMessage(Messages.tpTeleportedFromTo.replaceAll("\\{player\\}", Evaldor.getName(target)).replaceAll("\\{player2\\}", Evaldor.getName(target2))); target.sendMessage(Messages.tpSomeoneTeleportedYouTo.replaceAll("\\{player\\}", Evaldor.getName(sender)).replaceAll("\\{player2\\}", Evaldor.getName(target2))); target2.sendMessage(Messages.tpSomeoneTeleportedToYou.replaceAll("\\{player\\}", Evaldor.getName(sender)).replaceAll("\\{player2\\}", Evaldor.getName(target))); return true; } else if (target == null && target2 == null) { sender.sendMessage(Messages.tpBothPlayersOffline); return true; } else if (target == null) { sender.sendMessage(Messages.playerNotFound.replaceAll("\\{player\\}", Evaldor.getName(target))); return true; } else if (target2 == null) { sender.sendMessage(Messages.playerNotFound.replaceAll("\\{player\\}", Evaldor.getName(target2))); return true; } else { return true; } } else { sender.sendMessage(Messages.wrongUsage + command.getUsage()); return true; } } }
true
4a15b355a8d91ec56d6c80ddad4a2ea747012a2a
Java
dpolivaev/freeplane
/freeplane/src/org/freeplane/features/map/SummaryNode.java
UTF-8
2,150
2.140625
2
[]
no_license
/* * Freeplane - mind map editor * Copyright (C) 2011 dimitry * * This file author is dimitry * * 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 2 of the License, 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, see <http://www.gnu.org/licenses/>. */ package org.freeplane.features.map; import org.freeplane.core.extension.IExtension; import org.freeplane.features.mode.NodeHookDescriptor; import org.freeplane.features.mode.PersistentNodeHook; import org.freeplane.n3.nanoxml.XMLElement; /** * @author Dimitry Polivaev * Apr 9, 2011 */ @NodeHookDescriptor(hookName = "SummaryNode", onceForMap = false) public class SummaryNode extends PersistentNodeHook implements IExtension{ public static void install(){ new SummaryNode(); new FirstGroupNode(); }; static public boolean isFirstGroupNode(final NodeModel nodeModel) { return nodeModel.containsExtension(FirstGroupNode.class); } @Override protected IExtension createExtension(NodeModel node, XMLElement element) { return this; } static public boolean isSummaryNode(final NodeModel nodeModel) { return nodeModel.containsExtension(SummaryNode.class); } public static int getSummaryLevel(NodeModel node) { if(node.isRoot() || ! isSummaryNode(node)) return 0; final NodeModel parentNode = node.getParentNode(); final int index = parentNode.getIndex(node); final boolean isleft = node.isLeft(); int level = 1; for(int i = index - 1; i > 0; i--){ final NodeModel child = (NodeModel) parentNode.getChildAt(i); if(isleft == child.isLeft()){ if( isSummaryNode(child)) level++; else return level; } } return level; } }
true
879a563b3ec6b2b0c8374f381ce1a3fc51a0fb4b
Java
zhongxingyu/Seer
/Diff-Raw-Data/11/11_f5057091735f09c2e16efa0e9270245a989844f3/SessionResult/11_f5057091735f09c2e16efa0e9270245a989844f3_SessionResult_t.java
UTF-8
6,662
2.671875
3
[]
no_license
package com.delin.speedlogger.Results; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.delin.speedlogger.Math.Geometry; import com.delin.speedlogger.Math.Interpolator; import com.delin.speedlogger.Serialization.GPXSerializer; import android.location.Location; public class SessionResult { class Point { public long time = -1; public float speed = -1.f; public float distance = -1.f; } private long mStartTime = 0; private long mTotalTime = 0; private float mMaxSpeed = 0; private float mTotalDistance = 0; private boolean mValid = false; private List<Location> mLocList = new ArrayList<Location>(); private String mFilename; // gpx file public SessionResult() { } public SessionResult(List<Location> locList) { SetLocations(locList); } public List<Location> getLocations() { if(mLocList == null) LoadGPX(); return mLocList; } public void SaveGPX() { if(mLocList == null || mLocList.size() < 2) return; GPXSerializer gpxLog = new GPXSerializer(mFilename, true); gpxLog.SaveAllFixes(mLocList); gpxLog.Stop(); } private void LoadGPX() { GPXSerializer gpxLog = new GPXSerializer(mFilename, false); mLocList = gpxLog.GetAllFixes(); // HINT: we can check gpx data here to prevent hacks } public void DeleteGPX() { GPXSerializer.DeleteGPX(mFilename); } public List<Location> GetLocations() { return mLocList; } public void SetLocations(List<Location> locs) { // do a full copy mLocList.clear(); mLocList.addAll(locs); Recalc(); } public void SaveToGPX(final String filename) { GPXSerializer gpxSaver = new GPXSerializer(filename, true); for (Iterator<Location> it = mLocList.iterator(); it.hasNext(); ) { gpxSaver.AddFix(it.next()); } gpxSaver.Stop(); } /** * Returns time at which specified speed has been reached * * @param speed desired speed, in m/s * @return Time at which specified speed has been reached, in milliseconds * or -1 in case of error */ public long GetTimeAtSpeed(final float speed) { // look at the cache // then look at loclist itself for (int i=1; i<mLocList.size(); i++) { if (speed < mLocList.get(i).getSpeed()) { // we found a closest largest fix, do linear interpolation return Interpolator.Lerp(mLocList.get(i-1).getSpeed(), mLocList.get(i-1).getTime(), mLocList.get(i).getSpeed(), mLocList.get(i).getTime(), speed) - mStartTime; //return mLocList.get(i).getTime() - mStartTime; } } return -1; } /** * Returns time at which specified speed has been reached after * starting from origin speed * * @param toSpeed origin speed, in m/s * @param fromSpeed desired speed, in m/s * @return Time at which specified speed has been reached, in milliseconds * or -1 in case of error */ public long GetTimeAtSpeed(final float toSpeed, final float fromSpeed) { long retval = -1; long fromTime = 0; // check input parameters if (toSpeed<fromSpeed || toSpeed<0 ) return retval; fromTime = retval = GetTimeAtSpeed(fromSpeed); // get 'from' time if (retval!=-1) { // if it's ('from') ok - get 'to' time retval = GetTimeAtSpeed(toSpeed); if (retval!=-1) retval = retval - fromTime >0 ? retval - fromTime : -1; // if 'to' is ok - calc difference } return retval; } public long GetTimeAtDistance(final float distance) { // look at the cache // then look at loclist itself float dist= 0.f; for (int i=1; i<mLocList.size(); i++) { dist = Geometry.DistBetweenLocs(mLocList.get(0),mLocList.get(i),false); if (distance < dist) { // we found a closest largest fix return mLocList.get(i).getTime() - mStartTime; // TODO: very rough, intepolate that } } return -1; } public Point GetInfoAtDistance(final float distance) { // look at the cache // then look at loclist itself Point point = new Point(); float dist= 0.f; for (int i=1; i<mLocList.size(); i++) { dist = Geometry.DistBetweenLocs(mLocList.get(0),mLocList.get(i),false); if (distance < dist) { // we found a closest largest fix point.time = mLocList.get(i).getTime() - mStartTime; // TODO: very rough, intepolate that point.speed = mLocList.get(i).getSpeed(); point.distance = distance; return point; } } return point; } /** * Indicates state of results * * If state is invalid - results may be incorrect * * @return Valid or not */ public boolean IsValid() { return mValid; } /** * Returns top speed * * @return Speed, in m/s */ public float GetMaxSpeed() { return mMaxSpeed; } /** * Returns distance on which top speed has been achieved * * @return Distance, in meters */ public float GetTotalDistance() { return mTotalDistance; } /** * Returns time taken on achievement top speed * * @return Time, in milliseconds, since StartTime! */ public long GetTotalTime() { return mTotalTime; } /** * Returns time at which session has been started * * @return Time at which session has been started, in milliseconds since 01.01.1970 UTC */ public long GetStartTime() { return mStartTime; } public void SetStartTime(long startTime) { mStartTime = startTime; mFilename = Long.toString(mStartTime) + ".gpx"; } public void SetMaxSpeed(float maxSpeed) { mMaxSpeed = maxSpeed; } public void SetTotalDistance(float totalDistance) { mTotalDistance = totalDistance; } public void SetTotalTime(long totalTime) { mTotalTime = totalTime; } private void Recalc() { mValid = false; if(mLocList == null || mLocList.size() < 2) return; mValid = true; Location origin = mLocList.get(0); Location dest = mLocList.get(0); mStartTime = mLocList.get(0).getTime(); for (int i=1; i<mLocList.size(); i++){ if (mMaxSpeed < mLocList.get(i).getSpeed()) { dest = mLocList.get(i); mMaxSpeed = dest.getSpeed(); } } mTotalTime = dest.getTime() - mStartTime; mTotalDistance = Geometry.DistBetweenLocs(origin,dest,false); // seems incorrect float[] results = new float[3]; Location.distanceBetween(origin.getLatitude(), origin.getLongitude(), dest.getLatitude(), dest.getLongitude(), results); mTotalDistance = results[0]; } }
true
f9deae1cee3901e4e8102f358c82d88f96f3dae3
Java
mzhua/DiyCode
/app/src/main/java/im/hua/diycode/ui/topic/detail/reply/TopicReplyRVAdapter.java
UTF-8
4,388
1.953125
2
[]
no_license
package im.hua.diycode.ui.topic.detail.reply; import android.content.Intent; import android.net.Uri; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.view.View; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import im.hua.diycode.Constants; import im.hua.diycode.R; import im.hua.diycode.data.entity.TopicReplyEntity; import im.hua.diycode.util.ImageViewLoader; import im.hua.diycode.util.ShowTimeFormatter; import im.hua.mvp.framework.SimpleRVAdapter; /** * Created by hua on 2016/12/13. */ public class TopicReplyRVAdapter extends SimpleRVAdapter<TopicReplyEntity, TopicReplyRVAdapter.ItemViewHolder> { private TopicReplyActivity mTopicReplyActivity; public TopicReplyRVAdapter(TopicReplyActivity topicReplyActivity) { mTopicReplyActivity = topicReplyActivity; } @Override public DiffUtil.Callback getDiffCallback(List<TopicReplyEntity> data, List<TopicReplyEntity> newData) { return null; } @Override public int getItemLayoutRes() { return R.layout.topic_reply_list_item; } @Override public ItemViewHolder getItemViewHolder(View view) { return new ItemViewHolder(view); } @Override public void bindView(final ItemViewHolder holder, final TopicReplyEntity data, int position) { holder.mTopicReplyTime.setText(ShowTimeFormatter.getFormatTime(data.getUpdated_at(), "")); holder.mTopicReplyUserName.setText(data.getUser().getName()); holder.mTopicReplyFav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTopicReplyActivity.onFavClick(v,data); } }); holder.mTopicReplyPraise.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTopicReplyActivity.onPraiseClick(v,data); } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mTopicReplyActivity.onItemClick(v,data); } }); holder.mTopicReplyTitle.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("#")) { return true; } else if (url.startsWith("/")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.BASE_URL + url)); holder.itemView.getContext().startActivity(intent); return true; } else { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); holder.itemView.getContext().startActivity(intent); return true; } } }); holder.mTopicReplyTitle.loadDataWithBaseURL(Constants.BASE_URL,data.getBody_html(), "text/html; charset=UTF-8;","UTF-8",null); ImageViewLoader.loadUrl(holder.itemView.getContext(), data.getUser().getAvatar_url(), holder.mTopicReplyUserHeader); } class ItemViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.topic_reply_user_header) ImageView mTopicReplyUserHeader; @BindView(R.id.topic_reply_fav) ImageView mTopicReplyFav; @BindView(R.id.topic_reply_praise) ImageView mTopicReplyPraise; @BindView(R.id.topic_reply_user_name) TextView mTopicReplyUserName; @BindView(R.id.topic_reply_node_name) TextView mTopicReplyNodeName; @BindView(R.id.topic_reply_time) TextView mTopicReplyTime; @BindView(R.id.topic_reply_title) WebView mTopicReplyTitle; public ItemViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
true
d67fba4e6bd103ca449f5297837b4ecdc59de813
Java
Ninjaman494/ExpandableTextView
/library/src/main/java/ninjaman494/expandabletextview/ExpandableTextView.java
UTF-8
3,858
3.0625
3
[ "Apache-2.0" ]
permissive
package ninjaman494.expandabletextview; import android.animation.ObjectAnimator; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; /** A custom View which replicates the Google Play Store dropdown description. Uses two TextViews * to achieve this effect, one for the "blurb" and another for the full description("desp"). Each * half of the View can be independently stylized. * * Usage: * Use as a regular view. To activate dropdown, call toggle() * setBlurbText: set the text for blurb portion * setDespText: set the text for the description portion * getBlurbView: returns the TextView for the blurb portion, which can then be stylized * getDespView: returns the TextView for the desp portion, which can then be stylized * * Optional Attributes(currently not in XML): * startExpanded: starts the View expanded instead of collapsed * setCollapsedLineCount: set the number of lines for the blurb. Default is 3. * setAnimSpeed: set the expand/collapse animation speed. Default is 375 ms * * Created by ninjaman494 on 5/23/2017. */ public class ExpandableTextView extends LinearLayout { private TextView blurbView; private TextView despView; private boolean isExpanded = false; private int collapsedLineCount = 3; private int animSpeed = 375; private void init(Context context){ View root = inflate(context,R.layout.expandable_textview,this); blurbView = (TextView)root.findViewById(R.id.blurbView); despView = (TextView)root.findViewById(R.id.despView); this.setOrientation(VERTICAL); int blurbHeight = blurbView.getLineHeight() * blurbView.getMaxLines(); blurbView.setHeight(blurbHeight); } public ExpandableTextView(Context context) { super(context); init(context); } public ExpandableTextView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public ExpandableTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public boolean isExpanded(){ return isExpanded; } public void startExpanded(boolean expanded){ isExpanded = expanded; if(isExpanded){ despView.setMaxLines(Integer.MAX_VALUE); } } public void setCollapsedLineCount(int lineCount){ collapsedLineCount = lineCount; blurbView.setMaxLines(collapsedLineCount); int blurbHeight = blurbView.getLineHeight() * blurbView.getMaxLines(); blurbView.setHeight(blurbHeight); } public void setBlurbText(String text){ blurbView.setText(text); } public void setDespText(String text){ despView.setText(text); } public void setAnimSpeed(int animSpeed){ this.animSpeed = animSpeed; } public TextView getBlurbView(){ return blurbView; } public TextView getDespView(){ return despView; } public void toggle() { if (!isExpanded) { System.out.println("Expanding"); isExpanded = true; despView.setMaxLines(Integer.MAX_VALUE); int expandedHeight = despView.getLineCount() * despView.getLineHeight(); ObjectAnimator animation = ObjectAnimator.ofInt(despView, "Height",expandedHeight); animation.setDuration(animSpeed); animation.start(); } else { System.out.println("Collapsing"); isExpanded = false; despView.setMaxLines(0); ObjectAnimator animation = ObjectAnimator.ofInt(despView, "Height",0); animation.setDuration(animSpeed); animation.start(); } } }
true
8658f940452b76367b389998c0f66a765d723e06
Java
Paul-Wallstone/EmployeeAppRest
/src/main/java/com/mastery/java/task/PagesPathEnum.java
UTF-8
241
2.21875
2
[]
no_license
package com.mastery.java.task; public enum PagesPathEnum { HOME_PAGE("home"); private final String path; PagesPathEnum(String path) { this.path = path; } public String getPath() { return path; } }
true
375d118aa47f2a5150893e623520063392b03b90
Java
jiyeshin/Javafirst
/jy.shin0718/src/event/EventHandling1.java
UTF-8
2,754
3.375
3
[]
no_license
package event; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.TextEvent; import java.awt.event.TextListener; public class EventHandling1 extends Frame { // 생성자 public EventHandling1() { setBounds(1300, 700, 550, 800); setTitle("Event Handling Test"); Panel panel = new Panel(); //여러 개를 배치하기 위해서 패널 생성 Panel panelSouth = new Panel(); //여러 개를 배치하기 위해서 패널 생성 TextField tf1=new TextField(10); panel.add(tf1); Label plus=new Label(" + "); panel.add(plus); TextField tf2=new TextField(10); panel.add(tf2); Label assign=new Label(" = "); panel.add(assign); TextField result=new TextField(10); panel.add(result); Button btnResult = new Button("Result"); btnResult.setFont(new Font("바탕",20,40)); ActionListener actionResult=new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String n1=tf1.getText(); String n2=tf2.getText(); int r=Integer.parseInt(n1)+Integer.parseInt(n2); result.setText(r+""); } }; btnResult.addActionListener(actionResult); panel.add(btnResult); Button btnExit = new Button("Exit"); btnExit.setFont(new Font("바탕",20,40)); ActionListener actionExit = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }; btnExit.addActionListener(actionExit); panelSouth.add(btnExit); Label lbPw=new Label("P/W"); panel.add(lbPw); TextField pw=new TextField(15); panel.add(pw); Label pwResult=new Label(); panel.add(pwResult); //텍스트 필드의 내용이 변경될 때 처리할 수 있는 인터페이스의 인스턴스를 생성 TextListener textListener=new TextListener() { @Override public void textValueChanged(TextEvent e) { String password=pw.getText(); int dae=0; int so=0; int num=0; int etc=0; for(int i=0;i<password.length();i=i+1) {//password의 모든 글자를 순회 char ch=password.charAt(i); if(ch>='A'&&ch<='Z') { dae=dae+1; } else if(ch>='a'&&ch<='z') { so=so+1; } else if(ch>='0'&&ch<='9') { num=num+1; } else { etc=etc+1; } } if(dae*so*num*etc>0) { pwResult.setBackground(Color.YELLOW); pwResult.setText("O"); } else { pwResult.setBackground(Color.RED); pwResult.setText("X"); } } }; pw.addTextListener(textListener); add("South",panelSouth); add(panel); setVisible(true); } }
true
09bd154225e9aa1835ca03db219ab5ba2cc67d3c
Java
Krish-Khatri/Course-Management-Application
/src/main/java/accounts/StudentAccount.java
UTF-8
2,754
3.296875
3
[]
no_license
package accounts; import database.Database; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * @author Krish Khatri */ public class StudentAccount extends Account { private ArrayList<String> courses; public StudentAccount(){} public StudentAccount(String username , String password){ this.user_name = username; this.password = password; } public String GetFirstName(){ return first_name; } public String GetLastName(){ return last_name; } public String GetID(){ return id; } /** * Get courses student is taking * @return Courses Student is Taking */ public ArrayList<String> getCourses(){ String sql = "select coursename from courses"; try { PreparedStatement preparedStatement = Database.ConnectDatabase().prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); courses = new ArrayList<String>(); while (resultSet.next()){ sql = "select * from " + resultSet.getString(1) + "course where studentid = " + id; preparedStatement = Database.ConnectDatabase().prepareStatement(sql); ResultSet studentsinclass = preparedStatement.executeQuery(); if (studentsinclass.next()){ courses.add(resultSet.getString(1)); } } } catch (SQLException se){ se.printStackTrace(System.out); } return courses; } /** * Checks if student exists * @return True if student is in database */ @Override public boolean InDatabase(){ boolean exists = false; String sql = "select id, lastname, firstname, from StudentAccounts where username = ? and password = ?"; try { PreparedStatement preparedStatement = Database.ConnectDatabase().prepareStatement(sql); preparedStatement.setString(1,this.user_name); preparedStatement.setString(2,this.password); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()){ initAccount(resultSet); exists = true; } } catch (SQLException se){ se.printStackTrace(System.out); } return exists; } private void initAccount(ResultSet resultSet){ try { this.id = resultSet.getString(1); this.last_name = resultSet.getString(2); this.first_name = resultSet.getString(3); } catch (SQLException se){ se.printStackTrace(System.out); } } }
true
1a74df516d573dd407e09166a18a462dfacd99c2
Java
zippo88888888/Read
/app/src/main/java/com/official/read/weight/lu_recycler_view/holder/SiViewHolder.java
UTF-8
731
2.3125
2
[]
no_license
package com.official.read.weight.lu_recycler_view.holder; import android.view.View; import android.widget.TextView; import com.official.read.R; import com.official.read.weight.lu_recycler_view.Visitable; import com.official.read.weight.lu_recycler_view.entity.Si; /** * com.official.read.weight.lu_recycler_view.holder * Created by ZP on 2017/8/8. * description: * version: 1.0 */ public class SiViewHolder extends BetterViewHolder { private TextView si; public SiViewHolder(View itemView) { super(itemView); si = (TextView) itemView.findViewById(R.id.si_text); } @Override public void bindItem(Visitable visitable) { Si i = (Si) visitable; si.setText(i.si); } }
true
b133eb3167603d2aa0f9c0d765e5cda64103bdc8
Java
859162000/cbms
/platform/account/model/src/main/java/com/prcsteel/platform/account/model/dto/CustAccountDto.java
UTF-8
492
2.140625
2
[]
no_license
package com.prcsteel.platform.account.model.dto; import com.prcsteel.platform.account.model.model.Account; public class CustAccountDto extends Account{ private Long accountId; private String accountName; public Long getAccountId() { return accountId; } public void setAccountId(Long accountId) { this.accountId = accountId; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } }
true
9fc81f53f0535a790f96ea075179f95f36f2a1ea
Java
gecatar/course
/javacourse/chatapplication/src/main/java/com/sirma/itt/evgeni/comunication/ComunicatorListener.java
UTF-8
656
2.53125
3
[]
no_license
package com.sirma.itt.evgeni.comunication; /** * Allow communication between Comunicator and other objects. * * @author Evgeni Stefanov * */ public interface ComunicatorListener { /** * Change conection status. * * @param conectionCondition */ public void setConectionStatus(String conectionCondition); /** * When new message is received. * * @param name * @param text */ public void showMesage(String name, String text); /** * Add user. * * @param name */ public void addUser(String name); /** * Remove user. * * @param name */ public void removeUser(String name); }
true
b9e71818d5a0b973b65ff55fdf71e2a746b56c89
Java
fortochkinf/directoriesAndFilesReview
/src/main/java/com/blckRbbit/server/service/FileService.java
UTF-8
4,141
2.734375
3
[]
no_license
package com.blckRbbit.server.service; import com.blckRbbit.server.entity.FileEntity; import com.blckRbbit.server.repository.FileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @Service public class FileService { @Autowired private FileRepository fileRepository; @Autowired private JdbcTemplate jdbcTemplate; @Transactional public void register(FileEntity files) { String path = files.getDirectory().getPath(); File folder = new File(path); File[] listOfFiles = folder.listFiles(); if (listOfFiles==null || listOfFiles.length == 0) { jdbcTemplate.update("insert into file_entity(name, size, directory_and_files) values (?, ?, ?)", "empty", 0, files.getDirectory().getId()); } assert listOfFiles != null; List<File> sorted = sort(listOfFiles); for(File file : sorted) { jdbcTemplate.update("insert into file_entity(name, size, directory_and_files) values (?, ?, ?)", file.getName(), file.length(), files.getDirectory().getId()); } } private List<File> sort(File[] listOfFiles) { // вывод списка по очереди директории -> файлы List<File> dirs= new ArrayList<>(); List<File> files= new ArrayList<>(); for(File file : listOfFiles) { if (file.isDirectory()) { dirs.add(file); } if (file.isFile()) { files.add(file); } } Collections.sort(dirs); Collections.sort(files); sortOfNumber(dirs); sortOfNumber(files); if (dirs.isEmpty()) { return files; } else if (files.isEmpty()) { return dirs; } List<File> result = new ArrayList<>(dirs); result.addAll(files); return result; } private List<File> sortOfNumber (List<File> filesOrDirs) { //сортировка списка файлов, с именем, содержащим число, по возрастанию числа List<File> numbersInFileNames = new ArrayList<>(); for (File element : filesOrDirs) { if (isNumber(element.getName())) { numbersInFileNames.add(element); } } if (numbersInFileNames.isEmpty() || numbersInFileNames.size() == 1) return filesOrDirs; for (int j = 0; j < numbersInFileNames.size()- 1; j++) { for (int i = 0; i < numbersInFileNames.size() - 1; i++) { if (numberInFileName(numbersInFileNames.get(i).getName()) > numberInFileName(numbersInFileNames.get(i + 1).getName())) { swap(i, i + 1, numbersInFileNames); } } } return numbersInFileNames; } private int numberInFileName (String name) { Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(name); int result = 0; int start = 0; while (matcher.find(start)) { String value = name.substring(matcher.start(), matcher.end()); result = Integer.parseInt(value); start = matcher.end(); } return result; } private List<File> swap(int x, int y, List <File> files) { // меняет местами элементы списка File temp = files.get(x); files.set(x, files.get(y)); files.set(y, temp); return files; } private boolean isNumber(String str) { //проверяет, есть ли в имени файла число for (char symbol : str.toCharArray()) { if (Character.isDigit(symbol)) return true; } return false; } }
true
58cc4bdc7860b94d21acca6b05804577dc73e355
Java
coco-in-bluemoon/spring-vuejs
/summary/chapter03/code/messages/src/main/java/app/messages/App.java
UTF-8
454
1.890625
2
[]
no_license
package app.messages; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); MessageService messageService = context.getBean(MessageService.class); messageService.save("Hello Spring!"); } }
true
d54cdb612b95a189d4908c2a04912431a85be3a4
Java
enaawy/gproject
/gp_JADX/com/google/wireless/android/finsky/dfe/p513g/p514a/C7468s.java
UTF-8
2,840
1.625
2
[]
no_license
package com.google.wireless.android.finsky.dfe.p513g.p514a; import com.google.protobuf.nano.C7213a; import com.google.protobuf.nano.C7219h; import com.google.protobuf.nano.CodedOutputByteBufferNano; import com.google.protobuf.nano.b; import com.google.protobuf.nano.i; public final class C7468s extends b { public static volatile C7468s[] f37935a; public int f37936b; public String f37937c; public C7470u f37938d; public C7460k f37939e; public static C7468s[] m35689d() { if (f37935a == null) { synchronized (C7219h.f35465b) { if (f37935a == null) { f37935a = new C7468s[0]; } } } return f37935a; } public C7468s() { this.f37936b = 0; this.f37937c = ""; this.f37938d = null; this.f37939e = null; this.aO = null; this.aP = -1; } public final void m35691a(CodedOutputByteBufferNano codedOutputByteBufferNano) { if ((this.f37936b & 1) != 0) { codedOutputByteBufferNano.m33521a(1, this.f37937c); } if (this.f37938d != null) { codedOutputByteBufferNano.m33532b(3, this.f37938d); } if (this.f37939e != null) { codedOutputByteBufferNano.m33532b(4, this.f37939e); } super.a(codedOutputByteBufferNano); } protected final int m35692b() { int b = super.b(); if ((this.f37936b & 1) != 0) { b += CodedOutputByteBufferNano.m33493b(1, this.f37937c); } if (this.f37938d != null) { b += CodedOutputByteBufferNano.m33503d(3, this.f37938d); } if (this.f37939e != null) { return b + CodedOutputByteBufferNano.m33503d(4, this.f37939e); } return b; } public final /* synthetic */ i m35690a(C7213a c7213a) { while (true) { int a = c7213a.m33550a(); switch (a) { case 0: break; case 10: this.f37937c = c7213a.m33564f(); this.f37936b |= 1; continue; case 26: if (this.f37938d == null) { this.f37938d = new C7470u(); } c7213a.m33552a(this.f37938d); continue; case 34: if (this.f37939e == null) { this.f37939e = new C7460k(); } c7213a.m33552a(this.f37939e); continue; default: if (!super.a(c7213a, a)) { break; } continue; } return this; } } }
true