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
1bb4d02fda15c17289de82f200b87eaa795cbffc
Java
Flyonsnow/Study-Demo
/spring-cloud-alibaba-demo/nacos-discovery-example/src/main/java/com/example/nacos/dubbo/provider/nacos/discovery/NacosDiscoveryExampleApplication.java
UTF-8
684
1.851563
2
[ "Apache-2.0" ]
permissive
package com.example.nacos.dubbo.provider.nacos.discovery; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * 注意spring cloud的版本要与spring boot版本匹配 spring-boot 2.1.x需要对应sc G版, 否则出现无法注册问题 * <p> * 该example展示使用nacos-discovery进行注册的依赖 */ @SpringBootApplication @EnableDiscoveryClient public class NacosDiscoveryExampleApplication { public static void main(String[] args) { SpringApplication.run(NacosDiscoveryExampleApplication.class, args); } }
true
06dc5e54a630d7eaece9fe578656a22f16a6d027
Java
tvd12/ezyfox-examples
/ezyfox-bean/src/main/java/com/tvd12/ezyfox/example/bean/repository/BookRepository.java
UTF-8
348
2.296875
2
[ "Apache-2.0" ]
permissive
package com.tvd12.ezyfox.example.bean.repository; import com.tvd12.ezyfox.bean.annotation.EzySingleton; import com.tvd12.ezyfox.example.bean.entity.Book; import lombok.AllArgsConstructor; @AllArgsConstructor @EzySingleton public class BookRepository { public void save(Book book) { System.out.println("saved book: " + book); } }
true
ccffd825bc0808f2451748fde953e8f8dbbc605a
Java
noohk329/comento-workspace
/[1주차] 개발 환경 세팅/springweb/src/main/java/com/hk/service/MovieService.java
UTF-8
228
1.851563
2
[]
no_license
package com.hk.service; import java.util.List; import com.hk.vo.MovieVO; // 비즈니스 로직 작성. DB 처리 시 많이 이용. public interface MovieService { public List<MovieVO> selectMovie() throws Exception; }
true
f1e3381563380408c208840b70313ff21e758657
Java
binfoo/springmvc
/Test15-SpringMVC2/src/main/java/org/binfoo/UserController.java
UTF-8
2,918
2.6875
3
[]
no_license
package org.binfoo; import com.google.gson.Gson; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; /** * 1.@ResponseBody 这个注解可以让我们将返回值放在response体内, * 而不是返回一个html页面,当我们在移动端比如Android、或者通过Ajax来访问服务端的数据的时候,就可以通过这个注解。 2.@RequestBody 这个注解允许request的参数在request体中,而不是直接放在地址后面。 3.@PathVariable 这个注解用来接收路径参数 4.@RestController 这是一个组合注解,组合了@Controller和@ResponseBody两个,在开发中我们可以用@RestController这一个, 也可以用后面两个,使用这个可以自动将一个对象转为xml或者json返回给客户端。 */ /** * Created by binfoo on 2017/9/9. */ @Controller @RequestMapping("/user") public class UserController { //http://localhost:8080/user/ @ResponseBody @RequestMapping(produces = "text/plain;charset=UTF-8") public String user(HttpServletRequest request){ return "url:" + request.getRequestURL() + " can access"; } //http://localhost:8080/user/user/张三 @ResponseBody @RequestMapping(value = "/user/{str}",produces = "text/plain;charset=utf-8") public String pathVar(@PathVariable String str,HttpServletRequest request){ //url:http://localhost:8080/user/user/%E5%BC%A0%E4%B8%89 can access , str is 张三 return "url:" + request.getRequestURL() + " can access,str is " + str; } //http://localhost:8080/user/rp?id=100 @ResponseBody @RequestMapping(value = "/rp",produces = "text/plain;charset=UTF-8") public String requestParams(long id,HttpServletRequest request){ //url:http://localhost:8080/user/rp can access , username is :100 return "url:" + request.getRequestURL()+" can access and username is " + id; } //http://localhost:8080/user/json?username=%E5%BC%A0%E4%B8%89&password=123 @ResponseBody @RequestMapping(value = "json",produces = "application/json;charset=UTF-8") public String passObj(UserBean user,HttpServletRequest request){ Gson gson = new Gson(); //{"username":"张三","password":"123"} return gson.toJson(user); } @ResponseBody @RequestMapping(value = "/getJson",produces = "application/json;charset=UTF-8") public UserBean passObj(UserBean user){ return user; } //http://localhost:8080/user/n1 //http://localhost:8080/user/n2 @ResponseBody @RequestMapping(value = {"/n1","/n2"},produces = "text/plain;charset=UTF-8") public String group(){ return "不同路径定位到同一方法"; } }
true
54a7ca42c4624b0b9b2d0d698463d8974617e139
Java
lionoa/SSM
/src/main/java/com/example/pojo/Book.java
UTF-8
416
2
2
[]
no_license
package com.example.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.stereotype.Component; @Component @Data @AllArgsConstructor @NoArgsConstructor @ToString public class Book { private Integer id; private String bookName; private Integer price; private Integer bookNums; private String bookType; }
true
56c09ff36999536069a2ead436b2efba1ddbefda
Java
yuluoqian/videoManager
/src/main/java/org/lc/video/controller/VideoController.java
UTF-8
2,765
2.234375
2
[ "Apache-2.0" ]
permissive
package org.lc.video.controller; import org.lc.video.model.Course; import org.lc.video.model.Teacher; import org.lc.video.model.Video; import org.lc.video.service.ICourseService; import org.lc.video.service.ITeacherService; import org.lc.video.service.IVideoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller public class VideoController { @Autowired private IVideoService videoService; @Autowired private ITeacherService teacherService; @Autowired private ICourseService courseService; @RequestMapping("videos/all") public String allVideo(Model model){ model.addAttribute("active","video"); //所有视频列表 List<Video> videoList = videoService.findAllVideo(); model.addAttribute("videoList",videoList); //所有讲师列表 List<Teacher> teacherList = teacherService.findAllTeacher(); model.addAttribute("teacherList",teacherList); //所有课程 List<Course> courseList = courseService.findAllCourse(); model.addAttribute("courseList",courseList); System.out.println("-------->查询到的视频:"); for (Video teacher : videoList) { System.out.println(teacher.getTitle()); } return "admin/video"; } @RequestMapping("video/save") public String saveVideo(Video video){ int num = videoService.saveVideo(video); if (num > 0){ System.out.println("保存成功"); } else{ System.out.println("保存失败"); } return "redirect:/videos/all.do"; } @RequestMapping("video/delete") @ResponseBody public String deleteVideo(Video video){ int num = videoService.deleteVideo(video); return num > 0? "yes":"no"; } @RequestMapping("video/search") public String searchVideo(String searchTitle,String searchTeacher,String searchCourse,Model model){ model.addAttribute("active","video"); List<Video> videoList = videoService.findVideo(searchTitle, searchTeacher, searchCourse); model.addAttribute("videoList",videoList); //所有讲师列表 List<Teacher> teacherList = teacherService.findAllTeacher(); model.addAttribute("teacherList",teacherList); //所有课程 List<Course> courseList = courseService.findAllCourse(); model.addAttribute("courseList",courseList); return "admin/video"; } }
true
5c29e43069a439382ecbb97ce6e4967a357b4be8
Java
YINQIEIE/SimpleIndicator
/app/src/main/java/com/yq/simpleindicator/MainActivity.java
UTF-8
1,468
2.265625
2
[]
no_license
package com.yq.simpleindicator; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private SimpleIndicator indicator; private ViewPager viewpager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); assignViews(); List<String> titles = new ArrayList<>(); ArrayList<TextView> views = new ArrayList<>(); for (int i = 0; i < 15; i++) { titles.add("标题" + (i + 1)); TextView tv = new TextView(this); tv.setText("pager" + (i + 1)); tv.setTextSize(18); tv.setGravity(Gravity.CENTER); tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); views.add(tv); } viewpager.setAdapter(new ViewPagerAdapter(views)); indicator.setTabItemTitles(titles); indicator.setViewPager(viewpager, 0); } private void assignViews() { indicator = (SimpleIndicator) findViewById(R.id.id_indicator); viewpager = (ViewPager) findViewById(R.id.viewpager); } }
true
c68a5bff80e34e2d2863a8d084d833784684abf7
Java
RionPark/jwc
/src/숙제/d20200624/장재민/Bus_1.java
UTF-8
267
2.65625
3
[]
no_license
package 숙제.d20200624.장재민; public class Bus_1 extends Car_1 { public void type() { } public static void main(String [] args) { Bus_1 b = new Bus_1(); b.type = "버스"; System.out.println("차종은 " + b.type + " 입니다."); } }
true
d00a8b9cc83aee8f0f8f7cfebbed268924d77863
Java
uniprot/enzymeportal
/benchmark/unisave/src/main/java/uk/ac/ebi/ep/unisave/repositories/UnisaveEntryCustomRepository.java
UTF-8
542
1.773438
2
[ "Apache-2.0" ]
permissive
package uk.ac.ebi.ep.unisave.repositories; import com.couchbase.client.java.document.JsonDocument; import java.util.List; import java.util.Set; import org.springframework.data.repository.NoRepositoryBean; import uk.ac.ebi.ep.unisave.documents.UnisaveEntry; /** * * @author Joseph */ @NoRepositoryBean public interface UnisaveEntryCustomRepository { List<UnisaveEntry> findEntrieByAccession(String accession); void loadUnisaveEntries(List<UnisaveEntry> entries); void loadUnisaveEntries(Set<JsonDocument> jsonDocuments); }
true
a2a9cfac3a7a89515f211779c92db1c9b7255283
Java
Nisfeight8/travel_permits_management_system
/tpms_api/src/main/java/travel/permits/management/system/api/validator/RoleNameValidator.java
UTF-8
856
2.25
2
[]
no_license
package travel.permits.management.system.api.validator; import org.springframework.beans.factory.annotation.Autowired; import travel.permits.management.system.api.model.enums.RoleName; import travel.permits.management.system.api.repository.AuthorityRepository; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class RoleNameValidator implements ConstraintValidator<UniqueRoleName, String> { @Override public void initialize(UniqueRoleName roleName) { } @Autowired AuthorityRepository authRepository; @Override public boolean isValid(String roleNameField, ConstraintValidatorContext cxt) { return !authRepository.existsByAuthority(RoleName.getByRoleName(roleNameField))&&RoleName.getByRoleName(roleNameField)!=null; } }
true
0f9bb3bad032dd43d117415dde56b828d8ba2dcb
Java
s-samann/Palladio-Addons-IntBIIS
/edu.kit.ipd.sdq.eventsim/src/edu/kit/ipd/sdq/eventsim/interpreter/seff/strategies/AcquireActionTraversalStrategy.java
UTF-8
2,396
2.375
2
[]
no_license
package edu.kit.ipd.sdq.eventsim.interpreter.seff.strategies; import de.uka.ipd.sdq.pcm.repository.PassiveResource; import de.uka.ipd.sdq.pcm.seff.AcquireAction; import edu.kit.ipd.sdq.eventsim.entities.Request; import edu.kit.ipd.sdq.eventsim.entities.SimPassiveResource; import edu.kit.ipd.sdq.eventsim.events.ResumeSeffTraversalEvent; import edu.kit.ipd.sdq.eventsim.exceptions.unchecked.EventSimException; import edu.kit.ipd.sdq.eventsim.interpreter.seff.IRequestTraversalInstruction; import edu.kit.ipd.sdq.eventsim.interpreter.seff.ISeffTraversalStrategy; import edu.kit.ipd.sdq.eventsim.interpreter.seff.instructions.RequestTraversalInstructionFactory; import edu.kit.ipd.sdq.eventsim.interpreter.state.RequestState; /** * This traversal strategy is responsible for {@link AcquireAction}s. * * @author Philipp Merkle * */ public class AcquireActionTraversalStrategy implements ISeffTraversalStrategy<AcquireAction> { /** * {@inheritDoc} */ @Override public IRequestTraversalInstruction traverse(final AcquireAction action, final Request request, final RequestState state) { if (!action.getResourceDemand_Action().isEmpty()) { throw new EventSimException("Parametric resource demands are not yet supported for AcquireActions."); } final PassiveResource passiveResouce = action.getPassiveresource_AcquireAction(); final SimPassiveResource res = state.getComponent().getPassiveResource(passiveResouce); final boolean acquired = res.acquire(request.getSimulatedProcess(), 1, false, action.getTimeoutValue()); if (acquired) { return RequestTraversalInstructionFactory.traverseNextAction(action.getSuccessor_AbstractAction()); } else { request.passivate(new ResumeSeffTraversalEvent(request.getModel(), state)); // here, it is assumed that the passive resource grants access to waiting processes as // soon as the requested capacity becomes available. Thus, we do not need to acquire the // passive resource again as this will be done within the release method. Accordingly // the traversal resumes with the successor of this action. return RequestTraversalInstructionFactory.interruptTraversal(action.getSuccessor_AbstractAction()); } } }
true
7575d105e98edbaa23d3f022fbc66f5b8636f261
Java
lizhengdao/SmartHouse
/src/cn/com/zzwfang/bean/AttentionBean.java
UTF-8
2,146
1.851563
2
[]
no_license
package cn.com.zzwfang.bean; public class AttentionBean extends BaseBean { private String Photo; private String Titel; private int TypeF; private int TypeT; private String Diretion; private String Floor; private String TotalFloor; private String EstName; private String Price; private String Square; private String AgentId; private String PropertyId; private long Lat; private long Lng; public String getPhoto() { return Photo; } public void setPhoto(String photo) { Photo = photo; } public String getTitel() { return Titel; } public void setTitel(String titel) { Titel = titel; } public int getTypeF() { return TypeF; } public void setTypeF(int typeF) { TypeF = typeF; } public int getTypeT() { return TypeT; } public void setTypeT(int typeT) { TypeT = typeT; } public String getDiretion() { return Diretion; } public void setDiretion(String diretion) { Diretion = diretion; } public String getFloor() { return Floor; } public void setFloor(String floor) { Floor = floor; } public String getTotalFloor() { return TotalFloor; } public void setTotalFloor(String totalFloor) { TotalFloor = totalFloor; } public String getEstName() { return EstName; } public void setEstName(String estName) { EstName = estName; } public String getPrice() { return Price; } public void setPrice(String price) { Price = price; } public String getSquare() { return Square; } public void setSquare(String square) { Square = square; } public String getAgentId() { return AgentId; } public void setAgentId(String agentId) { AgentId = agentId; } public String getPropertyId() { return PropertyId; } public void setPropertyId(String propertyId) { PropertyId = propertyId; } public long getLat() { return Lat; } public void setLat(long lat) { Lat = lat; } public long getLng() { return Lng; } public void setLng(long lng) { Lng = lng; } }
true
13fe26c6931401fdbc340e5efe8577d60a3bf7a9
Java
kaiTran56/GUI
/JDBC/src/learn/JDBC/TestConnectMySql.java
UTF-8
1,924
3.0625
3
[]
no_license
package learn.JDBC; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class TestConnectMySql { public static Connection connect; public static ResultSet result; public static void main(String[] args) { Properties pro = new Properties(); try { pro.load(new FileInputStream("mysql.properties")); String user = pro.getProperty("user"); String password = pro.getProperty("password"); String url = pro.getProperty("url"); initialize(user,password,url); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void initialize(String user, String password,String url) { try { System.out.println("Connecting..."); Class.forName("com.mysql.cj.jdbc.Driver"); connect = DriverManager.getConnection(url, user, password); connect.setAutoCommit(false); Statement statement = connect.createStatement(); statement.executeUpdate("Insert into student value(14,'Ngoc Anh',7,'End game');"); //statement.executeUpdate("Delete from student where name like 'Ngoc Anh';"); result = statement.executeQuery("select * from student ;"); boolean ok = true; if(ok) { connect.commit(); System.out.println("Make commit!"); }else { connect.rollback(); System.out.println("Make rollback!"); } System.out.println("Access granted !"); while(result.next()) { System.out.println(result.getInt(1)+" - "+result.getString(2)+" - "+result.getInt(3)+" - "+ result.getString(4)); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
6ef19e58911c97adc1862e8d30e7eabe5062f981
Java
Lucky-Lea/myssm
/ssm/src/main/java/com/lea/controller/UserHandler.java
UTF-8
1,292
2.203125
2
[]
no_license
package com.lea.controller; import com.lea.entity.User; import com.lea.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpSession; @Controller @RequestMapping("/user") public class UserHandler { @Autowired private UserService userService; @GetMapping("/index") public ModelAndView findAll(){ ModelAndView modelAndView=new ModelAndView(); modelAndView.setViewName("index"); modelAndView.addObject("list",userService.findAll()); return modelAndView; } @RequestMapping("login") public String login(@RequestParam("name") String name, @RequestParam("password") String password, HttpSession session, Model model){ User user = userService.login(name,password); if(user == null){ return "login"; }else{ session.setAttribute("user",user); return "redirect:/user/index"; } } }
true
72a4df8be87245cacc751f7fd3fff0ce9f397467
Java
teartao/jarvis
/jarvis-jdbc/src/main/java/net/hehe/example/JdbcTemplateEg.java
UTF-8
11,274
2.65625
3
[ "Apache-2.0" ]
permissive
package net.hehe.example; import org.springframework.jdbc.core.*; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.Assert; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * @Author neo·tao * @Date 2017/11/22 * @Desc */ public class JdbcTemplateEg { private JdbcTemplate jdbcTemplate; /** * 创建表 */ public void create(String tableName) { //tb_test1 jdbcTemplate.execute("create table " + tableName + " (id integer,user_name varchar2(40),password varchar2(40))"); } //jdbcTemplate.update适合于insert 、update和delete操作; /** * 第一个参数为执行sql * 第二个参数为参数数据 */ public void save3(User user) { Assert.isNull(user, "user is not null"); jdbcTemplate.update("insert into tb_test1(name,password) values(?,?)", new Object[]{user.getUsername(), user.getPassword()}); } /** * 第一个参数为执行sql * 第二个参数为参数数据 * 第三个参数为参数类型 */ public void save(User user) { Assert.isNull(user, "user is not null"); jdbcTemplate.update( "insert into tb_test1(name,password) values(?,?)", new Object[]{user.getUsername(), user.getPassword()}, new int[]{java.sql.Types.VARCHAR, java.sql.Types.VARCHAR} ); } //避免sql注入 public void save2(final User user) { Assert.isNull(user, "user is not null"); jdbcTemplate.update("insert into tb_test1(name,password) values(?,?)", new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); } }); } public void save4(User user) { Assert.isNull(user, "user is not null"); jdbcTemplate.update("insert into tb_test1(name,password) values(?,?)", new Object[]{user.getUsername(), user.getPassword()}); } //返回插入的主键 public List save5(final User user) { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement("insert into tb_test1(name,password) values(?,?)", new String[]{"id"}); ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); return ps; } }, keyHolder); return keyHolder.getKeyList(); } public void update(final User user) { jdbcTemplate.update( "update tb_test1 set name=?,password=? where id = ?", new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); ps.setInt(3, user.getId()); } } ); } public void delete(User user) { Assert.isNull(user, "user is not null"); jdbcTemplate.update( "delete from tb_test1 where id = ?", new Object[]{user.getId()}, new int[]{java.sql.Types.INTEGER}); } @Deprecated //因为没有查询条件,所以用处不大 public int queryForInt1() { return jdbcTemplate.queryForObject("select count(0) from tb_test1", Integer.class); } public int queryForInt2(User user) { return jdbcTemplate.queryForObject("select count(0) from tb_test1 where username = ?", new Object[]{user.getUsername()}, Integer.class); } //最全的参数3个 public int queryForInt3(User user) { return jdbcTemplate.queryForObject("select count(0) from tb_test1 where username = ?", new Object[]{user.getUsername()}, new int[]{java.sql.Types.VARCHAR}, Integer.class); } //可以返回是一个基本类型的值 @Deprecated //因为没有查询条件,所以用处不大 public String queryForObject1(User user) { return (String) jdbcTemplate.queryForObject("select username from tb_test1 where id = 100", String.class); } //可以返回值是一个对象 @Deprecated //因为没有查询条件,所以用处不大 public User queryForObject2(User user) { return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = 100", User.class); //class是结果数据的java类型 } @Deprecated //因为没有查询条件,所以用处不大 public User queryForObject3(User user) { return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = 100", new RowMapper() { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); return user; } } ); } public User queryForObject4(User user) { return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = ?", new Object[]{user.getId()}, User.class); //class是结果数据的java类型 实际上这里是做反射,将查询的结果和User进行对应复制 } public User queryForObject5(User user) { return (User) jdbcTemplate.queryForObject( "select * from tb_test1 where id = ?", new Object[]{user.getId()}, new RowMapper() { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); return user; } }); //class是结果数据的java类型 } public User queryForObject(User user) { //方法有返回值 return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = ?", new Object[]{user.getId()}, new int[]{java.sql.Types.INTEGER}, new RowMapper() { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); return user; } } ); } @SuppressWarnings("unchecked") public List<User> queryForList1(User user) { return (List<User>) jdbcTemplate.queryForList("select * from tb_test1 where username = ?", new Object[]{user.getUsername()}, User.class); } @SuppressWarnings("unchecked") public List<String> queryForList2(User user) { return (List<String>) jdbcTemplate.queryForList("select username from tb_test1 where sex = ?", new Object[]{user.getSex()}, String.class); } @SuppressWarnings("unchecked") //最全的参数查询 public List<User> queryForList3(User user) { return (List<User>) jdbcTemplate.queryForList("select * from tb_test1 where username = ?", new Object[]{user.getUsername()}, new int[]{java.sql.Types.VARCHAR}, User.class); } //通过RowCallbackHandler对Select语句得到的每行记录进行解析,并为其创建一个User数据对象。实现了手动的OR映射。 public User queryUserById4(String id) { final User user = new User(); //该方法返回值为void this.jdbcTemplate.query("select * from tb_test1 where id = ?", new Object[]{id}, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); } }); return user; } @SuppressWarnings("unchecked") public List<User> list(User user) { return jdbcTemplate.query("select * from tb_test1 where username like '%?%'", new Object[]{user.getUsername()}, new int[]{java.sql.Types.VARCHAR}, new RowMapper() { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); return user; } }); } //批量操作 适合于增、删、改操作 public int[] batchUpdate(final List users) { int[] updateCounts = jdbcTemplate.batchUpdate( "update tb_test1 set username = ?, password = ? where id = ?", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setString(1, ((User) users.get(i)).getUsername()); ps.setString(2, ((User) users.get(i)).getPassword()); ps.setLong(3, ((User) users.get(i)).getId()); } @Override public int getBatchSize() { return users.size(); } } ); return updateCounts; } //调用存储过程 public void callProcedure(int id) { this.jdbcTemplate.update("call SUPPORT.REFRESH_USERS_SUMMARY(?)", new Object[]{Long.valueOf(id)}); } }
true
5745fa76c06ff004ca618f58d58a0f65249cf6fb
Java
bakhodir10/BS-framework
/src/bs/framework/Finco.java
UTF-8
1,740
2.890625
3
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
package bs.framework; import bs.framework.customer.ICustomer; import bs.framework.account.IAccount; import bs.framework.ui.Forum; import java.util.ArrayList; import java.util.List; public class Finco implements IFinco { private String name; private List<ICustomer> customerList; private List<IAccount> accountList; public Finco(String name) { this.name = name; this.customerList = new ArrayList<>(); this.accountList = new ArrayList<>(); } @Override public void addInterest() { this.accountList.forEach(e -> e.addInterest()); } @Override public void create(ICustomer customer, IAccount account) { customer.addAccount(account); this.accountList.add(account); this.customerList.add(customer); } @Override public void deposit(IAccount account, double amount) { account.deposit(account, amount); } @Override public void withdraw(IAccount account, double amount) { account.withdraw(account, amount); } @Override public String report() { String report = "Sample report\n"; for (IAccount acc : accountList) report += acc.getBalance() + "\n"; return report; } static List<String> s = new ArrayList<String>(); public static void main(String[] args) { s.add("name"); s.add("accNum"); s.add("street"); Forum base = new Forum("FrameWork Test"); base.setScrollPanel(s); base.setVisible(true); } public String getName() { return name; } public List<ICustomer> getCustomerList() { return customerList; } public List<IAccount> getAccountList() { return accountList; } }
true
05a0834c4cfce38a49d29426857bfe50aea1a518
Java
dmitrybilyk/interviews
/src/main/java/com/learn/exercises/If1.java
UTF-8
809
3.8125
4
[]
no_license
package com.learn.exercises; public class If1 { static boolean b; public static void main(String [] args) { short hand = 42; if (hand < 50 && !b) /* Line 7 */ { hand++; } if (hand > 50) { ; /* Line 9 */ } else if (hand > 40) { hand += 7; hand++; } else { --hand; } System.out.println(hand); // int i = 1; // while(false){ // System.out.println("fsdfs"); // } } } //In Java, boolean instance variables are initialized to false, so the if test on line 7 // is true and hand is incremented. Line 9 is legal syntax, a do nothing statement. // The else-if is true so hand has 7 added to it and is then incremented.
true
291563e6a6d05d08f9eda0a5c63821b094a36680
Java
Flynn81/gd
/app/src/main/java/com/woodlawn/globaldominion/MainMenuActivity.java
UTF-8
1,452
2.234375
2
[]
no_license
package com.woodlawn.globaldominion; import com.woodlawn.globaldominion.map.TestMapView; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.EditText; import android.view.View; import android.view.View.OnClickListener; public class MainMenuActivity extends Activity implements OnClickListener { private int mGameSize = TestMapView.SMALL; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_menu); findViewById(R.id.p).setOnClickListener(this); findViewById(R.id.small).setOnClickListener(this); findViewById(R.id.medium).setOnClickListener(this); findViewById(R.id.large).setOnClickListener(this); } public void onClick(View v) { if(v.getId() == R.id.p) { EditText edit = (EditText) findViewById(R.id.npe); int numPlayers = Integer.valueOf(edit.getText().toString()); Intent intent = new Intent(MainMenuActivity.this, GameActivity.class); intent.putExtra(GameActivity.EXTRA_NUMBER_OF_PLAYERS, numPlayers); intent.putExtra(GameActivity.EXTRA_GAME_SIZE, mGameSize); startActivity(intent); } else if(v.getId() == R.id.small){ mGameSize = TestMapView.SMALL; } else if(v.getId() == R.id.medium){ mGameSize = TestMapView.MEDIUM; } else if(v.getId() == R.id.large){ mGameSize = TestMapView.LARGE; } } }
true
64497fe99f12c84293a1887711509b8f9d2d31a5
Java
chongchong01/selenium_java
/src/main/java/test2.java
UTF-8
829
2.046875
2
[]
no_license
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.List; import java.util.Map; import com.esotericsoftware.yamlbeans.YamlException; import com.esotericsoftware.yamlbeans.YamlReader; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import util.YamlRead; public class test2 { public static void main(String[] args) throws FileNotFoundException, YamlException { YamlRead yamlRead = new YamlRead("/Login.yaml"); List list = (List) yamlRead.getYmal().get("check"); System.out.println(list); for(Object l: list){ System.out.println(((Map)l).get("element_info")); System.out.println(((Map)l).get("find_type")); } } }
true
a62a5cfa92aaaa7bb178f149170da511993abae4
Java
SKAPUSTIANSKYI/i
/wf-base/src/main/java/org/wf/dp/dniprorada/base/model/FlowSlot.java
UTF-8
627
2.28125
2
[]
no_license
package org.wf.dp.dniprorada.base.model; import org.joda.time.DateTime; import javax.persistence.Column; /** * Slot of the Flow. Stored in regional server. * * User: goodg_000 * Date: 14.06.2015 * Time: 15:26 */ @javax.persistence.Entity public class FlowSlot extends NamedEntity { @Column private String sData; @Column private DateTime sDate; public String getsData() { return sData; } public void setsData(String sData) { this.sData = sData; } public DateTime getsDate() { return sDate; } public void setsDate(DateTime sDate) { this.sDate = sDate; } }
true
d537f510bb47b39da886691518d5cd5a85704783
Java
KrisBiserovKrumov/ProgramicBasic
/fundamentals/src/basicSyntax/Vacation.java
UTF-8
1,767
3.578125
4
[]
no_license
package basicSyntax; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Vacation { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int persons = Integer.parseInt(reader.readLine()); String type = reader.readLine(); String day = reader.readLine(); double price = 0; if (day.equals("Friday")){ if (type.equals("Students")){ price += 8.45 * persons; }else if (type.equals("Business")){ price += 10.90 * persons; }else if (type.equals("Regular")){ price += 15 * persons; } }else if (day.equals("Saturday")){ if (type.equals("Students")){ price += 9.80 * persons; }else if (type.equals("Business")){ price += 15.60 * persons; }else if (type.equals("Regular")){ price += 20 * persons; } }else if (day.equals("Sunday")){ if (type.equals("Students")){ price += 10.46 * persons; }else if (type.equals("Business")){ price += 16 * persons; }else if (type.equals("Regular")){ price += 22.50 * persons; } } if (persons >= 30 && type.equals("Students")){ price *= 0.85; }if (type.equals("Regular") && persons >= 10 && persons <= 20){ price *= 0.95; }if (type.equals("Business") && persons >= 100){ price -= (price / persons) * 10; } System.out.printf("Total price: %.2f" , price); } }
true
58b6e6ad8f8cdd1db35a372cad555847169d12fc
Java
delightsoft/DSCommon
/app/code/docflow/compiler/Compiler110DocumentsStep1.java
UTF-8
34,129
2.203125
2
[ "Apache-2.0" ]
permissive
package code.docflow.compiler; // // Author: Alexey Zorkaltsev (alexey@zorkaltsev.com) // import code.docflow.controlflow.Result; import code.docflow.DocflowConfig; import code.docflow.collections.Item; import code.docflow.compiler.enums.*; import code.docflow.model.*; import code.docflow.yaml.YamlMessages; import code.docflow.utils.NamesUtil; import code.docflow.yaml.compositeKeyHandlers.TransitionCompositeKeyHandler; import java.util.*; /** * 1. Checks that fields do not have reserved names. * 2. Create Document.entities. * 3. Adds implicit fields (like id, rev, create etc.). * 4. Sets Field.index and Field.endIndex. * 5. Sets Field.fullname. * 6. Builds Document.allFields. * 7. Builds Document.implicitFields. * 8. Processes 'textstorage' attribute on fields, and conditionally adds 'textStorage' field. * 9. Collects fields to Entities * 10. Links Fields of type Structure to it's Entity * 11. Generates Entity.javaClassName and Entity.tableName */ public class Compiler110DocumentsStep1 { private static final Comparator<DocType> DOCUMENT_ASCENDING_SORT_BY_NAME = new Comparator<DocType>() { public int compare(DocType o1, DocType o2) { return o1.name.compareTo(o2.name); } }; public static void doJob(DocflowConfig docflowConfig, Result result) { docflowConfig.documentsArray = new DocType[docflowConfig.documents.size()]; int di = 0; for (DocType doc : docflowConfig.documents.values()) { doc.index = di; docflowConfig.documentsArray[di++] = doc; } Arrays.sort(docflowConfig.documentsArray, DOCUMENT_ASCENDING_SORT_BY_NAME); for (int i = 0; i < docflowConfig.documentsArray.length; i++) { DocType doc = docflowConfig.documentsArray[i]; if (doc.task) { doc.simple = doc.rev = true; if (doc.states != null) result.addMsg(YamlMessages.error_NoStatesInTaskDoc, doc.name); } if (doc.light) doc.simple = true; // empty fields list, if none if (doc.fields == null) doc.fields = new LinkedHashMap<String, Field>(); if (doc.actions == null) doc.actions = new LinkedHashMap<String, Action>(); if (doc.states == null) doc.states = new LinkedHashMap<String, State>(); if (doc.task) { // Note: Reference schema you can see in {DSCommonTest}/docflow/documents/ControlsTask.yaml // add field 'result' FieldSimple fieldResult = new FieldSimple(); fieldResult.name = BuiltInFields.RESULT.toString(); fieldResult.type = BuiltInTypes.RESULT; fieldResult.derived = true; fieldResult.accessedFields = new HashSet<String>(); doc.fields.put(BuiltInFields.RESULT.name(), fieldResult); // add actions addAction(doc, TaskActions.STARTJOB); addAction(doc, TaskActions.BACKTOAWAIT); addAction(doc, TaskActions.CANCEL) .display = true; addAction(doc, TaskActions.SUCCESS); addAction(doc, TaskActions.ERROR); // add states // - new final State newState = addState(doc, BuiltInStates.NEW); newState.update = newState.view = fieldsViewUpdateList(BuiltInFieldsGroups.UPDATABLE); addTransition(newState, CrudActions.CREATE, TaskStates.AWAIT); // - await final State awaitState = addState(doc, TaskStates.AWAIT); awaitState.view = fieldsViewUpdateList(BuiltInFieldsGroups.NONRESULT); addTransition(awaitState, TaskActions.STARTJOB, TaskStates.RUNNING); addTransition(awaitState, TaskActions.CANCEL, TaskStates.ERROR); // - running final State runningState = addState(doc, TaskStates.RUNNING); runningState.view = fieldsViewUpdateList(BuiltInFieldsGroups.NONRESULT); addTransition(runningState, TaskActions.BACKTOAWAIT, TaskStates.AWAIT); addTransition(runningState, TaskActions.SUCCESS, TaskStates.SUCCESS); addTransition(runningState, TaskActions.ERROR, TaskStates.ERROR); addTransition(runningState, TaskActions.CANCEL, TaskStates.ERROR.toString()); // - canceled final State canceledState = addState(doc, TaskStates.CANCELED); canceledState.view = fieldsViewUpdateList(BuiltInFieldsGroups.NONRESULT); addTransition(canceledState, TaskActions.SUCCESS, TaskStates.SUCCESS); addTransition(canceledState, TaskActions.ERROR, TaskStates.ERROR); // -success final State successState = addState(doc, TaskStates.SUCCESS); successState.view = fieldsViewUpdateList(BuiltInFieldsGroups.ALL, BuiltInFields.RESULT); // - error final State errorState = addState(doc, TaskStates.ERROR); errorState.view = fieldsViewUpdateList(BuiltInFieldsGroups.NONRESULT, BuiltInFields.RESULT); } else { // regular document (not task) // States: // - new final State newState = addState(doc, BuiltInStates.NEW, true); if (newState.update == null) newState.update = fieldsViewUpdateList(BuiltInFieldsGroups.UPDATABLE); // Rule: NEW state must be first in yaml states for (State state : doc.states.values()) { if (state != newState) result.addMsg(YamlMessages.error_DocumentNewStateMustComeFirst, doc.name, state.name, BuiltInStates.NEW.toString()); break; } // - persisted, if none persisted states State firstPersistedState = null; if (doc.states.size() < 2) { firstPersistedState = addState(doc, BuiltInStates.PERSISTED); firstPersistedState.view = fieldsViewUpdateList(BuiltInFieldsGroups.ALL); if (!doc.simple) firstPersistedState.update = firstPersistedState.view; } else { int p = 0; for (State state : doc.states.values()) { if (p == 1) { firstPersistedState = state; break; } p++; } } // Rule: NEW state has one and only one transtion CREATE to first persisted state if (newState.transitions == null || newState.transitions.size() == 0) { addTransition(newState, CrudActions.CREATE, firstPersistedState.name); } else if (newState.transitions.size() > 1 || newState.transitions.get(CrudActions.CREATE.name()) == null) { result.addMsg(YamlMessages.error_DocumentNewStateCanOnlyHasCreateTransitions, doc.name, BuiltInStates.NEW.toString(), CrudActions.CREATE.toString()); } if (doc.states.size() == 2) { // Rule: In two states document all non-service actions are transitions to persisted state firstPersistedState.transitions = new LinkedHashMap<String, Transition>(); for (Action action : doc.actions.values()) // Note: This happends priod building doc.actionsArray. So Update is not marked as implicit action yet if (!action.service && !CrudActions.UPDATE.name().equals(action.name.toUpperCase())) { final Transition transition = new Transition(); transition.name = action.name; transition.endState = firstPersistedState.name; firstPersistedState.transitions.put(transition.name.toUpperCase(), transition); } } else { // any state documents must have 'rev' to coordinate state transitions in a parallel environment doc.rev = true; } } // detailed fields validation. builds Entities. adds implicit fields. final Entity entity = new Entity(); entity.name = doc.name; entity.tableName = "doc_" + NamesUtil.wordsToUnderscoreSeparated(doc.name); entity.type = doc.report ? EntityType.REPORT : (doc.light ? EntityType.LIGHT_DOCUMENT : (doc.simple ? EntityType.SIMPLE_DOCUMENT : EntityType.DOCUMENT)); entity.document = doc; doc.entities.add(entity); indexFieldsAtLevel(docflowConfig, doc, entity, null, "", doc.fields, 0, result); if (entity.type == EntityType.DOCUMENT) { doc.historyTableName = "doc_" + NamesUtil.wordsToUnderscoreSeparated(doc.name) + "_history"; doc.historyEntityName = doc.name + "History"; } doc.textField = doc.fieldByFullname.get(BuiltInFields.TEXT.name()); if (doc.textField == null) { if (doc.textSourceField != null) result.addMsg(YamlMessages.error_FieldDocTypeDoesNotSupportText, doc.name, doc.textSourceField.fullname); } else { doc.textField.calculated = !doc.blendText; if (doc.blendText && doc.textSourceField != null) result.addMsg(YamlMessages.error_FieldFieldTextInBlendTextDoc, doc.name, doc.textSourceField.fullname); } docflowConfig.documentByTable.put(entity.tableName.toUpperCase(), doc); } } private static Action addAction(DocType doc, Enum action) { if (doc.actions == null) doc.actions = new LinkedHashMap<String, Action>(); Action res = doc.actions.get(action.name()); if (res == null) { res = new Action(); res.name = action.toString(); doc.actions.put(action.name(), res); } return res; } private static LinkedHashMap<String, Item> fieldsViewUpdateList(Enum... fieldOrFieldsGroups) { final LinkedHashMap<String, Item> res = new LinkedHashMap<String, Item>(); for (Enum fieldOrFieldsGroup : fieldOrFieldsGroups) if (fieldOrFieldsGroup instanceof BuiltInFieldsGroups) { final Item updatableFields = new Item("_" + fieldOrFieldsGroup.toString()); res.put("_" + fieldOrFieldsGroup.name(), updatableFields); } else { final Item updatableFields = new Item(fieldOrFieldsGroup.toString()); res.put(fieldOrFieldsGroup.name(), updatableFields); } return res; } private static boolean hasState(DocType doc, Enum state) { return doc.states.containsKey(state.name()); } private static State addState(DocType doc, Enum state) { return addState(doc, state, false); } private static State addState(DocType doc, Enum state, boolean unshift) { State res = doc.states.get(state.name()); if (res == null) { res = new State(); res.name = state.toString(); res.transitions = new LinkedHashMap<String, Transition>(); if (unshift && doc.states.size() > 0) { final LinkedHashMap<String, State> newStatesList = new LinkedHashMap<String, State>(); newStatesList.put(state.name(), res); newStatesList.putAll(doc.states); doc.states = newStatesList; } else doc.states.put(state.name(), res); } return res; } private static Transition addTransition(State state, Enum action, Enum endState) { return addTransition(state, action, endState.toString(), null); } private static Transition addTransition(State state, Enum action, String endState) { return addTransition(state, action, endState, null); } private static Transition addTransition(State state, Enum action, Enum endState, Enum precondition) { return addTransition(state, action, endState.toString(), precondition); } private static Transition addTransition(State state, Enum action, String endState, Enum precondition) { if (state.transitions == null) state.transitions = new LinkedHashMap<String, Transition>(); Transition res = new Transition(); res.name = action.toString(); res.endState = endState; if (precondition != null) res.preconditions = new String[] {precondition.toString()}; final String key = TransitionCompositeKeyHandler.INSTANCE.key(res); final Transition existing = state.transitions.get(key); if (existing != null) return existing; state.transitions.put(key, res); return res; } private static int indexFieldsAtLevel(DocflowConfig docflowConfig, DocType doc, Entity entity, FieldStructure structure, String namePrefix, LinkedHashMap<String, Field> fields, int index, Result result) { switch (entity.type) { case LIGHT_DOCUMENT: case SIMPLE_DOCUMENT: index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.ID, doc.implicitFields), index, result); if (doc.rev) index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.REV, doc.implicitFields), index, result); index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.TEXT, doc.implicitFields), index, result); break; case DOCUMENT: index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.ID, doc.implicitFields), index, result); index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.REV, doc.implicitFields), index, result); index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.TEXT, doc.implicitFields), index, result); break; case SUBTABLE: index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.ID, doc.implicitFields), index, result); index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.I, doc.implicitFields), index, result); entity.fkField = buildBuiltInField(doc, structure, BuiltInFields.FK, doc.implicitFields); index = processField(docflowConfig, doc, entity, structure, namePrefix, entity.fkField, index, result); break; } if (entity.type != EntityType.SUBTABLE && entity.type != EntityType.STRUCTURE && entity.type != EntityType.REPORT_STRUCTURE) { if (entity.document.linkedDocument) // Rule: Any document might be flagged as linked index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.SUBJ, doc.implicitFields), index, result); if (doc.states.size() > 2) // Rule: Only two state are a new-state and one persisted state, when there is no need in the STATE field index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.STATE, doc.implicitFields), index, result); } for (Field fld : fields.values()) { if (structure != null) { fld.derived |= structure.derived; fld.calculated |= structure.calculated; } boolean isReservedName = false; final String upperCasedName = fld.name.toUpperCase(); try { BuiltInFields fldName = BuiltInFields.valueOf(upperCasedName); switch (entity.type) { case SIMPLE_DOCUMENT: switch (fldName) { case CREATOR: case CREATED: case TEXT: isReservedName = true; } // fallthru case LIGHT_DOCUMENT: switch (fldName) { case ID: case SUBJ: case REV: case STATE: case TEXT: isReservedName = true; } break; case DOCUMENT: switch (fldName) { case ID: case REV: case SUBJ: case STATE: case TEXT: case TEXT_STORAGE: case MODIFIED: case CREATED: case DELETED: isReservedName = true; } break; case REPORT: switch (fldName) { case STATE: case TEXT: isReservedName = true; } break; case SUBTABLE: switch (fldName) { case ID: case I: case FK: case TEXT_STORAGE: case TEXT: isReservedName = true; } break; } } catch (IllegalArgumentException e) { // it's BuiltInFields.valueOf(upperCasedName) failed, and this is expected behaviour } if (isReservedName) { result.addMsg(YamlMessages.error_FieldHasReservedName, doc.name, namePrefix + fld.name); continue; } if (fld.textstorage) entity.hasTextStorage = true; fld.template = (structure != null ? structure.template : ("_" + doc.name)) + "_" + fld.name; if (!doc.udt) { // _udt document fields was already processed in previouse steps. // apply UDType, if that's the case if (fld.type == null) { final Field fldType = docflowConfig.fieldTypes.get(fld.udtType.toUpperCase()); if (fldType == null) { result.addMsg(YamlMessages.error_FieldHasUnknownType, doc.name, namePrefix + fld.name, fld.udtType); continue; } if (!(fldType instanceof FieldSimple)) { result.addMsg(YamlMessages.error_FieldHasNotSimpleType, doc.name, namePrefix + fld.name, fld.udtType); continue; } fldType.mergeTo(fld); } // apply named enum type if (fld.type == BuiltInTypes.ENUM) if (fld.udtType != null) { Field fldType = docflowConfig.fieldTypes.get(fld.udtType.toUpperCase()); if (fldType == null) { result.addMsg(YamlMessages.error_FieldHasUnknownType, doc.name, namePrefix + fld.name, fld.udtType); continue; } if (!(fldType instanceof FieldEnum)) { result.addMsg(YamlMessages.error_FieldNotAnEnumType, doc.name, namePrefix + fld.name, fld.udtType); continue; } fldType.mergeTo(fld); } else { FieldEnum fieldEnum = (FieldEnum) fld; fieldEnum.enumTypeName = (structure != null ? structure.entity.getClassName() : doc.getClassName()) + "$" + NamesUtil.turnFirstLetterInUpperCase(fld.name); } // apply named structure type if (fld.type == BuiltInTypes.STRUCTURE) if (fld.udtType != null) { Field fldType = docflowConfig.fieldTypes.get(fld.udtType.toUpperCase()); if (fldType == null) { result.addMsg(YamlMessages.error_FieldHasUnknownType, doc.name, namePrefix + fld.name, fld.udtType); continue; } if (!(fldType instanceof FieldStructure) || fldType.type != BuiltInTypes.STRUCTURE) { result.addMsg(YamlMessages.error_FieldNotAStructureType, doc.name, namePrefix + fld.name, fld.udtType); continue; } fldType.deepCopy().mergeTo(fld); } // apply named subtable type if (fld.type == BuiltInTypes.SUBTABLE) if (fld.udtType != null) { Field fldType = docflowConfig.fieldTypes.get(fld.udtType.toUpperCase()); if (fldType == null) { result.addMsg(YamlMessages.error_FieldHasUnknownType, doc.name, namePrefix + fld.name, fld.udtType); continue; } if (!(fldType instanceof FieldStructure) || fldType.type != BuiltInTypes.SUBTABLE) { result.addMsg(YamlMessages.error_FieldNotASubtableType, doc.name, namePrefix + fld.name, fld.udtType); continue; } fldType.deepCopy().mergeTo(fld); } } index = processField(docflowConfig, doc, entity, structure, namePrefix, fld, index, result); validateFieldType(doc, fld, result); if ((fld instanceof FieldSimple) && ((FieldSimple) fld).text) { if (doc.entities.get(0) != entity) result.addMsg(YamlMessages.error_FieldFieldTextCannotBeInASubtable, doc.name, namePrefix + fld.name); else if (doc.textSourceField != null) result.addMsg(YamlMessages.error_FieldAnotherFieldIsText, doc.name, namePrefix + fld.name); else doc.textSourceField = fld; } if (fld.type == BuiltInTypes.JAVA) { if (!doc.report && !fld.calculated) result.addMsg(YamlMessages.error_FieldMustBeCalculated, doc.name, namePrefix + fld.name, BuiltInTypes.JAVA.toString().toLowerCase()); } else if (fld.type == BuiltInTypes.REFERS) { final String docName = ((FieldReference) fld).refDocument; final DocType document = DocflowConfig.instance.documents.get(docName.toUpperCase()); if (document == null) result.addMsg(YamlMessages.error_FieldRefersUndefinedDocument, doc.name, namePrefix + fld.name, docName); } else if (fld.type == BuiltInTypes.POLYMORPHIC_REFERS) { final FieldPolymorphicReference fpr = (FieldPolymorphicReference) fld; if (fpr.refDocuments != null) { fpr.refDocumentsNames = new TreeSet<String>(); for (int i = 0; i < fpr.refDocuments.length; i++) { String docName = fpr.refDocuments[i]; fpr.refDocumentsNames.add(docName.toUpperCase()); final DocType document = DocflowConfig.instance.documents.get(docName.toUpperCase()); if (document == null) result.addMsg(YamlMessages.error_FieldRefersUndefinedDocument, doc.name, namePrefix + fld.name, docName); } } } } if (entity.type == EntityType.DOCUMENT) { index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.CREATED, doc.implicitFields), index, result); index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.MODIFIED, doc.implicitFields), index, result); index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.DELETED, doc.implicitFields), index, result); if (entity.hasTextStorage) index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.TEXT_STORAGE, doc.implicitFields), index, result); } else { if (entity.type == EntityType.SIMPLE_DOCUMENT) { index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.CREATOR, doc.implicitFields), index, result); index = processField(docflowConfig, doc, entity, structure, namePrefix, buildBuiltInField(doc, structure, BuiltInFields.CREATED, doc.implicitFields), index, result); } } return index; } private static int processField(DocflowConfig docflowConfig, DocType doc, Entity entity, FieldStructure structure, String namePrefix, Field field, int index, Result result) { Field fld = field; fld.document = doc; fld.entity = entity; fld.fullname = namePrefix + fld.name; fld.structure = structure; fld.index = index++; fld.endIndex = index; entity.fields.add(field); doc.fieldByFullname.put(fld.fullname.toUpperCase(), fld); doc.allFields.add(fld); if (fld instanceof FieldStructure) { final FieldStructure fldStructure = (FieldStructure) fld; entity = new Entity(); entity.parent = structure != null ? structure.entity : doc.entities.get(0); entity.outerStructure = entity.parent.type == EntityType.STRUCTURE ? entity.parent.outerStructure : entity.parent; entity.name = entity.parent.name + "_" + NamesUtil.turnFirstLetterInUpperCase(fld.name); entity.structureField = fld; entity.tableName = "doc_" + NamesUtil.wordsToUnderscoreSeparated(entity.name); entity.type = doc.report ? EntityType.REPORT_STRUCTURE : (fldStructure.single ? EntityType.STRUCTURE : EntityType.SUBTABLE); entity.document = doc; doc.entities.add(entity); fldStructure.entity = entity; fld.endIndex = index = indexFieldsAtLevel(docflowConfig, doc, entity, fldStructure, fld.fullname + ".", fldStructure.fields, index, result); } return index; } private static void validateFieldType(DocType doc, Field fld, Result result) { if (fld.calculated) // then it's implicitly 'derived' fld.derived = true; // Rule: Enforce Java style of field naming fld.name = NamesUtil.turnFirstLetterInLowerCase(fld.name); for (int j = 0; j < fld.type.required.length; j++) { String attr = fld.type.required[j]; if (!fld.accessedFields.contains(attr.toUpperCase())) result.addMsg(YamlMessages.error_FieldMustHaveGivenAttributeSpecified, doc.name, fld.fullname, fld.type.toString(), attr); } if (fld instanceof FieldSimple) { FieldSimple fieldSimple = (FieldSimple) fld; for (int j = 0; j < FieldSimple.typeAttrs.length; j++) { String attr = FieldSimple.typeAttrs[j]; if (fld.accessedFields.contains(attr.toUpperCase())) { boolean found = false; for (int k = 0; k < fld.type.required.length; k++) if (attr.equals(fld.type.required[k])) { found = true; break; } if (!found) for (int k = 0; k < fld.type.optional.length; k++) if (attr.equals(fld.type.optional[k])) { found = true; break; } if (!found) { result.addMsg(YamlMessages.error_FieldMustNotHaveGivenAttributeSpecified, doc.name, fld.fullname, fld.type.toString(), attr); } } } if (fld.accessedFields.contains("TEXT")) if (fld.type != BuiltInTypes.STRING && fld.type != BuiltInTypes.TEXT) result.addMsg(YamlMessages.error_FieldTextIsOnlyApplicableToString, doc.name, fld.fullname); boolean isMaxLengthAssignedFromLength = false; if (fld.accessedFields.contains("LENGTH")) if (fld.accessedFields.contains("MAXLENGTH")) { if (fieldSimple.maxLength > fieldSimple.length) result.addMsg(YamlMessages.error_FieldMustHasMaxLengthAttrBiggerThenLength, doc.name, fld.fullname); } else { // by default maxLength same as length isMaxLengthAssignedFromLength = true; fieldSimple.maxLength = fieldSimple.length; fld.accessedFields.add("MAXLENGTH"); } if (fld.accessedFields.contains("MINLENGTH") && (isMaxLengthAssignedFromLength || fld.accessedFields.contains("MAXLENGTH"))) if (fieldSimple.minLength > fieldSimple.maxLength) result.addMsg(isMaxLengthAssignedFromLength ? YamlMessages.error_FieldMustHasMinLengthAttrBiggerThenLength : YamlMessages.error_FieldMustHasMinLengthAttrBiggerThenMaxLength, doc.name, fld.fullname); if (fld.accessedFields.contains("MIN") && fld.accessedFields.contains("MAX")) if (fieldSimple.min > fieldSimple.max) result.addMsg(YamlMessages.error_FieldMustHasMinAttrBiggerThenMax, doc.name, fld.fullname); } } /** * Creates document instance of Field for given implicit field, based on hardcoded rules. Adds new field to implicitFields list. * * @return New instance of the field. */ private static Field buildBuiltInField(DocType doc, FieldStructure structure, BuiltInFields implicitFieldType, ArrayList<Field> implicitFields) { Field field = null; switch (implicitFieldType) { case ID: field = new FieldSimple(); field.type = BuiltInTypes.LONG; break; case REV: field = new FieldSimple(); field.type = BuiltInTypes.INT; break; case I: field = new FieldSimple(); field.type = BuiltInTypes.INT; break; case FK: field = new FieldSimple(); field.type = BuiltInTypes.REFERS; break; case CREATED: case MODIFIED: field = new FieldSimple(); field.type = BuiltInTypes.DATETIME; break; case DELETED: field = new FieldSimple(); field.type = BuiltInTypes.BOOL; break; case STATE: field = new FieldSimple(); field.type = BuiltInTypes.STRING; ((FieldSimple) field).length = ((FieldSimple) field).maxLength = 100; break; case TEXT_STORAGE: field = new FieldSimple(); field.type = BuiltInTypes.TEXT; break; case TEXT: FieldSimple textField = new FieldSimple(); field = textField; field.derived = true; field.type = BuiltInTypes.STRING; ((FieldSimple) field).length = ((FieldSimple) field).maxLength = 200; break; case SUBJ: final FieldPolymorphicReference subjField = new FieldPolymorphicReference(); field = subjField; subjField.type = BuiltInTypes.POLYMORPHIC_REFERS; subjField.refDocuments = new String[0]; break; case CREATOR: field = new FieldSimple(); field.type = BuiltInTypes.STRING; ((FieldSimple) field).length = ((FieldSimple) field).maxLength = 100; break; } field.name = implicitFieldType.toString(); field.implicitFieldType = implicitFieldType; field.required = (implicitFieldType != BuiltInFields.TEXT_STORAGE); field.nullable = (implicitFieldType == BuiltInFields.RESULT || implicitFieldType == BuiltInFields.TEXT_STORAGE); field.hidden = true; field.template = (structure != null ? structure.template : ("_" + doc.name)) + "_" + field.name; implicitFields.add(field); return field; } }
true
71e9b891776e6b279b2d4ea50a411d4b54dd0f0f
Java
joaogutierrre/java-collections-practice
/src/br/com/learn/TestaCurso2.java
ISO-8859-1
992
3.125
3
[]
no_license
package br.com.learn; public class TestaCurso2 { public static void main(String[] args) { Curso javaColecoes = new Curso("Dominando as colees do Java", "Paulo Silveira"); javaColecoes.adiciona(new Aula("Trabalhando com ArrayList", 21)); javaColecoes.adiciona(new Aula("Listas de Objetos", 20)); javaColecoes.adiciona(new Aula("Relacionamentos com colees", 25)); /*Old way to display courses & classes lists * * List<Aula> aulasImutaveis = javaColecoes.getAulas(); List<Aula> aulas = new ArrayList<>(aulasImutaveis); int tempo = javaColecoes.getTempoTotal(); String nome = javaColecoes.getNome(); Collections.sort(aulas); System.out.println("Curso: " + nome + ". Tempo total: " + tempo +" hrs."); System.out.println(aulas);*/ /*New way to display courses & classes lists"/ * */ String cursoAulas = javaColecoes.toString(); System.out.println(cursoAulas); } }
true
32970fa21a7d2a2d804f20d2abe3778c94368c93
Java
bajajris/ipldashboard
/src/main/java/com/rishabh/ipldashboard/data/MatchInput.java
UTF-8
1,472
1.976563
2
[]
no_license
package com.rishabh.ipldashboard.data; import lombok.Getter; import lombok.Setter; public class MatchInput { private @Getter @Setter String id; private @Getter @Setter String date; private @Getter @Setter String city; private @Getter @Setter String player_of_match; private @Getter @Setter String venue; private @Getter @Setter String neutral_venue; private @Getter @Setter String team1; private @Getter @Setter String team2; private @Getter @Setter String toss_winner; private @Getter @Setter String toss_decision; private @Getter @Setter String winner; private @Getter @Setter String result; private @Getter @Setter String result_margin; private @Getter @Setter String eliminator; private @Getter @Setter String method; private @Getter @Setter String umpire1; private @Getter @Setter String umpire2; @Override public String toString() { return "MatchInput [city=" + city + ", date=" + date + ", eliminator=" + eliminator + ", id=" + id + ", method=" + method + ", neutral_venue=" + neutral_venue + ", player_of_match=" + player_of_match + ", result=" + result + ", result_margin=" + result_margin + ", team1=" + team1 + ", team2=" + team2 + ", toss_decision=" + toss_decision + ", toss_winner=" + toss_winner + ", umpire1=" + umpire1 + ", umpire2=" + umpire2 + ", venue=" + venue + ", winner=" + winner + "]"; } }
true
ea40f089c71f2717b161f2f79afce92dd065d253
Java
ohadfisher/triangle
/src/main/java/triangle/controller/TriangleController.java
UTF-8
875
2.140625
2
[]
no_license
package triangle.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import triangle.model.State; import triangle.model.Triangle; import triangle.service.StorageService; import java.util.List; @RestController public class TriangleController { private static final Logger log = LoggerFactory.getLogger(TriangleController.class); @Autowired StorageService storageService; @RequestMapping(value = "/addTriangle", method = RequestMethod.POST) public void add(@RequestBody Triangle triangleInput) { log.info("TriangleController.addTriangle: " + triangleInput + "\n"); storageService.add(triangleInput); } }
true
2af86ef0b75a8fc2dedfc340dc45fb5cc64a652d
Java
Guliaiev/Patterns
/src/test/java/ru/netology/CardOrderTest.java
UTF-8
3,800
2.21875
2
[]
no_license
package ru.netology; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.Keys; import java.time.Duration; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selectors.withText; import static com.codeborne.selenide.Selenide.*; import static java.time.Duration.ofSeconds; public class CardOrderTest { String name = DataGenerator.makeName(); String phone = DataGenerator.makePhone(); String city = DataGenerator.makeCity(); public static void correctFieldsCheks() { String name = DataGenerator.makeName(); String phone = DataGenerator.makePhone(); String city = DataGenerator.makeCity(); $("[data-test-id=city] input").setValue(city); $("[data-test-id=date] input").sendKeys(Keys.BACK_SPACE); $("[data-test-id=date] input").sendKeys(DataGenerator.forwardDate(3)); $("[data-test-id=name] input").setValue(name); $("[data-test-id=phone] input").setValue(phone); } public static void clickButton() { $("[data-test-id=agreement]").click(); $(".button__text").click(); } @BeforeEach void setUp() { open("http://localhost:9999/"); } @Test void shouldNewRequest() { $("[data-test-id=city] input").setValue(city); $("[data-test-id=date] input").doubleClick().sendKeys(Keys.BACK_SPACE); $("[data-test-id=date] input").sendKeys(DataGenerator.forwardDate(3)); $("[data-test-id=name] input").setValue(name); $("[data-test-id=phone] input").setValue(phone); $("[data-test-id=agreement] .checkbox__box").click(); $(withText("Запланировать")).click(); $("[data-test-id='success-notification']").shouldBe(visible, ofSeconds(15)); $$("[data-test-id='success-notification']>.notification__content").findBy(text("Встреча успешно запланирована на")).shouldBe(visible); $("[placeholder='Дата встречи']").sendKeys(Keys.chord(Keys.CONTROL, "a") + Keys.BACK_SPACE); $("[placeholder='Дата встречи']").setValue(DataGenerator.forwardDate(5)); $(withText("Запланировать")).click(); $("[data-test-id='replan-notification']").shouldBe(visible); $("[data-test-id='replan-notification']>.notification__content").shouldHave(text("У вас уже" + " запланирована встреча на другую дату. Перепланировать?")); $("[data-test-id=date] input").setValue(DataGenerator.forwardDate(5)); $("[data-test-id=replan-notification] .notification__title").shouldHave(exactText("Необходимо" + " подтверждение")); $(withText("Перепланировать")).click(); $("[data-test-id='success-notification']>.notification__content").shouldBe(visible) .shouldHave(exactText("Встреча успешно запланирована на " + DataGenerator.forwardDate(5))); } @Test void shouldRequest() { $("[data-test-id=city] input").setValue(city); $("[data-test-id=date] input").doubleClick().sendKeys(Keys.BACK_SPACE); $("[data-test-id=date] input").setValue(DataGenerator.forwardDate(3)); $("[data-test-id=name] input").setValue(name); $("[data-test-id=phone] input").setValue(phone); $("[data-test-id=agreement]").click(); $(".button__text").click(); $(withText("Успешно!")) .shouldBe(visible, Duration.ofSeconds(15)); $$(".notification").findBy(text("Встреча успешно запланирована на")).shouldBe(visible); } }
true
aaeeb1a211e3ab48d904c8e6a69a8ed7007444f0
Java
nqduy91299/DesignPattern_LAB
/DP_3rdShift/src/DP/duynguyen/lab1/MultipleThread.java
UTF-8
365
2.734375
3
[]
no_license
package DP.duynguyen.lab1; public class MultipleThread implements Runnable { private String name; public MultipleThread(String name) { // TODO Auto-generated constructor stub this.name = name; } @Override public void run() { Logger logger = Logger.getInstance(); System.out.println("Thread " + name + " " + logger.toString()); } }
true
d691bc80c4f0113b8e3f492fa6322eae396d343e
Java
barry3377/Ussd
/src/main/java/com/ussd/app/Ussd/controller/DepartementController.java
UTF-8
2,054
2.203125
2
[]
no_license
package com.ussd.app.Ussd.controller; import com.ussd.app.Ussd.entities.Departement; import com.ussd.app.Ussd.repository.DepartementRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @Controller public class DepartementController { @Autowired private DepartementRepository departementRepository; @RequestMapping(value="/dep",method = RequestMethod.GET) public String listdep(Model model){ List<Departement>services= (List<Departement>) departementRepository.findAll(); model.addAttribute("services",services); model.addAttribute("service",new Departement()); return "service/service.html"; } @RequestMapping(value="/service" ,method = RequestMethod.GET) public String addservice(Model model){ Departement departement=new Departement(); model.addAttribute("departement",departement); return "service/addService.html"; } @PostMapping(value="/saveService") public String saveDep(Model model, Departement departement, BindingResult h ){ // if(h.hasErrors()){ // // return "service/addService"; // } departementRepository.save(departement); model.addAttribute("services", departementRepository.findAll()); return "redirect:/dep"; } @GetMapping(value="/editservice/{id}") public String showUpdateForm(@PathVariable("id") long id, Model model) { Departement departement = departementRepository.findById(id).get(); model.addAttribute("departement", departement); return "service/editService"; } @GetMapping(value="/deleteservice/{id}") public String deletedep(@PathVariable("id") long id, Model model) { departementRepository.deleteById(id); return "redirect:/dep"; } }
true
44ae890a35a1e4332ed3a518a9211d62b6bd18f3
Java
bazelbuild/bazel
/src/main/java/com/google/devtools/build/lib/starlarkbuildapi/config/ConfigGlobalLibraryApi.java
UTF-8
7,149
2.15625
2
[ "Apache-2.0" ]
permissive
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.starlarkbuildapi.config; import com.google.devtools.build.docgen.annot.GlobalMethods; import com.google.devtools.build.docgen.annot.GlobalMethods.Environment; import com.google.devtools.build.docgen.annot.StarlarkConstructor; import net.starlark.java.annot.Param; import net.starlark.java.annot.ParamType; import net.starlark.java.annot.StarlarkMethod; import net.starlark.java.eval.Dict; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.Sequence; import net.starlark.java.eval.StarlarkCallable; import net.starlark.java.eval.StarlarkThread; /** A collection of top-level Starlark functions pertaining to configuration. */ @GlobalMethods(environment = Environment.BZL) public interface ConfigGlobalLibraryApi { @StarlarkMethod( name = "transition", doc = "A transition that reads a set of input build settings and writes a set of output build " + "settings.<p>Example:</p><p><pre class=\"language-python\">\n" + "def _transition_impl(settings, attr):\n" + " # This transition just reads the current CPU value as a demonstration.\n" + " # A real transition could incorporate this into its followup logic.\n" + " current_cpu = settings[\"//command_line_option:cpu\"]\n" + " return {\"//command_line_option:compilation_mode\": \"dbg\"}\n" + "\n" + "build_in_debug_mode = transition(\n" + " implementation = _transition_impl,\n" + " inputs = [\"//command_line_option:cpu\"],\n" + " outputs = [\"//command_line_option:compilation_mode\"],\n" + ")</pre></p><p>For more details see <a" + " href=\"https://bazel.build/rules/config#user-defined-transitions\">here</a>.</p>", parameters = { @Param( name = "implementation", positional = false, named = true, // TODO(cparsons): The settings dict should take actual Label objects as keys and not // strings. Update the documentation. doc = "The function implementing this transition. This function always has two " + "parameters: <code>settings</code> and <code>attr</code>. The " + "<code>settings</code> param is a dictionary whose set of keys is defined " + "by the inputs parameter. So, for each build setting " + "<code>--//foo=bar</code>, if <code>inputs</code> contains " + "<code>//foo</code>, <code>settings</code> will " + "have an entry <code>settings['//foo']='bar'</code>.<p>" + "The <code>attr</code> param is a reference to <code>ctx.attr</code>. This " + "gives the implementation function access to the rule's attributes to make " + "attribute-parameterized transitions possible.<p>" + "This function must return a <code>dict</code> from build setting identifier " + "to build setting value; this represents the configuration transition: for " + "each entry in the returned <code>dict</code>, the transition updates that " + "setting to the new value. All other settings are unchanged. This function " + "can also return a <code>list</code> of <code>dict</code>s or a " + "<code>dict</code> of <code>dict</code>s in the case of a " + "split transition."), @Param( name = "inputs", allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)}, positional = false, named = true, doc = "List of build settings that can be read by this transition. This becomes the " + "key set of the settings parameter of the implementation function " + "parameter."), @Param( name = "outputs", allowedTypes = {@ParamType(type = Sequence.class, generic1 = String.class)}, positional = false, named = true, doc = "List of build settings that can be written by this transition. This must be " + "a superset of the key set of the dictionary returned by this transition."), }, useStarlarkThread = true) @StarlarkConstructor ConfigurationTransitionApi transition( StarlarkCallable implementation, Sequence<?> inputs, // <String> expected Sequence<?> outputs, // <String> expected StarlarkThread thread) throws EvalException; @StarlarkMethod( name = "analysis_test_transition", doc = "<p> Creates a configuration transition to be applied on an analysis-test rule's" + " dependencies. This transition may only be applied on attributes of rules with" + " <code>analysis_test = True</code>. Such rules are restricted in capabilities (for" + " example, the size of their dependency tree is limited), so transitions created" + " using this function are limited in potential scope as compared to transitions" + " created using <a" + " href=\"../builtins/transition.html\"><code>transition()</code></a>. <p>This" + " function is primarily designed to facilitate the <a" + " href=\"https://bazel.build/rules/testing\">Analysis Test Framework</a> core" + " library. See its documentation (or its implementation) for best practices.", parameters = { @Param( name = "settings", positional = false, named = true, doc = "A dictionary containing information about configuration settings which " + "should be set by this configuration transition. Keys are build setting " + "labels and values are their new post-transition values. All other settings " + "are unchanged. Use this to declare specific configuration settings that " + "an analysis test requires to be set in order to pass."), }, useStarlarkThread = true) ConfigurationTransitionApi analysisTestTransition( Dict<?, ?> changedSettings, // <String, String> expected StarlarkThread thread) throws EvalException; }
true
f02f2b432a296343642fa5bcf9e954cb96212ee2
Java
nourkhattab/BravoChat
/chatapp/src/main/java/org/chat21/android/core/authentication/task/RefreshFirebaseInstanceIdTask.java
UTF-8
3,730
2.15625
2
[]
no_license
package org.chat21.android.core.authentication.task; import android.app.Application; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import org.chat21.android.core.ChatManager; import org.chat21.android.utils.ChatUtils; import org.chat21.android.utils.StringUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.chat21.android.utils.DebugConstants.DEBUG_LOGIN; /** * Created by andrealeo */ public class RefreshFirebaseInstanceIdTask extends AsyncTask<Object, Object, Void> { private static final String TAG_TOKEN = "TAG_TOKEN"; public RefreshFirebaseInstanceIdTask() { Log.d(DEBUG_LOGIN, "RefreshFirebaseInstanceIdTask"); } public void generateInstance() { String token = FirebaseInstanceId.getInstance().getToken(); Log.d(DEBUG_LOGIN, "SaveFirebaseInstanceIdService.onTokenRefresh:" + " called with instanceId: " + token); Log.i(TAG_TOKEN, "SaveFirebaseInstanceIdService: token == " + token); FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); String appId = ChatManager.Configuration.appId; if (firebaseUser != null && StringUtils.isValid(appId)) { DatabaseReference root; if (StringUtils.isValid(ChatManager.Configuration.firebaseUrl)) { root = FirebaseDatabase.getInstance() .getReferenceFromUrl(ChatManager.Configuration.firebaseUrl); } else { root = FirebaseDatabase.getInstance().getReference(); } DatabaseReference firebaseUsersPath = root .child("apps/" + ChatManager.Configuration.appId + "/users/" + firebaseUser.getUid() + "/instances/" + token); Map<String, Object> device = new HashMap<>(); device.put("device_model", ChatUtils.getDeviceModel()); device.put("platform", "Android"); device.put("platform_version", ChatUtils.getSystemVersion()); device.put("language", "En"); firebaseUsersPath.setValue(device); // placeholder value Log.i(DEBUG_LOGIN, "SaveFirebaseInstanceIdService.onTokenRefresh: " + "saved with token: " + token + ", appId: " + appId + ", firebaseUsersPath: " + firebaseUsersPath); } else { Log.i(DEBUG_LOGIN, "SaveFirebaseInstanceIdService.onTokenRefresh:" + "user is null. token == " + token + ", appId == " + appId); } } @Override protected Void doInBackground(Object... params) { try { FirebaseInstanceId.getInstance().deleteInstanceId(); Log.i(DEBUG_LOGIN, "RefreshFirebaseInstanceIdTask.doInBackground: instanceId deleted with success."); // Now manually call onTokenRefresh() Log.d(DEBUG_LOGIN, "RefreshFirebaseInstanceIdTask.doInBackground: Getting new token"); // String token = FirebaseInstanceId.getInstance().getToken(); // Log.i(TAG_TOKEN, "RefreshFirebaseInstanceIdTask: token == " + token); } catch (IOException e) { Log.e(DEBUG_LOGIN, "RefreshFirebaseInstanceIdTask.doInBackground: deleteInstanceIdCatch: " + e.getMessage()); } return null; } }
true
b26c0d1af3a45598405f0fbb26ffbb3a56a0bece
Java
antoniofurone/cy-bss-core
/cy-bss-core/src/org/cysoft/bss/core/dao/mysql/CountryMysql.java
UTF-8
5,227
2.3125
2
[ "MIT" ]
permissive
package org.cysoft.bss.core.dao.mysql; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.cysoft.bss.core.common.CyBssException; import org.cysoft.bss.core.dao.CountryDao; import org.cysoft.bss.core.model.Country; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; public class CountryMysql extends CyBssMysqlDao implements CountryDao{ private static final Logger logger = LoggerFactory.getLogger(CountryMysql.class); @Override public List<Country> getCountryAll() { // TODO Auto-generated method stub logger.info("CountryMysql.getCountryAll() >>>"); String query="select CON_N_COUNTRY_ID,CON_S_CODE,CON_S_NAME from BSST_CON_COUNTRY"; JdbcTemplate jdbcTemplate = new JdbcTemplate(tx.getDataSource()); logger.info(query); List<Country> ret = jdbcTemplate.query( query, new RowMapperCountry()); logger.info("CountryMysql.getCountryAll() <<<"); return ret; } private class RowMapperCountry implements RowMapper<Country>{ @Override public Country mapRow(ResultSet rs, int rownum) throws SQLException { // TODO Auto-generated method stub Country country=new Country(); country.setId(rs.getLong("CON_N_COUNTRY_ID")); country.setCode(rs.getString("CON_S_CODE")); country.setName(rs.getString("CON_S_NAME")); return country; } } @Override public long add(Country country) throws CyBssException { // TODO Auto-generated method stub logger.info("CountryMysql.add() >>>"); String cmd="insert into BSST_CON_COUNTRY(CON_S_CODE,CON_S_NAME) "; cmd+=" values (?,?)"; JdbcTemplate jdbcTemplate = new JdbcTemplate(tx.getDataSource()); logger.info(cmd+"["+country+"]"); try { jdbcTemplate.update(cmd, new Object[]{ country.getCode(),country.getName() }); } catch (DataAccessException e) { // TODO Auto-generated catch block logger.error(e.toString()); throw new CyBssException(e); } logger.info("CountryMysql.add() <<<"); return getLastInsertId(jdbcTemplate); } @Override public void update(long id, Country country) throws CyBssException { // TODO Auto-generated method stub logger.info("CountryMysql.update() >>>"); String cmd="update BSST_CON_COUNTRY set CON_S_CODE=?,CON_S_NAME=? "; cmd+="where CON_N_COUNTRY_ID=?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(tx.getDataSource()); logger.info(cmd+"["+country+"]"); try { jdbcTemplate.update(cmd, new Object[]{ country.getCode(),country.getName(),id }); } catch (DataAccessException e) { // TODO Auto-generated catch block logger.error(e.toString()); throw new CyBssException(e); } logger.info("CountryMysql.update() <<<"); } @Override public Country get(long id) { // TODO Auto-generated method stub logger.info("CountryMysql.get() >>>"); // TODO Auto-generated method stub JdbcTemplate jdbcTemplate = new JdbcTemplate(tx.getDataSource()); String query="select CON_N_COUNTRY_ID,CON_S_CODE,CON_S_NAME from BSST_CON_COUNTRY"; query+=" where CON_N_COUNTRY_ID=?"; logger.info(query+"["+id+"]"); Country ret=null; try { ret=jdbcTemplate.queryForObject(query, new Object[] { id }, new RowMapperCountry()); } catch(IncorrectResultSizeDataAccessException e){ logger.info("CountryMysql.IncorrectResultSizeDataAccessException:"+e.getMessage()); } logger.info("CountryMysql.get() <<<"); return ret; } @Override public void remove(long id) throws CyBssException { // TODO Auto-generated method stub logger.info("CountryMysql.remove() >>>"); String cmd="delete from BSST_CON_COUNTRY where CON_N_COUNTRY_ID=?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(tx.getDataSource()); logger.info(cmd+"["+id+"]"); try { jdbcTemplate.update(cmd, new Object[]{ id }); } catch (DataAccessException e) { // TODO Auto-generated catch block logger.error(e.toString()); throw new CyBssException(e); } logger.info("CountryMysql.remove() <<<"); } @Override public List<Country> find(String name) { // TODO Auto-generated method stub String query="select CON_N_COUNTRY_ID,CON_S_CODE,CON_S_NAME from BSST_CON_COUNTRY"; if (!name.equals("")) query+=" WHERE "; List<Object> parms=new ArrayList<Object>(); if (!name.equals("")){ if (!name.contains("%")) query+=" CON_S_NAME=?"; else query+=" CON_S_NAME like ?"; parms.add(name); } query+=" order by CON_S_NAME"; JdbcTemplate jdbcTemplate = new JdbcTemplate(tx.getDataSource()); logger.info(query+"[name="+name+"]"); List<Country> ret=jdbcTemplate.query(query, parms.toArray(),new RowMapperCountry()); logger.info("CountryMysql.find() <<<"); return ret; } }
true
9aa1daafc14fc36152b07a18ec2cb86fef797b84
Java
lqblgl/Canvas
/app/src/main/java/com/example/canvasdemo/Signature/SignatureActivity.java
UTF-8
434
1.734375
2
[]
no_license
package com.example.canvasdemo.Signature; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.example.canvasdemo.R; public class SignatureActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.signature_layout); } }
true
665476c1979ffd8e3cab41fda922ebb011d4f13c
Java
se3mis/SPS_VERSION
/SPSEJBService/ejbModule/inventory/model/InwrhmapPK.java
UTF-8
1,314
2.5
2
[]
no_license
package inventory.model; import java.io.Serializable; import javax.persistence.*; /** * The primary key class for the INWRHMAP database table. * */ @Embeddable public class InwrhmapPK implements Serializable { //default serial version id, required for serializable classes. private static final long serialVersionUID = 1L; @Column(name="DEPT_ID") private String deptId; @Column(name="WRH_DEPT") private String wrhDept; public InwrhmapPK() { } public String getDeptId() { return this.deptId; } public void setDeptId(String deptId) { this.deptId = deptId; } public String getWrhDept() { return this.wrhDept; } public void setWrhDept(String wrhDept) { this.wrhDept = wrhDept; } public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof InwrhmapPK)) { return false; } InwrhmapPK castOther = (InwrhmapPK)other; return this.deptId.equals(castOther.deptId) && this.wrhDept.equals(castOther.wrhDept); } public int hashCode() { final int prime = 31; int hash = 17; hash = hash * prime + this.deptId.hashCode(); hash = hash * prime + this.wrhDept.hashCode(); return hash; } @Override public String toString() { return "InwrhmapPK [deptId=" + deptId + ", wrhDept=" + wrhDept + "]"; } }
true
1c3d201c12c173b44f9ff0d987f9367ff592feb0
Java
Allen0003/Part-time-AU
/Triple A Super/QuickBase/inputObjs/Insert.java
UTF-8
681
2.03125
2
[]
no_license
package QuickBase.inputObjs; import java.util.HashMap; public class Insert { String udata = "qdbapi"; String ticket; String apptoken; HashMap<String, String> field; public String getUdata() { return udata; } public void setUdata(String udata) { this.udata = udata; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getApptoken() { return apptoken; } public void setApptoken(String apptoken) { this.apptoken = apptoken; } public HashMap<String, String> getField() { return field; } public void setFields(HashMap<String, String> field) { this.field = field; } }
true
2d61dd6a0bb80893087b6f3d152c7536f0a0a515
Java
pearly0603/restapigitproject
/JavaBasic/src/InputOutPut/checkFileIsHidden.java
UTF-8
496
2.96875
3
[]
no_license
package InputOutPut; import java.io.File; import java.io.IOException; public class checkFileIsHidden { public static void main(String[] args) throws IOException , SecurityException { File file = new File("D:\\programs\\testData\\checker hidden\\myHiddenFile.txt"); //File file = new File("D:\\programs\\testData\\checker hidden\\myOpenFile.txt"); if(file.isHidden()) { System.out.println("This file is hidden"); }else { System.out.println("This file is not hidden"); } } }
true
1ae7b96fa4d9684774d32232cca07fe5783007d3
Java
yogithesymbian/Menjadi-Android-Developer-Expert
/app/src/main/java/id/scode/submission/BookSubmission.java
UTF-8
2,486
2.609375
3
[]
no_license
package id.scode.submission; import android.os.Parcel; import android.os.Parcelable; /** * Created by Dani on 12/24/2018. * Yogi Arif Widodo * Getter and Setter , Parcelable , */ public class BookSubmission implements Parcelable { private String judulBuku; private String newsOlder; private String spoiler; private String hrgBuku; private String detailBuku; public BookSubmission(String judulBuku, String newsOlder, String spoiler, String hrgBuku, String detailBuku) { this.judulBuku = judulBuku; this.newsOlder = newsOlder; this.spoiler = spoiler; this.hrgBuku = hrgBuku; this.detailBuku = detailBuku; } public String getDetailBuku() { return detailBuku; } public void setDetailBuku(String detailBuku) { this.detailBuku = detailBuku; } public String getHrgBuku() { return hrgBuku; } public void setHrgBuku(String hrgBuku) { this.hrgBuku = hrgBuku; } public String getJudulBuku() { return judulBuku; } public void setJudulBuku(String judulBuku) { this.judulBuku = judulBuku; } public String getNewsOlder() { return newsOlder; } public void setNewsOlder(String newsOlder) { this.newsOlder = newsOlder; } public String getSpoiler() { return spoiler; } public void setSpoiler(String spoiler) { this.spoiler = spoiler; } // parcelable public BookSubmission() { } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.judulBuku); dest.writeString(this.newsOlder); dest.writeString(this.spoiler); dest.writeString(this.hrgBuku); dest.writeString(this.detailBuku); } protected BookSubmission(Parcel in) { this.judulBuku = in.readString(); this.newsOlder = in.readString(); this.spoiler = in.readString(); this.hrgBuku = in.readString(); this.detailBuku = in.readString(); } public static final Creator<BookSubmission> CREATOR = new Creator<BookSubmission>() { @Override public BookSubmission createFromParcel(Parcel source) { return new BookSubmission(source); } @Override public BookSubmission[] newArray(int size) { return new BookSubmission[size]; } }; }
true
308c2654d2d3dbb462dcf99032b41c77f1e8bda1
Java
ZeroOneSummer/zos
/src/main/java/com/dm/zos/controller/orderSysReport/entity/BBill.java
UTF-8
6,552
2.171875
2
[]
no_license
package com.dm.zos.controller.orderSysReport.entity; import com.alibaba.fastjson.JSON; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; @Table(name = "b_bill") public class BBill { /** * 主键id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 用户资金账户ID */ @Column(name = "acc_id") private Integer accId; /** * 用户创建时间 */ @Column(name = "create_time") private Date createTime; /** * 更新时间 */ @Column(name = "update_time") private Date updateTime; /** * 账单关闭时间 */ @Column(name = "invalid_time") private Date invalidTime; /** * 本期开始日期 */ @Column(name = "begin_date") private Date beginDate; /** * 本期结束日期(账单结算日期) */ @Column(name = "end_date") private Date endDate; /** * 本月即将过期金豆 */ @Column(name = "valalid_bounty") private BigDecimal valalidBounty; /** * 当前剩余金豆总额 */ @Column(name = "surplus_bounty") private BigDecimal surplusBounty; /** * 本期收入金豆总额 */ @Column(name = "bounty_in") private BigDecimal bountyIn; /** * 本期支出金豆总额 */ @Column(name = "bounty_pay") private BigDecimal bountyPay; /** * 结算次数 */ @Column(name = "settle_accounts") private Integer settleAccounts; /** * 账单是否有效 */ @Column(name = "isValid") private Integer isvalid; /** * 获取主键id * * @return id - 主键id */ public Long getId() { return id; } /** * 设置主键id * * @param id 主键id */ public void setId(Long id) { this.id = id; } /** * 获取用户资金账户ID * * @return acc_id - 用户资金账户ID */ public Integer getAccId() { return accId; } /** * 设置用户资金账户ID * * @param accId 用户资金账户ID */ public void setAccId(Integer accId) { this.accId = accId; } /** * 获取用户创建时间 * * @return create_time - 用户创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置用户创建时间 * * @param createTime 用户创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取更新时间 * * @return update_time - 更新时间 */ public Date getUpdateTime() { return updateTime; } /** * 设置更新时间 * * @param updateTime 更新时间 */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /** * 获取账单关闭时间 * * @return invalid_time - 账单关闭时间 */ public Date getInvalidTime() { return invalidTime; } /** * 设置账单关闭时间 * * @param invalidTime 账单关闭时间 */ public void setInvalidTime(Date invalidTime) { this.invalidTime = invalidTime; } /** * 获取本期开始日期 * * @return begin_date - 本期开始日期 */ public Date getBeginDate() { return beginDate; } /** * 设置本期开始日期 * * @param beginDate 本期开始日期 */ public void setBeginDate(Date beginDate) { this.beginDate = beginDate; } /** * 获取本期结束日期(账单结算日期) * * @return end_date - 本期结束日期(账单结算日期) */ public Date getEndDate() { return endDate; } /** * 设置本期结束日期(账单结算日期) * * @param endDate 本期结束日期(账单结算日期) */ public void setEndDate(Date endDate) { this.endDate = endDate; } /** * 获取本月即将过期金豆 * * @return valalid_bounty - 本月即将过期金豆 */ public BigDecimal getValalidBounty() { return valalidBounty; } /** * 设置本月即将过期金豆 * * @param valalidBounty 本月即将过期金豆 */ public void setValalidBounty(BigDecimal valalidBounty) { this.valalidBounty = valalidBounty; } /** * 获取当前剩余金豆总额 * * @return surplus_bounty - 当前剩余金豆总额 */ public BigDecimal getSurplusBounty() { return surplusBounty; } /** * 设置当前剩余金豆总额 * * @param surplusBounty 当前剩余金豆总额 */ public void setSurplusBounty(BigDecimal surplusBounty) { this.surplusBounty = surplusBounty; } /** * 获取本期收入金豆总额 * * @return bounty_in - 本期收入金豆总额 */ public BigDecimal getBountyIn() { return bountyIn; } /** * 设置本期收入金豆总额 * * @param bountyIn 本期收入金豆总额 */ public void setBountyIn(BigDecimal bountyIn) { this.bountyIn = bountyIn; } /** * 获取本期支出金豆总额 * * @return bounty_pay - 本期支出金豆总额 */ public BigDecimal getBountyPay() { return bountyPay; } /** * 设置本期支出金豆总额 * * @param bountyPay 本期支出金豆总额 */ public void setBountyPay(BigDecimal bountyPay) { this.bountyPay = bountyPay; } /** * 获取结算次数 * * @return settle_accounts - 结算次数 */ public Integer getSettleAccounts() { return settleAccounts; } /** * 设置结算次数 * * @param settleAccounts 结算次数 */ public void setSettleAccounts(Integer settleAccounts) { this.settleAccounts = settleAccounts; } /** * 获取账单是否有效 * * @return isValid - 账单是否有效 */ public Integer getIsvalid() { return isvalid; } /** * 设置账单是否有效 * * @param isvalid 账单是否有效 */ public void setIsvalid(Integer isvalid) { this.isvalid = isvalid; } @Override public String toString() { return JSON.toJSONString(this); } }
true
cc4c65dc0c763d63e22c40c59b945cdc1fb8daf6
Java
Trink0/NoTube-Beancounter-2.0
/listeners/facebook/facebook-core/src/main/java/io/beancounter/listener/facebook/core/model/FacebookData.java
UTF-8
652
1.992188
2
[]
no_license
package io.beancounter.listener.facebook.core.model; import com.restfb.Facebook; import com.restfb.types.NamedFacebookType; /** * @author Enrico Candino ( enrico.candino@gmail.com ) */ public class FacebookData extends NamedFacebookType { @Facebook private String category; @Facebook("created_time") private String createdTime; public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getCreatedTime() { return createdTime; } public void setCreatedTime(String createdTime) { this.createdTime = createdTime; } }
true
05062cabd22260b6ed57a8f5bb502481198abbb5
Java
Witsacco/Mockery
/src/com/witsacco/mockery/events/MessageScoredEventHandler.java
UTF-8
207
1.601563
2
[]
no_license
package com.witsacco.mockery.events; import com.google.gwt.event.shared.EventHandler; public interface MessageScoredEventHandler extends EventHandler { void onMessageScored( MessageScoredEvent event ); }
true
da0c0e7d621f0257fe179951b21c12db6e6a8342
Java
strupos/viewstream
/main/java/com/stream/viewstream/app/MainActivity.java
UTF-8
1,535
2.375
2
[]
no_license
package com.stream.viewstream.app; import android.app.Activity; import android.app.ProgressDialog; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; public class MainActivity extends Activity { private static ProgressDialog progressDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //displays "loading" circle during buffering progressDialog = ProgressDialog.show(this, "", "Buffering...", true); setContentView(R.layout.activity_main); final VideoView player = (VideoView) findViewById(R.id.player); //specify the HLS stream URL here String streamUrl = "http://170.obj.netromedia.net/ODExtreme/mp4:Extremists.m4v/playlist.m3u8"; player.setVideoURI(Uri.parse(streamUrl)); //keep the screen on during viewing player.setKeepScreenOn(true); //loads the media controller/scrubber and sets skip/rewind to disabled player.setMediaController(new MediaController(this, false)); player.requestFocus(); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override //clears loading circle when the stream is ready and starts the stream public void onPrepared(MediaPlayer mp) { progressDialog.dismiss(); player.start(); } }); } }
true
c75c3bad75e2819b90b63b583bdbfe75f72736ac
Java
RamesesDev/osiris2
/server/rameses-xmpp-service/src/com/rameses/xmpp/service/ResponseService.java
UTF-8
2,631
2.078125
2
[]
no_license
/* * ResponseService.java * * Created on June 13, 2012, 9:50 AM * @author jaycverg */ package com.rameses.xmpp.service; import com.rameses.server.common.AppContext; import com.rameses.server.common.JndiUtil; import com.rameses.service.ScriptServiceContext; import com.rameses.service.ServiceProxy; import java.util.HashMap; import java.util.Map; import javax.naming.InitialContext; public class ResponseService implements ResponseServiceMBean { private String remoteHost; private String remoteContext; private String remoteServiceName = "ResponseService"; public ResponseService() { } public void start() throws Exception { System.out.println("BINDING RESPONSE SERVICE"); InitialContext ictx = new InitialContext(); JndiUtil.bind( ictx, AppContext.getPath() + ResponseService.class.getSimpleName(), this ); } public void stop() throws Exception { System.out.println("UNBINDING RESPONSE SERVICE"); InitialContext ictx = new InitialContext(); JndiUtil.unbind(ictx, AppContext.getPath() + ResponseService.class.getSimpleName()); } public void sendResponse(Map request, Object message) throws Exception { Map conf = new HashMap(); conf.put("app.host", remoteHost); conf.put("app.context", remoteContext); ScriptServiceContext ssc = new ScriptServiceContext(conf); ServiceProxy proxy = ssc.create(remoteServiceName); proxy.invoke("sendResponse", new Object[]{ request, message}); } public Object getResponse(String requestId) throws Exception { Map conf = new HashMap(); conf.put("app.host", remoteHost); conf.put("app.context", remoteContext); ScriptServiceContext ssc = new ScriptServiceContext(conf); ServiceProxy proxy = ssc.create(remoteServiceName); return proxy.invoke("getResponse", new Object[]{requestId}); } //<editor-fold defaultstate="collapsed" desc=" Getters/Setters "> public String getRemoteHost() { return remoteHost; } public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } public String getRemoteContext() { return remoteContext; } public void setRemoteContext(String remoteContext) { this.remoteContext = remoteContext; } public String getRemoteServiceName() { return remoteServiceName; } public void setRemoteServiceName(String remoteServiceName) { this.remoteServiceName = remoteServiceName; } //</editor-fold> }
true
0d5358b745e10be30e029a3a7b6c1779a123ccb1
Java
timatimtem/DesignPattern
/DesignPatterns/src/FactoryExamplePizzaFactoryMethod/ChicagoStyleVeggiePizza.java
UTF-8
306
2.59375
3
[]
no_license
package FactoryExamplePizzaFactoryMethod; public class ChicagoStyleVeggiePizza extends Pizza { public ChicagoStyleVeggiePizza() { name = "Chicago style veggie pizza"; dough = "Tasty dough"; sauce = "Marinara sauce"; toppings.add("NO MEAT, extra vegetables"); } }
true
b8c5e854cb087b1699476fdd7e27be17566c0e2d
Java
iloveruning/campustao
/vertx-web-spring-boot-starter/src/main/java/com/arunning/vertx/web/spring/Registry.java
UTF-8
243
1.898438
2
[]
no_license
package com.arunning.vertx.web.spring; import java.util.List; /** * @author chenliangliang * @date 2019/3/21 */ public interface Registry<T> { void register(T t); boolean remove(T t); List<T> lookup(); void clear(); }
true
099905df486a9eb06f4288add83637dfcef5f1c1
Java
gauravsaxena1611/Non-Veggies
/NonVeggies/src/main/java/com/nonveggies/entity/order/NvOrderInvoicePayment.java
UTF-8
1,308
1.921875
2
[]
no_license
package com.nonveggies.entity.order; // Generated Jan 2, 2016 7:30:29 AM by Hibernate Tools 3.4.0.CR1 import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; /** * NvOrderInvoicePayment generated by hbm2java */ @Entity @Table(name = "nv_order_invoice_payment", catalog = "NVPrestashop") public class NvOrderInvoicePayment implements java.io.Serializable { private NvOrderInvoicePaymentId id; private int idOrder; public NvOrderInvoicePayment() { } public NvOrderInvoicePayment(NvOrderInvoicePaymentId id, int idOrder) { this.id = id; this.idOrder = idOrder; } @EmbeddedId @AttributeOverrides({ @AttributeOverride(name = "idOrderInvoice", column = @Column(name = "id_order_invoice", nullable = false)), @AttributeOverride(name = "idOrderPayment", column = @Column(name = "id_order_payment", nullable = false)) }) public NvOrderInvoicePaymentId getId() { return this.id; } public void setId(NvOrderInvoicePaymentId id) { this.id = id; } @Column(name = "id_order", nullable = false) public int getIdOrder() { return this.idOrder; } public void setIdOrder(int idOrder) { this.idOrder = idOrder; } }
true
e245b1de8a13ca8bfdd657e85b73a03e7ea2bc12
Java
sureshbe007/VisirxPatient_2.5.1
/app/src/main/java/com/visirx/patient/api/EMRFullImageRes.java
UTF-8
592
1.820313
2
[]
no_license
package com.visirx.patient.api; /** * Created by aa on 20.1.16. */ public class EMRFullImageRes { private ResponseHeader responseHeader; private byte[] emrFullImageFile; public ResponseHeader getResponseHeader() { return responseHeader; } public void setResponseHeader(ResponseHeader responseHeader) { this.responseHeader = responseHeader; } public byte[] getEmrFullImageFile() { return emrFullImageFile; } public void setEmrFullImageFile(byte[] emrFullImageFile) { this.emrFullImageFile = emrFullImageFile; } }
true
8fbbcedc16534099d6064c15c81bf46a601962c9
Java
anders88/jsonbuddy
/src/test/java/org/jsonbuddy/JsonParserTest.java
UTF-8
11,632
2.484375
2
[ "Apache-2.0" ]
permissive
package org.jsonbuddy; import org.assertj.core.data.Offset; import org.jsonbuddy.parse.JsonParseException; import org.jsonbuddy.parse.JsonParser; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Base64; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @SuppressWarnings({"OptionalGetWithoutIsPresent", "deprecation"}) public class JsonParserTest { @Test public void shouldParseEmptyObject() { assertThat(JsonParser.parseToObject(new StringReader("{}")).isObject()).isTrue(); assertThat(JsonParser.parseToArray(new StringReader("[]")).isArray()).isTrue(); } @Test public void shouldParseEmptyStream() { assertThat(JsonParser.parseToObject(new ByteArrayInputStream("{}".getBytes())).isObject()).isTrue(); assertThat(JsonParser.parseToArray(new ByteArrayInputStream("[]".getBytes())).isArray()).isTrue(); } @Test public void shouldParseEmptyString() { assertThat(JsonParser.parseToObject("{}").isObject()).isTrue(); assertThat(JsonParser.parseToArray("[]").isArray()).isTrue(); } @Test public void shouldParseObjectWithStringValue() throws IOException { StringReader input = new StringReader(fixQuotes("{'name':'Darth Vader'}")); JsonObject jsonObject = (JsonObject) JsonParser.parseNode(input); assertThat(jsonObject.stringValue("name")).isPresent().contains("Darth Vader"); } @Test public void shouldHandleMultipleValuesInObject() throws IOException { StringReader input = new StringReader(fixQuotes("{'firstname':'Darth', 'lastname': 'Vader'}")); JsonObject jsonObject = (JsonObject) JsonParser.parseNode(input); assertThat(jsonObject.stringValue("firstname")).isPresent().contains("Darth"); assertThat(jsonObject.stringValue("lastname")).isPresent().contains("Vader"); } @Test public void shouldHandleArrays() { JsonArray array = JsonArray.parse(fixQuotes("['one','two','three']")); assertThat(array.strings()).containsExactly("one", "two", "three"); } @Test public void shouldHandleEmptyArrays() { JsonArray jsonArray = JsonArray.parse("[ \n\n ]"); assertThat(jsonArray).isEmpty(); } @Test public void shouldWarnOnWrongParseType() { assertThatThrownBy(() -> JsonArray.parse(fixQuotes("{'foo':'bar'}"))) .hasMessageContaining("Expected JSON array got class org.jsonbuddy.JsonObject"); assertThatThrownBy(() -> JsonArray.parse("")) .hasMessageContaining("Expected JSON array got null"); assertThatThrownBy(() -> JsonObject.parse(fixQuotes("['foo', 'bar']"))) .hasMessageContaining("Expected JSON object got class org.jsonbuddy.JsonArray"); assertThatThrownBy(() -> JsonObject.parse("")) .hasMessageContaining("Expected JSON object got null"); } @Test public void shouldHandleObjectWithArray() throws IOException { StringReader input = new StringReader(fixQuotes("{'name':'Anakin','children':['Luke','Leia']}")); JsonObject vader = (JsonObject) JsonParser.parseNode(input); List<String> children = vader.requiredArray("children").stringStream() .collect(Collectors.toList()); assertThat(children).containsExactly("Luke", "Leia"); } @Test public void shouldHandleString() { JsonObject obj = (JsonObject) JsonParser.parse("{}"); assertThat(obj).isNotNull(); } @Test public void shouldHandleBoolean() { JsonObject jsonObject = (JsonObject) JsonParser.parse(fixQuotes("{'boolVal':false}")); JsonNode boolVal = jsonObject.value("boolVal").get(); assertThat(boolVal).isInstanceOf(JsonBoolean.class); assertThat(((JsonBoolean) boolVal).booleanValue()).isFalse(); } @Test public void shouldHandleNull() { JsonObject jsonObject = (JsonObject) JsonParser.parse(fixQuotes("{'boolVal':null}")); JsonNode nullVal = jsonObject.value("boolVal").get(); assertThat(nullVal).isInstanceOf(JsonNull.class); } @Test public void shouldHandleInteger() { JsonObject jsonObject = JsonObject.parse(fixQuotes("{'theMeaning':42}")); JsonNode theMeaning = jsonObject.value("theMeaning").get(); assertThat(theMeaning).isInstanceOf(JsonNumber.class); JsonNumber intVal = (JsonNumber) theMeaning; assertThat(intVal.intValue()).isEqualTo(42); assertThat(intVal.longValue()).isEqualTo(42); assertThat(intVal.shortValue()).isEqualTo((short) 42); assertThat(intVal.floatValue()).isEqualTo(42.0f); assertThat(intVal.byteValue()).isEqualTo((byte) 42); JsonNode jsonNode = JsonParser.parse("42"); assertThat(jsonNode).isEqualTo(new JsonNumber(42L)); } @Test public void shouldHandleComplexNumbers() { JsonObject jsonObject = JsonObject.parse(fixQuotes("{'a':-1,'b':3.14,'c':2.5e3}")); assertThat(jsonObject.requiredLong("a")).isEqualTo(-1); assertThat(jsonObject.requiredDouble("b")).isEqualTo(3.14d); assertThat(jsonObject.requiredDouble("c")).isEqualTo(2500d); } @Test public void shouldHandleSpecialCharacters() { String input = fixQuotes("{'eval':'quote:\\\" backslash\\\\ \\/slash \\f bell\\b tab\\t newline\\nrest'}"); JsonObject val = JsonObject.parse(input); assertThat(val.stringValue("eval").get()).isEqualTo("quote:\" backslash\\ /slash \f bell\b tab\t newline\nrest"); } @Test public void shouldThrowExceptionIfJsonIsInvalid() { validateException("{'name':'Darth Vader'", "JsonObject not closed. Expected }"); validateException("{'name':'Darth Vader' :", "JsonObject not closed. Expected }"); validateException("['Luke'", "Expected , or ] in array"); validateException("{'name'}", "Expected value for objectkey name"); validateException("{'name' 'Darth'", "Expected value for objectkey name"); validateException("[", "Expected , or ] in array"); validateException("[1 2]", "Expected , or ] in array"); validateException("[1, 2", "Expected , or ] in array"); validateException("[1, 2 :", "Expected , or ] in array"); validateException("{'dummy':2gh}", "Illegal value '2g'"); validateException("{'name':'Luke}", "JsonString not closed. Expected \""); validateException("{'name':'Luke", "JsonString not closed. Expected \""); validateException("{'name':Luke}", "Unexpected character 'L'"); validateException("{'foo':", "Expected value for key foo"); validateException("'aborted escape \\", "JsonString not closed. Ended in escape sequence"); validateException("unquoted", "Unexpected character 'u'"); validateException("foo", "Unexpected value foo"); } private void validateException(String json, String errormessage) { assertThatThrownBy(() -> JsonParser.parse(fixQuotes(json))) .hasMessage(errormessage); } @Test public void shouldHandleLinebreaks() { String jsonWithLinebreak = fixQuotes("{\n'name':'Darth',\n'title':'Dark Lord'\n}"); JsonNode result = JsonParser.parse(jsonWithLinebreak); assertThat(result).isInstanceOf(JsonObject.class); JsonObject jsonObject = (JsonObject) result; assertThat(jsonObject.requiredString("name")).isEqualTo("Darth"); assertThat(jsonObject.requiredString("title")).isEqualTo("Dark Lord"); } @Test public void shouldParseToInstant() { JsonObject jsonObject = JsonObject.parse(fixQuotes("{'time':'2015-08-30T11:21:12.314Z'}")); Optional<JsonNode> time = jsonObject.value("time"); assertThat(time).isPresent().containsInstanceOf(JsonString.class); JsonString jsonInstantValue = (JsonString) time.get(); assertThat(jsonInstantValue.instantValue()).isEqualTo(LocalDateTime.of(2015, 8, 30, 13, 21, 12, 314000000).atOffset(ZoneOffset.ofHours(2)).toInstant()); } @Test public void shouldHandleEmptyArray() { JsonObject jsonObject = JsonObject.parse("{\"properties\":{\"myEmptyList\":[]}}"); assertThat(jsonObject.requiredObject("properties").requiredArray("myEmptyList")).isEmpty(); } @Test public void shouldHandleNestedObjectFollowedByAnotherProperty() { JsonObject jsonObject = JsonObject.parse(fixQuotes("{'objone':{'color':'blue'},'name':'Darth Vader'}")); assertThat(jsonObject.requiredString("name")).isEqualTo("Darth Vader"); } @Test public void shouldHandleLineshifts() { JsonObject.parse(fixQuotes("{'tablevalues':\n['one','two']}")); } @Test public void shouldHandleSpecialCharsAfterNumbers() { String val = "{\"id\":4326\r}"; JsonObject jsonObject = JsonObject.parse(val); assertThat(jsonObject.requiredLong("id")).isEqualTo(4326); } @Test public void shouldHandleEmptyString() { JsonObject jsonObject = JsonObject.parse(fixQuotes("{'emptyString':''}")); assertThat(jsonObject.requiredString("emptyString")).isEqualTo(""); } @Test public void shouldHandleNestedArrays() { String json = "{\"coordinates\":[[9.0, 80.0]]}"; JsonObject jsonObject = JsonObject.parse(json); assertThat(jsonObject).isNotNull(); } @Test public void shouldHandleNullElementsInArray() { String json = fixQuotes("['one',null,'two']"); JsonArray jsonArray = JsonArray.parse(json); assertThat(jsonArray.size()).isEqualTo(3); assertThat(jsonArray.get(1, JsonNull.class)).isEqualTo(new JsonNull()); } @Test public void shouldHandleUnicode() { JsonObject jsonObject = JsonObject.parse(fixQuotes("{'value':'with\\u22A1xx'}")); assertThat(jsonObject.requiredString("value")).isEqualTo("with\u22A1xx"); } @Test public void shouldParseBase64EncodedJsonArray() { JsonArray expected = new JsonArray().add(new JsonObject().put("Some", "value")); String base64EncodedString = Base64.getEncoder().encodeToString(expected.toJson().getBytes()); JsonArray jsonArray = (JsonArray) JsonParser.parseFromBase64encodedString(base64EncodedString); assertThat(jsonArray).isEqualTo(expected); } @Test public void shouldThrowExceptionWhenInputNotJson() { String notJsonString = "Some value"; String base64EncodedString = Base64.getEncoder().encodeToString(notJsonString.getBytes()); assertThatThrownBy(() -> JsonObject.parseFromBase64encodedString(base64EncodedString)) .isInstanceOf(JsonParseException.class); } @Test public void shouldThrowExceptionWhenInputNotBase64Encoded() { JsonObject expected = new JsonObject().put("one", "two"); assertThatThrownBy(() -> JsonObject.parseFromBase64encodedString(expected.toJson())) .isInstanceOf(IllegalArgumentException.class); } @Test public void shouldHandleNumbersWithExponent() { JsonObject parsed = JsonObject.parse("{\"numval\" : 0e+1}"); assertThat(parsed.requiredDouble("numval")).isCloseTo(0d, Offset.offset(0.00001d)); } private static String fixQuotes(String content) { return content.replace("'", "\""); } }
true
8c81c650abb07d72c5364e688cfb950fe0a0a61b
Java
Andreas237/AndroidPolicyAutomation
/ExtractedJars/PACT_com.pactforcure.app/javafiles/android/support/v7/widget/StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem.java
UTF-8
9,248
1.984375
2
[ "MIT" ]
permissive
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v7.widget; import android.os.Parcel; import android.os.Parcelable; import java.util.Arrays; // Referenced classes of package android.support.v7.widget: // StaggeredGridLayoutManager static class StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem implements Parcelable { public int describeContents() { return 0; // 0 0:iconst_0 // 1 1:ireturn } int getGapForSpan(int i) { if(mGapPerSpan == null) //* 0 0:aload_0 //* 1 1:getfield #48 <Field int[] mGapPerSpan> //* 2 4:ifnonnull 9 return 0; // 3 7:iconst_0 // 4 8:ireturn else return mGapPerSpan[i]; // 5 9:aload_0 // 6 10:getfield #48 <Field int[] mGapPerSpan> // 7 13:iload_1 // 8 14:iaload // 9 15:ireturn } public String toString() { return (new StringBuilder()).append("FullSpanItem{mPosition=").append(mPosition).append(", mGapDir=").append(mGapDir).append(", mHasUnwantedGapAfter=").append(mHasUnwantedGapAfter).append(", mGapPerSpan=").append(Arrays.toString(mGapPerSpan)).append('}').toString(); // 0 0:new #59 <Class StringBuilder> // 1 3:dup // 2 4:invokespecial #60 <Method void StringBuilder()> // 3 7:ldc1 #62 <String "FullSpanItem{mPosition="> // 4 9:invokevirtual #66 <Method StringBuilder StringBuilder.append(String)> // 5 12:aload_0 // 6 13:getfield #42 <Field int mPosition> // 7 16:invokevirtual #69 <Method StringBuilder StringBuilder.append(int)> // 8 19:ldc1 #71 <String ", mGapDir="> // 9 21:invokevirtual #66 <Method StringBuilder StringBuilder.append(String)> // 10 24:aload_0 // 11 25:getfield #44 <Field int mGapDir> // 12 28:invokevirtual #69 <Method StringBuilder StringBuilder.append(int)> // 13 31:ldc1 #73 <String ", mHasUnwantedGapAfter="> // 14 33:invokevirtual #66 <Method StringBuilder StringBuilder.append(String)> // 15 36:aload_0 // 16 37:getfield #46 <Field boolean mHasUnwantedGapAfter> // 17 40:invokevirtual #76 <Method StringBuilder StringBuilder.append(boolean)> // 18 43:ldc1 #78 <String ", mGapPerSpan="> // 19 45:invokevirtual #66 <Method StringBuilder StringBuilder.append(String)> // 20 48:aload_0 // 21 49:getfield #48 <Field int[] mGapPerSpan> // 22 52:invokestatic #83 <Method String Arrays.toString(int[])> // 23 55:invokevirtual #66 <Method StringBuilder StringBuilder.append(String)> // 24 58:bipush 125 // 25 60:invokevirtual #86 <Method StringBuilder StringBuilder.append(char)> // 26 63:invokevirtual #88 <Method String StringBuilder.toString()> // 27 66:areturn } public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(mPosition); // 0 0:aload_1 // 1 1:aload_0 // 2 2:getfield #42 <Field int mPosition> // 3 5:invokevirtual #94 <Method void Parcel.writeInt(int)> parcel.writeInt(mGapDir); // 4 8:aload_1 // 5 9:aload_0 // 6 10:getfield #44 <Field int mGapDir> // 7 13:invokevirtual #94 <Method void Parcel.writeInt(int)> if(mHasUnwantedGapAfter) //* 8 16:aload_0 //* 9 17:getfield #46 <Field boolean mHasUnwantedGapAfter> //* 10 20:ifeq 63 i = 1; // 11 23:iconst_1 // 12 24:istore_2 else //* 13 25:aload_1 //* 14 26:iload_2 //* 15 27:invokevirtual #94 <Method void Parcel.writeInt(int)> //* 16 30:aload_0 //* 17 31:getfield #48 <Field int[] mGapPerSpan> //* 18 34:ifnull 68 //* 19 37:aload_0 //* 20 38:getfield #48 <Field int[] mGapPerSpan> //* 21 41:arraylength //* 22 42:ifle 68 //* 23 45:aload_1 //* 24 46:aload_0 //* 25 47:getfield #48 <Field int[] mGapPerSpan> //* 26 50:arraylength //* 27 51:invokevirtual #94 <Method void Parcel.writeInt(int)> //* 28 54:aload_1 //* 29 55:aload_0 //* 30 56:getfield #48 <Field int[] mGapPerSpan> //* 31 59:invokevirtual #97 <Method void Parcel.writeIntArray(int[])> //* 32 62:return i = 0; // 33 63:iconst_0 // 34 64:istore_2 parcel.writeInt(i); if(mGapPerSpan != null && mGapPerSpan.length > 0) { parcel.writeInt(mGapPerSpan.length); parcel.writeIntArray(mGapPerSpan); return; } else //* 35 65:goto 25 { parcel.writeInt(0); // 36 68:aload_1 // 37 69:iconst_0 // 38 70:invokevirtual #94 <Method void Parcel.writeInt(int)> return; // 39 73:return } } public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() { public StaggeredGridLayoutManager.LazySpanLookup.FullSpanItem createFromParcel(Parcel parcel) { return new StaggeredGridLayoutManager.LazySpanLookup.FullSpanItem(parcel); // 0 0:new #9 <Class StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem> // 1 3:dup // 2 4:aload_1 // 3 5:invokespecial #25 <Method void StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem(Parcel)> // 4 8:areturn } public volatile Object createFromParcel(Parcel parcel) { return ((Object) (createFromParcel(parcel))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokevirtual #28 <Method StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem createFromParcel(Parcel)> // 3 5:areturn } public StaggeredGridLayoutManager.LazySpanLookup.FullSpanItem[] newArray(int i) { return new StaggeredGridLayoutManager.LazySpanLookup.FullSpanItem[i]; // 0 0:iload_1 // 1 1:anewarray StaggeredGridLayoutManager.LazySpanLookup.FullSpanItem[] // 2 4:areturn } public volatile Object[] newArray(int i) { return ((Object []) (newArray(i))); // 0 0:aload_0 // 1 1:iload_1 // 2 2:invokevirtual #33 <Method StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem[] newArray(int)> // 3 5:areturn } } ; int mGapDir; int mGapPerSpan[]; boolean mHasUnwantedGapAfter; int mPosition; static { // 0 0:new #14 <Class StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem$1> // 1 3:dup // 2 4:invokespecial #29 <Method void StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem$1()> // 3 7:putstatic #31 <Field android.os.Parcelable$Creator CREATOR> //* 4 10:return } StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem() { // 0 0:aload_0 // 1 1:invokespecial #33 <Method void Object()> // 2 4:return } StaggeredGridLayoutManager$LazySpanLookup$FullSpanItem(Parcel parcel) { boolean flag = true; // 0 0:iconst_1 // 1 1:istore_3 super(); // 2 2:aload_0 // 3 3:invokespecial #33 <Method void Object()> mPosition = parcel.readInt(); // 4 6:aload_0 // 5 7:aload_1 // 6 8:invokevirtual #40 <Method int Parcel.readInt()> // 7 11:putfield #42 <Field int mPosition> mGapDir = parcel.readInt(); // 8 14:aload_0 // 9 15:aload_1 // 10 16:invokevirtual #40 <Method int Parcel.readInt()> // 11 19:putfield #44 <Field int mGapDir> int i; if(parcel.readInt() != 1) //* 12 22:aload_1 //* 13 23:invokevirtual #40 <Method int Parcel.readInt()> //* 14 26:iconst_1 //* 15 27:icmpne 60 //* 16 30:aload_0 //* 17 31:iload_3 //* 18 32:putfield #46 <Field boolean mHasUnwantedGapAfter> //* 19 35:aload_1 //* 20 36:invokevirtual #40 <Method int Parcel.readInt()> //* 21 39:istore_2 //* 22 40:iload_2 //* 23 41:ifle 59 //* 24 44:aload_0 //* 25 45:iload_2 //* 26 46:newarray int[] //* 27 48:putfield #48 <Field int[] mGapPerSpan> //* 28 51:aload_1 //* 29 52:aload_0 //* 30 53:getfield #48 <Field int[] mGapPerSpan> //* 31 56:invokevirtual #52 <Method void Parcel.readIntArray(int[])> //* 32 59:return flag = false; // 33 60:iconst_0 // 34 61:istore_3 mHasUnwantedGapAfter = flag; i = parcel.readInt(); if(i > 0) { mGapPerSpan = new int[i]; parcel.readIntArray(mGapPerSpan); } //* 35 62:goto 30 } }
true
a2f97a67e1ffc2299e1aabfbc2749a06a4ef59c9
Java
redmic-project/server-vessel-vessels
/vessels-lib/src/test/java/es/redmic/vesselslib/unit/events/tracking/VesselTrackingEventFactoryTest.java
UTF-8
13,574
1.960938
2
[ "Apache-2.0" ]
permissive
package es.redmic.vesselslib.unit.events.tracking; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import es.redmic.brokerlib.avro.common.Event; import es.redmic.brokerlib.avro.common.EventError; import es.redmic.vesselslib.events.vesseltracking.VesselTrackingEventFactory; import es.redmic.vesselslib.events.vesseltracking.VesselTrackingEventTypes; import es.redmic.vesselslib.events.vesseltracking.common.VesselTrackingEvent; import es.redmic.vesselslib.events.vesseltracking.create.CreateVesselTrackingCancelledEvent; import es.redmic.vesselslib.events.vesseltracking.create.CreateVesselTrackingConfirmedEvent; import es.redmic.vesselslib.events.vesseltracking.create.CreateVesselTrackingEnrichedEvent; import es.redmic.vesselslib.events.vesseltracking.create.CreateVesselTrackingEvent; import es.redmic.vesselslib.events.vesseltracking.create.CreateVesselTrackingFailedEvent; import es.redmic.vesselslib.events.vesseltracking.create.VesselTrackingCreatedEvent; import es.redmic.vesselslib.events.vesseltracking.delete.DeleteVesselTrackingCancelledEvent; import es.redmic.vesselslib.events.vesseltracking.delete.DeleteVesselTrackingCheckFailedEvent; import es.redmic.vesselslib.events.vesseltracking.delete.DeleteVesselTrackingCheckedEvent; import es.redmic.vesselslib.events.vesseltracking.delete.DeleteVesselTrackingConfirmedEvent; import es.redmic.vesselslib.events.vesseltracking.delete.DeleteVesselTrackingEvent; import es.redmic.vesselslib.events.vesseltracking.delete.DeleteVesselTrackingFailedEvent; import es.redmic.vesselslib.events.vesseltracking.delete.VesselTrackingDeletedEvent; import es.redmic.vesselslib.events.vesseltracking.update.UpdateVesselTrackingCancelledEvent; import es.redmic.vesselslib.events.vesseltracking.update.UpdateVesselTrackingConfirmedEvent; import es.redmic.vesselslib.events.vesseltracking.update.UpdateVesselTrackingEnrichedEvent; import es.redmic.vesselslib.events.vesseltracking.update.UpdateVesselTrackingEvent; import es.redmic.vesselslib.events.vesseltracking.update.UpdateVesselTrackingFailedEvent; import es.redmic.vesselslib.events.vesseltracking.update.VesselTrackingUpdatedEvent; import es.redmic.vesselslib.unit.utils.VesselTrackingDataUtil; public class VesselTrackingEventFactoryTest { @Test public void GetEvent_ReturnDeleteVesselTrackingEvent_IfTypeIsDelete() { Event source = VesselTrackingDataUtil.getDeleteVesselTrackingCheckedEvent(); DeleteVesselTrackingEvent event = (DeleteVesselTrackingEvent) VesselTrackingEventFactory.getEvent(source, VesselTrackingEventTypes.DELETE); assertEquals(VesselTrackingEventTypes.DELETE, event.getType()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnDeleteVesselTrackingCheckedEvent_IfTypeIsDelete_Checked() { Event source = VesselTrackingDataUtil.getCheckDeleteVesselTrackingEvent(); DeleteVesselTrackingCheckedEvent event = (DeleteVesselTrackingCheckedEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.DELETE_CHECKED); assertEquals(VesselTrackingEventTypes.DELETE_CHECKED, event.getType()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnCreateVesselTrackingConfirmedEvent_IfTypeIsCreateConfirmed() { Event source = VesselTrackingDataUtil.getCreateConfirmedEvent(); CreateVesselTrackingConfirmedEvent event = (CreateVesselTrackingConfirmedEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.CREATE_CONFIRMED); assertEquals(VesselTrackingEventTypes.CREATE_CONFIRMED, event.getType()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnUpdateVesselTrackingConfirmedEvent_IfTypeIsUpdateConfirmed() { Event source = VesselTrackingDataUtil.getUpdateVesselTrackingConfirmedEvent(); UpdateVesselTrackingConfirmedEvent event = (UpdateVesselTrackingConfirmedEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.UPDATE_CONFIRMED); assertEquals(VesselTrackingEventTypes.UPDATE_CONFIRMED, event.getType()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnDeleteVesselTrackingConfirmedEvent_IfTypeIsDeleteConfirmed() { Event source = VesselTrackingDataUtil.getDeleteVesselTrackingConfirmedEvent(); DeleteVesselTrackingConfirmedEvent event = (DeleteVesselTrackingConfirmedEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.DELETE_CONFIRMED); assertEquals(VesselTrackingEventTypes.DELETE_CONFIRMED, event.getType()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnDeleteVesselTrackingCheckedEvent_IfTypeIsDeleted() { Event source = VesselTrackingDataUtil.getDeleteVesselTrackingConfirmedEvent(); VesselTrackingDeletedEvent event = (VesselTrackingDeletedEvent) VesselTrackingEventFactory.getEvent(source, VesselTrackingEventTypes.DELETED); assertEquals(VesselTrackingEventTypes.DELETED, event.getType()); checkMetadataFields(source, event); } ///////////////////////// @Test public void GetEvent_ReturnCreateVesselTrackingEnrichedEvent_IfTypeIsCreateEnriched() { Event source = VesselTrackingDataUtil.getEnrichCreateVesselTrackingEvent(); CreateVesselTrackingEnrichedEvent event = (CreateVesselTrackingEnrichedEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.CREATE_ENRICHED, ((VesselTrackingEvent) source).getVesselTracking()); assertEquals(VesselTrackingEventTypes.CREATE_ENRICHED, event.getType()); assertNotNull(event.getVesselTracking()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnUpdateVesselTrackingEnrichedEvent_IfTypeIsUpdateEnriched() { Event source = VesselTrackingDataUtil.getEnrichUpdateVesselTrackingEvent(); UpdateVesselTrackingEnrichedEvent event = (UpdateVesselTrackingEnrichedEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.UPDATE_ENRICHED, ((VesselTrackingEvent) source).getVesselTracking()); assertEquals(VesselTrackingEventTypes.UPDATE_ENRICHED, event.getType()); assertNotNull(event.getVesselTracking()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnCreateVesselTrackingEvent_IfTypeIsCreate() { Event source = VesselTrackingDataUtil.getCreateVesselTrackingEnrichedEvent(); CreateVesselTrackingEvent event = (CreateVesselTrackingEvent) VesselTrackingEventFactory.getEvent(source, VesselTrackingEventTypes.CREATE, VesselTrackingDataUtil.getVesselTracking()); assertEquals(VesselTrackingEventTypes.CREATE, event.getType()); assertNotNull(event.getVesselTracking()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnVesselTrackingCreatedEvent_IfTypeIsCreated() { Event source = VesselTrackingDataUtil.getCreateConfirmedEvent(); VesselTrackingCreatedEvent event = (VesselTrackingCreatedEvent) VesselTrackingEventFactory.getEvent(source, VesselTrackingEventTypes.CREATED, VesselTrackingDataUtil.getVesselTracking()); assertEquals(VesselTrackingEventTypes.CREATED, event.getType()); assertNotNull(event.getVesselTracking()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnUpdateVesselTrackingEvent_IfTypeIsUpdate() { Event source = VesselTrackingDataUtil.getUpdateVesselTrackingEnrichedEvent(); UpdateVesselTrackingEvent event = (UpdateVesselTrackingEvent) VesselTrackingEventFactory.getEvent(source, VesselTrackingEventTypes.UPDATE, VesselTrackingDataUtil.getVesselTracking()); assertEquals(VesselTrackingEventTypes.UPDATE, event.getType()); assertNotNull(event.getVesselTracking()); checkMetadataFields(source, event); } @Test public void GetEvent_ReturnVesselTrackingCreatedEvent_IfTypeIsUpdated() { Event source = VesselTrackingDataUtil.getUpdateVesselTrackingConfirmedEvent(); VesselTrackingUpdatedEvent event = (VesselTrackingUpdatedEvent) VesselTrackingEventFactory.getEvent(source, VesselTrackingEventTypes.UPDATED, VesselTrackingDataUtil.getVesselTracking()); assertEquals(VesselTrackingEventTypes.UPDATED, event.getType()); assertNotNull(event.getVesselTracking()); checkMetadataFields(source, event); } /////////////////// @Test public void GetEvent_ReturnCreateVesselTrackingFailedEvent_IfTypeIsCreateFailed() { CreateVesselTrackingFailedEvent exception = VesselTrackingDataUtil.getCreateVesselTrackingFailedEvent(); Event source = VesselTrackingDataUtil.getCreateEvent(); CreateVesselTrackingFailedEvent event = (CreateVesselTrackingFailedEvent) VesselTrackingEventFactory.getEvent( source, VesselTrackingEventTypes.CREATE_FAILED, exception.getExceptionType(), exception.getArguments()); assertEquals(VesselTrackingEventTypes.CREATE_FAILED, event.getType()); checkMetadataFields(source, event); checkErrorFields(exception, event); } @Test public void GetEvent_ReturnUpdateVesselTrackingFailedEvent_IfTypeIsUpdateFailed() { UpdateVesselTrackingFailedEvent exception = VesselTrackingDataUtil.getUpdateVesselTrackingFailedEvent(); Event source = VesselTrackingDataUtil.getUpdateEvent(); UpdateVesselTrackingFailedEvent event = (UpdateVesselTrackingFailedEvent) VesselTrackingEventFactory.getEvent( source, VesselTrackingEventTypes.UPDATE_FAILED, exception.getExceptionType(), exception.getArguments()); assertEquals(VesselTrackingEventTypes.UPDATE_FAILED, event.getType()); checkMetadataFields(source, event); checkErrorFields(exception, event); } @Test public void GetEvent_ReturnDeleteVesselTrackingFailedEventt_IfTypeIsDeleteFailed() { DeleteVesselTrackingFailedEvent exception = VesselTrackingDataUtil.getDeleteVesselTrackingFailedEvent(); Event source = VesselTrackingDataUtil.getDeleteEvent(); DeleteVesselTrackingFailedEvent event = (DeleteVesselTrackingFailedEvent) VesselTrackingEventFactory.getEvent( source, VesselTrackingEventTypes.DELETE_FAILED, exception.getExceptionType(), exception.getArguments()); assertEquals(VesselTrackingEventTypes.DELETE_FAILED, event.getType()); checkMetadataFields(source, event); checkErrorFields(exception, event); } @Test public void GetEvent_ReturnDeleteVesselTrackingCheckFailedEvent_IfTypeIsDeleteCheckFailed() { DeleteVesselTrackingCheckFailedEvent exception = VesselTrackingDataUtil .getDeleteVesselTrackingCheckFailedEvent(); Event source = VesselTrackingDataUtil.getCheckDeleteVesselTrackingEvent(); DeleteVesselTrackingCheckFailedEvent event = (DeleteVesselTrackingCheckFailedEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.DELETE_CHECK_FAILED, exception.getExceptionType(), exception.getArguments()); assertEquals(VesselTrackingEventTypes.DELETE_CHECK_FAILED, event.getType()); checkMetadataFields(source, event); checkErrorFields(exception, event); } @Test public void GetEvent_ReturnCreateVesselTrackingCancelledEvent_IfTypeIsCreateCancelled() { CreateVesselTrackingCancelledEvent exception = VesselTrackingDataUtil.getCreateVesselTrackingCancelledEvent(); Event source = VesselTrackingDataUtil.getCreateEvent(); CreateVesselTrackingCancelledEvent event = (CreateVesselTrackingCancelledEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.CREATE_CANCELLED, exception.getExceptionType(), exception.getArguments()); assertEquals(VesselTrackingEventTypes.CREATE_CANCELLED, event.getType()); checkMetadataFields(source, event); checkErrorFields(exception, event); } //////////////////// @Test public void GetEvent_ReturnUpdateVesselTrackingCancelledEvent_IfTypeIsUpdateCancelled() { UpdateVesselTrackingCancelledEvent exception = VesselTrackingDataUtil.getUpdateVesselTrackingCancelledEvent(); Event source = VesselTrackingDataUtil.getUpdateEvent(); UpdateVesselTrackingCancelledEvent event = (UpdateVesselTrackingCancelledEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.UPDATE_CANCELLED, VesselTrackingDataUtil.getVesselTracking(), exception.getExceptionType(), exception.getArguments()); assertEquals(VesselTrackingEventTypes.UPDATE_CANCELLED, event.getType()); checkMetadataFields(source, event); checkErrorFields(exception, event); assertNotNull(event.getVesselTracking()); } @Test public void GetEvent_ReturnDeleteVesselTrackingCancelledEvent_IfTypeIsDeleteCancelled() { DeleteVesselTrackingCancelledEvent exception = VesselTrackingDataUtil.getDeleteVesselTrackingCancelledEvent(); Event source = VesselTrackingDataUtil.getDeleteEvent(); DeleteVesselTrackingCancelledEvent event = (DeleteVesselTrackingCancelledEvent) VesselTrackingEventFactory .getEvent(source, VesselTrackingEventTypes.DELETE_CANCELLED, VesselTrackingDataUtil.getVesselTracking(), exception.getExceptionType(), exception.getArguments()); assertEquals(VesselTrackingEventTypes.DELETE_CANCELLED, event.getType()); checkMetadataFields(source, event); checkErrorFields(exception, event); assertNotNull(event.getVesselTracking()); } //////////////////// private void checkMetadataFields(Event source, Event evt) { assertEquals(source.getAggregateId(), evt.getAggregateId()); assertEquals(source.getVersion(), evt.getVersion()); assertEquals(source.getSessionId(), evt.getSessionId()); assertEquals(source.getUserId(), evt.getUserId()); } private void checkErrorFields(EventError source, EventError evt) { assertEquals(source.getExceptionType(), evt.getExceptionType()); assertEquals(source.getArguments(), evt.getArguments()); } }
true
f62f7f6c139261bc35f6549ada9e8ad8a328afaa
Java
ForruQ/blueblood
/src/main/java/com/blueblood/controller/DashboardController.java
UTF-8
6,317
2
2
[]
no_license
package com.blueblood.controller; import com.blueblood.dao.impl.IDeliveredDAO; import com.blueblood.model.Delivered; import com.blueblood.model.Invoice; import com.blueblood.model.Stock; import com.blueblood.service.impl.IDeliveredService; import com.blueblood.service.impl.IInvoice1Service; import com.blueblood.service.impl.IInvoiceService; import com.blueblood.service.impl.IStockService; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value = "dash") public class DashboardController { @Autowired IStockService stockService; @Autowired IInvoice1Service invoice1Service; @Autowired IInvoiceService invoiceService; @Autowired IDeliveredService deliveredService; @RequestMapping(value = "/dash") public ModelAndView dash(){ int totalIncome = (int) stockService.totalIncome(); int totalCost = (int)stockService.totalCost(); int totalSales = (int)stockService.totalSales(); int investment = (int)stockService.investment(); long count = invoice1Service.getCountbyCid(); List<Invoice> iList = invoiceService.getAll(); System.out.println(count + ".........................."); Map<String, Object> map = new HashMap<String, Object>(); map.put("totalIncome", totalIncome); map.put("totalCost", totalCost); map.put("totalSales", totalSales); map.put("investment", investment); map.put("iList", iList); return new ModelAndView("dash/dash", "map", map); } @RequestMapping(value = "/stock") public String stock(){ return "dash/stock"; } @RequestMapping(value = "/sales") public ModelAndView reports(){ int oCount = (int)invoiceService.getCount(); int dCount = (int)invoice1Service.getCount(); int totalSales = (int)stockService.totalSales(); // double investment = stockService.investment(); int count = (int)invoice1Service.getCountbyCid(); List<Stock> qList = stockService.getTopSelelingProductQty(); List<Stock> vList = stockService.getTopSelelingProductValue(); List<Stock> pList = stockService.getTopSelelingProductByProfit(); List<Delivered> dList = deliveredService.getByDays(); List<Delivered> wList = deliveredService.getByWeaks(); List<Delivered> mList = deliveredService.getByMonths(); List<Delivered> yList = deliveredService.getByYears(); int todaysSales = (int)deliveredService.getTodaysSales(); int currentWeek = (int)deliveredService.getCurrentWeek(); int previousWeek = (int)deliveredService.getPreviousWeek(); int currentMonth = (int)deliveredService.getCurrentMonth(); int currentyear = (int)deliveredService.getCurrentYear(); Map<String, Object> map = new HashMap<String, Object>(); map.put("oCount", oCount); map.put("dCount", dCount); map.put("totalSales", totalSales); map.put("count", count); map.put("qList", qList); map.put("vList", vList); map.put("pList", pList); map.put("dList", dList); map.put("wList", wList); map.put("mList", mList); map.put("yList", yList); map.put("todaysSales", todaysSales); map.put("currentWeek", currentWeek); map.put("previousWeek", previousWeek); map.put("currentMonth", currentMonth); map.put("currentyear", currentyear); return new ModelAndView("reports/sales", "map", map); } @RequestMapping(value = "/dailySales") public ModelAndView todaysSales(){ List<Delivered> dList = deliveredService.getByDays(); Map<String, Object> map = new HashMap<String, Object>(); map.put("dList", dList); return new ModelAndView("reports/todaysSales", "map", map); } @RequestMapping(value = "/weeklySales") public ModelAndView weeksSales(){ List<Delivered> wList = deliveredService.getByWeaks(); Map<String, Object> map = new HashMap<String, Object>(); map.put("wList", wList); return new ModelAndView("reports/weeksSales", "map", map); } @RequestMapping(value = "/monthlySales") public ModelAndView monthlySales(){ List<Delivered> mList = deliveredService.getByMonths(); Map<String, Object> map = new HashMap<String, Object>(); map.put("mList", mList); return new ModelAndView("reports/monthlySales", "map", map); } @RequestMapping(value = "/yearlySales") public ModelAndView yearlySales(){ List<Delivered> yList = deliveredService.getByYears(); Map<String, Object> map = new HashMap<String, Object>(); map.put("yList", yList); return new ModelAndView("reports/yearlySales", "map", map); } @RequestMapping(value = "/topProduct") public ModelAndView topProduct(){ List<Stock> qList = stockService.getTopSelelingProductQty(); List<Stock> vList = stockService.getTopSelelingProductValue(); List<Stock> pList = stockService.getTopSelelingProductByProfit(); Map<String, Object> map = new HashMap<String, Object>(); map.put("qList", qList); map.put("vList", vList); map.put("pList", pList); return new ModelAndView("reports/topProduct", "map", map); } @RequestMapping(value = "/salesByCustomer") public ModelAndView salesByCustomer(){ List<Delivered> cList = deliveredService.getByCustomer(); Map<String, Object> map = new HashMap<String, Object>(); map.put("cList", cList); return new ModelAndView("reports/salesByCustomer", "map", map); } @RequestMapping(value = "/salesByProduct") public ModelAndView salesByProduct(){ List<Delivered> cList = deliveredService.getByProduct(); Map<String, Object> map = new HashMap<String, Object>(); map.put("cList", cList); return new ModelAndView("reports/salesByProduct", "map", map); } }
true
22117f4473453f6553ca57a485899257d10b672f
Java
CallCoders/my-Experience
/JavaRushHomeWork/src/com/javarush/test/level08/lesson11/home08/Solution.java
UTF-8
1,143
3.21875
3
[]
no_license
package com.javarush.test.level08.lesson11.home08; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; /** * User: General * Date: 12/21/12 * Time: 11:59 PM */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int[] array = new int[20]; for (int i = 0; i < array.length; i++) { array[i] = Integer.parseInt(reader.readLine()); } sort(array); System.out.println(array[0]); System.out.println(array[1]); System.out.println(array[2]); System.out.println(array[3]); System.out.println(array[4]); } public static void sort(int[] array) { Arrays.sort(array); int f = 0; for (int i = 0; i< array.length/2;i++) { int first = array[i]; int last = array[array.length - i - 1]; array[i] = last; array[array.length - i - 1] = first; } } }
true
e5c225a4cf977d286c6e84c96667f25e566a2d86
Java
meta-shreyash-khandelwal/GET2019
/EAD/EAD Assignment-5.1(September 2)/model/Product.java
UTF-8
1,124
2.890625
3
[]
no_license
package model; public class Product { private String productCode; private String productName; private String productType; private double price; private int quantity; public Product(String productCode, String productName, String productType, double price,int quantity) { super(); this.productCode = productCode; this.productName = productName; this.productType = productType; this.price = price; this.quantity=quantity; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }
true
c088ee23bff7eb755bcf0eb9ec8f583c24abb958
Java
Robert-Graham98/RobertGrahamMindexCodeChallenge
/src/main/java/com/mindex/challenge/DataBootstrap.java
UTF-8
1,105
2.625
3
[]
no_license
package com.mindex.challenge; import com.fasterxml.jackson.databind.ObjectMapper; import com.mindex.challenge.dao.EmployeeRepository; import com.mindex.challenge.data.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.IOException; import java.io.InputStream; @Component public class DataBootstrap { private static final String DATASTORE_LOCATION = "/static/employee_database.json"; @Autowired private EmployeeRepository employeeRepository; @Autowired private ObjectMapper objectMapper; @PostConstruct public void init() { InputStream inputStream = this.getClass().getResourceAsStream(DATASTORE_LOCATION); Employee[] employees = null; try { employees = objectMapper.readValue(inputStream, Employee[].class); } catch (IOException e) { throw new RuntimeException(e); } for (Employee employee : employees) { employeeRepository.insert(employee); } } }
true
32e4e46f7ef21da07af9e708d61f4ded87d3f332
Java
apache/netbeans
/ide/html.validation/src/org/netbeans/modules/html/validation/CharacterHandlerReader.java
UTF-8
3,996
2.078125
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.netbeans.modules.html.validation; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; import java.util.LinkedList; import java.util.List; import nu.validator.htmlparser.common.CharacterHandler; import org.xml.sax.SAXException; /** * * @author marekfukala */ public class CharacterHandlerReader extends Reader { private List<CharacterHandler> handlers = new LinkedList<>(); private boolean reading = false; private Reader reader; public CharacterHandlerReader(Reader reader) { this.reader = reader; } public void addCharacterHandler(CharacterHandler handler) { handlers.add(handler); } public boolean removeCharacterHandler(CharacterHandler handler) { return handlers.remove(handler); } @Override public void mark(int readAheadLimit) throws IOException { reader.mark(readAheadLimit); } @Override public int read() throws IOException { reading(); int read = reader.read(); characters(new char[]{(char) read}, 0, 1); return read; } @Override public int read(char[] cbuf, int off, int len) throws IOException { reading(); int read = reader.read(cbuf, off, len); characters(cbuf, off, len); return read; } @Override public void reset() throws IOException { reader.reset(); } @Override public long skip(long ns) throws IOException { return reader.skip(ns); } //implementation copied from the StringReader @Override public int read(CharBuffer target) throws IOException { reading(); int len = target.remaining(); char[] cbuf = new char[len]; int n = read(cbuf, 0, len); if (n > 0) { characters(cbuf, 0, n); } target.put(cbuf, 0, n); return n; } @Override public int read(char[] cbuf) throws IOException { return read(cbuf, 0, cbuf.length); } @Override public void close() throws IOException { reader.close(); end(); } private void characters(char[] chars, int offset, int len) throws IOException { assert chars != null; assert chars.length > 0; assert offset >= 0; assert len > 0; try { for (CharacterHandler handler : handlers) { handler.characters(chars, offset, len); } } catch (SAXException ex) { throw new IOException(ex); } } private void start() throws IOException { try { for (CharacterHandler handler : handlers) { handler.start(); } } catch (SAXException ex) { throw new IOException(ex); } } private void end() { try { for (CharacterHandler handler : handlers) { handler.end(); } } catch (SAXException ex) { throw new RuntimeException(ex); } } private void reading() throws IOException { if(!reading) { start(); reading = true; } } }
true
4f5b4d5bf622e11fafde569e6e3beaf3adfb66e2
Java
bcgit/bc-java
/core/src/main/java/org/bouncycastle/asn1/ocsp/OCSPResponseStatus.java
UTF-8
2,547
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
package org.bouncycastle.asn1.ocsp; import java.math.BigInteger; import org.bouncycastle.asn1.ASN1Enumerated; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; /** * OCSP RFC 2560, RFC 6960 * <p> * The OCSPResponseStatus enumeration. * <pre> * OCSPResponseStatus ::= ENUMERATED { * successful (0), --Response has valid confirmations * malformedRequest (1), --Illegal confirmation request * internalError (2), --Internal error in issuer * tryLater (3), --Try again later * --(4) is not used * sigRequired (5), --Must sign the request * unauthorized (6) --Request unauthorized * } * </pre> */ public class OCSPResponseStatus extends ASN1Object { public static final int SUCCESSFUL = 0; public static final int MALFORMED_REQUEST = 1; public static final int INTERNAL_ERROR = 2; public static final int TRY_LATER = 3; public static final int SIG_REQUIRED = 5; public static final int UNAUTHORIZED = 6; private ASN1Enumerated value; /** * RFC 2560, RFC 6960 * <p> * The OCSPResponseStatus enumeration. * <pre> * OCSPResponseStatus ::= ENUMERATED { * successful (0), --Response has valid confirmations * malformedRequest (1), --Illegal confirmation request * internalError (2), --Internal error in issuer * tryLater (3), --Try again later * --(4) is not used * sigRequired (5), --Must sign the request * unauthorized (6) --Request unauthorized * } * </pre> */ public OCSPResponseStatus( int value) { this(new ASN1Enumerated(value)); } private OCSPResponseStatus( ASN1Enumerated value) { this.value = value; } public static OCSPResponseStatus getInstance( Object obj) { if (obj instanceof OCSPResponseStatus) { return (OCSPResponseStatus)obj; } else if (obj != null) { return new OCSPResponseStatus(ASN1Enumerated.getInstance(obj)); } return null; } public int getIntValue() { return value.intValueExact(); } public BigInteger getValue() { return value.getValue(); } public ASN1Primitive toASN1Primitive() { return value; } }
true
0c53aed052d46dbd1e91598e14576bebb9b3cbe7
Java
BooksCup/crawler-server
/src/main/java/com/bc/crawler/server/service/WeavePriceService.java
UTF-8
1,342
2.125
2
[]
no_license
package com.bc.crawler.server.service; import com.bc.crawler.server.entity.WeavePrice; import com.github.pagehelper.PageInfo; import java.util.List; import java.util.Map; /** * 纺织品价格趋势 * * @author zhou */ public interface WeavePriceService { /** * 获取纺织品类型列表 * * @return 纺织品类型列表 */ List<String> getWeaveTypeList(); /** * 获取纺织品价格分页信息 * * @param pageNum 当前分页数 * @param pageSize 分页大小 * @param paramMap 参数map * @return 纺织品价格分页信息 */ PageInfo<WeavePrice> getWeavePricePageInfo(int pageNum, int pageSize, Map<String, Object> paramMap); /** * 获取纺织品价格列表 * * @param paramMap 参数map * @return 纺织品价格列表 */ List<WeavePrice> getWeavePriceList(Map<String, Object> paramMap); /** * 获取纺织品价格列表(多类型) * * @param paramMap 参数map * @return 纺织品价格列表 */ List<WeavePrice> getWeavePriceListByMultipleType(Map<String, Object> paramMap); /** * 获取最后一次交易日期 * * @param paramMap 参数map * @return 最后一次交易日期 */ String getLastWeavePriceDate(Map<String, Object> paramMap); }
true
15e66b93cac2fb36575a004803ba1474c7129f51
Java
ryeong/Proj3_ECoomerce
/src/test/java/test/MyOracleConnectionTest.java
UTF-8
725
2.40625
2
[]
no_license
package test; import java.sql.Connection; import java.sql.DriverManager; import org.junit.Test; public class MyOracleConnectionTest { private String driver ="oracle.jdbc.driver.OracleDriver"; private String url="jdbc:oracle:thin:@211.183.7.23:1522:orcl"; private String user="proj"; private String pass="proj"; @Test public void testConnection() throws Exception { Class.forName(driver); Connection conn = null; try { conn=DriverManager.getConnection(url,user,pass); } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn!=null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
true
ec403b88f597ebe64788beb13cf38cedccd9ecea
Java
AndrewLowrie/codewars
/java/src/main/java/EightKyu/CalculateAverage.java
UTF-8
529
3.59375
4
[]
no_license
package EightKyu; // Write function avg which calculates average of numbers in given list. public class CalculateAverage { public static double find_average(int[] array){ int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum / array.length * 1.0; } public static void main(String[] args) { CalculateAverage.find_average(new int[]{1,1,1}); // 1 CalculateAverage.find_average(new int[]{1, 2, 3}); // 2 } }
true
22e95006c5c37a0dc1b894b26bb0e7d087083d9a
Java
nkarusala/CS-2340-Fall-2014
/src/spacetrader/ships/Shield.java
UTF-8
1,815
3.265625
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 spacetrader.ships; import spacetrader.planets.TechLevel; /** * * @author Caleb */ public class Shield extends Equipment { private ShieldType type; private int health; /** * Creates a Shield object. * * @param type the type of shield this object will be */ public Shield(ShieldType type) { this.type = type; this.health = type.power(); } @Override public String getName() { return type.toString(); } @Override public String getEquipmentName() { return "Shield"; } @Override public int getBasePrice() { return type.price(); } @Override public TechLevel getMinTechLevel() { return type.minTechLevel(); } /** * Gets the defense of this shield. * * @return the shield's defense */ public int getHealth() { return health; } /** * Sets the power remaining of this shield. The health can't be set higher * than the shield's power. * * @param health the power remaining * @return the amount the new health is over the max health */ public int setHealth(int health) { if (health > type.power()) { this.health = type.power(); } else { this.health = health; } return health - type.power(); } /** * Gets the type of this Shield. * * @return The type of this shield */ public ShieldType getType() { return type; } @Override public String toString() { return type.toString(); } }
true
1ec5d131f7a4266a89d3d99f0ac7b55e05fb4a1b
Java
545461665/selenium_code
/selenium.framework/src/main/java/selenium/framework/report/ReportNGUtils.java
UTF-8
8,002
2.484375
2
[]
no_license
package selenium.framework.report; import org.testng.*; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.*; /** * 报告工具类 */ public class ReportNGUtils { private static final NumberFormat DURATION_FORMAT = new DecimalFormat( "#0.000"); public long getDuration(ITestContext context) { long duration = getDuration(context.getPassedConfigurations() .getAllResults()); duration += getDuration(context.getPassedTests().getAllResults()); duration += getDuration(context.getSkippedConfigurations() .getAllResults()); duration += getDuration(context.getSkippedTests().getAllResults()); duration += getDuration(context.getFailedConfigurations() .getAllResults()); duration += getDuration(context.getFailedTests().getAllResults()); return duration; } private long getDuration(Set<ITestResult> results) { long duration = 0; for (ITestResult result : results) { duration += (result.getEndMillis() - result.getStartMillis()); } return duration; } public String formatDuration(long startMillis, long endMillis) { long elapsed = endMillis - startMillis; return formatDuration(elapsed); } public String formatDuration(long elapsed) { double seconds = (double) elapsed / 1000; return DURATION_FORMAT.format(seconds); } public List<Throwable> getCauses(Throwable t) { List<Throwable> causes = new LinkedList<Throwable>(); Throwable next = t; while (next.getCause() != null) { next = next.getCause(); causes.add(next); } return causes; } public List<String> getTestOutput(ITestResult result) { return Reporter.getOutput(result); } public List<String> getAllOutput() { return Reporter.getOutput(); } public boolean hasArguments(ITestResult result) { return result.getParameters().length > 0; } public String getArguments(ITestResult result) { Object[] arguments = result.getParameters(); List<String> argumentStrings = new ArrayList<String>(arguments.length); for (Object argument : arguments) { argumentStrings.add(renderArgument(argument)); } return commaSeparate(argumentStrings); } private String renderArgument(Object argument) { if (argument == null) { return "null"; } else if (argument instanceof String) { return "\"" + argument + "\""; } else if (argument instanceof Character) { return "\'" + argument + "\'"; } else { return argument.toString(); } } public boolean hasDependentGroups(ITestResult result) { return result.getMethod().getGroupsDependedUpon().length > 0; } public String getDependentGroups(ITestResult result) { String[] groups = result.getMethod().getGroupsDependedUpon(); return commaSeparate(Arrays.asList(groups)); } public boolean hasDependentMethods(ITestResult result) { return result.getMethod().getMethodsDependedUpon().length > 0; } public String getDependentMethods(ITestResult result) { String[] methods = result.getMethod().getMethodsDependedUpon(); return commaSeparate(Arrays.asList(methods)); } public boolean hasSkipException(ITestResult result) { return result.getThrowable() instanceof SkipException; } public String getSkipExceptionMessage(ITestResult result) { return hasSkipException(result) ? result.getThrowable().getMessage() : ""; } public boolean hasGroups(ISuite suite) { return !suite.getMethodsByGroups().isEmpty(); } private String commaSeparate(Collection<String> strings) { StringBuilder buffer = new StringBuilder(); Iterator<String> iterator = strings.iterator(); while (iterator.hasNext()) { String string = iterator.next(); buffer.append(string); if (iterator.hasNext()) { buffer.append(", "); } } return buffer.toString(); } public String escapeString(String s) { if (s == null) { return null; } StringBuilder buffer = new StringBuilder(); for (int i = 0; i < s.length(); i++) { buffer.append(escapeChar(s.charAt(i))); } return buffer.toString(); } private String escapeChar(char character) { switch (character) { // case '<': // return "&lt;"; // case '>': // return "&gt;"; // case '"': // return "&quot;"; // case '\'': // return "&apos;"; // case '&': // return "&amp;"; default: return String.valueOf(character); } } public String escapeHTMLString(String s) { if (s == null) { return null; } StringBuilder buffer = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case ' ': // 除了最后一个,在一个连续的空格都被转换为一个非中断的空格 (&nbsp;)。 char nextCh = i + 1 < s.length() ? s.charAt(i + 1) : 0; buffer.append(nextCh == ' ' ? "&nbsp;" : " "); break; case '\n': buffer.append("<br/>\n"); break; default: buffer.append(escapeChar(ch)); } } return buffer.toString(); } public String stripThreadName(String threadId) { if (threadId == null) { return null; } else { int index = threadId.lastIndexOf('@'); return index >= 0 ? threadId.substring(0, index) : threadId; } } public long getStartTime(List<IInvokedMethod> methods) { long startTime = System.currentTimeMillis(); for (IInvokedMethod method : methods) { startTime = Math.min(startTime, method.getDate()); } return startTime; } public long getEndTime(ISuite suite, IInvokedMethod method, List<IInvokedMethod> methods) { boolean found = false; for (IInvokedMethod m : methods) { if (m == method) { found = true; } // Once a method is found, find subsequent method on same thread. else if (found && m.getTestMethod().getId().equals(method.getTestMethod().getId())) { return m.getDate(); } } return getEndTime(suite, method); } private long getEndTime(ISuite suite, IInvokedMethod method) { // 从测试套件中的所有测试中,找到最新的结束时间. for (Map.Entry<String, ISuiteResult> entry : suite.getResults().entrySet()) { ITestContext testContext = entry.getValue().getTestContext(); for (ITestNGMethod m : testContext.getAllTestMethods()) { if (method == m) { return testContext.getEndDate().getTime(); } } // 如果我们找不到一个匹配的测试方法,它必须是一个配置方法。 for (ITestNGMethod m : testContext.getPassedConfigurations().getAllMethods()) { if (method == m) { return testContext.getEndDate().getTime(); } } for (ITestNGMethod m : testContext.getFailedConfigurations().getAllMethods()) { if (method == m) { return testContext.getEndDate().getTime(); } } } throw new IllegalStateException("Could not find matching end time."); } }
true
137e3f55a88a37d1a0dc0fe7efcdeb013a3fa485
Java
joji-harada/collegedb
/testing/Test.java
UTF-8
2,985
3
3
[]
no_license
package testing; import college.Course; import college.Major; import college.Rank; import college.Student; import college.Title; import list.LinkedList; import java.io.PrintStream; import java.util.ArrayList; import java.util.Iterator; import list.LinkedList; import utility.List; import utility.Batch; public class Test { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); list.add(7); list.add(8); list.add(9); list.add(10); Iterator<Integer> itr = list.iterator(); while(itr.hasNext()) { if(itr.next() % 2 == 0) { itr.remove(); } } System.out.println(list); LinkedList<Integer> clist = new LinkedList<Integer>(); clist.add(1); clist.add(2); clist.add(3); clist.add(4); clist.add(5); clist.add(6); clist.add(8); clist.add(9); clist.add(10); System.out.println(clist); utility.Iterator<Integer> litr = clist.iterator(); while(litr.hasNext()) { if(litr.next() % 2 == 0) { litr.remove(); } } System.out.println(clist); // Student omar = new Student.Builder() // .setName("Omar Osman") // .setAge(23) // .setRank(Rank.JUN) // .setMajor(Major.CSC) // .setCourse(new Course(Title.CSC, 3.9)) // .setCourse(new Course(Title.PHYS, 4.0)) // .setCourse(new Course(Title.MATH, 3.9)) // .build(); // // // Student george = new Student.Builder() // .setName("George Allison") // .setAge(27) // .setRank(Rank.JUN) // .setMajor(Major.CSC) // .setCourse(new Course(Title.CSC, 4.0)) // .setCourse(new Course(Title.PHYS, 3.3)) // .setCourse(new Course(Title.MATH, 3.2)) // .build(); // // Student jasmine = new Student.Builder() // .setName("Jasmine Evans") // .setAge(21) // .setRank(Rank.JUN) // .setMajor(Major.CSC) // .setCourse(new Course(Title.CSC, 3.9)) // .setCourse(new Course(Title.ENG, 3.6)) // .setCourse(new Course(Title.MATH, 3.4)) // .build(); // // // List<Student> list = new ArrayList<Student>(); // list.add(omar); // list.add(jasmine); // list.add(george); // // System.out.println("Georges gpa: " + george.gpa()); // System.out.println("Omars gpa: " + omar.gpa()); // System.out.println("Jasmines gpa: " + jasmine.gpa()); // System.out.println(); // System.out.println("omar.gpa() > george.gpa(): " + (omar.gpa() > george.gpa())); // System.out.println(); // System.out.println(Batch.indexOf(list, "Omar Osman")); // System.out.println(Batch.indexOf(list, "Jasmine Evans")); // System.out.println(Batch.indexOf(list, "George Allison")); // System.out.println(Batch.indexOf(list, "Arlene Ford")); // System.out.println(); // System.out.println(); // Batch.selectionSort(list, Student::compareGPA); // Batch.quickSort(list); // System.out.println(list); } }
true
4eabc893d3a5f84383b8d15868fbcbb3f007980f
Java
1228857713/jvmOnJava
/java-study/src/main/java/com/wangzhen/javastudy/jucx/locks/ReentrantReadWriteLock.java
UTF-8
2,870
2.515625
3
[]
no_license
package com.wangzhen.javastudy.jucx.locks; import java.util.concurrent.TimeUnit; public class ReentrantReadWriteLock implements ReadWriteLock,java.io.Serializable { private static final long serialVersionUID = -6992448646407690164L; @Override public Lock readLock() { return null; } @Override public Lock writeLock() { return null; } abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 6317671515068378041L; static final int SHARED_SHIFT = 16; static final int SHARED_UNIT = (1 << SHARED_SHIFT); static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1; static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1; /** Returns the number of shared holds represented in count */ static int sharedCount(int c) { return c >>> SHARED_SHIFT; } /** Returns the number of exclusive holds represented in count */ static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; } static final class HoldCounter{ int count = 0; final long tid = getThreadId(Thread.currentThread()); } static final class ThreadLocalHoldCounter extends ThreadLocal<HoldCounter>{ public HoldCounter initialValue(){ return new HoldCounter(); } } private transient ThreadLocalHoldCounter readHolds; private transient HoldCounter cachedHoldCounter; private transient Thread firstReader = null; private transient int firstReaderHoldCount; } public static class ReadLock implements Lock, java.io.Serializable { private static final long serialVersionUID = -5992448646407690164L; @Override public void lock() { } @Override public void lockInterruptibly() throws InterruptedException { } @Override public boolean tyrLock() { return false; } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return false; } @Override public void unlock() { } @Override public Condition newConDition() { return null; } } static final long getThreadId(Thread thread) { return UNSAFE.getLongVolatile(thread, TID_OFFSET); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long TID_OFFSET; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> tk = Thread.class; TID_OFFSET = UNSAFE.objectFieldOffset (tk.getDeclaredField("tid")); } catch (Exception e) { throw new Error(e); } } }
true
01056ec1be0dcff5986305ad428809bc4e7cf3ac
Java
ChenMingzhe/consulo-javascript
/web-browser-impl/src/main/java/consulo/javascript/client/module/extension/ClientJavaScriptModuleExtension.java
UTF-8
3,862
1.867188
2
[ "Apache-2.0" ]
permissive
package consulo.javascript.client.module.extension; import javax.annotation.Nonnull; import org.jdom.Element; import javax.annotation.Nullable; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.SdkTable; import com.intellij.openapi.projectRoots.SdkType; import consulo.annotation.access.RequiredReadAction; import consulo.javascript.client.module.sdk.ClientJavaScriptSdkType; import consulo.javascript.lang.StandardJavaScriptVersions; import consulo.javascript.module.extension.JavaScriptModuleExtension; import consulo.lang.LanguageVersion; import consulo.module.extension.ModuleInheritableNamedPointer; import consulo.module.extension.impl.ModuleExtensionImpl; import consulo.module.extension.impl.ModuleInheritableNamedPointerImpl; import consulo.roots.ModuleRootLayer; import consulo.roots.impl.ModuleRootLayerImpl; import consulo.util.pointers.NamedPointer; /** * @author VISTALL * @since 29.06.14 */ public class ClientJavaScriptModuleExtension extends ModuleExtensionImpl<ClientJavaScriptModuleExtension> implements JavaScriptModuleExtension<ClientJavaScriptModuleExtension> { private ModuleInheritableNamedPointerImpl<Sdk> myPointer; protected LanguageVersion myLanguageVersion = StandardJavaScriptVersions.getInstance().getDefaultVersion(); public ClientJavaScriptModuleExtension(@Nonnull String id, @Nonnull ModuleRootLayer rootLayer) { super(id, rootLayer); myPointer = new ModuleInheritableNamedPointerImpl<Sdk>(rootLayer, id) { @Nullable @Override public String getItemNameFromModule(@Nonnull Module module) { ClientJavaScriptModuleExtension extension = ModuleUtilCore.getExtension(module, ClientJavaScriptModuleExtension.class); if(extension == null) { return null; } return extension.getSdkName(); } @Nullable @Override public Sdk getItemFromModule(@Nonnull Module module) { ClientJavaScriptModuleExtension extension = ModuleUtilCore.getExtension(module, ClientJavaScriptModuleExtension.class); if(extension == null) { return null; } return extension.getSdk(); } @Nonnull @Override public NamedPointer<Sdk> getPointer(@Nonnull ModuleRootLayer moduleRootLayer, @Nonnull String name) { return ((ModuleRootLayerImpl)moduleRootLayer).getRootModel().getConfigurationAccessor().getSdkPointer(name); } }; Sdk sdkByType = SdkTable.getInstance().findPredefinedSdkByType(ClientJavaScriptSdkType.getInstance()); myPointer.set(null, sdkByType); } @RequiredReadAction @Override protected void loadStateImpl(@Nonnull Element element) { super.loadStateImpl(element); myLanguageVersion = StandardJavaScriptVersions.getInstance().findVersionById(element.getAttributeValue("language-version")); } @Override protected void getStateImpl(@Nonnull Element element) { super.getStateImpl(element); if(myLanguageVersion != StandardJavaScriptVersions.getInstance().getDefaultVersion()) { element.setAttribute("language-version", myLanguageVersion.getId()); } } @Nonnull @Override public ModuleInheritableNamedPointer<Sdk> getInheritableSdk() { return myPointer; } @Nullable @Override public Sdk getSdk() { return myPointer.get(); } @Nullable @Override public String getSdkName() { return myPointer.getName(); } @Nonnull @Override public Class<? extends SdkType> getSdkTypeClass() { throw new IllegalArgumentException(); } @Nonnull @Override public LanguageVersion getLanguageVersion() { return myLanguageVersion; } @RequiredReadAction @Override public void commit(@Nonnull ClientJavaScriptModuleExtension mutableModuleExtension) { super.commit(mutableModuleExtension); myLanguageVersion = mutableModuleExtension.getLanguageVersion(); } }
true
be3527031bad365446fcd664e5c255a6d45c2aec
Java
DevRobert/trading
/trading-domain/src/main/java/trading/domain/DateSequenceGenerator.java
UTF-8
919
3.359375
3
[]
no_license
package trading.domain; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class DateSequenceGenerator { private LocalDate nextDate; public DateSequenceGenerator(LocalDate initialDate) { this.nextDate = initialDate; } public LocalDate nextDate() { LocalDate result = this.nextDate; this.nextDate = this.nextDate.plusDays(1); return result; } public List<LocalDate> nextDates(int dayCount) { if(dayCount == 0) { throw new RuntimeException("The day count must not be zero."); } if(dayCount < 0) { throw new RuntimeException("The day count must not be negative."); } List<LocalDate> result = new ArrayList<>(); for(int dayIndex = 0; dayIndex < dayCount; dayIndex++) { result.add(this.nextDate()); } return result; } }
true
130d531b5d2849deac91dd7fba301267048c09a6
Java
lyzh1688/rpc
/src/main/java/rpc/core/MessageSendExecutor.java
UTF-8
563
2.21875
2
[]
no_license
package rpc.core; import rpc.netty.NettyClient; import java.lang.reflect.Proxy; /** * Created by kfzx-liuyz1 on 2017/2/20. */ public class MessageSendExecutor { private NettyClient nettyClient = null; public MessageSendExecutor(String clientName){ this.nettyClient = ClientContainer.Instance().getClient(clientName); } public <T> T execute(Class<T> rpcInterface){ return (T) Proxy.newProxyInstance(rpcInterface.getClassLoader(),new Class<?>[] {rpcInterface},new MessageSendProxy<T>(rpcInterface,this.nettyClient)); } }
true
e37011052ae5d34a488523e89938bd204b388127
Java
nbenjamin/circuit-breaker
/customerAddressService/src/main/java/com/nbenja/springboot/domain/CustomerDetails.java
UTF-8
1,076
2.734375
3
[]
no_license
package com.nbenja.springboot.domain; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class CustomerDetails { private Customer customer; private Address address; public CustomerDetails() { } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj, true); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, true); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } }
true
8e701d6d1e864922263981716a7c60adfd716954
Java
HakAl/Concept
/app/src/main/java/concept/com/labtech/ui/ABaseActivity.java
UTF-8
1,528
2.515625
3
[]
no_license
package concept.com.labtech.ui; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import concept.com.labtech.injection.ActivityScopeModule; import concept.com.labtech.injection.DaggerApplication; import concept.com.labtech.injection.DaggerInjector; import dagger.ObjectGraph; /** Create the activity graph by .plus-ing our modules onto the application graph. ** Inject ourselves so subclasses will have dependencies fulfilled when this method returns. **/ public abstract class ABaseActivity extends ActionBarActivity implements DaggerInjector { private ObjectGraph mActivityGraph; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DaggerApplication application = (DaggerApplication) getApplication(); mActivityGraph = application.getObjectGraph().plus(geActivitytModules()); mActivityGraph.inject(this); } @Override protected void onDestroy() { mActivityGraph = null; super.onDestroy(); } /** Inject the supplied {@code object} using the activity-specific graph. **/ @Override public void inject(Object object) { mActivityGraph.inject(object); } public ObjectGraph getObjectGraph() { return mActivityGraph; } protected Object[] geActivitytModules() { return new Object[]{ new ActivityScopeModule(this), }; } protected <T> T find(int id) { return (T) findViewById(id); } }
true
e78366459f4185c878a7db004d30c6a2dfb1015d
Java
elvinKhalafov/sale_home_admin
/src/main/java/com/sale/home/admin/repository/UserRepositoryImpl.java
UTF-8
4,789
2.21875
2
[]
no_license
package com.sale.home.admin.repository; import com.sale.home.admin.model.Role; import com.sale.home.admin.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.lang.Nullable; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @Repository public class UserRepositoryImpl implements UserRepository { private final String GET_USER_BY_EMAIL = "select * from user u inner join role r on u.id_role = r.id_role where u.email = ? and u.id_role = 1"; private final String GET_ALL_USERS = "select id_user, email, status, first_name, last_name, r.id_role as user_role_id , role_type from `user` u inner join role r on u.id_role=r.id_role where status=?"; private final String GET_USER_BY_ID = "select id_user, email, status, first_name, last_name, r.id_role as user_role_id , role_type from `user` u inner join role r on u.id_role=r.id_role where id_user = ?"; private final String UPDATE_USER_STATUS = "update user set status = ? where id_user = ?"; private final String DELETE_USER_BY_ID = "delete from `user` where id_user = ?"; @Autowired private JdbcTemplate jdbcTemplate; @Override public User loginUser(String email) { User user; try { user = jdbcTemplate.queryForObject(GET_USER_BY_EMAIL, new Object[]{email}, new RowMapper<User>() { @Nullable @Override public User mapRow(ResultSet rs, int i) throws SQLException { User user = new User(); user.setIdUser(rs.getInt("id_user")); user.setEmail(rs.getString("email")); user.setPassword(rs.getString("password")); user.setFirstName(rs.getString("first_name")); user.setLastName(rs.getString("last_name")); user.setToken(rs.getString("token")); user.setStatus(rs.getInt("status")); Role role = new Role(); role.setIdRole(rs.getInt("id_role")); role.setRoleType(rs.getString("role_type")); user.setRole(role); return user; } }); } catch (EmptyResultDataAccessException er) { return null; } return user; } @Override public List<User> getAllUsersByStatus(int status) { List<User> users =jdbcTemplate.query(GET_ALL_USERS, new Object[]{status}, new RowMapper<User>() { @Nullable @Override public User mapRow(ResultSet rs, int i) throws SQLException { User user = new User(); user.setIdUser(rs.getInt("id_user")); user.setEmail(rs.getString("email")); user.setFirstName(rs.getString("first_name")); user.setLastName(rs.getString("last_name")); user.setStatus(rs.getInt("status")); Role role = new Role(); role.setIdRole(rs.getInt("user_role_id")); role.setRoleType(rs.getString("role_type")); user.setRole(role); return user; } }); return users; } @Override public User getUserDetail(int id) { return jdbcTemplate.queryForObject(GET_USER_BY_ID, new Object[]{id}, new RowMapper<User>() { @Nullable @Override public User mapRow(ResultSet rs, int i) throws SQLException { User user = new User(); user.setIdUser(rs.getInt("id_user")); user.setEmail(rs.getString("email")); user.setFirstName(rs.getString("first_name")); user.setLastName(rs.getString("last_name")); user.setStatus(rs.getInt("status")); Role role = new Role(); role.setIdRole(rs.getInt("user_role_id")); role.setRoleType(rs.getString("role_type")); user.setRole(role); return user; } }); } @Override public void updateUserStatus(int id, int status) { int i = jdbcTemplate.update(UPDATE_USER_STATUS, new Object[] {status, id}); if(i==0){ throw new RuntimeException(); } } @Override public void deleteUserById(int id) { int i = jdbcTemplate.update(DELETE_USER_BY_ID, new Object[] { id}); if(i==0){ throw new RuntimeException(); } } }
true
5acf8d464df8b8a68b07f81e04e9e2a647340450
Java
YoungDawnGE/CarRental
/src/main/java/controller/UserController.java
UTF-8
5,602
2.3125
2
[]
no_license
package controller; import entity.Admin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import entity.User; import service.UserService; import util.EncryptionMD5; import util.ResponseEntity; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/signUp") public String signUp() { return "user/signUp"; } @RequestMapping("/checkID") @ResponseBody public ResponseEntity checkID(@RequestBody Map<String,String> map) { String id = map.get("id"); System.out.println("user ID:"+id); User user = this.userService.findUserById(id); System.out.println(user); if (user == null) { return new ResponseEntity(1, "", "此ID可用"); }else { return new ResponseEntity(0, "", "*此ID已被占用"); } } //注册了之后返回登陆界面 @RequestMapping("/addUser")//自己预先注册只有账号和密码 public String addUser(User user,ModelMap modelMap) { String password= EncryptionMD5.md5(user.getPassword()); user.setPassword(password); modelMap.put("user",user); System.out.println(user); this.userService.insertUser(user); return "redirect:/login"; } //管理员帮忙注册user @RequestMapping("/adminAddUser") @ResponseBody public ResponseEntity adminAddUser(@RequestBody User user) { String password= EncryptionMD5.md5(user.getPassword()); user.setPassword(password); System.out.println(user); this.userService.insertUser(user); return new ResponseEntity(1, "", "添加成功"); } //返回所有用户信息 @RequestMapping("/showUser") public String showUser(ModelMap modelMap) { List<User> users = this.userService.getAllUser(); System.out.println(); modelMap.put("userList", users); return "user/userList"; } @RequestMapping("/login") public ModelAndView login(User user, RedirectAttributes redirectAttributes, HttpSession session ) { ModelAndView mv=new ModelAndView(); System.out.println("user的login"); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("id",user.getId()); String password = EncryptionMD5.md5(user.getPassword()); map.put("password", password); //查询ID和密码都输入正确的客户 User u = this.userService.getWhomIsLogin(map); System.out.println(u); if (u == null) { mv.setViewName("redirect:/login"); redirectAttributes.addFlashAttribute("message", "您的账号或密码有误"); }else { mv.setViewName("redirect:/user/home"); redirectAttributes.addFlashAttribute("user", u); session.setAttribute("user",u); } return mv; } @RequestMapping("/home") public String toEmpHome(HttpSession session) { User user = (User)session.getAttribute("user"); System.out.println("session:"+user); if (user == null) { return "redirect:/login"; } return "user/userFirstPage"; } @RequestMapping("/logout") public String logout(SessionStatus sessionStatus) { sessionStatus.setComplete(); return "redirect:/login"; } @RequestMapping("/updateUserForm") public String toUpdateEmp(@RequestParam("id") String id, ModelMap modelMap) { User user = this.userService.findUserById(id); modelMap.put("user", user); return "user/userUpdate"; } @RequestMapping("/changeInfo") public String changeInfo(@RequestParam("id") String id, ModelMap modelMap){ User user = this.userService.findUserById(id); modelMap.put("user", user); return "user/userPersonal"; } @RequestMapping("/updateUser") @ResponseBody public ResponseEntity updateUser(@RequestBody User user) { String newPassword = user.getPassword(); if (newPassword.length() != 32) { String ps = EncryptionMD5.md5(newPassword); user.setPassword(ps); } this.userService.updateUserByID(user); System.out.println("更新 user:"+user); return new ResponseEntity(1, "", "更新用户信息成功"); } @RequestMapping("/deleteUser") @ResponseBody public ResponseEntity deleteUser(@RequestParam("id") String id) { System.out.println("删除 id:"+id); this.userService.deleteUserByID(id); return new ResponseEntity(1, "", "删除成功"); } @RequestMapping("/firstPage") public ModelAndView toFirstPage(HttpSession session) { ModelAndView mv = new ModelAndView(); User user = (User)session.getAttribute("user"); System.out.println("session:"+user); if (user == null) { mv.setViewName("redirect:/login"); return mv; } else { mv.setViewName("user/userFirstPage"); return mv; } } }
true
215f3b530959145c4a64b62910983653ba7f53c0
Java
KanatImagambetov/Spring2020B18_Java
/src/day36_StaticBlock/StaticBlock2.java
UTF-8
562
3.296875
3
[]
no_license
package day36_StaticBlock; import day34_CustomClass.Tester; public class StaticBlock2 { static int a; static int b; int c; static Tester tester1=new Tester(); public static void main(String[] args) { // tester1.setTesterInfo("Jean",123,"SDET",120000); System.out.println(tester1); } static { a=100; b=200; // c=100; // static only exepts static if(100>200){ a=100; }else{ b=200; } tester1.setTesterInfo("Jean",123,"SDET",120000); } }
true
2d542fd61338265e978f11c05007c0623f98dbfb
Java
Valemos/artclass
/app/src/main/java/com/app/artclass/database/DatabaseConverters.java
UTF-8
2,810
2.5625
3
[]
no_license
package com.app.artclass.database; import android.os.Build; import androidx.annotation.RequiresApi; import androidx.room.TypeConverter; import com.app.artclass.WEEKDAY; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.text.DecimalFormat; import java.text.NumberFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; @RequiresApi(api = Build.VERSION_CODES.O) public class DatabaseConverters { static Gson gson = new Gson(); public static DateTimeFormatter getTimeFormatter() { return timeFormatter; } public static DateTimeFormatter getDateFormatter() { return dateFormatter; } public static DateTimeFormatter getDateTimeFormatter() { return dateTimeFormatter; } private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy-HH:mm"); private static NumberFormat moneyFormat = new DecimalFormat("##'₴'"); public static NumberFormat getMoneyFormat() { return moneyFormat; } @TypeConverter public String fromLocalDate(LocalDate date){ return date.format(dateFormatter); } @TypeConverter public LocalDate toLocalDate(String date){ return LocalDate.parse(date,dateFormatter); } @TypeConverter public String fromLocalTime(LocalTime time){ return time.format(timeFormatter); } @TypeConverter public LocalTime toLocalTime(String time){ return LocalTime.parse(time,timeFormatter); } @TypeConverter public String fromLocalDateTime(LocalDateTime dateTime){ return dateTime.format(dateTimeFormatter); } @TypeConverter public LocalDateTime toLocalDateTime(String dateTime){ return LocalDateTime.parse(dateTime,dateTimeFormatter); } // list converter @TypeConverter public List<String> stringToStrList(String data) { if (data == null) { return Collections.emptyList(); } Type listType = new TypeToken<List<String>>() {}.getType(); return gson.fromJson(data, listType); } @TypeConverter public String strListToString(List<String> list) { return gson.toJson(list); } @TypeConverter public String weekdayToString(WEEKDAY weekday){ return weekday.toString(); } @TypeConverter public WEEKDAY stringToWeekday(String weekdayStr){ return WEEKDAY.valueOf(weekdayStr); } }
true
5441c915d07f78cea051212b120f7f8a60e68153
Java
gocd/gocd
/server/src/test-fast/java/com/thoughtworks/go/config/CachedGoConfigTest.java
UTF-8
10,002
1.640625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2023 Thoughtworks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config; import com.thoughtworks.go.config.commands.EntityConfigUpdateCommand; import com.thoughtworks.go.config.update.FullConfigUpdateCommand; import com.thoughtworks.go.listener.ConfigChangedListener; import com.thoughtworks.go.listener.EntityConfigChangedListener; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.MaintenanceModeService; import com.thoughtworks.go.serverhealth.ServerHealthService; import com.thoughtworks.go.serverhealth.ServerHealthState; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) public class CachedGoConfigTest { @Mock private CachedGoConfig cachedGoConfig; @Mock private GoFileConfigDataSource dataSource; private GoConfigHolder configHolder; @Mock private ServerHealthService serverHealthService; @Mock private GoConfigMigrator goConfigMigrator; @Mock private MaintenanceModeService maintenanceModeService; @BeforeEach public void setUp() throws Exception { configHolder = new GoConfigHolder(new BasicCruiseConfig(), new BasicCruiseConfig()); cachedGoConfig = new CachedGoConfig(serverHealthService, dataSource, mock(CachedGoPartials.class), goConfigMigrator, maintenanceModeService); lenient().when(dataSource.load()).thenReturn(configHolder); } @Test public void shouldNotLoadConfigXMLDuringMaintenanceMode() { when(maintenanceModeService.isMaintenanceMode()).thenReturn(true); cachedGoConfig.onTimer(); verifyNoInteractions(dataSource); } @Test public void shouldDelegateWriteEntityConfigCallToDataSource() { EntityConfigUpdateCommand saveCommand = mock(EntityConfigUpdateCommand.class); GoConfigHolder savedConfig = new GoConfigHolder(new BasicCruiseConfig(), new BasicCruiseConfig()); GoConfigHolder holderBeforeUpdate = cachedGoConfig.loadConfigHolder(); Username user = new Username(new CaseInsensitiveString("user")); EntityConfigSaveResult entityConfigSaveResult = mock(EntityConfigSaveResult.class); when(entityConfigSaveResult.getConfigHolder()).thenReturn(savedConfig); when(entityConfigSaveResult.getEntityConfig()).thenReturn(new PipelineConfig()); when(dataSource.writeEntityWithLock(saveCommand, holderBeforeUpdate, user)).thenReturn(entityConfigSaveResult); cachedGoConfig.writeEntityWithLock(saveCommand, user); assertThat(cachedGoConfig.loadConfigHolder(), is(savedConfig)); assertThat(cachedGoConfig.currentConfig(), is(savedConfig.config)); assertThat(cachedGoConfig.loadForEditing(), is(savedConfig.configForEdit)); verify(dataSource).writeEntityWithLock(saveCommand, holderBeforeUpdate, user); } @Test public void shouldLoadConfigHolderIfNotAvailable() throws Exception { cachedGoConfig.forceReload(); assertThat(cachedGoConfig.loadConfigHolder(), is(configHolder)); } @Test public void shouldNotifyConfigListenersWhenConfigChanges() throws Exception { when(dataSource.writeWithLock(any(UpdateConfigCommand.class), any(GoConfigHolder.class))).thenReturn(new GoFileConfigDataSource.GoConfigSaveResult(configHolder, ConfigSaveState.UPDATED)); final ConfigChangedListener listener = mock(ConfigChangedListener.class); cachedGoConfig.registerListener(listener); cachedGoConfig.forceReload(); cachedGoConfig.writeWithLock(cruiseConfig -> cruiseConfig); verify(listener, times(2)).onConfigChange(any(BasicCruiseConfig.class)); } @Test public void shouldNotNotifyWhenConfigIsNullDuringRegistration() throws Exception { final ConfigChangedListener listener = mock(ConfigChangedListener.class); cachedGoConfig.registerListener(listener); verifyNoMoreInteractions(listener); } @Test public void shouldNotifyConcernedListenersWhenEntityChanges() { final boolean[] pipelineConfigChangeListenerCalled = {false}; final boolean[] agentConfigChangeListenerCalled = {false}; final boolean[] cruiseConfigChangeListenerCalled = {false}; EntityConfigChangedListener<PipelineConfig> pipelineConfigChangeListener = new EntityConfigChangedListener<>() { @Override public void onEntityConfigChange(PipelineConfig entity) { pipelineConfigChangeListenerCalled[0] = true; } }; EntityConfigChangedListener<Agent> agentConfigChangeListener = new EntityConfigChangedListener<>() { @Override public void onEntityConfigChange(Agent entity) { agentConfigChangeListenerCalled[0] = true; } }; EntityConfigChangedListener<CruiseConfig> cruiseConfigChangeListener = new EntityConfigChangedListener<>() { @Override public void onEntityConfigChange(CruiseConfig entity) { cruiseConfigChangeListenerCalled[0] = true; } }; cachedGoConfig.registerListener(pipelineConfigChangeListener); cachedGoConfig.registerListener(agentConfigChangeListener); cachedGoConfig.registerListener(cruiseConfigChangeListener); EntityConfigUpdateCommand configCommand = mock(EntityConfigUpdateCommand.class); EntityConfigSaveResult entityConfigSaveResult = mock(EntityConfigSaveResult.class); when(entityConfigSaveResult.getConfigHolder()).thenReturn(configHolder); when(entityConfigSaveResult.getEntityConfig()).thenReturn(new PipelineConfig()); Username user = new Username(new CaseInsensitiveString("user")); when(dataSource.writeEntityWithLock(configCommand, configHolder, user)).thenReturn(entityConfigSaveResult); cachedGoConfig.loadConfigIfNull(); cachedGoConfig.writeEntityWithLock(configCommand, user); assertThat(pipelineConfigChangeListenerCalled[0], is(true)); assertThat(agentConfigChangeListenerCalled[0], is(false)); assertThat(cruiseConfigChangeListenerCalled[0], is(false)); } @Test public void shouldWriteFullConfigWithLock() { FullConfigUpdateCommand fullConfigUpdateCommand = mock(FullConfigUpdateCommand.class); when(dataSource.writeFullConfigWithLock(any(FullConfigUpdateCommand.class), any(GoConfigHolder.class))).thenReturn(new GoFileConfigDataSource.GoConfigSaveResult(null, null)); cachedGoConfig.forceReload(); cachedGoConfig.writeFullConfigWithLock(fullConfigUpdateCommand); verify(dataSource).writeFullConfigWithLock(fullConfigUpdateCommand, cachedGoConfig.loadConfigHolder()); } @Test public void shouldUpdateCachesPostWriteFullConfigWithLock() { BasicCruiseConfig config = mock(BasicCruiseConfig.class); BasicCruiseConfig configForEdit = mock(BasicCruiseConfig.class); BasicCruiseConfig mergedConfigForEdit = mock(BasicCruiseConfig.class); GoConfigHolder goConfigHolder = new GoConfigHolder(config, configForEdit); goConfigHolder.mergedConfigForEdit = mergedConfigForEdit; ConfigSaveState configSaveState = ConfigSaveState.UPDATED; when(dataSource.writeFullConfigWithLock(any(FullConfigUpdateCommand.class), any(GoConfigHolder.class))) .thenReturn(new GoFileConfigDataSource.GoConfigSaveResult(goConfigHolder, configSaveState)); cachedGoConfig.forceReload(); ConfigSaveState saveState = cachedGoConfig.writeFullConfigWithLock(mock(FullConfigUpdateCommand.class)); assertThat(saveState, is(configSaveState)); assertThat(cachedGoConfig.currentConfig(), is(config)); assertThat(cachedGoConfig.loadForEditing(), is(configForEdit)); assertThat(cachedGoConfig.loadConfigHolder(), is(goConfigHolder)); assertThat(cachedGoConfig.loadMergedForEditing(), is(mergedConfigForEdit)); verify(serverHealthService, times(2)).update(any(ServerHealthState.class)); } @Test public void shouldUpgradeConfigFile() throws Exception { cachedGoConfig.upgradeConfig(); verify(goConfigMigrator).migrate(); } @Test public void shouldUpdateCachesPostConfigUpgade() throws Exception { BasicCruiseConfig config = mock(BasicCruiseConfig.class); BasicCruiseConfig configForEdit = mock(BasicCruiseConfig.class); BasicCruiseConfig mergedConfigForEdit = mock(BasicCruiseConfig.class); GoConfigHolder goConfigHolder = new GoConfigHolder(config, configForEdit); goConfigHolder.mergedConfigForEdit = mergedConfigForEdit; when(goConfigMigrator.migrate()).thenReturn(goConfigHolder); cachedGoConfig.upgradeConfig(); assertThat(cachedGoConfig.currentConfig(), is(config)); assertThat(cachedGoConfig.loadForEditing(), is(configForEdit)); assertThat(cachedGoConfig.loadConfigHolder(), is(goConfigHolder)); assertThat(cachedGoConfig.loadMergedForEditing(), is(mergedConfigForEdit)); verify(serverHealthService).update(any(ServerHealthState.class)); } }
true
8d5fa637bb21a242d072fd176744615bf0b8a520
Java
luigiDB/salesTaxes
/src/main/java/receipt/impl/ReceiptProduct.java
UTF-8
1,709
2.875
3
[]
no_license
package receipt.impl; import cart.IBilledProduct; import receipt.IReceiptProduct; import java.math.BigDecimal; import java.util.Objects; public class ReceiptProduct implements IReceiptProduct { private final String product; private final int quantity; private final BigDecimal price; public static IReceiptProduct from(IBilledProduct product) { Objects.requireNonNull(product); return new ReceiptProduct(product.getProduct().getProduct(), product.getQuantity(), product.getProduct().getTaxedPrice().multiply(BigDecimal.valueOf(product.getQuantity()))); } public ReceiptProduct(String product, int quantity, BigDecimal price) { Objects.requireNonNull(product); Objects.requireNonNull(price); this.product = product; this.quantity = quantity; this.price = price; } @Override public String getProduct() { return product; } @Override public int getQuantity() { return quantity; } @Override public BigDecimal getPrice() { return price; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReceiptProduct that = (ReceiptProduct) o; if (quantity != that.quantity) return false; if (!product.equals(that.product)) return false; return price.compareTo(that.price) == 0; } @Override public int hashCode() { int result = product.hashCode(); result = 31 * result + quantity; result = 31 * result + price.setScale(2).hashCode(); return result; } }
true
83504a786861b5ae7d3903e3a83b74d5a3c8d20b
Java
geraldvindas/TCU_655_Mi_cuenca
/app/src/main/java/com/ucr/micuenca/MapaImagenes.java
UTF-8
1,278
2.375
2
[]
no_license
package com.ucr.micuenca; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; public class MapaImagenes extends PagerAdapter { private Context mContext; private int[] nImagenesId = new int[] {R.drawable.mapa_completo, R.drawable.mapa_izquierda, R.drawable.mapa_centro, R.drawable.mapa_derecha}; MapaImagenes(Context context){ mContext = context; } @Override public int getCount() { return nImagenesId.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { ImageView imageView = new ImageView(mContext); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(nImagenesId[position]); container.addView(imageView, 0); return imageView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((ImageView) object); } }
true
442b039f82c46e4eef59f9e403dda1c8a2e4e708
Java
maximuszeng/IM-Dec
/webapi/src/main/java/com/eim/webapi/vo/base/AccessUserVO.java
UTF-8
2,880
1.734375
2
[]
no_license
package com.eim.webapi.vo.base; import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.eim.webapi.vo.common.BaseVO; import com.fasterxml.jackson.annotation.JsonProperty; @XmlRootElement(name = "u") public class AccessUserVO extends BaseVO implements Serializable { private static final long serialVersionUID = -518128477815180710L; private Long appId; private Long auid; private String name; private String email; private String mobile; private Long accessTime; private String sessionId; // HTTP Headers // Client private String acceptLanguage; private String userAgent; private String referer; private String ipAddress; @JsonProperty("appId") public Long getAppId() { return appId; } @XmlElement(name = "appId") public void setAppId(Long appId) { this.appId = appId; } @JsonProperty("auid") public Long getAuid() { return auid; } @XmlElement(name = "auid") public void setAuid(Long auid) { this.auid = auid; } @JsonProperty("ipAddress") public String getIpAddress() { return ipAddress; } @XmlElement(name = "ipAddress") public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } @JsonProperty("name") public String getName() { return name; } @XmlElement(name = "name") public void setName(String name) { this.name = name; } @JsonProperty("email") public String getEmail() { return email; } @XmlElement(name = "email") public void setEmail(String email) { this.email = email; } @JsonProperty("mobile") public String getMobile() { return mobile; } @XmlElement(name = "mobile") public void setMobile(String mobile) { this.mobile = mobile; } @JsonProperty("accessTime") public Long getAccessTime() { return accessTime; } @XmlElement(name = "accessTime") public void setAccessTime(Long accessTime) { this.accessTime = accessTime; } @JsonProperty("sessionId") public String getSessionId() { return sessionId; } @XmlElement(name = "sessionId") public void setSessionId(String sessionId) { this.sessionId = sessionId; } @JsonProperty("acceptLanguage") public String getAcceptLanguage() { return acceptLanguage; } @XmlElement(name = "acceptLanguage") public void setAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; } @JsonProperty("userAgent") public String getUserAgent() { return userAgent; } @XmlElement(name = "userAgent") public void setUserAgent(String userAgent) { this.userAgent = userAgent; } @JsonProperty("referer") public String getReferer() { return referer; } @XmlElement(name = "referer") public void setReferer(String referer) { this.referer = referer; } }
true
e3ee9e17463a460ea1c7b12834419a698d9cda47
Java
i-Android/meetup-client
/src/com/galaxy/meetup/client/util/Dates.java
UTF-8
2,403
2.4375
2
[]
no_license
/** * galaxy inc. * meetup client for android */ package com.galaxy.meetup.client.util; import android.content.Context; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import com.galaxy.meetup.client.android.R; /** * * @author sihai * */ public class Dates { private static Time sThenTime; public static CharSequence getAbbreviatedRelativeTimeSpanString(Context context, long l) { long l1 = System.currentTimeMillis(); if(l1 - l < 60000L) { return context.getResources().getText(R.string.posted_just_now); } else { try { return DateUtils.getRelativeTimeSpanString(l, l1, 60000L, 0x50000).toString(); } catch (Exception e) { if(EsLog.isLoggable("Dates", 3)) Log.d("Dates", (new StringBuilder("DateUtils.getRelativeTimeSpanString threw an exception! time=")).append(l).append(", now=").append(l1).append("\n").append(e.getMessage()).toString()); return getShortRelativeTimeSpanString(context, l); } } } private static synchronized long getNumberOfDaysPassed(long l, long l1) { int j; if(sThenTime == null) sThenTime = new Time(); sThenTime.set(l); int i = Time.getJulianDay(l, sThenTime.gmtoff); sThenTime.set(l1); j = Math.abs(Time.getJulianDay(l1, sThenTime.gmtoff) - i); long l2 = j; return l2; } public static CharSequence getRelativeTimeSpanString(Context context, long l) { long l1 = System.currentTimeMillis(); if(l1 - l < 60000L) { return context.getResources().getText(R.string.posted_just_now); } else { try { return DateUtils.getRelativeTimeSpanString(l, l1, 60000L, 0x40000).toString(); } catch (Exception e) { if(EsLog.isLoggable("Dates", 3)) Log.d("Dates", (new StringBuilder("DateUtils.getRelativeTimeSpanString threw an exception! time=")).append(l).append(", now=").append(l1).append("\n").append(e.getMessage()).toString()); return getShortRelativeTimeSpanString(context, l); } } } public static CharSequence getShortRelativeTimeSpanString(Context context, long l) { // TODO return ""; } }
true
67bd4f0c55140276922cf4ba3d43ae9d157e4779
Java
Ryan2000/JavaII
/Shapes_Hoyda/src/com/ryanhoyda/a2shapes/Circle.java
UTF-8
504
3.21875
3
[]
no_license
package com.ryanhoyda.a2shapes; public class Circle extends Shapes { public static final double PI = 3.1416; //should be Math.PI private double radius; public Circle(double radius) { super(); this.radius = radius; } public double getRadius() { return radius; } @Override public double area() { // TODO Auto-generated method stub return PI*radius*radius; } @Override public double circumference() { // TODO Auto-generated method stub return 2*PI*radius; } }
true
f1e0f51864ba9b74dbd16f964033c8a51fd69544
Java
rosoareslv/SED99
/java/sonarqube/2018/12/CredentialsLocalAuthentication.java
UTF-8
6,999
2.15625
2
[]
no_license
/* * SonarQube * Copyright (C) 2009-2018 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.authentication; import java.security.SecureRandom; import javax.annotation.Nullable; import org.apache.commons.codec.digest.DigestUtils; import org.mindrot.jbcrypt.BCrypt; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.event.AuthenticationEvent.Method; import org.sonar.server.authentication.event.AuthenticationEvent.Source; import org.sonar.server.authentication.event.AuthenticationException; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * Validates the password of a "local" user (password is stored in * database). */ public class CredentialsLocalAuthentication { private final DbClient dbClient; private static final SecureRandom SECURE_RANDOM = new SecureRandom(); // The default hash method that must be used is BCRYPT private static final HashMethod DEFAULT = HashMethod.BCRYPT; public CredentialsLocalAuthentication(DbClient dbClient) { this.dbClient = dbClient; } /** * This method authenticate a user with his password against the value stored in user. * If authentication failed an AuthenticationException will be thrown containing the failure message. * If the password must be updated because an old algorithm is used, the UserDto is updated but the session * is not committed */ public void authenticate(DbSession session, UserDto user, @Nullable String password, Method method) { if (user.getHashMethod() == null) { throw AuthenticationException.newBuilder() .setSource(Source.local(method)) .setLogin(user.getLogin()) .setMessage("null hash method") .build(); } HashMethod hashMethod; try { hashMethod = HashMethod.valueOf(user.getHashMethod()); } catch (IllegalArgumentException ex) { throw AuthenticationException.newBuilder() .setSource(Source.local(method)) .setLogin(user.getLogin()) .setMessage(format("Unknown hash method [%s]", user.getHashMethod())) .build(); } AuthenticationResult result = hashMethod.checkCredentials(user, password); if (!result.isSuccessful()) { throw AuthenticationException.newBuilder() .setSource(Source.local(method)) .setLogin(user.getLogin()) .setMessage(result.getFailureMessage()) .build(); } // Upgrade the password if it's an old hashMethod if (hashMethod != DEFAULT) { DEFAULT.storeHashPassword(user, password); dbClient.userDao().update(session, user); } } /** * Method used to store the password as a hash in database. * The crypted_password, salt and hash_method are set */ public void storeHashPassword(UserDto user, String password) { DEFAULT.storeHashPassword(user, password); } public enum HashMethod implements HashFunction { SHA1(new Sha1Function()), BCRYPT(new BcryptFunction()); private HashFunction hashFunction; HashMethod(HashFunction hashFunction) { this.hashFunction = hashFunction; } @Override public AuthenticationResult checkCredentials(UserDto user, String password) { return hashFunction.checkCredentials(user, password); } @Override public void storeHashPassword(UserDto user, String password) { hashFunction.storeHashPassword(user, password); } } private static class AuthenticationResult { private final boolean successful; private final String failureMessage; private AuthenticationResult(boolean successful, String failureMessage) { checkArgument((successful && failureMessage.isEmpty()) || (!successful && !failureMessage.isEmpty()), "Incorrect parameters"); this.successful = successful; this.failureMessage = failureMessage; } public boolean isSuccessful() { return successful; } public String getFailureMessage() { return failureMessage; } } public interface HashFunction { AuthenticationResult checkCredentials(UserDto user, String password); void storeHashPassword(UserDto user, String password); } /** * Implementation of deprecated SHA1 hash function */ private static final class Sha1Function implements HashFunction { @Override public AuthenticationResult checkCredentials(UserDto user, String password) { if (user.getCryptedPassword() == null) { return new AuthenticationResult(false, "null password in DB"); } if (user.getSalt() == null) { return new AuthenticationResult(false, "null salt"); } if (!user.getCryptedPassword().equals(hash(user.getSalt(), password))) { return new AuthenticationResult(false, "wrong password"); } return new AuthenticationResult(true, ""); } @Override public void storeHashPassword(UserDto user, String password) { requireNonNull(password, "Password cannot be null"); byte[] saltRandom = new byte[20]; SECURE_RANDOM.nextBytes(saltRandom); String salt = DigestUtils.sha1Hex(saltRandom); user.setHashMethod(HashMethod.SHA1.name()) .setCryptedPassword(hash(salt, password)) .setSalt(salt); } private static String hash(String salt, String password) { return DigestUtils.sha1Hex("--" + salt + "--" + password + "--"); } } /** * Implementation of bcrypt hash function */ private static final class BcryptFunction implements HashFunction { @Override public AuthenticationResult checkCredentials(UserDto user, String password) { if (!BCrypt.checkpw(password, user.getCryptedPassword())) { return new AuthenticationResult(false, "wrong password"); } return new AuthenticationResult(true, ""); } @Override public void storeHashPassword(UserDto user, String password) { requireNonNull(password, "Password cannot be null"); user.setHashMethod(HashMethod.BCRYPT.name()) .setCryptedPassword(BCrypt.hashpw(password, BCrypt.gensalt(12))) .setSalt(null); } } }
true
169025b261e4d7c315c030fa111a8b888c23b74f
Java
strzelaczinho/reddit
/src/CHALLENGE_33_DIFFICULT_TSP/Main.java
UTF-8
4,870
3.25
3
[]
no_license
package CHALLENGE_33_DIFFICULT_TSP; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Main { private static class Point implements Comparable<Point> { private final double x; private final double y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } public double getDistance(Point dest) { double distX = dest.getX() - x; double distY = dest.getY() - y; distX *= distX; distY *= distY; return Math.sqrt(distX + distY); } @Override public String toString() { return "{ X: " + x + "; Y: " + y + " }"; } @Override public boolean equals(Object obj) { if (obj instanceof Point) { Point point = (Point) obj; return point.x == x && point.y == y; } return false; } @Override public int compareTo(Point other) { int result = Double.compare(x, other.getX()); if (result == 0) { result = Double.compare(y, other.getY()); } return result; } } private static Point getNextPoint(List<Point> points, int start) { return points.get(start == points.size() - 1 ? 0 : start + 1); } private static double getTotalDistance(List<Point> points) { double shortestDist = 0; for (int t = 0; t < points.size(); ++t) { shortestDist += points.get(t).getDistance(getNextPoint(points, t)); } return shortestDist; } public static void main(String[] args) { long start = System.currentTimeMillis(); double[][] graph = Reference.GREYBEARD; if (graph.length <= 1) { System.out.println("SOLUTION: 0"); return; } LinkedList<Point> points = new LinkedList<>(); ArrayDeque<Point> collisions = new ArrayDeque<>(graph.length); // O(n) System.out.println("Input Graph: "); for (int t = 0; t < graph.length; ++t) { Point point = new Point(graph[t][0], graph[t][1]); points.add(point); System.out.println(point); } // O(nlog(n)) Collections.sort(points); List<Point> virtualSolution; // O(n^2) for (int t = 0; t < points.size(); ++t) { Point point = points.get(t); for (int s = t + 1; s < points.size(); ++s) { Point other = points.get(s); if (point.getY() == other.getY()) { collisions.add(other); points.remove(s); } } virtualSolution = new ArrayList<>(points); Collections.swap(virtualSolution, t, t == 0 ? points.size() - 1 : t - 1); double solutionDist = 0; double virtualDist = 0; for (int s = 0; s < points.size(); ++s) { solutionDist += points.get(s).getDistance(getNextPoint(points, s)); virtualDist += virtualSolution.get(s).getDistance(getNextPoint(virtualSolution, s)); } if (virtualDist < solutionDist) { points = new LinkedList<>(virtualSolution); } } if (!collisions.isEmpty()) { Map<Double, Integer> distances = new HashMap<>(points.size(), 1F); // O(n^3) while (!collisions.isEmpty()) { Point c = collisions.remove(); for (int t = 0; t < points.size(); ++t) { virtualSolution = new ArrayList<>(points); virtualSolution.add(t, c); distances.put(getTotalDistance(virtualSolution), t); } points.add(distances.get(Collections.min(distances.keySet())), c); distances.clear(); } } System.out.println('\n' + " --- RESULT ---"); for (Point point : points) { System.out.println(point); } System.out.println('\n' + " --- VERIFICATION ---"); System.out.println("Graph Length:\t" + graph.length); System.out.println("Solution Size:\t" + points.size()); System.out.println("VERIFIED: " + (points.size() == graph.length)); System.out.println('\n' + " --- FINAL PHASE ---"); System.out.println("SOLUTION: " + getTotalDistance(points)); System.out.println("Runtime: " + (System.currentTimeMillis() - start) + " ms"); } }
true
81b5b756e256f5df52786154b9606a8c292659eb
Java
pannicole/pingball1
/src/Pingball/Pingball/Board.java
UTF-8
18,882
3.265625
3
[]
no_license
package Pingball; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import physics.Angle; import physics.LineSegment; /** * The class Board. It stores a list of its balls, a list of its gadgets (stored as ComplexBoardElements), * references to its neighboring Boards (and their names), and a map that describes all the triggers in the Board. * @author kaixiao * */ public class Board { private int fps; private List<Ball> balls; private Board leftboard = null; private Board rightboard = null; private Board topboard = null; private Board bottomboard = null; private String leftName; private String rightName; private String topName; private String bottomName; private String name; private List<ComplexBoardElement> elements; private Map<ComplexBoardElement, List<ComplexBoardElement>> triggers; private final double gravity; private final double mu1; private final double mu2; private List<BallMessage> exitBalls; /** * * Constructor for a board, creates a new board object with fields for each * of the parameters * * @param balls * : the list of balls on the board * @param name * : the name of the board * @param elements * : the board elements located on the board * @param fps the framerate of the board * @param l the standard unit of measurement on the board */ public Board(int fps, String name, double gravity, double friction1, double friction2, List<Ball> balls, List<ComplexBoardElement> elements) { triggers = new HashMap<ComplexBoardElement, List<ComplexBoardElement>>(); this.fps = fps; this.balls = balls; this.name = name; this.elements = elements; this.gravity = gravity; this.mu1 = friction1; this.mu2 = friction2; ComplexBoardElement leftWall = new ComplexWall(new LineSegment(0.0, 0.0, 0.0, 20.0), "leftWall", "left"); ComplexBoardElement rightWall = new ComplexWall(new LineSegment(20.0, 0.0, 20.0, 20.0), "rightWall", "right"); ComplexBoardElement topWall = new ComplexWall(new LineSegment(0.0, 0.0, 20.0, 0.0), "topWall", "top"); ComplexBoardElement bottomWall = new ComplexWall(new LineSegment(0.0, 20.0, 20.0, 20.0), "bottomWall", "bottom"); elements.add(leftWall); elements.add(rightWall); elements.add(topWall); elements.add(bottomWall); } /** * gets the elements in this board, such as bumpers and absorbers * @return a List of ComplexBoardElements that make up the board */ public List<ComplexBoardElement> getElements(){ return this.elements; } public Board getLeftBoard() { return leftboard; } public Board getRightBoard() { return rightboard; } public Board getUpperBoard() { return topboard; } public Board getLowerBoard() { return bottomboard; } /** * toggles the visibility of a wall based on an integer input * if the integer is 0 mod 4, it toggles the visibility of the right wall * 1 mod 4 - top * 2 mod 4 - left * 3 mod 4 - bottom * easy way to remember - it goes in the same order as angles in math * @param index the index of the wall, can be any integer because it will be modded 4 * Note: The numbers were changed up a bit, so now left is 1, and it increases going * counterclockwise up to 4 */ public void toggleInvis(int index, String otherBoardName) { //left = 1, top = 2, right = 3, bottom = 4 int ind = 3-index % 4; for (ComplexBoardElement cbe : elements) { if (cbe.isComplexWall()) { String direction = ((ComplexWall) cbe).getDirection(); if(direction.equals("right") && ind == 0) { ((ComplexWall) cbe).toggleVisible(); setRight(otherBoardName); } else if(direction.equals("top") && ind == 1) { ((ComplexWall) cbe).toggleVisible(); setTop(otherBoardName); } else if(direction.equals("left") && ind == 2) { ((ComplexWall) cbe).toggleVisible(); setLeft(otherBoardName); } else if(direction.equals("bottom") && ind == 3) { ((ComplexWall) cbe).toggleVisible(); setBottom(otherBoardName); } } } } /** * connects this board to another board on the right * @param rightName the name of the board to be connected on the right */ public void setRight(String rightName) { this.rightName = rightName; } /** * connects this board to another board on the left * @param rightName the name of the board to be connected on the left */ public void setLeft(String leftName) { this.leftName = leftName; } /** * connects this board to another board on the top * @param rightName the name of the board to be connected on the top */ public void setTop(String topName) { this.topName = topName; } /** * connects this board to another board on the bottom * @param rightName the name of the board to be connected on the bottom */ public void setBottom(String bottomName) { this.bottomName = bottomName; } /** * gets the name of this board * @return a String representing the name of this board, can't be the same as any other boards on this server */ public String getName() { return this.name; } /** * Adds a ball to the list of balls in play on this board * * @param ball * : the ball that is coming into the board */ public synchronized void enterBall(BallMessage message) { if (!this.name.equals(message.getDestination())) { throw new RuntimeException("this ball got put in the wrong board! it was headed for " + message.getDestination() + " but it got put in " + this.name + "!!!"); } Ball newball = message.getBall(); if (message.getDirection().equals("left")) { //if it left through the left wall of the previous board, it should come in the rightmost side of the current board newball.place(20, newball.getY()); } else if (message.getDirection().equals("right")) { //if it left through the right wall of the previous board, it should come in the leftmost side of the current board newball.place(1, newball.getY()); } else if (message.getDirection().equals("top")) { //if it left through the top wall of the previous board, it should come in the bottom-most side of the current board newball.place(newball.getX(), 20); } else if (message.getDirection().equals("bottom")) { //if it left through the bottom wall of the previous board, it should come in the topmost side of the current board newball.place(newball.getX(), 1); } else { throw new RuntimeException("you messed up in your declarations! uh oh! getDirection was something other than left right top or bottom!!!"); } balls.add(newball); } /** * Removes a ball from the list of balls in play on this board * * @param ball * : the ball that is leaving the board */ public synchronized Ball exitBall(Ball ball) { balls.remove(ball); return ball; } /** * Helper method for converting this board to a String * @return a 2D array of Strings that represent what String should go in each cell in the final 22x22 printed grid */ private String[][] toStringHelper() { final int WIDTH = 22; final int HEIGHT = 22; String[][] toStringHelper = new String[WIDTH][HEIGHT]; // make the walls and initialize empty array for all other elements for (int i = 0; i < WIDTH; i++) { for (int j = 0; j < HEIGHT; j++) { if (i == 0 || i == WIDTH - 1 || j == 0 || j == HEIGHT - 1) { toStringHelper[i][j] = "."; } else { toStringHelper[i][j] = " "; } } } // add neighboring wall names if (this.getLeftBoard() != null) { for (int jj = 0; jj < this.getLeftBoard().getName().length(); jj++) { toStringHelper[jj + 1][0] = this.getLeftBoard().getName() .substring(jj, jj + 1); } } if (this.getRightBoard() != null) { for (int jj = 0; jj < this.getRightBoard().getName().length(); jj++) { toStringHelper[jj + 1][WIDTH-1] = this.getRightBoard().getName() .substring(jj, jj + 1); } } if (this.getUpperBoard() != null) { for (int jj = 0; jj < this.getUpperBoard().getName().length(); jj++) { toStringHelper[0][jj + 1] = this.getUpperBoard().getName() .substring(jj, jj + 1); } } if (this.getLowerBoard() != null) { for (int jj = 0; jj < this.getLowerBoard().getName().length(); jj++) { toStringHelper[WIDTH-1][jj + 1] = this.getLowerBoard().getName() .substring(jj, jj + 1); } } // add elements for (ComplexBoardElement e : elements) { // flipper if (e.isFlipper()) { Flipper d = (Flipper) e; int x = (int) (d.getX() + 0.5) + 1 ; int y = (int) (d.getY() + 0.5) + 1; if (e.toString() == "|") { toStringHelper[y][x] = d.toString(); toStringHelper[y + 1][x] = d.toString(); } else { toStringHelper[y][x] = d.toString(); if (d.isRight()) { toStringHelper[y][x - 1] = d.toString(); } toStringHelper[y][x + 1] = d.toString(); } } // absorber else if (e.isAbsorber()) { Absorber f = (Absorber) e; for (int i = (int) f.getX() + 1; i < f.getLength() + f.getX() + 1; i++) { for (int j = (int) f.getY() + 1; j < f.getHeight() + f.getY() + 1; j++) { toStringHelper[j][i] = e.toString(); } } } else if (e.isComplexWall()) { //Special } else { // square, circle, triangle bumper int x = (int) (e.getX() + 0.5)+1; int y = (int) (e.getY() + 0.5)+1; toStringHelper[y][x] = e.toString(); } } //add the balls into the array //if there is already something there, add it to the closest square that it came from for (Ball ball : balls) { int x = (int) (ball.getX() + 0.5)+1; int y = (int) (ball.getY() + 0.5)+1; if (toStringHelper[y][x].equals(" ")) { toStringHelper[y][x] = "*"; } else { Angle direction = ball.getVelocity().angle(); Angle zero = new Angle(0); //Angle fortyfive = new Angle(0.25*Math.PI); Angle ninety = new Angle(0.5* Math.PI); //Angle onethirtyfive = new Angle(0.75*Math.PI); Angle oneeighty = new Angle(Math.PI); //Angle twotwentyfive = new Angle(1.25*Math.PI); Angle twoseventy = new Angle(1.5*Math.PI); //Angle threefifteen = new Angle(1.75*Math.PI); Angle threesixty = new Angle(2*Math.PI); //if it's coming from the top right, move it to the top right if (direction.compareTo(zero) == 1 && direction.compareTo(ninety) <= 0) { toStringHelper[y-1][x+1] = "*"; } //if it's coming from the top left, move it to the top left else if (direction.compareTo(ninety) == 1 && direction.compareTo(oneeighty) <= 0) { toStringHelper[y-1][x-1] = "*"; } //if it's coming from the bottom left, move it to the bottom left else if (direction.compareTo(oneeighty) == 1 && direction.compareTo(twoseventy) <= 0) { toStringHelper[y+1][x-1] = "*"; } //if it's coming from the bottom right, move it to the bottom right else if (direction.compareTo(twoseventy) == 1 && direction.compareTo(threesixty) <= 0) { toStringHelper[y+1][x+1] = "*"; } } } return toStringHelper; } /** * the toString() method * * @return A string representation of the board */ public String toString() { final int WIDTH = 22; String[][] strArr = toStringHelper(); String str = ""; for (int i = 0; i < WIDTH ; i++) { for (int j = 0; j < WIDTH; j++) { str += strArr[i][j]; } str += "\n"; } return str; } /** * Mutates the board and the board elements by iterating through all the components of the board * and performing the correct operations */ public void step() { //rotates any flippers that might be on the board if necessary List<ComplexBoardElement> actionTriggers = new ArrayList<ComplexBoardElement>(); for (ComplexBoardElement gadget : elements) { if (gadget.isFlipper()) { gadget = (Flipper)(gadget); if(((Flipper) gadget).getRotating()) { if (((Flipper) gadget).getRotated() == 90.0 || ((Flipper) gadget).getRotated() == 0.0) { ((Flipper) gadget).stopRotating(); ((Flipper) gadget).resetRotated(); } else { ((Flipper) gadget).rotateStep(0.04/fps); } } } } //Now moves the balls forward and checks for collisions for (Ball ball : balls) { boolean firstElt = true; ComplexBoardElement closestComplexPart = null; for (ComplexBoardElement elt : elements) { if (firstElt || closestComplexPart.timeUntilCollision(ball) > elt.timeUntilCollision(ball) && elt.timeUntilCollision(ball) > 0.0) { firstElt = false; closestComplexPart = elt; } } if (closestComplexPart.timeUntilCollision(ball) < 0.04 / fps) { ball.step(closestComplexPart.timeUntilCollision(ball), this.gravity, this.mu1, this.mu2); if (!closestComplexPart.checkRemove()) closestComplexPart.bounce(ball); //Check if the ball hit an invisible wall //If it did, add it to the exitBalls list then remove it from this board's list of balls else { ComplexWall invisWall = (ComplexWall)(closestComplexPart); if (invisWall.getDirection().equals("left")) { exitBalls.add(new BallMessage(this.exitBall(ball), this.leftName, "left")); } else if (invisWall.getDirection().equals("right")) { exitBalls.add(new BallMessage(this.exitBall(ball), this.rightName, "right")); } else if (invisWall.getDirection().equals("top")) { exitBalls.add(new BallMessage(this.exitBall(ball), this.topName, "top")); } else if (invisWall.getDirection().equals("bottom")) { exitBalls.add(new BallMessage(this.exitBall(ball), this.bottomName, "bottom")); } else { throw new RuntimeException("you initialized your boards wrong!"); } } //The closestComlexPart was just hit, so call its trigger. actionTriggers.add(closestComplexPart); } //If no collisions, step forward a bit else { ball.step(0.04/fps, this.gravity, this.mu1, this.mu2); } } //Perform all triggered actions. for (ComplexBoardElement actionTrigger : actionTriggers) { List<ComplexBoardElement> actionables = triggers.get(actionTrigger); if (actionables != null) { for (ComplexBoardElement actionElt : actionables) { actionElt.action(); } } } } /** * Extracts the list of BallMessages for the balls that need to leave the board * empties exitBalls while it does so * @return a list of BallMessages for each of the balls that needs to leave the board */ public List<BallMessage> extractExitBalls() { List<BallMessage> extractBalls = new ArrayList<BallMessage>(); while(this.exitBalls != null && this.exitBalls.size() > 0) { extractBalls.add(exitBalls.remove(0)); } return extractBalls; } /** * @param side * : the number that corresponds to the side that */ public void setNeighbor(Board board, Side side) { if (side == Side.LEFT) leftboard = board; if (side == Side.RIGHT) rightboard = board; if (side == Side.TOP) topboard = board; if (side == Side.BOTTOM) bottomboard = board; } /** * Adds a trigger to the list of triggers * * @param elt * - a ComplexBoardElement that triggers something * @param elt1 * - a ComplexBoardElement that is triggered by the first * element. */ public void addTrigger(ComplexBoardElement elt, ComplexBoardElement elt1) { List<ComplexBoardElement> elements = triggers.get(elt); if (elements == null) { elements = new ArrayList<ComplexBoardElement>(); } elements.add(elt1); triggers.put(elt, elements); } }
true
11a9ae98340ebd32540179651b6d4c829e08edc6
Java
cmjman/iBookClubServer
/src/com/shining/ibookclubserver/bean/UserBean.java
UTF-8
1,364
2.125
2
[]
no_license
package com.shining.ibookclubserver.bean; public class UserBean { private int id; private String email; private String password; private String nickname; private String picture; private int age; private String sex; private String registertime; private String interest; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getRegistertime() { return registertime; } public void setRegistertime(String registertime) { this.registertime = registertime; } public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest; } }
true
a39e8953e7383a5e70868af4284d876280eba6ce
Java
kokubum/ChessProject
/src/game/Game.java
UTF-8
18,102
3.4375
3
[]
no_license
package game; import board.BoardGame; import chronometer.Chronometer; import game.enums.GameLevel; import game.enums.TypePiece; import pieces.*; import java.util.ArrayList; import java.util.Iterator; public class Game { private Player player1, player2; private Player playerTurn; //Jogador que vai jogar private BoardGame boardGame; //Tabuleiro de xadrez private static int gameNumber = 0; //Numero do jogo que será iniciado (static = caracterista da classe jogo, antes de ser instânciada) private GameLevel level; //Nivel de dificuldade do jogo | Intimamente relacionado ao funcionamento do cronômetro private Chronometer chronometer; private boolean isYourKingInCheck; private boolean gameOver; //Construtor do Game vai instanciar todos os seus objetos devido a agregação forte relacionada a ele public Game(String nickPlayer1, String nickPlayer2, boolean whitePlayer1, boolean whitePlayer2, GameLevel level) { this.player1 = new Player(nickPlayer1, whitePlayer1); this.player2 = new Player(nickPlayer2, whitePlayer2); this.isYourKingInCheck = false; this.setGameOver(false); this.boardGame = new BoardGame(); ++gameNumber; //A cada jogo criado seu número irá ser modificado this.level = level; this.chronometer = new Chronometer(this.level); this.myTurn(); } //Método para definir se o Rei está em Check ou não (OBS: Supõe que o jogador não vai botar seu próprio rei em check public boolean isKingInCheck(Piece piece,Player player) { ArrayList<Position>checkingPosition = null; //Testo se a peça que se moveu é um peão, devido ao overload no método showPossibleMoves() if(piece instanceof PawnP) { if(piece.getPosition().getX()>0 && piece.getPosition().getX() <7) { PawnP pawn = (PawnP)piece; checkingPosition = this.showPossibleMoves(player, pawn); } } else { checkingPosition = this.showPossibleMoves(player, piece); } //Preciso verificar que as movimentações não são nulas (piece não tem como se mover) if(checkingPosition!=null) { for(Position aux:checkingPosition) { //Eu não testo a cor da peça pois no método showPossibleMoves ele ja remove a possibilidade da peça se mover pra uma posição //em que há uma peça da mesma cor que ela if(this.boardGame.getBoardMatrix()[aux.getX()][aux.getY()]!=null) { //Se uma dessas movimentações for a posição que se encontra o King então o jogador está em check if(this.boardGame.getBoardMatrix()[aux.getX()][aux.getY()] instanceof KingP) { return true; } } } } //Se não, ele não está return false; } //Método para definir de quem vai começar o jogo public void myTurn() { if(this.player1.isWhitePlayer()==true) { this.setPlayerTurn(player1); } else { this.setPlayerTurn(player2); } } //Método para movimentar uma peça public boolean movePiece(Position position,Piece piece,Player player) { PawnP pawn = null; //Crio uma arrayList auxiliar para receber as movimentaçoes possiveis, devido ao Overload no metodo showPossibleMoves() ArrayList<Position> auxiliarMoves=null; //Crio uma variável booleana para dizer se o jogador escolheu um local válido boolean isPossible=false; //Se a peça for um peão preciso fazer um casting e passar o metodo para o arrayList auxiliar com seu metodo correspondente if(piece instanceof PawnP) { pawn = (PawnP)piece; auxiliarMoves = this.showPossibleMoves(player, pawn); } else { auxiliarMoves = this.showPossibleMoves(player,piece); } for(Position aux:auxiliarMoves) { //Se a posição escolhida estiver na lista de possiveis movimentações, entao isPossible = true if(position.equals(aux)) { isPossible=true; } } if(isPossible) { if(pawn!=null) { pawn.setFirstMove(false); } //Verifico se a posição escolhida resulta em um check mate if(this.boardGame.getBoardMatrix()[position.getX()][position.getY()]!=null) { if(isCheckMate(position)) { player.setWinner(true); this.gameOver = true; //É preciso criar algum metodo para finalizar o jogo, assim não precisaremos ficar checando todo momento } } //Se isPossible == true, entao a posição do tabuleiro ira referenciar a peça this.boardGame.getBoardMatrix()[position.getX()][position.getY()]=piece; //A posiçao anterior da peça ira referenciar null, indicando que não há mais uma peça ali this.boardGame.getBoardMatrix()[piece.getPosition().getX()][piece.getPosition().getY()]=null; //Logo, para finalizar a movimentação setamos a posição da peça para a posição que ela ira se mover piece.setPosition(position); //Checo, se depois da jogada, a peça movida vai pôr o rei em Check this.isYourKingInCheck = this.isKingInCheck(piece, player); } else { //Usuario clicou em um lugar que não é possivel mover } return isPossible; } /* Método para remover das movimentações possiveis as posições que possuirem peças da mesma cor que a peça que quer se mover, e quando alguma peça interromper o caminho */ public void removeMoves(ArrayList<Position> moves,Piece piece) { Position aux = new Position(piece.getPosition().getX(),piece.getPosition().getY()); Position position=null; //Testamos se a piece passada por parâmetro é uma instância da Torre ou Rainha //Essa parte do método estamos tratando as movimentações horizontais ou verticais if(piece instanceof TowerP || piece instanceof QueenP) { //Percorro a lista de possiveis movimentos com um iterador for(Iterator<Position>it=moves.iterator();it.hasNext();) { position=it.next(); //Se em um desses movimentos tiver uma peça, sabemos entao que essa peça esta bloquendo o resto dos movimento if(this.boardGame.getBoardMatrix()[position.getX()][position.getY()]!=null) { //É criado outro iterador para poder pegar as posições bloqueadas e então remove-las do arraylist Iterator<Position>itAux=it; //Se a peça estiver bloquendo o movimento vertical if(position.getY()==aux.getY()) { //Vertical -> Subindo if(position.getX()>aux.getX()) { //Removo todas as possiveis movimentações depois da peça encontrada while(position.getX()<7 && itAux.hasNext()) { position=itAux.next(); itAux.remove(); } } //Vertical-> Descendo else if(position.getX()<aux.getX()) { //Removo todas as possiveis movimentações depois da peça encontrada while(position.getX()>0 && itAux.hasNext()) { position=itAux.next(); itAux.remove(); } } } //Se a peça estiver bloquenado o movimento horizontal else if(position.getX()==aux.getX()) { //Horizontal -> Para direita if(position.getY()>aux.getY()) { //Removo todas as possiveis movimentações depois da peça encontrada while(position.getY()<7 && itAux.hasNext()) { position=itAux.next(); itAux.remove(); } } //Horizontal -> Para esquerda else if(position.getY()<aux.getY()) { //Removo todas as possiveis movimentações depois da peça encontrada while(position.getY()>0 && itAux.hasNext()) { position=itAux.next(); itAux.remove(); } } } } } } //Testamos se a piece é uma instancia de Rainha ou Bispo if(piece instanceof QueenP || piece instanceof BishopP) { //Crio um iterador para poder passar pelo arraylist de possiveis movimentos for(Iterator<Position>it = moves.iterator();it.hasNext();) { position=it.next(); //Se em uma dessas posições tiver uma peça if(this.boardGame.getBoardMatrix()[position.getX()][position.getY()]!=null) { //Crio um iterador auxiliar para poder acessar as movimentações que essa peça encontrada bloqueia Iterator<Position>itAux=it; //Vou removendo as possiveis posições da diagonal inferior direita logo após a peça que está bloqueando a movimentação if(position.getX()>aux.getX()) { if(position.getY()>aux.getY()) { while((position.getX()<7 && position.getY()<7) && itAux.hasNext()) { position=itAux.next(); itAux.remove(); } } //Vou removendo as possiveis posições da diagonal inferior esquerda logo após a peça que está bloqueando a movimentação else if(position.getY()<aux.getY()) { while((position.getX()<7 && position.getY()>0) && itAux.hasNext()) { position=itAux.next(); itAux.remove(); } } } //Vou removendo as possiveis posições da diagonal superior direita logo após a peça que está bloqueando a movimentação else if(position.getX()<aux.getX()) { if(position.getY()>aux.getY()) { while((position.getX()>0 && position.getY()<7) && itAux.hasNext()) { position=itAux.next(); itAux.remove(); } } //Vou removendo as possiveis posições da diagonal superior esquerda logo após a peça que está bloqueando a movimentação else if(position.getY()<aux.getY()) { while((position.getX()>0 && position.getY()>0) && itAux.hasNext() ) { position=itAux.next(); itAux.remove(); } } } } } } //Testo se a peça passada como parâmetro é um peão else if(piece instanceof PawnP) { //Faço um castingo da peça para poder usar a funcao .isFirstMove() da classe PawnP PawnP pawn = (PawnP)piece; //Testo se é a primeiro movimentação do peão if(pawn.isFirstMove()==true) { for(Iterator<Position>it=moves.iterator();it.hasNext();) { position=it.next(); //Se for, é analisado se há uma peça logo em frente ao peão e removo a possivel posiçao logo depois dela if(this.boardGame.getBoardMatrix()[position.getX()][position.getY()]!=null) { if((position.getX()==aux.getX()+1 && position.getY()==aux.getY() || (position.getX()==aux.getX()-1 && position.getY()==aux.getY()))){ if(it.hasNext()) { it.next(); it.remove(); } } } } } } /*Ultima parte onde tratamos de remover as possiveis movimentações onde ja se tem uma peça sendo essa da mesma cor da peça que quer se mover*/ for(Iterator<Position>it=moves.iterator();it.hasNext();) { position=it.next(); if(this.boardGame.getBoardMatrix()[position.getX()][position.getY()]!=null) { if(this.boardGame.getBoardMatrix()[position.getX()][position.getY()].isWhite()==piece.isWhite()) { it.remove(); } } } } /*Método em que é recebido um jogador, uma peça e o tabuleiro em que o jogo está acontecendo para realizar a movimentação das peças, este metodo será chamado quando o jogador clicar em cima da peça do seu próprio time e apartir dai as possiveis movimentações serão mostradas*/ public ArrayList<Position> showPossibleMoves(Player player, Piece piece){ ArrayList<Position>moves; moves = null; //verificando se o jogador é do time branco e se ele clicou em uma peça do time branco if(player.isWhitePlayer()) { if(piece.isWhite()){ moves = piece.possibleMoves(); //Método polimorfico, logo não precisa de instance of, nem casting } else { //A peça é do time preto e o jogador é do time branco } } //Verificando se o jogador é do time preto e se ele clicou em uma peça do time preto else { if(!player.isWhitePlayer()) { if(!piece.isWhite()){ moves = piece.possibleMoves(); //Método polimorfico, logo não precisa de instance of, nem casting } else { //A peça é do time branco e o jogador é do time preto } } } this.removeMoves(moves, piece); //retorna as possiveis movimentações de uma peça para a interface grafica mostrar na tela return moves; } //Implementando a sobrecarga do método showPossibleMoves() para o peão public ArrayList<Position> showPossibleMoves(Player player,PawnP pawn){ ArrayList<Position>moves; moves = null; Position pos = new Position(pawn.getPosition().getX(),pawn.getPosition().getY());//Usado apenas para diminuir tamanho das chamadas //Verificando se o jogador é do time branco e ele clicou em um peão tambem branco if(player.isWhitePlayer()) { if(pawn.isWhite()) { moves = pawn.possibleMoves();//Metódo presente em pawnP //Além da movimentação normal, o peão tambem pode ter outras movimentações específicas //1- Movimentação En Passant if(pos.getX()<=5) { //Teste se duas casas a frente do peão tem uma peça que seja a instancia de um peão tambem if(this.boardGame.getBoardMatrix()[pos.getX()+2][pos.getY()]!=null){ //Checo tambem se entre os dois não há uma peça, se houver, não tem como fazer essa jogada if(this.boardGame.getBoardMatrix()[pos.getX()+1][pos.getY()]==null) { if(this.boardGame.getBoardMatrix()[pos.getX()+2][pos.getY()].getTypePiece() == TypePiece.PAWN) { moves.add(new Position(pos.getX()+2,pos.getY())); } } } } //Se o peão estiver na borda esquerda if(pos.getY()==0) { //Se tiver uma peça na sua diagonal direita inferior if(this.boardGame.getBoardMatrix()[pos.getX()+1][1]!=null) { moves.add(new Position(pos.getX()+1,1)); } } //Se o peão estiver na borda direita else if (pos.getY()==7) { //Se tiver uma peça em sua diagonal esquerda inferior if(this.boardGame.getBoardMatrix()[pos.getX()+1][6]!=null) { moves.add(new Position(pos.getX()+1,6)); } } //Se o peão estiver pelo centro else { //Se em sua diagonal esquerda inferior tiver uma peça if(this.boardGame.getBoardMatrix()[pos.getX()+1][pos.getY()-1]!=null) { moves.add(new Position(pos.getX()+1,pos.getY()-1)); } //Se em sua diagonal direita inferior tiver uma peça if (this.boardGame.getBoardMatrix()[pos.getX()+1][pos.getY()+1]!=null) { moves.add(new Position(pos.getX()+1,pos.getY()+1)); } } } else { //Jogador do time branco e peão do time preto } } //Jogador do time preto e peça tambem do time preto else if(!player.isWhitePlayer()) { if(!pawn.isWhite()) { moves = pawn.possibleMoves(); //En Passant if(pos.getX()>=2) { if(this.boardGame.getBoardMatrix()[pos.getX()-2][pos.getY()]!=null) { if(this.boardGame.getBoardMatrix()[pos.getX()-1][pos.getY()]==null) { if(this.boardGame.getBoardMatrix()[pos.getX()-2][pos.getY()].getTypePiece()==TypePiece.PAWN) { moves.add(new Position(pos.getX()-2,pos.getY())); } } } } //Se o peão estiver na borda esquerda if(pos.getY()==0) { //Se tiver uma peça na sua diagonal direita superior if(this.boardGame.getBoardMatrix()[pos.getX()-1][1]!=null) { moves.add(new Position(pos.getX()-1,1)); } } //Se o peão estiver na borda direita else if (pos.getY()==7) { //Se tiver uma peça em sua diagonal esquerda superior if(this.boardGame.getBoardMatrix()[pos.getX()-1][6]!=null) { moves.add(new Position(pos.getX()-1,6)); } } //Se o peão estiver pelo centro else { //Se em sua diagonal esquerda superior tiver uma peça if(this.boardGame.getBoardMatrix()[pos.getX()-1][pos.getY()-1]!=null) { moves.add(new Position(pos.getX()-1,pos.getY()-1)); } //Se em sua diagonal direita superior tiver uma peça if (this.boardGame.getBoardMatrix()[pos.getX()-1][pos.getY()+1]!=null) { moves.add(new Position(pos.getX()-1,pos.getY()+1)); } } } else { //Jogador do time preto e peça do time branco } } this.removeMoves(moves, pawn); return moves; } //Método que é chamado quando um peão atravessa o tabuleiro ou pode ser chamado depois de realizado uma movimentação public void turnQueen(PawnP pawn) { //Tratanto para os peões do time branco e se ele atravessou o mapa if(pawn.isWhite() && (pawn.getPosition().getX() == 7)) { this.boardGame.getBoardMatrix()[7][pawn.getPosition().getY()] = new QueenP(true, pawn.getPosition()); } //Tratando para os peões do time preto e se ele atravessou o mapa else if(!pawn.isWhite() && (pawn.getPosition().getX() == 0)){ this.boardGame.getBoardMatrix()[0][pawn.getPosition().getY()] = new QueenP(false, pawn.getPosition()); } } //Este método recebe uma posição que é onde a peça irá e se tiver um rei nesta posição é dado check mate public boolean isCheckMate(Position position) { if(this.boardGame.getBoardMatrix()[position.getX()][position.getY()].getTypePiece() == TypePiece.KING) { return true; } else { return false; } } //Getter e Setters da classe Game public Player getPlayer1() { return player1; } public void setPlayer1(Player player1) { this.player1 = player1; } public Player getPlayer2() { return player2; } public void setPlayer2(Player player2) { this.player2 = player2; } public BoardGame getBoardGame() { return boardGame; } public void setBoardGame(BoardGame boardGame) { this.boardGame = boardGame; } public static int getGameNumber() { return gameNumber; } public static void setGameNumber(int gameNumber) { Game.gameNumber = gameNumber; } public GameLevel getLevel() { return level; } public void setLevel(GameLevel level) { this.level = level; } public Chronometer getChronometer() { return chronometer; } public void setChronometer(Chronometer chronometer) { this.chronometer = chronometer; } public Player getPlayerTurn() { return playerTurn; } public void setPlayerTurn(Player playerTurn) { this.playerTurn = playerTurn; } public boolean getKingInCheck() { return this.isYourKingInCheck; } public void setKingInCheck(boolean isKingInCheck) { this.isYourKingInCheck = isKingInCheck; } public boolean isGameOver() { return gameOver; } public void setGameOver(boolean gameOver) { this.gameOver = gameOver; } }
true
5acea26902e7281fe0ab990e4234c7518e00269e
Java
bellmit/szgq
/project4eclipse/SRRPTask/src/main/java/com/icfcc/SRRPDao/s1/jpa/repository/InvestorDao.java
UTF-8
1,464
2.1875
2
[]
no_license
package com.icfcc.SRRPDao.s1.jpa.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Component; import com.icfcc.SRRPDao.s1.jpa.entity.Investor; @Component public interface InvestorDao extends PagingAndSortingRepository<Investor, String>, JpaSpecificationExecutor<Investor> { /** * 根据机构的id查询机构的基本信息 * @param id * @param stopFlag * @param auditStatus * @return */ @Query("select e from Investor e where e.investorId=? and e.stopFlag=? and e.auditStatus=? ") Investor findInverstorById(String id, String stopFlag, String auditStatus); // 查询机构表中的信息所有机构信息EnterpriceInvestor @Query("select e from Investor e where e.stopFlag= ? and e.auditStatus=? ") List<Investor> findAllInverstor(String stopFlag, String auditStatus); @Modifying @Query("update Investor t set t.stopFlag=?2 where t.id=?1") public void updateStopFlag(String id, String stopFlag); @Modifying @Query("update Investor t set t.auditStatus=?2 where t.id=?1") public void updateAuditStatus(String id,String auditStatus); @Query("select count(e) from Investor e where e.stopFlag= '1' and e.auditStatus='2'") public Long countInvestor(); }
true
e5a1a11749d45f5c7aef4ac1c4f2256566bc8c0c
Java
xianzhixianzhixian/thread
/src/timer/schedule/Run0.java
UTF-8
1,216
3.71875
4
[]
no_license
package timer.schedule; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * schedule(TimerTask task,Date time)的用法,非守护线程形式 * @author: xianzhixianzhixian * @date: 2019-01-28 21:27 */ public class Run0 { private static Timer timer = new Timer(); //默认为非守护线程形式 static public class MyTask extends TimerTask { @Override public void run() { System.out.println("运行了!时间为:"+new Date()); } } public static void main(String[] args) { try { MyTask task = new MyTask(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = "2019-01-28 21:33:00"; Date dateRef = sdf.parse(dateString); System.out.println("字符串时间:"+dateRef.toLocaleString()+" 当前时间:"+new Date().toLocaleString()); timer.schedule(task, dateRef); //这里创建的是守护线程,所以执行到该步骤后线程并不会自己停止 } catch (Exception e) { e.printStackTrace(); } } }
true
97d426ffb99fe0a6f43409e786b69c38f24eb7bf
Java
wiltonlazary/unipop
/unipop-core/src/org/unipop/query/aggregation/AggregateVertexQuery.java
UTF-8
1,897
2.0625
2
[ "Apache-2.0" ]
permissive
//package org.unipop.query.aggregation; // //import org.apache.tinkerpop.gremlin.structure.Direction; //import org.apache.tinkerpop.gremlin.structure.Vertex; //import org.unipop.process.group.traversal.SemanticKeyTraversal; //import org.unipop.process.group.traversal.SemanticReducerTraversal; //import org.unipop.process.group.traversal.SemanticValuesTraversal; //import org.unipop.query.predicates.PredicatesHolder; //import org.unipop.query.StepDescriptor; //import org.unipop.query.controller.UniQueryController; //import org.unipop.query.VertexQuery; // //import java.util.List; // //public class AggregateVertexQuery extends AggregateQuery implements VertexQuery { // // private final List<Vertex> vertices; // private final Direction direction; // // public AggregateVertexQuery(List<Vertex> vertices, // Direction direction, // PredicatesHolder predicates, // SemanticKeyTraversal key, // SemanticValuesTraversal values, // SemanticReducerTraversal reduce, // StepDescriptor stepDescriptor) { // super(predicates, key, values, reduce, stepDescriptor); // this.vertices = vertices; // this.direction = direction; // } // // @Override // public List<Vertex> getVertices() { // return vertices; // } // // @Override // public Direction getDirection() { // return direction; // } // // public interface AggregateVertexController extends UniQueryController { // void query(AggregateVertexQuery uniQuery); // } // // @Override // public String toString() { // return "AggregateVertexQuery{" + // "vertices=" + vertices + // ", direction=" + direction + // '}'; // } //}
true
ea31a91b3b391a5d36d414a64c19eb6db6951b25
Java
UnderADome/BlogSite_Simple
/src/main/java/com/site/blog/Mapper/ArticleQueryAll.java
UTF-8
1,320
1.859375
2
[]
no_license
package com.site.blog.Mapper; import com.github.pagehelper.Page; import com.site.blog.Model.Article; import com.site.blog.Response.RArticle; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.ResultType; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; @Repository @Mapper public interface ArticleQueryAll { @Select("select article.id, article_item.item, article.title, article.article_content, article.pic from " + "article, article_item where article.item = article_item.id;") @ResultType(RArticle.class) List<RArticle> selectAllArticle(); @Select("select article.id, article_item.item, article.title, article.article_content, article.pic from " + "article, article_item where article.item = article_item.id") @ResultType(RArticle.class) Page<RArticle> selectArticleByPage(); @Select("select article.id, article_item.item, article.title, " + "article.article_content, article.pic, article.user_id, article.create_time " + "from article, article_item where article.item = article_item.id and article.id = #{id};") @ResultType(RArticle.class) RArticle selectArticleById(int id); }
true
93d4bb8a4d48ba29b6f9a90615d8c033af7857e0
Java
sunailian/BM
/Book/src/com/htdz/utms/model/Student.java
UTF-8
1,251
2.265625
2
[]
no_license
package com.htdz.utms.model; public class Student { private String studentno; private String password1; private String name; private Long age; private String gender; private String stuclass; private String department; private Long permitted; public String getPassword1() { return password1; } public void setPassword1(String password1) { this.password1 = password1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getStuclass() { return stuclass; } public void setStuclass(String stuclass) { this.stuclass = stuclass; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public Long getPermitted() { return permitted; } public void setPermitted(Long permitted) { this.permitted = permitted; } public String getStudentno() { return studentno; } public void setStudentno(String studentno) { this.studentno = studentno; } }
true
60d2ee8c5e82f80e1a218ba1dd4d32d1c5e08d69
Java
neaguMarinela/codingAdvanced
/src/main/java/java_ex/ExecuteList.java
UTF-8
644
3.140625
3
[]
no_license
package java_ex; public class ExecuteList { public static void main(String[] args) { MyList list = new MyList(); list.add("Item-1"); list.add("Item-2"); list.add("Item-3"); list.add("Item-4"); list.add("Item-5"); list.add("Item-6"); list.add("Item-7"); list.add("Item-8"); list.add("Item-9"); list.add("Item-10"); list.add("Item-11"); list.add("Item-12"); list.remove("Item-9"); for(int i= 0; i<list.size(); i++) { System.out.println(list.get(i)); } } }
true
69d125c1ae57126d80d6c092d4b81cb851b9cefa
Java
mvanderbeek123/UCLove
/app/src/main/java/com/epl/uclouvain/uclove/ChatActivity.java
UTF-8
3,247
2.4375
2
[]
no_license
package com.epl.uclouvain.uclove; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.view.View.OnClickListener; import android.widget.ListView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; /** * Created by delphine on 02/05/16. */ public class ChatActivity extends Activity { ListView listView; List<String> messages; ArrayAdapter<String> messageAdapteur; ChatDAO chatdao; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat); listView = (ListView) findViewById(R.id.listView); messages = new ArrayList<String>(); chatdao = new ChatDAO(this); chatdao.open(); ArrayList<ChatMessage> cmlist = chatdao.historique(Controler.logged_user, Controler.chat_user); chatdao.close(); for (int i=0; i<cmlist.size(); i++) { ChatMessage histo = cmlist.get(i); messages.add(histo.getLogin1() + " " + histo.getMsg_date()) ; messages.add(histo.getMsg()); messages.add(""); } messageAdapteur = new ArrayAdapter<String>(ChatActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, messages); listView.setAdapter(messageAdapteur); final EditText editMessage = (EditText) findViewById(R.id.message); Button btnEnvoie = (Button) findViewById(R.id.envoyer); btnEnvoie.setOnClickListener(new OnClickListener() { @SuppressWarnings("deprecation") public void onClick(View v) { String msg = editMessage.getText().toString(); String msgdate = new SimpleDateFormat("HH:mm").format(Calendar.getInstance().getTime()); if (msg.length() > 0) { //SmsManager.getDefault().sendTextMessage(num, null, msg, null, null); // texte devrait etre ajouter dans la base de donnee editMessage.setText(""); messages.add(Controler.logged_user + " " + msgdate); messages.add(msg); messages.add(""); ChatMessage cm = new ChatMessage(); cm.setMsg(msg); cm.setLogin1(Controler.logged_user); cm.setLogin2(Controler.chat_user); cm.setMsg_date(msgdate); chatdao.open(); chatdao.ajouter(cm); chatdao.close(); messageAdapteur = new ArrayAdapter<String>(ChatActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, messages); listView.setAdapter(messageAdapteur); } else { //On affiche un petit message d'erreur dans un Toast Toast.makeText(ChatActivity.this, "Enter le message", Toast.LENGTH_SHORT).show(); } } }); } }
true
edc735a39ee38aeb003672d1c2b601bdf6a106f3
Java
moutainhigh/sanlly-platform
/sanlly-production/src/main/java/com/sanlly/production/service/EdiService.java
UTF-8
8,033
1.78125
2
[]
no_license
package com.sanlly.production.service; import java.util.List; import com.sanlly.common.models.output.SelectOutput; import com.sanlly.common.models.output.pagination.PagedList; import com.sanlly.production.models.input.edi.AddAutoPoolInput; import com.sanlly.production.models.input.edi.AddAutoSendInput; import com.sanlly.production.models.input.edi.AddEdiPoolInput; import com.sanlly.production.models.input.edi.AddEdiSearchInput; import com.sanlly.production.models.input.edi.AutoIntoPoolSearchInput; import com.sanlly.production.models.input.edi.AutoSendSearchInput; import com.sanlly.production.models.input.edi.CompanyCodeSearchInput; import com.sanlly.production.models.input.edi.CompanyContainerUserSearchInput; import com.sanlly.production.models.input.edi.CompanyEdiSearchInput; import com.sanlly.production.models.input.edi.EdiFileSearchInput; import com.sanlly.production.models.input.edi.EdiPoolSearchInput; import com.sanlly.production.models.input.edi.EdiTypeContainerUserInput; import com.sanlly.production.models.input.edi.EditAutoPoolInput; import com.sanlly.production.models.input.edi.EditAutoSendInput; import com.sanlly.production.models.input.edi.EditEdiConfigInput; import com.sanlly.production.models.input.edi.EditEdiPoolInput; import com.sanlly.production.models.input.edi.GenerateEvaluationNoInput; import com.sanlly.production.models.input.edi.ImportEdiPoolInput; import com.sanlly.production.models.input.edi.SendEdiInput; import com.sanlly.production.models.output.edi.AddEdiResponseOutput; import com.sanlly.production.models.output.edi.AutoIntoPoolDetailOutput; import com.sanlly.production.models.output.edi.AutoIntoPoolOutput; import com.sanlly.production.models.output.edi.AutoSendDetailOutput; import com.sanlly.production.models.output.edi.AutoSendOutput; import com.sanlly.production.models.output.edi.CompanyCodeOutput; import com.sanlly.production.models.output.edi.CompanyContainerUserOutput; import com.sanlly.production.models.output.edi.CompanyEdiConfigOutput; import com.sanlly.production.models.output.edi.EdiEditInfoOutput; import com.sanlly.production.models.output.edi.EdiFileDetailOutput; import com.sanlly.production.models.output.edi.EdiPoolOutput; import com.sanlly.production.models.output.edi.EditCompanyEdiOutput; import com.sanlly.production.models.output.edi.ExportEdiOutput; import com.sanlly.production.models.output.pti.AddEdiPoolOutput; /** * edi接口 * @author RexSheng * 2019年10月14日 下午1:33:23 */ public interface EdiService { /** * edi池列表查询 * @param input * @return */ PagedList<EdiPoolOutput> getEdiPoolList(EdiPoolSearchInput input); /** * edi池新增数据列表查询 * @param input * @return */ List<AddEdiResponseOutput> addEdiPoolSearchList(AddEdiSearchInput input) throws Exception; /** * edi池导入数据 * @param input * @return */ List<AddEdiResponseOutput> importEdiPool(ImportEdiPoolInput input); /** * edi池新增 * @param input */ AddEdiPoolOutput addPool(AddEdiPoolInput input); /** * 校验估价单号格式 * @param format * @return */ Boolean validateEvaluationFormat(String format); /** * 重新生成估价单号 * @param input */ void reGenerateEvaluationNo(GenerateEvaluationNoInput input); /** * edi池撤销数据 * @param input */ void deletePool(GenerateEvaluationNoInput input); /** * edi池导出数据 * @param input * @return * @throws Exception */ ExportEdiOutput exportPool(GenerateEvaluationNoInput input) throws Exception; /** * edi池发送 * @param input * @return * @throws Exception */ AddEdiPoolOutput sendPool(SendEdiInput input) throws Exception; /** * 获取单条edi池数据 * @param input */ EdiEditInfoOutput getPoolInfo(Integer poolId); /** * 修改edi池数据 * @param input */ void editPool(EditEdiPoolInput input); /** * 客户edi类型配置查询 * @param input * @return */ PagedList<CompanyEdiConfigOutput> getCompanyEdiList(CompanyEdiSearchInput input); /** * 获取edi配置信息 * @param configId * @return */ EditCompanyEdiOutput getCompanyEdiInfo(Integer configId); /** * 修改edi配置信息 * @param input */ void updateCompanyEdiInfo(EditEdiConfigInput input); /** * 新增edi配置信息 * @param input */ void addCompanyEdiInfo(EditEdiConfigInput input); /** * 删除edi配置信息 * @param ids */ void deleteCompanyEdiInfo(Integer[] ids); /** * 获取所有EDI文件格式名 * @return */ List<SelectOutput> getAllFileFormat(); /** * 获取所有EXCEL模板 * @return */ List<String> getAllExcelTemplates(); /** * 根据公司,用箱人获取对应的edi类型 * @param input * @return */ List<String> getAllEdiConfigByContainerUser(EdiTypeContainerUserInput input); /** * edi自动报价配置,查询列表 * @param input * @return */ PagedList<AutoSendOutput> getAutoSendList(AutoSendSearchInput input); /** * 新增自动报价配置 * @param input */ void addAutoSendConfig(AddAutoSendInput input); /** * 获取自动报价配置 * @param id * @return */ AutoSendDetailOutput getAutoSendConfig(Integer id); /** * 修改自动报价配置 * @param input */ void updateAutoSendConfig(EditAutoSendInput input); /** * 删除自动报价配置 * @param id */ void deleteAutoSendConfig(Integer[] ids); /** * 自动进入edi池配置查询列表 * @param input * @return */ PagedList<AutoIntoPoolOutput> getAutoPoolList(AutoIntoPoolSearchInput input); /** * 自动进入edi池详细信息 * @param input * @return */ AutoIntoPoolDetailOutput getAutoPoolDetail(Integer id); /** * 新增自动进入edi池配置 * @param input */ void addAutoPoolConfig(AddAutoPoolInput input); /** * 修改自动进入edi池配置 * @param input */ void updateAutoPoolConfig(EditAutoPoolInput input); /** * 删除自动进入edi池配置 * @param id */ void deleteAutoPoolConfig(Integer[] ids); /** * EDI文件格式列表 * @param input * @return */ PagedList<EdiFileDetailOutput> getFileFormatPagedList(EdiFileSearchInput input); /** * 新增EDI文件格式 * @param input * @return */ void addFileFormat(EdiFileDetailOutput input); /** * 修改EDI文件格式 * @param input * @return */ void updateFileFormat(EdiFileDetailOutput input); /** * 删除EDI文件格式 * @param input * @return */ void deleteFileFormat(Integer[] ids); /** * 获取EDI文件格式 * @param input * @return */ EdiFileDetailOutput getFileFormat(Integer id); /** * 公司-用箱人 接收地址配置搜索条件 * @param input * @return */ PagedList<CompanyContainerUserOutput> getCompanyContainerUserPagedList(CompanyContainerUserSearchInput input); /** * 获取公司-用箱人 接收地址配置 * @param id * @return */ CompanyContainerUserOutput getCompanyContainerUser(Integer id); /** * 新增公司-用箱人 接收地址配置 * @param input */ void addCompanyContainerUser(CompanyContainerUserOutput input); /** * 修改公司-用箱人 接收地址配置 * @param input */ void updateCompanyContainerUser(CompanyContainerUserOutput input); /** * 删除公司-用箱人 接收地址配置 * @param ids */ void deleteCompanyContainerUser(Integer[] ids); /** * 公司与代码对应搜索列表 * @param input * @return */ PagedList<CompanyCodeOutput> getCompanyCodePagedList(CompanyCodeSearchInput input); /** * 获取公司与代码对应 * @param id * @return */ CompanyCodeOutput getCompanyCode(Integer id); /** * 新增公司与代码对应 * @param input */ void addCompanyCode(CompanyCodeOutput input); /** * 修改公司与代码对应 * @param input */ void updateCompanyCode(CompanyCodeOutput input); /** * 删除公司与代码对应 * @param ids */ void deleteCompanyCode(Integer[] ids); }
true
e700076509128c99314e9ce2ac68522448958744
Java
ZPJeck/ideaTest
/jeesite-master/src/main/java/com/thinkgem/jeesite/common/enums/RoleEnum.java
UTF-8
854
2.296875
2
[ "Apache-2.0" ]
permissive
package com.thinkgem.jeesite.common.enums; /** * @Author: ZPJeck * @Description: * @Date: 2018/9/29 19:56 */ public enum RoleEnum { HUI_YUAN("会员","huiyuan","0"), GUAN_LI_YUAN("管理员","dept","1"), ; private String name; private String enName; private String type; RoleEnum(String name, String enName, String type) { this.name = name; this.enName = enName; this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEnName() { return enName; } public void setEnName(String enName) { this.enName = enName; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
true
542f5d3f25b702828f0caf1ad26613d344f077df
Java
StephenOTT/TAXII-Worker
/src/main/java/io/digitalstate/camunda/client/common/EngineName.java
UTF-8
415
1.898438
2
[ "MIT" ]
permissive
package io.digitalstate.camunda.client.common; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Optional; public interface EngineName { /** * Allows the storage of a engine name for use with factory and generic web clients that may change their destination based on the engine that the request is for. * @return */ @JsonIgnore Optional<String> getEngineName(); }
true
786e9a2c9e828c7854d6cb1a353fd9be292f7f1e
Java
dubing/Dropwizard
/src/main/java/com/mt/Core/StoreEx.java
UTF-8
501
2.390625
2
[]
no_license
package com.mt.Core; /** * Created by bing.du on 3/5/14. */ public class StoreEx extends Store { private String productName; public StoreEx(Store store) { setid(store.getId()); setName(store.getName()); setaddress(store.getAddress()); //setProductId(store.getProductId()); } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } }
true
1ca0c0df2b124c4e94ec37ac9bfa65807a8ed4ad
Java
segmentio/analytics-android
/analytics-wear/src/main/java/com/segment/analytics/WearDispatcher.java
UTF-8
4,665
1.984375
2
[ "MIT" ]
permissive
/** * The MIT License (MIT) * * Copyright (c) 2014 Segment.io, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.segment.analytics; import static android.os.Process.THREAD_PRIORITY_BACKGROUND; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.Node; import com.google.android.gms.wearable.NodeApi; import com.google.android.gms.wearable.Wearable; import com.segment.analytics.internal.Utils; import java.util.Collection; import java.util.HashSet; class WearDispatcher { private static final String DISPATCHER_THREAD_NAME = Utils.THREAD_PREFIX + "Wear-Dispatcher"; final Handler handler; final HandlerThread dispatcherThread; final GoogleApiClient googleApiClient; final Cartographer cartographer; WearDispatcher(Context context) { googleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API).build(); cartographer = Cartographer.INSTANCE; dispatcherThread = new HandlerThread(DISPATCHER_THREAD_NAME, THREAD_PRIORITY_BACKGROUND); dispatcherThread.start(); handler = new DispatcherHandler(dispatcherThread.getLooper(), this); } void dispatchPayload(WearPayload payload) { handler.sendMessage(handler.obtainMessage(DispatcherHandler.REQUEST_DISPATCH, payload)); } void performDispatch(WearPayload payload) { googleApiClient.blockingConnect(); for (String node : getNodes(googleApiClient)) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage( googleApiClient, node, WearAnalytics.ANALYTICS_PATH, cartographer.toJson(payload).getBytes()) .await(); if (!result.getStatus().isSuccess()) { // todo: log error } } } private Collection<String> getNodes(GoogleApiClient googleApiClient) { HashSet<String> results = new HashSet<>(); NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(); for (Node node : nodes.getNodes()) { results.add(node.getId()); } return results; } private static class DispatcherHandler extends Handler { static final int REQUEST_DISPATCH = 0; private final WearDispatcher wearDispatcher; public DispatcherHandler(Looper looper, WearDispatcher wearDispatcher) { super(looper); this.wearDispatcher = wearDispatcher; } @Override public void handleMessage(final Message msg) { switch (msg.what) { case REQUEST_DISPATCH: WearPayload payload = (WearPayload) msg.obj; wearDispatcher.performDispatch(payload); break; default: Analytics.HANDLER.post( new Runnable() { @Override public void run() { throw new AssertionError( "Unhandled dispatcher message." + msg.what); } }); } } } }
true
1d56634661a498f018e95a1de26c92528a5df191
Java
Yuna-Kim93/ACLAP-Back
/ACAPPROJECT/aclap_project/src/main/java/bit/com/a/service/noClassDateService.java
UTF-8
1,190
2.40625
2
[]
no_license
package bit.com.a.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import bit.com.a.dao.noClassDateDao; import bit.com.a.dto.noClassDateDto; import bit.com.a.dto.onedayClassDto; @Service @Transactional public class noClassDateService { @Autowired noClassDateDao noClassDateDao; // 추가 public void addNoClassDate(noClassDateDto dto) { noClassDateDao.addNoClassDate(dto); System.out.println("== (Service) addNoClassDate Success! =="); }; // 삭제 public void deleteNoClassDate(onedayClassDto dto) { int n = noClassDateDao.deleteNoClassDate(dto); if(n>0) System.out.println("=== (Service) deleteNoClass Success ==="); }; // 출력 public List<String> getNoClassDate(onedayClassDto dto){ List <String> list = noClassDateDao.getNoClassDate(dto); List <String> output = new ArrayList<>(); if(list!=null) { for (String str : list) output.add(str.substring(0, 10)); System.out.println("=== (Service) getNoClassDate Success ==="); } return output; }; }
true
119c0e611ad6808e429aa85c00669c1b2c94db4d
Java
zkoalas/dynamic-datasource-spring-boot-starter
/src/main/java/com/baomidou/dynamic/datasource/spring/boot/autoconfigure/dbcp2/Dbcp2Config.java
UTF-8
11,933
1.671875
2
[ "Apache-2.0" ]
permissive
/* * Copyright © 2018 organization baomidou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baomidou.dynamic.datasource.spring.boot.autoconfigure.dbcp2; import lombok.Data; import org.apache.commons.dbcp2.BasicDataSource; import java.util.List; import java.util.Set; @Data public class Dbcp2Config { private Boolean defaultAutoCommit; private Boolean defaultReadOnly; private Integer defaultTransactionIsolation; private Integer defaultQueryTimeoutSeconds; private String defaultCatalog; private String defaultSchema; private Boolean cacheState; private Boolean lifo; private Integer maxTotal; private Integer maxIdle; private Integer minIdle; private Integer initialSize; private Long maxWaitMillis; private Boolean poolPreparedStatements; private Boolean clearStatementPoolOnReturn; private Integer maxOpenPreparedStatements; private Boolean testOnCreate; private Boolean testOnBorrow; private Boolean testOnReturn; private Long timeBetweenEvictionRunsMillis; private Integer numTestsPerEvictionRun; private Long minEvictableIdleTimeMillis; private Long softMinEvictableIdleTimeMillis; private String evictionPolicyClassName; private Boolean testWhileIdle; private String validationQuery; private Integer validationQueryTimeoutSeconds; private String connectionFactoryClassName; private List<String> connectionInitSqls; private Boolean accessToUnderlyingConnectionAllowed; private Long maxConnLifetimeMillis; private Boolean logExpiredConnections; private String jmxName; private Boolean autoCommitOnReturn; private Boolean rollbackOnReturn; private Set<String> disconnectionSqlCodes; private Boolean fastFailValidation; private String connectionProperties; public BasicDataSource toDbcpDataSource(Dbcp2Config g) { BasicDataSource dataSource = new BasicDataSource(); Boolean tempDefaultAutoCommit = defaultAutoCommit == null ? g.getDefaultAutoCommit() : defaultAutoCommit; if (tempDefaultAutoCommit != null) { dataSource.setDefaultAutoCommit(tempDefaultAutoCommit); } Boolean tempDefaultReadOnly = defaultReadOnly == null ? g.getDefaultReadOnly() : defaultReadOnly; if (tempDefaultReadOnly != null) { dataSource.setDefaultReadOnly(tempDefaultReadOnly); } Integer tempDefaultTransactionIsolation = defaultTransactionIsolation == null ? g.getDefaultTransactionIsolation() : defaultTransactionIsolation; if (tempDefaultTransactionIsolation != null) { dataSource.setDefaultTransactionIsolation(tempDefaultTransactionIsolation); } Integer tempDefaultQueryTimeoutSeconds = defaultQueryTimeoutSeconds == null ? g.getDefaultQueryTimeoutSeconds() : defaultQueryTimeoutSeconds; if (tempDefaultQueryTimeoutSeconds != null) { dataSource.setDefaultQueryTimeout(tempDefaultQueryTimeoutSeconds); } String tempDefaultCatalog = defaultCatalog == null ? g.getDefaultCatalog() : defaultCatalog; if (tempDefaultCatalog != null) { dataSource.setDefaultCatalog(tempDefaultCatalog); } String tempDefaultSchema = defaultSchema == null ? g.getDefaultSchema() : defaultSchema; if (tempDefaultSchema != null) { dataSource.setDefaultSchema(tempDefaultSchema); } Boolean tempCacheState = cacheState == null ? g.getCacheState() : cacheState; if (tempCacheState != null) { dataSource.setCacheState(tempCacheState); } Boolean tempLifo = lifo == null ? g.getLifo() : lifo; if (tempLifo != null) { dataSource.setLifo(tempLifo); } Integer tempMaxTotal = maxTotal == null ? g.getMaxTotal() : maxTotal; if (tempMaxTotal != null) { dataSource.setMaxTotal(tempMaxTotal); } Integer tempMaxIdle = maxIdle == null ? g.getMaxIdle() : maxIdle; if (tempMaxIdle != null) { dataSource.setMaxIdle(tempMaxIdle); } Integer tempMinIdle = minIdle == null ? g.getMinIdle() : minIdle; if (tempMinIdle != null) { dataSource.setMinIdle(tempMinIdle); } Integer tempInitialSize = initialSize == null ? g.getInitialSize() : initialSize; if (tempInitialSize != null) { dataSource.setInitialSize(tempInitialSize); } Long tempMaxWaitMillis = maxWaitMillis == null ? g.getMaxWaitMillis() : maxWaitMillis; if (tempMaxWaitMillis != null) { dataSource.setMaxWaitMillis(tempMaxWaitMillis); } Boolean tempPoolPreparedStatements = poolPreparedStatements == null ? g.getPoolPreparedStatements() : poolPreparedStatements; if (tempPoolPreparedStatements != null) { dataSource.setPoolPreparedStatements(tempPoolPreparedStatements); } Boolean tempClearStatementPoolOnReturn = clearStatementPoolOnReturn == null ? g.getClearStatementPoolOnReturn() : clearStatementPoolOnReturn; if (tempClearStatementPoolOnReturn != null) { dataSource.setClearStatementPoolOnReturn(tempClearStatementPoolOnReturn); } Integer tempMaxOpenPreparedStatements = maxOpenPreparedStatements == null ? g.getMaxOpenPreparedStatements() : maxOpenPreparedStatements; if (tempMaxOpenPreparedStatements != null) { dataSource.setMaxOpenPreparedStatements(tempMaxOpenPreparedStatements); } Boolean tempTestOnCreate = testOnCreate == null ? g.getTestOnCreate() : testOnCreate; if (tempTestOnCreate != null) { dataSource.setTestOnCreate(tempTestOnCreate); } Boolean tempTestOnBorrow = testOnBorrow == null ? g.getTestOnBorrow() : testOnBorrow; if (tempTestOnBorrow != null) { dataSource.setTestOnBorrow(tempTestOnBorrow); } Boolean tempTestOnReturn = testOnReturn == null ? g.getTestOnReturn() : testOnReturn; if (tempTestOnReturn != null) { dataSource.setTestOnReturn(tempTestOnReturn); } Long tempTimeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis == null ? g.getTimeBetweenEvictionRunsMillis() : timeBetweenEvictionRunsMillis; if (tempTimeBetweenEvictionRunsMillis != null) { dataSource.setTimeBetweenEvictionRunsMillis(tempTimeBetweenEvictionRunsMillis); } Integer tempNumTestsPerEvictionRun = numTestsPerEvictionRun == null ? g.getNumTestsPerEvictionRun() : numTestsPerEvictionRun; if (tempNumTestsPerEvictionRun != null) { dataSource.setNumTestsPerEvictionRun(tempNumTestsPerEvictionRun); } Long tempMinEvictableIdleTimeMillis = minEvictableIdleTimeMillis == null ? g.getMinEvictableIdleTimeMillis() : minEvictableIdleTimeMillis; if (tempMinEvictableIdleTimeMillis != null) { dataSource.setMinEvictableIdleTimeMillis(tempMinEvictableIdleTimeMillis); } Long tempSoftMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis == null ? g.getSoftMinEvictableIdleTimeMillis() : softMinEvictableIdleTimeMillis; if (tempSoftMinEvictableIdleTimeMillis != null) { dataSource.setSoftMinEvictableIdleTimeMillis(tempSoftMinEvictableIdleTimeMillis); } String tempEvictionPolicyClassName = evictionPolicyClassName == null ? g.getEvictionPolicyClassName() : evictionPolicyClassName; if (tempEvictionPolicyClassName != null) { dataSource.setEvictionPolicyClassName(tempEvictionPolicyClassName); } Boolean tempTestWhileIdle = testWhileIdle == null ? g.getTestWhileIdle() : testWhileIdle; if (tempTestWhileIdle != null) { dataSource.setTestWhileIdle(tempTestWhileIdle); } String tempValidationQuery = validationQuery == null ? g.getValidationQuery() : validationQuery; if (tempValidationQuery != null) { dataSource.setValidationQuery(tempValidationQuery); } Integer tempValidationQueryTimeoutSeconds = validationQueryTimeoutSeconds == null ? g.getValidationQueryTimeoutSeconds() : validationQueryTimeoutSeconds; if (tempValidationQueryTimeoutSeconds != null) { dataSource.setValidationQueryTimeout(tempValidationQueryTimeoutSeconds); } String tempConnectionFactoryClassName = connectionFactoryClassName == null ? g.getConnectionFactoryClassName() : connectionFactoryClassName; if (tempConnectionFactoryClassName != null) { dataSource.setConnectionFactoryClassName(tempConnectionFactoryClassName); } List<String> tempConnectionInitSqls = connectionInitSqls == null ? g.getConnectionInitSqls() : connectionInitSqls; if (tempConnectionInitSqls != null && tempConnectionInitSqls.size() > 0) { dataSource.setConnectionInitSqls(tempConnectionInitSqls); } Boolean tempAccessToUnderlyingConnectionAllowed = accessToUnderlyingConnectionAllowed == null ? g.getAccessToUnderlyingConnectionAllowed() : accessToUnderlyingConnectionAllowed; if (tempAccessToUnderlyingConnectionAllowed != null) { dataSource.setAccessToUnderlyingConnectionAllowed(tempAccessToUnderlyingConnectionAllowed); } Long tempMaxConnLifetimeMillis = maxConnLifetimeMillis == null ? g.getMaxConnLifetimeMillis() : maxConnLifetimeMillis; if (tempMaxConnLifetimeMillis != null) { dataSource.setMaxConnLifetimeMillis(tempMaxConnLifetimeMillis); } Boolean tempLogExpiredConnections = logExpiredConnections == null ? g.getLogExpiredConnections() : logExpiredConnections; if (tempLogExpiredConnections != null) { dataSource.setLogExpiredConnections(tempLogExpiredConnections); } String tempJmxName = jmxName == null ? g.getJmxName() : jmxName; if (tempJmxName != null) { dataSource.setJmxName(tempJmxName); } Boolean tempAutoCommitOnReturn = autoCommitOnReturn == null ? g.getAutoCommitOnReturn() : autoCommitOnReturn; if (tempAutoCommitOnReturn != null) { dataSource.setAutoCommitOnReturn(tempAutoCommitOnReturn); } Boolean tempRollbackOnReturn = rollbackOnReturn == null ? g.getRollbackOnReturn() : rollbackOnReturn; if (tempRollbackOnReturn != null) { dataSource.setRollbackOnReturn(tempRollbackOnReturn); } Set<String> tempDisconnectionSqlCodes = disconnectionSqlCodes == null ? g.getDisconnectionSqlCodes() : disconnectionSqlCodes; if (tempDisconnectionSqlCodes != null && tempDisconnectionSqlCodes.size() > 0) { dataSource.setDisconnectionSqlCodes(tempDisconnectionSqlCodes); } Boolean tempFastFailValidation = fastFailValidation == null ? g.getFastFailValidation() : fastFailValidation; if (tempFastFailValidation != null) { dataSource.setFastFailValidation(tempFastFailValidation); } String tempConnectionProperties = connectionProperties == null ? g.getConnectionProperties() : connectionProperties; if (tempConnectionProperties != null) { dataSource.setConnectionProperties(tempConnectionProperties); } return dataSource; } }
true
e26564813af278d4e5f3c9d3c2868bedf2b828bd
Java
akshayrajan/Medically
/medically2/app/src/main/java/com/example/akshayrajan/medically/MainActivity.java
UTF-8
2,027
1.734375
2
[]
no_license
package com.example.akshayrajan.medically; import android.app.ActionBar; import android.app.Activity; import android.app.FragmentTransaction; import android.content.Intent; import android.support.design.widget.TabLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class MainActivity extends AppCompatActivity { private Button mbutton = null; private TextView mTextView = null; private EditText ed1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); ed1 = (EditText) findViewById(R.id.editText1); mbutton = (Button) findViewById(R.id.loginbutton); mbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getApplicationContext(), PrescriptionRetrieval.class); i.putExtra("email",ed1.getText().toString()); startActivity(i); } }); mTextView = (TextView) findViewById(R.id.noaccount); mTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getApplicationContext(), signup.class); startActivity(i); } }); } }
true
3bb8d2fa7aa0eecdc03c5f4b45ea88a503606f9f
Java
caleb-chou/codingbat
/java/array-1/front11.java
UTF-8
235
2.3125
2
[]
no_license
public int[] front11(int[] a, int[] b) { int[] fin = new int[((a.length > 0) ? 1 : 0) + ((b.length > 0) ? 1 : 0)]; if(fin.length > 0) fin[0] = (a.length > 0) ? a[0] : b[0]; if(fin.length > 1) fin[1] = b[0]; return fin; }
true
b3906462f233a4d94e68a0c7cae8f5d87fbaf77b
Java
tokyobs/cooper
/cooper-server/cooper-server-main/src/main/java/jdepend/server/service/RemoteServiceFactory.java
UTF-8
1,273
1.945313
2
[ "Apache-2.0" ]
permissive
package jdepend.server.service; import java.rmi.RemoteException; import jdepend.server.service.analyzer.AnalyzerService; import jdepend.server.service.analyzer.AnalyzerServiceImpl; import jdepend.server.service.impl.JDependRemoteServiceImpl; import jdepend.server.service.impl.JDependSessionServiceImpl; import jdepend.server.service.score.ScoreRemoteService; import jdepend.server.service.score.ScoreRemoteServiceImpl; import jdepend.server.service.session.JDependSessionService; import jdepend.server.service.user.UserRemoteServiceImpl; public class RemoteServiceFactory { public static AnalyzerService createAnalyzerService() throws RemoteException { return new AnalyzerServiceImpl(); } public static JDependRemoteServiceImpl createJDependRemoteService() throws RemoteException { return new JDependRemoteServiceImpl(); } public static JDependSessionService createJDependSessionService() throws RemoteException { return new JDependSessionServiceImpl(); } public static ScoreRemoteService createScoreRemoteService() throws RemoteException { return new ScoreRemoteServiceImpl(); } public static UserRemoteServiceImpl createUserRemoteService() throws RemoteException { return new UserRemoteServiceImpl(); } }
true
6a58085dba8504995156661278cb5c0cd8b63de8
Java
andrewthompson120/ComS_227
/Homework/Miniassignment1/src/mini1/TallyNumber.java
UTF-8
5,260
3.671875
4
[]
no_license
package mini1; import java.util.Scanner; public class TallyNumber { private int userValue = 0; // Gets the user value in the constructor private String userString = ""; // Gets the user string from the constructor private int currentIntTally = 0; // Running int tally private String currentStrTally = ""; // Running String tally private int tempInt = 0; private String tempStr = ""; /** * Constructs a tally number with the given integer value. * @param givenValue */ public TallyNumber(int givenValue) { if (givenValue < 0) { userValue = -1; } else { userValue = givenValue; } currentIntTally = userValue; currentStrTally = normalizeString(userValue); if (userValue == -1) { currentStrTally = ""; } } /** * Constructs a TallyNumber with the given string representation. * @param givenString */ public TallyNumber(String givenString) { String inputString = givenString; if (inputString.length() == 0 || inputString.charAt(0) == ' ') { currentStrTally = ""; currentIntTally = 0; } else if(onlyNumbers(inputString) == 0) { currentIntTally = -1; currentStrTally = ""; } else { userString = givenString; currentIntTally = normalizeInt(userString); currentStrTally = inputString; } } /** * Adds the value of the given TallyNumber to this one. * After the operation, this TallyNumber's value will be the sum of this * and the given number, and its representation will the fully normalized form. * The given TallyNumber is not modified. * @param other (int) */ public void add(TallyNumber other) { } /** * Add the given TallyNumber to this one by concatenating the corresponding * tally groups. After the operation, this TallyNumber's value will be the * sum of this and the given number, and its representation will consist of * each of this number's tally groups concatenated with the corresponding * tally group from the given number's representation. The given * TallyNumber is not modified. * @param other */ public void combine(TallyNumber other) { } /** * Converts this TallyNumber's representation to its normalized * form without changing the value. */ public void normalize() { currentIntTally = normalizeInt(currentStrTally); } /** * Returns the integer value of this tally number. */ public int getIntValue() { return currentIntTally; } /** * Returns the string representation of this tally number. */ public String getStringValue() { return currentStrTally; } /** * Method that returns the normalized int from the string * @param input * @return total (aka normalized int) */ private int normalizeInt(String input) { String inputString = input; String tempString = ""; int returnInt = 0; int numberDigits = 1; int tens = 0; int fives = 0; int ones = 0; char one = '|'; char five = '*'; Scanner readString = new Scanner(inputString); while (readString.hasNext()) { numberDigits++; } for (int j = numberDigits; j > 0; j--) { tempString = readString.next(); for (int x = 0; x < tempString.length(); x++) { if(tempString.charAt(x) == one) { ones++; } else if (tempString.charAt(x) == five) { fives++; } } returnInt = returnInt + (fives * 5 + ones) * tenPower(tens); tens++; fives = 0; ones = 0; } readString.close(); return returnInt; } /** * Method that normalizes string. It is separate since it is called many times; * @param input * @return tallyString (aka normallized string) */ private String normalizeString(int input) { String returnString = ""; String toString = Integer.toString(input); int methodInput = input; int numberDigits = toString.length(); int fives = 0; int ones = 0; int digit = numberDigits-1; System.out.println(digit); /* char zero = '0'; char one = '|'; char five = '*'; char space = ' '; */ for (int i = 0; i < numberDigits; i++) { ones = (methodInput / tenPower(digit)) % 5; methodInput = methodInput - (tenPower(digit) * ones); fives = (methodInput / tenPower(digit)) / 5; if(ones > 0) { for(int j = 0; j < ones; j++) { returnString = returnString + "|"; } } if(fives > 0) { for(int k = 0; k < fives; k++) { returnString = returnString + "*"; } } if (fives == 0 && ones == 0) { returnString = returnString + "0"; } if (!(i + 1 == numberDigits)) { returnString = returnString + " "; } digit--; } return returnString; } private int tenPower(int power) { int exponent = power; int answer = 1; for (int b = 0; b < exponent; b++) { answer = answer * 10; } return answer; } private int onlyNumbers(String input) { String stringIn = input; int stringLength = stringIn.length(); int continueSearch = 1; char zero = '0'; char one = '|'; char five = '*'; char space = ' '; for (int i = 0; i < stringLength; i++) { if (!( stringIn.charAt(i) == zero || stringIn.charAt(i) == one || stringIn.charAt(i) == five || stringIn.charAt(i) == space )) { continueSearch = 0; break; } } return continueSearch; } }
true
aba885ed40e5d408205f1a926fc961d6c54d7b9f
Java
VitaliyFilatov/component_manager_client
/app/src/main/java/com/example/vitaliy/myapplication/Entity/ComplexComponent.java
UTF-8
391
2.40625
2
[]
no_license
package com.example.vitaliy.myapplication.Entity; public class ComplexComponent { public int id; public int component_id; public String name; public String code; public ComplexComponent(int id, int component_id, String name, String code) { this.id = id; this.component_id = component_id; this.name = name; this.code = code; } }
true