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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4ddd3be8c41830e59259f2f865450fc6b58da5eb | Java | mayee007/Client | /src/main/java/com/mine/SpringDataTest/Model/Technology.java | UTF-8 | 968 | 2.21875 | 2 | [] | no_license | package com.mine.SpringDataTest.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
//@RedisHash("Technology")
public class Technology implements java.io.Serializable {
int technologyId;
String technologyType;
String category;
public Technology() {
}
public Technology(int technologyId, String technologyType, String category) {
super();
this.technologyId = technologyId;
this.technologyType = technologyType;
this.category = category;
}
public int getTechnologyId() {
return technologyId;
}
public void setTechnologyId(int technologyId) {
this.technologyId = technologyId;
}
public String getTechnologyType() {
return technologyType;
}
public void setTechnologyType(String technologyType) {
this.technologyType = technologyType;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
| true |
a2d2a38e9933aee197276f50bb3d4126187a08bc | Java | shen1123/wuxing | /tu/src/main/java/com/carl/tu/api/ConsumerApi.java | UTF-8 | 2,237 | 1.835938 | 2 | [] | no_license | package com.carl.tu.api;
import com.carl.tu.conf.ESHighLevelRESTClientTool;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Arrays;
/**
* @author WIN10
* @date 2021-07-14 16:14
*/
@Component
@RabbitListener(queues = "rabbit")
@Controller
public class ConsumerApi {
@RabbitHandler
@RequestMapping("getEs")
@ResponseBody
public String pushListener(String apiSup) {
/*JSONObject json = JSON.parseObject(apiSup);
String id = json.get("id").toString();*/
GetResponse resp = ESHighLevelRESTClientTool.selectById("user", "1");
assert resp != null;
if (!resp.isExists()) {
SearchSourceBuilder builder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("account","carl");
matchQueryBuilder.fuzziness();
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//boolQuery.must(QueryBuilders.matchAllQuery());
boolQuery.filter(QueryBuilders.matchQuery("account","car11l"));
builder.query(boolQuery);
SearchRequest searchRequest = ESHighLevelRESTClientTool.gentSearchRequest("user", builder);
SearchResponse resp1 = ESHighLevelRESTClientTool.searchSyn(searchRequest);
return Arrays.toString(resp1.getHits().getHits());
}
String account = resp.getSource().get("account").toString();
System.out.println(account);
return account;
}
}
| true |
c92e704b103975e6a76f38f063c739d20722a0b7 | Java | alexandrubalea/studyit-backend | /src/main/java/com/ubbdevs/studyit/service/UserServiceImpl.java | UTF-8 | 6,536 | 2.140625 | 2 | [] | no_license | package com.ubbdevs.studyit.service;
import com.ubbdevs.studyit.dto.*;
import com.ubbdevs.studyit.exception.custom.DuplicateResourceException;
import com.ubbdevs.studyit.exception.custom.ResourceNotFoundException;
import com.ubbdevs.studyit.mapper.AuthenticationMapper;
import com.ubbdevs.studyit.mapper.GroupMapper;
import com.ubbdevs.studyit.mapper.ProfessorMapper;
import com.ubbdevs.studyit.mapper.StudentMapper;
import com.ubbdevs.studyit.model.Group;
import com.ubbdevs.studyit.model.entity.Professor;
import com.ubbdevs.studyit.model.entity.Student;
import com.ubbdevs.studyit.model.entity.User;
import com.ubbdevs.studyit.model.enums.Role;
import com.ubbdevs.studyit.repository.UserRepository;
import com.ubbdevs.studyit.service.oauth.AuthorizationService;
import com.ubbdevs.studyit.service.oauth.OauthAdaptorService;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
private final ClientDetailsAdaptorService clientDetailsAdaptorService;
private final AuthorizationService authorizationService;
private final OauthAdaptorService oauthAdaptorService;
private final EnrollmentService enrollmentService;
private final UserRepository userRepository;
private final AuthenticationMapper authenticationMapper;
private final StudentMapper studentMapper;
private final ProfessorMapper professorMapper;
private final GroupMapper groupMapper;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public List<Student> getAllStudentsFromGroup(final Group group, final boolean entireGroup) {
final Predicate<Student> groupFilterCriteria = entireGroup ?
(student) -> student.getGroup().withSemigroupBelongsToGroup(group) :
(student) -> student.getGroup().equals(group);
return userRepository.findAllByRole(Role.STUDENT)
.stream()
.filter(groupFilterCriteria)
.collect(Collectors.toList());
}
public AuthenticationDto createStudent(final String clientId, final StudentCreationDto studentCreationDto) {
clientDetailsAdaptorService.validateClientId(clientId);
final Student student = studentMapper.dtoToModel(studentCreationDto);
final Student createdStudent = checkIfEmailIsAvailableAndCreateStudent(student);
enrollmentService.enrollStudentAtMandatorySubjects(createdStudent);
final OAuth2AccessToken accessToken = oauthAdaptorService.loginUser(
clientId,
studentCreationDto.getEmail(),
studentCreationDto.getPassword()
);
return authenticationMapper.modelToDto(createdStudent.getId(), createdStudent.getRole(), accessToken);
}
public StudentDto getStudent() {
final long studentId = authorizationService.getUserId();
return studentMapper.modelToDto(getStudentById(studentId));
}
public Student getStudentById(final Long studentId) {
return (Student) findUserById(studentId);
}
public ProfessorDto getProfessor() {
final long professorId = authorizationService.getUserId();
return professorMapper.modelToDto(getProfessorById(professorId));
}
public Professor getProfessorById(final Long professorId) {
return (Professor) findUserById(professorId);
}
public StudentDto updateStudentInformation(final UpdateStudentDto updateStudentDto) {
final long studentId = authorizationService.getUserId();
final Student student = getStudentById(studentId);
student.setFirstName(updateStudentDto.getFirstName());
student.setLastName(updateStudentDto.getLastName());
if (updateStudentDto.getPassword() != null)
student.setPassword(bCryptPasswordEncoder.encode(updateStudentDto.getPassword()));
student.setGroup(groupMapper.dtoToModel(updateStudentDto.getGroup()));
return studentMapper.modelToDto(userRepository.save(student));
}
public ProfessorDto updateProfessorInformation(final ProfessorInformationDto professorInformationDto) {
final long professorId = authorizationService.getUserId();
final Professor professor = getProfessorById(professorId);
professor.setEmail(professorInformationDto.getEmail());
professor.setWebpageUrl(professorInformationDto.getWebpageUrl());
if (professorInformationDto.getPassword() != null)
professor.setPassword(bCryptPasswordEncoder.encode(professorInformationDto.getPassword()));
return professorMapper.modelToDto(userRepository.save(professor));
}
public void deleteUserAccount() {
final long userId = authorizationService.getUserId();
userRepository.deleteById(userId);
}
@Override
public List<EnrollmentDto> enrollStudentAtSubject(EnrollStudentDto enrollStudentDto) {
final Long studentId = authorizationService.getUserId();
return enrollmentService.enrollStudentAtSubject(getStudentById(studentId), enrollStudentDto);
}
@Override
public List<EnrollmentDto> getAllStudentEnrollments() {
final Long studentId = authorizationService.getUserId();
return enrollmentService.getAllStudentEnrollments(getStudentById(studentId));
}
@Override
public void deleteStudentEnrollment(final Long enrollmentId) {
enrollmentService.deleteStudentEnrollment(enrollmentId);
}
private Student checkIfEmailIsAvailableAndCreateStudent(final Student student) {
checkForUserWithEmail(student.getEmail());
student.setPassword(bCryptPasswordEncoder.encode(student.getPassword()));
student.setRole(Role.STUDENT);
return userRepository.save(student);
}
private User findUserById(final long id) {
return userRepository.findById(id)
.orElseThrow(() -> {
throw new ResourceNotFoundException("User with id " + id + " was not found");
});
}
private void checkForUserWithEmail(final String email) {
userRepository.findByEmail(email)
.ifPresent(s -> {
throw new DuplicateResourceException("Email address already registered");
});
}
}
| true |
0295e632a5f2106262f8dcc8bd969d316772bb8b | Java | lindaLiuDan/school-portal | /o-owner/src/main/java/com.info/modules/move/service/impl/MoveInfoSignupServiceImpl.java | UTF-8 | 4,120 | 2.078125 | 2 | [] | no_license | package com.info.modules.move.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info.date.DateUtils;
import com.info.modules.move.entity.MoveInfoSignupEntity;
import com.info.modules.move.form.MoveInfoSignForm;
import com.info.modules.move.vo.MoveVo;
import com.info.modules.move.dao.IMoveInfoSignupDao;
import com.info.modules.move.service.IMoveInfoSignupService;
import com.info.utils.Query;
import com.info.utils.ResultMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* 社区活动报名表
*
* @author Gaosx
* @email
* @date 2019-06-06 18:05:23
*/
@Service("moveInfoSignupService")
public class MoveInfoSignupServiceImpl extends ServiceImpl<IMoveInfoSignupDao, MoveInfoSignupEntity> implements IMoveInfoSignupService {
@Autowired
private IMoveInfoSignupDao signupDao;
/**
* @Author: Gaosx
* @Description: 社区活动报名表
* @Date: 2019-06-06 18:05:23
*/
@Override
public Integer queryPage(Map<String, Object> params) {
String parames = (String) params.get("params");
String endTime = (String) params.get("endTime");
String begTime = (String) params.get("begTime");
// Page<MoveInfoSignupEntity> page = this.selectPage(
// new Query<MoveInfoSignupEntity>(params).getPage(),
// //TODO mamopi的这玩意挺好用的你呢 小子?妹子?汉子?女汉子?
// //logger.info("----------------------------------傻子注意了请看该方法的业务层实现方法-----------------------------------")
// new EntityWrapper<MoveInfoSignupEntity>().setSqlSelect("请填入需要查询的字段,如果是全表查询则可以删除掉,否则将会报错误信息!!!!!!!")
// // TODO 几乎所有的表都带IS_DEL字段所以是 这个条件直接生成了 ,如果特殊需要的话可以去掉
// .eq("is_del", 1)
// .ge(StringUtils.isNotBlank(begTime), "creator_time", begTime)
// .le(StringUtils.isNotBlank(endTime), "creator_time", endTime)
// .like(StringUtils.isNotBlank(parames), "parames", parames)
// );
return 1;
}
/**
* @Description 活动报名
* @Author LiuDan
* @Date 2019/6/10 11:53
* @Param
* @Return
* @Exception
*/
@Override
public ResultMessage saveSign(MoveInfoSignForm form) {
//根据活动id 和报名人id 查询此用户是否已报过
MoveInfoSignupEntity one = this.getOne(new QueryWrapper<MoveInfoSignupEntity>().eq("user_id", form.getUserId()).eq("move_id", form.getMoveId()));
if(one!=null){
return ResultMessage.ok("您已报过此活动不能重复报名!");
}
MoveInfoSignupEntity signupEntity = new MoveInfoSignupEntity();
BeanUtils.copyProperties(form, signupEntity);
signupEntity.setCreatorTime(DateUtils.now());
boolean save = this.save(signupEntity);
if (save) {
return ResultMessage.ok();
}
return ResultMessage.err();
}
/**
* @Description 个人中心——查询我参加的活动
* @Author LiuDan
* @Date 2019/6/17 15:12
* @Param
* @Return
* @Exception
*/
@Override
public ResultMessage getMyJoinMove(Map<String, Object> params) {
IPage page = new Query().getPage(params);
Integer total = signupDao.findMyJoinMoveTotal(params);
List<MoveVo> list = null;
if (total > 0) {
list = signupDao.findMyJoinMoveList(params);
page.setTotal(total);
page.setRecords(list);
return ResultMessage.ok(page);
}
return ResultMessage.ok(null);
}
}
| true |
9a6791a0d0bea0f79ee2b875b3fe2422dfba9e1b | Java | suethan/love | /app/src/main/java/com/wisedu/scc/love/utils/BarCodeUtil.java | UTF-8 | 6,649 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | package com.wisedu.scc.love.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.wisedu.scc.love.bean.Book;
import com.wisedu.scc.love.bean.Product;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* @describe 条形码工具类
*/
public class BarCodeUtil {
private static final String DOUBAN_BOOK_URL = "https://api.douban.com/v2/book/isbn/";
private static final String CHNPDT_URL = "http://www.liantu.com/tiaoma/query.php";
/**
* 根据条形码获取书籍信息
* @param barCode
* @return
*/
public static Book getBarCode_Book(String barCode){
try {
String url = DOUBAN_BOOK_URL.concat(barCode);
String content = HttpsUtil.doHttpsGet(url, null);
Book book = parseBookInfo(content);
return book;
} catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 解析图书JSON数据,把解析的数据封装在一个Book对象中
* @return Book
*/
private static Book parseBookInfo(String str){
Book info = new Book();
try{
//先从String得到一个JSONObject对象
JSONObject mess = new JSONObject(str);
info.setId(mess.getString("id"));
info.setTitle(mess.getString("title"));
info.setBitmap(downLoadBitmap(mess.getString("image")));
info.setAuthor(parseAuthor(mess.getJSONArray("author")));
info.setPublisher(mess.getString("publisher"));
info.setPublishDate(mess.getString("pubdate"));
info.setISBN(mess.getString("isbn13"));
info.setSummary(mess.getString("summary"));
info.setAuthorInfo(mess.getString("author_intro"));
info.setPage(mess.getString("pages"));
info.setPrice(mess.getString("price"));
info.setContent(mess.getString("catalog"));
info.setRate(mess.getJSONObject("rating").getString("average"));
info.setTag(parseTags(mess.getJSONArray("tags")));
}catch (Exception e) {
e.printStackTrace();
return null;
}
return info;
}
/**
* 根据条形码获取书籍信息(该方法暂不可用)
* @param barCode
* @return
*/
public static Product getBarCode_Product(String barCode){
try {
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("ean", barCode);
String content = HttpsUtil.doHttpsPost(CHNPDT_URL, httpParams);
Product product = parseProductInfo(content);
return product;
} catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 解析商品
* @return Book
*/
private static Product parseProductInfo(String str){
Product info = new Product();
try{
//先从String得到一个JSONObject对象
JSONObject mess = new JSONObject(str);
info.setName(mess.getInt("price")+"");
info.setFactory(mess.getString("fac_name"));
info.setImage(downLoadBitmap(mess.getString("titleSrc")));
info.setDescription(parseAuthor(mess.getJSONArray("guobie")));
} catch (Exception e){
e.printStackTrace();
}
return info;
}
/**
* 请求某个url上的图片资源
* @return Bitmap
*/
private static Bitmap downLoadBitmap(String bmurl) {
Bitmap bm=null;
InputStream is =null;
BufferedInputStream bis=null;
try{
URL url=new URL(bmurl);
URLConnection connection=url.openConnection();
bis=new BufferedInputStream(connection.getInputStream());
//将请求返回的字节流编码成Bitmap
bm= BitmapFactory.decodeStream(bis);
}catch (Exception e){
e.printStackTrace();
}
//关闭IO流
finally {
try {
if(bis!=null)
bis.close();
if (is!=null)
is.close();
}catch (Exception e){
e.printStackTrace();
}
}
return bm;
}
/**
* 针对豆瓣图书的特殊信息,
* 抽出一个parseAuthor方法解析作者信息
* @return String
*/
private static String parseAuthor (JSONArray arr) {
StringBuffer str =new StringBuffer();
for(int i=0;i<arr.length();i++) {
try{
str=str.append(arr.getString(i)).append(" ");
}catch (Exception e){
e.printStackTrace();
}
}
return str.toString();
}
/**
* 针对豆瓣图书的特殊信息,抽出一个parseTags方法解析图书标签信息
* @return String
*/
private static String parseTags (JSONArray obj) {
StringBuffer str =new StringBuffer();
for(int i=0;i<obj.length();i++) {
try{
str=str.append(obj.getJSONObject(i).getString("name")).append(" ");
}catch (Exception e){
e.printStackTrace();
}
}
return str.toString();
}
/**
* 获取条形码类型
* @param code
* @return
*/
public static BarCodeType getBarCodeType(String code){
if(StringUtil.isEmpty(code)){
return BarCodeType.UNKNOWN;
} else {
int flag = Integer.parseInt(code.substring(0,3));
if (flag==980) {
return BarCodeType.BILL;
} else if (flag>=977&&flag<=979) {
return BarCodeType.BOOK;
} else if (flag>=981&&flag<=983) {
return BarCodeType.CURRENCYNOTE;
} else if (flag>=990&&flag<=999) {
return BarCodeType.COUPON;
} else if(flag>=690&&flag<=699){
return BarCodeType.CHNPDT;
} else {
return BarCodeType.FORPDT;
}
}
}
/**
* 条形码类型枚举
*/
public enum BarCodeType{
BOOK, // 书籍
BILL, // 应收票据
CURRENCYNOTE, // 普通流通券
COUPON, // 优惠券
CHNPDT, // 国内商品
FORPDT , // 国外商品
UNKNOWN // 未知类型
}
} | true |
e1c953bf4ef695f6342a304c5df7786b7137371c | Java | mellamonaranja/JAVA_Practice | /Ch08-Object/src/com/abs2/Terran.java | UTF-8 | 311 | 2.921875 | 3 | [] | no_license | package com.abs2;
public class Terran extends Unit{
boolean fly;
public Terran(String name, int energy, boolean fly) {
this.name=name;
this.energy=energy;
this.fly=fly;
}
@Override
public void decEnergy() {
energy -=2;
}
@Override
public void incEnergy() {
energy +=2;
}
}
| true |
87cd1c6f3eca89d17e92642f35a41eb6c68d5f63 | Java | csikobalint/JavaMinimal | /net/NetMaskConverter.java | UTF-8 | 227 | 2.359375 | 2 | [] | no_license | package net;
/**
* Naive implementation with String processing
**/
abstract class NetMaskConverter implements NetMaskConverterI{
final String dotFormat;
NetMaskConverter(String dotFormat){
this.dotFormat = dotFormat;
}
} | true |
b1df5bc2647a5c4e585cb4b6087869c0fca736cf | Java | Mlethe/view | /app/src/main/java/com/mlethe/app/view/day11/TouchActivity.java | UTF-8 | 1,031 | 2.28125 | 2 | [] | no_license | package com.mlethe.app.view.day11;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.mlethe.app.view.R;
import com.mlethe.app.view.day10.TouchView;
public class TouchActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touch2);
TouchView touchView = findViewById(R.id.touch_view);
touchView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("TAG", "onClick");
}
});
touchView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e("TAG", "onTouch -> " + event.getAction());
return false;
}
});
}
}
| true |
98903c58d5af4e3e65d2965b392314c95434a46d | Java | spriadka/PV260-BrainMethodCheck | /src/main/java/cz/muni/fi/pv260/brainmethod/visitor/AbstractCheckVisitor.java | UTF-8 | 869 | 2.359375 | 2 | [] | no_license | package cz.muni.fi.pv260.brainmethod.visitor;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import cz.muni.fi.pv260.brainmethod.BrainMethodCheck;
import java.util.Collection;
import java.util.HashSet;
public abstract class AbstractCheckVisitor {
protected VisitReport report;
protected BrainMethodCheck brainMethodCheck;
protected String name;
protected Collection<Integer> acceptableTokens;
public AbstractCheckVisitor(BrainMethodCheck check){
this.brainMethodCheck = check;
acceptableTokens = new HashSet<>();
}
public abstract void visitToken(DetailAST ast);
public abstract void leaveToken(DetailAST ast);
public abstract void reset();
public VisitReport getReport(){
return report;
}
public Collection<Integer> getAcceptableTokens(){
return acceptableTokens;
}
}
| true |
587d7ad67afb48ba63a9511de9f3a0587ab85b35 | Java | drakemd/Fluida | /app/src/main/java/edu/upi/cs/sukidaa/fluida/Materi/HukumPascal/HukumPascal.java | UTF-8 | 3,275 | 1.8125 | 2 | [] | no_license | package edu.upi.cs.sukidaa.fluida.Materi.HukumPascal;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.ImageButton;
import com.ToxicBakery.viewpager.transforms.DepthPageTransformer;
import com.ToxicBakery.viewpager.transforms.FlipHorizontalTransformer;
import edu.upi.cs.sukidaa.fluida.MainMenu;
import edu.upi.cs.sukidaa.fluida.Materi.Materi;
import edu.upi.cs.sukidaa.fluida.Materi.TekananAtmosfer.Atm1;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro1;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro10;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro11;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro2;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro3;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro4;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro5;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro6;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro7;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro8;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.Hidro9;
import edu.upi.cs.sukidaa.fluida.Materi.TekananHidrostatis.TekananHidrostatis;
import edu.upi.cs.sukidaa.fluida.Menu.NavigationDrawerActivity;
import edu.upi.cs.sukidaa.fluida.R;
public class HukumPascal extends NavigationDrawerActivity implements View.OnClickListener{
private Button materi, aplikasi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setToolbarTitle("Hukum Pascal");
ViewStub vs = (ViewStub)findViewById(R.id.viewStub);
vs.setLayoutResource(R.layout.hukumpascal);
vs.inflate();
materi = (Button) findViewById(R.id.btnMateriPascal);
aplikasi = (Button) findViewById(R.id.btnAplikasi);
materi.setOnClickListener(this);
aplikasi.setOnClickListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnMateriPascal:
Intent intent2 = new Intent(this, MateriHukumPascal.class);
startActivity(intent2);
finish();
break;
case R.id.btnAplikasi:
Intent intent = new Intent(this, AplikasiHukumPascal.class);
startActivity(intent);
finish();
break;
}
}
}
| true |
69e3a8da10ee8cf48a041138c869b781bb9b90f9 | Java | RiazShaik79/spring-activeMQ-email-notificaiton-subscriber-api | /src/main/java/io/javabrains/Receiver.java | UTF-8 | 667 | 2.25 | 2 | [] | no_license | package io.javabrains;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
@Autowired
private EmailService emailService;
@JmsListener(destination = "mailbox", containerFactory = "myFactory")
public void receiveMessage(Email email) {
System.out.println("Received <" + email + ">");
try {
emailService.sendSimpleMessage(email.getTo(), email.getSubject(), email.getBody());
} catch(Exception e) {
System.out.println("Email Exception : " + e);
}
}
} | true |
b831dbe60173e1ae3f0861f97d15476d8d6a9647 | Java | jenkinsci/buildgraph-view-plugin | /src/main/java/org/jenkinsci/plugins/buildgraphview/MatrixBuildDownstreamDeclarer.java | UTF-8 | 852 | 2.40625 | 2 | [] | no_license | package org.jenkinsci.plugins.buildgraphview;
import hudson.Extension;
import hudson.matrix.MatrixBuild;
import hudson.model.Run;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
/** Add all combination-builds of a Matrix-build to downstream-builds.
*
* Created by christianlangmann on 26/01/15.
*/
@Extension
public class MatrixBuildDownstreamDeclarer extends DownStreamRunDeclarer {
@Override
public List<Run> getDownStream(Run r) throws ExecutionException, InterruptedException {
List<Run> runs = new ArrayList<Run>();
if (r instanceof MatrixBuild) {
final MatrixBuild matrixRun = (MatrixBuild)r;
for (Run downstreamRun : matrixRun.getExactRuns()) {
runs.add(downstreamRun);
}
}
return runs;
}
}
| true |
18d09dba2c0167f561c360807b24f13a3d53d0ea | Java | saksityod/ChandraEduqaActive | /src/th/ac/chandra/eduqa/service/EduqaService.java | UTF-8 | 11,990 | 1.617188 | 2 | [] | no_license | package th.ac.chandra.eduqa.service;
import java.util.List;
import th.ac.chandra.eduqa.mapper.ResultService;
import th.ac.chandra.eduqa.model.BaselineModel;
import th.ac.chandra.eduqa.model.CdsEvidenceModel;
import th.ac.chandra.eduqa.model.CdsModel;
import th.ac.chandra.eduqa.model.CdsResultDetailModel;
import th.ac.chandra.eduqa.model.CdsResultModel;
import th.ac.chandra.eduqa.model.CriteriaGroupModel;
import th.ac.chandra.eduqa.model.CriteriaModel;
import th.ac.chandra.eduqa.model.DbConnModel;
import th.ac.chandra.eduqa.model.DbQueryModel;
import th.ac.chandra.eduqa.model.DescriptionModel;
import th.ac.chandra.eduqa.model.KpiEvidenceModel;
import th.ac.chandra.eduqa.model.KpiGroupModel;
import th.ac.chandra.eduqa.model.KpiGroupTypeModel;
import th.ac.chandra.eduqa.model.KpiLevelModel;
import th.ac.chandra.eduqa.model.KpiModel;
import th.ac.chandra.eduqa.model.KpiReComndModel;
import th.ac.chandra.eduqa.model.KpiResultDetailModel;
import th.ac.chandra.eduqa.model.KpiResultModel;
import th.ac.chandra.eduqa.model.KpiStrucModel;
import th.ac.chandra.eduqa.model.KpiTargetModel;
import th.ac.chandra.eduqa.model.KpiTypeModel;
import th.ac.chandra.eduqa.model.KpiUomModel;
import th.ac.chandra.eduqa.model.OrgModel;
import th.ac.chandra.eduqa.model.OrgTypeModel;
import th.ac.chandra.eduqa.model.StrucTypeModel;
import th.ac.chandra.eduqa.model.SysMonthModel;
import th.ac.chandra.eduqa.model.SysYearModel;
import th.ac.chandra.eduqa.model.ThresholdModel;
public interface EduqaService {
public Integer getResultPage();
public String getResultMessage();
public String getResultCode();
//kpi level
public ResultService saveKpiLevel(KpiLevelModel kpiLevelModel);
public ResultService updateKpiLevel(KpiLevelModel kpiLevelModel);
public Integer deleteKpiLevel(KpiLevelModel kpiLevelModel);
public KpiLevelModel findKpiLevelById(Integer kpiLevelId);
@SuppressWarnings("rawtypes")
public List searchKpiLevel(KpiLevelModel kpiLevelModel);
//KPI Group
public ResultService saveKpiGroup(KpiGroupModel kpiGroupModel);
public ResultService updateKpiGroup(KpiGroupModel kpiGroupModel);
public Integer deleteKpiGroup(KpiGroupModel kpiGroupModel);
public KpiGroupModel findKpiGroupById(Integer kpiGroupModel);
@SuppressWarnings("rawtypes")
public List searchKpiGroup(KpiGroupModel persistentInstance);
//KPI Group Type
public ResultService saveKpiGroupType(KpiGroupTypeModel kpiGroupModelType);
public ResultService updateKpiGroupType(KpiGroupTypeModel kpiGroupModelType);
public Integer deleteKpiGroupType(KpiGroupTypeModel kpiGroupModelType);
public KpiGroupTypeModel findKpiGroupTypeById(Integer kpiGroupModelType);
@SuppressWarnings("rawtypes")
public List searchKpiGroupType(KpiGroupTypeModel persistentInstance);
//KPI Type
public ResultService saveKpiType(KpiTypeModel kpiTypeModel);
public ResultService updateKpiType(KpiTypeModel kpiTypeModel);
public Integer deleteKpiType(KpiTypeModel kpiTypeModel);
public KpiTypeModel findKpiTypeById(Integer KpiTypeId);
@SuppressWarnings("rawtypes")
public List searchKpiType(KpiTypeModel persistentInstance);
//KPI Uom
public ResultService saveKpiUom(KpiUomModel kpiUomModel);
public ResultService updateKpiUom(KpiUomModel kpiUomModel);
public Integer deleteKpiUom(KpiUomModel kpiUomModel);
public KpiUomModel findKpiUomById(Integer KpiUomId);
@SuppressWarnings("rawtypes")
public List searchKpiUom(KpiUomModel persistentInstance);
//KPI Structure
public ResultService saveKpiStruc(KpiStrucModel kpiStrucModel);
public ResultService updateKpiStruc(KpiStrucModel kpiStrucModel);
public Integer deleteKpiStruc(KpiStrucModel kpiStrucModel);
public KpiStrucModel findKpiStrucById(Integer KpiStrucId);
@SuppressWarnings("rawtypes")
public List searchKpiStruc(KpiStrucModel persistentInstance);
//ORG
public OrgModel findOrgById(OrgModel orgModel);
public OrgModel searchOrg(OrgModel persistentInstance);
public List searchOrgByLevelId(OrgModel persistentInstance);
public List searchOrgGroupByCourseCode(OrgModel persistentInstance);
public List searchOrgByFacultyCode(OrgModel persistentInstance);
public List searchOrgIdByOthersCode(OrgModel persistentInstance);
public List getAllUniversity(OrgModel org);
public List getOrgFacultyOfUniversity(OrgModel org);
public List getOrgCourseOfFaculty(OrgModel org);
public List getOrgIdByOrgDetailFilter(OrgModel org);
//Org Type
@SuppressWarnings("rawtypes")
public List searchOrgType(OrgTypeModel persistentInstance);
//Structure Type
public List searchStrucType(StrucTypeModel persistentInstance);
//cds
public ResultService saveCds(CdsModel cdsModel);
public ResultService updateCds(CdsModel cdsModel);
public ResultService deleteCds(CdsModel cdsModel);
public ResultService findCdsById(Integer cdsId);
public ResultService searchCds(CdsModel cdsModel);
// database connection
public Integer saveConn(DbConnModel connModel);
public Integer updateConn(DbConnModel connModel);
public Integer deleteConn(DbConnModel connModel);
public DbConnModel findConnById(Integer connId);
@SuppressWarnings("rawtypes")
public List searchConn(DbConnModel connModel);
// query
public List resultPreviewQuery(DbQueryModel model);
// kpi
public Integer saveKpi(KpiModel kpiModel);
public Integer saveKpiFormula(KpiModel kpiModel);
public Integer updateKpi(KpiModel kpiModel);
public Integer deleteKpi(KpiModel kpiModel);
public KpiModel findKpiById(Integer kpiId);
public KpiModel findKpiWithDescById(Integer kpiId);
@SuppressWarnings("rawtypes")
public List searchKpi(KpiModel kpiModel);
// criteria group
public List searchCriteriaGroup(CriteriaGroupModel group);
public List searchCriteriaGroupDetail(CriteriaGroupModel groupDetail);
// criteria
public Integer saveCriteriaStandard(CriteriaModel criteria);
public Integer deleteCriteriaStandard(CriteriaModel criteria);
public List searchCriteriaStandard(CriteriaModel std);
// baseline
public List listBaseline(BaselineModel baseline);
public Integer deleteBaseline(BaselineModel baseline);
public Integer saveQuanBaseline(BaselineModel baseline);
public Integer saveRangeBaseline(BaselineModel baseline);
public Integer saveSpecBaseline(BaselineModel baseline);
//KPI Structure
public ResultService saveThreshold(ThresholdModel thresholdModel);
public ResultService updateThreshold(ThresholdModel thresholdModel);
public Integer deleteThreshold(ThresholdModel thresholdModel);
public ThresholdModel findThresholdById(Integer ThresholdId);
@SuppressWarnings("rawtypes")
public List searchThreshold(ThresholdModel persistentInstance);
//SYS YEAR
public SysYearModel getSysYear();
public Integer saveSysYear(SysYearModel thresholdModel);
public Integer updateSysYear(SysYearModel thresholdModel);
@SuppressWarnings("rawtypes")
public List searchSysYear(SysYearModel persistentInstance);
public Integer generateSysMonthBySysYear(SysYearModel model);
//SYS MONTH
public SysMonthModel findSysMonthById(Integer monthId);
public Integer saveSysMonth(SysMonthModel thresholdModel);
public Integer updateSysMonth(SysMonthModel thresholdModel);
@SuppressWarnings("rawtypes")
public List searchSysMonth(SysMonthModel persistentInstance);
public List getMonthsByCalendar(SysMonthModel months);
public List getYearsByAcad(SysMonthModel months);
public List getMonthId(SysMonthModel perSysMonthModel);
//KPI RECOMMEND
public Integer saveKpiReComnd(KpiReComndModel kpiReComndModel);
public Integer updateKpiReComnd(KpiReComndModel kpiReComndModel);
public Integer deleteKpiReComnd(KpiReComndModel kpiReComndModel);
public KpiReComndModel findKpiReComndById(Integer KpiReComndId);
@SuppressWarnings("rawtypes")
public List searchKpiReComnd(KpiReComndModel persistentInstance);
//KPI RESULT
public Integer saveKpiResult(KpiResultModel kpiResultModel);
public Integer updateKpiResult(KpiResultModel kpiResultModel);
public Integer deleteKpiResult(KpiResultModel kpiResultModel);
public KpiResultModel findKpiResultById(Integer KpiResultId);
@SuppressWarnings("rawtypes")
public List searchKpiResult(KpiResultModel persistentInstance);
public KpiResultModel findKpiResultByKpi(KpiResultModel model);
public List searchKpiResultWithActiveKpi(KpiResultModel model);
public ResultService saveResultOfOrg(KpiResultModel kpiResultM);
public ResultService deleteResultByOrg(KpiResultModel kpiResultM);
public KpiResultModel findKpiResultByIden(KpiResultModel model);
//CDS RESULT
public Integer saveCdsResult(CdsResultModel cdsResultModel);
public CdsResultModel findCdsResultById(Integer cdsResultId);
public List searchCdsByKpiId(CdsResultModel persistentInstance);
public List searchCdsResult(CdsResultModel persistentInstance);
public List getCdsWithKpi(CdsResultModel model);
public CdsResultModel findCdsResultByCds(CdsResultModel model);
//CDS RESULT DETAIL
public Integer saveCdsResultDetail(CdsResultDetailModel cdsResultDetailModel); // saveResultQuantyity // can't use by ER
public Integer updateCdsResultDetail(CdsResultDetailModel cdsResultDetailModel); // updateResultQuantity can't be exist by requirement
public CdsResultDetailModel findCdsResultDetailById(Integer cdsResultDetailId); // getResultDetail Quantity can't be exist by requirement
public List searchCdsResultDetail(CdsResultDetailModel persistentInstance); // can't be exist by requirement
public Integer saveResultQuantity(CdsResultModel cdsresult); // cds result have key(orgId,cdsId,monthId)
public CdsResultDetailModel findCdsResultDetail(CdsResultDetailModel dsResultDetailModel);
//CDS EVIDENCE
public Integer deleteCdsEvidence(CdsEvidenceModel cdsEvidenceModel);
public Integer saveCdsEvidence(CdsEvidenceModel cdsEvidenceModel);
public CdsEvidenceModel findCdsEvidenceById(Integer cdsEvidenceId);
public List searchCdsEvidence(CdsEvidenceModel evidence); // searchEvidenceQuantity() // retrieve list evidenceId,filename
//target
public List getKpiTarget(KpiTargetModel targetModel);
public Integer saveKpiTarget(KpiTargetModel targetModel);
// desctition (kpi)
public DescriptionModel getOrgOfUser(DescriptionModel Model);
public List getPeriods(DescriptionModel Model);
public List getUoms(DescriptionModel Model);
public List getCalendarTypes(DescriptionModel Model );
public List getCriTypes(DescriptionModel Model);
public List getCriMethods(DescriptionModel Model);
public List getKpiNameAll(DescriptionModel Model);
public List getUniversityAll(DescriptionModel Model);
public List getFacultyAll(DescriptionModel Model);
public List getCourseAll(DescriptionModel Model);
public List getMonthAll(DescriptionModel Model);
///???? add by p 20/10/2558
public List<KpiResultDetailModel> findCriteriaResult(KpiResultDetailModel model);
public KpiResultDetailModel findKpiResultDetailById(KpiResultDetailModel model);
public KpiResultDetailModel findKpiResultDetailByIdentify(KpiResultDetailModel model);
public Integer saveKpiResultDetail(KpiResultDetailModel model);
public Integer updateKpiResultDetailEvidence(KpiResultDetailModel model);
//evidence
public Integer saveKpiEvidence(KpiEvidenceModel model);
public Integer deleteKpiEvidence(KpiEvidenceModel model);
public List<KpiEvidenceModel> searchKpiEvidence(KpiEvidenceModel model);
public Integer deleteKpiXCds(KpiModel model);
public Integer deleteBaselineSpecDetailByKpiId(BaselineModel kpiId);
public Integer deleteBaselineQuanByKpiId(BaselineModel model);
public Integer deleteCriteriaStandardByKpiI(CriteriaModel model);
public Integer deleteKpiResultByKpiId(KpiResultModel model);
public Integer deleteRangeBaselineByKpiId(KpiResultModel model);
} | true |
937618a20838d3a0e006190458fcaa94040704a1 | Java | gameguyr/learning-spring | /src/test/java/lego/learningSpring/MultiplicationTest.java | UTF-8 | 458 | 2.703125 | 3 | [] | no_license | package lego.learningSpring;
import org.junit.jupiter.api.Test;
public class MultiplicationTest {
private final Multiplication addition = new Multiplication();
@Test
public void shouldMatchOperation() {
assert(addition.handles('*'));
assert(!addition.handles('/'));
}
@Test
public void shouldCorrectlyApplyFormula() {
assert(addition.apply(2, 2) == 4);
assert(addition.apply(12, 10) == 120);
}
}
| true |
addaca2386ff5e981a9e9029f0d12160dd780b29 | Java | austin110068/NEU_CS5010_PDP | /Lab/lab3/src/dungeon/Monster.java | UTF-8 | 1,223 | 3.765625 | 4 | [] | no_license | package dungeon;
/**
* Class representing monsters in our dungeon.
*/
public class Monster {
private final String name;
private final String description;
private final int hitpoints;
/**
* Constructor for a monster.
*
* @param name the name of the monster
* @param description the description of the monster
* @param hitpoints the number of hit points the monsters has
*/
public Monster(String name, String description, int hitpoints) {
this.name = name;
this.description = description;
this.hitpoints = hitpoints;
}
/**
* Accessor for the name of the monster.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Accessor for the description of the monster.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Accessor for the number of hit points this monster has.
*
* @return the hit points
*/
public int getHitpoints() {
return hitpoints;
}
@Override
public String toString() {
return String.format("%s (hitpoints = %d) is a %s", name, hitpoints, description);
}
}
| true |
9a0d5c2004a54a0d93cb7b5f242dc1d2c1b7905a | Java | Azat666/UserProject | /AndroidAppAzat2/app/src/main/java/com/example/student/androidappazat2/activitys/InformationActivity.java | UTF-8 | 2,614 | 1.960938 | 2 | [] | no_license | package com.example.student.androidappazat2.activitys;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.example.student.androidappazat2.Datas;
import com.example.student.androidappazat2.R;
import com.example.student.androidappazat2.models.Result;
import com.squareup.picasso.Picasso;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class InformationActivity extends AppCompatActivity {
private TextView nameText, usernameText,
phoneText, emailText, genderText;
private CircleImageView circleImageView;
private ImageButton locationButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findItems();
setViewDatas();
}
private void findItems() {
nameText = findViewById(R.id.info_name);
usernameText = findViewById(R.id.info_username);
phoneText = findViewById(R.id.info_phone);
emailText = findViewById(R.id.info_email);
genderText = findViewById(R.id.info_gender);
circleImageView = findViewById(R.id.info_image);
locationButton = findViewById(R.id.info_location);
}
private void setViewDatas() {
nameText.setText(getListItem().getName().getFirst());
usernameText.setText(getListItem().getLogin().getUsername());
phoneText.setText(getListItem().getPhone());
emailText.setText(getListItem().getEmail());
genderText.setText(getListItem().getGender());
Picasso.get().load(getListItem().getPicture().getLarge()).into(circleImageView);
locationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(InformationActivity.this, MapsActivity.class);
intent.putExtra(Datas.KEY_FOR_MAP, Objects.requireNonNull(getIntent().getExtras()).getInt(Datas.KEY_FOR_INFO));
startActivity(intent);
}
});
}
private Result getListItem() {
return Datas.list.get(Objects.requireNonNull(getIntent().getExtras()).getInt(Datas.KEY_FOR_INFO));
}
}
| true |
0bfe51f2c395a750d70a65b1dd9e63847eb2cb24 | Java | edgarlizcano/adminapp | /src/main/java/com/adminapp/models/UserModel.java | UTF-8 | 779 | 2.078125 | 2 | [] | no_license | package com.adminapp.models;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
import lombok.ToString;
import javax.persistence.*;
import java.util.List;
import java.util.Set;
@Entity
@Data
@ToString
@Table(name = "users")
public class UserModel extends Audit{
@Id
@Column(name = "iduser")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idUser;
@Column(name = "username")
private String userName;
@Column(name = "password")
private String password;
@Column(name = "email")
private String email;
@Column(name = "status")
private String status;
@OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
@JsonManagedReference
private List<UserRoleModel> roles;
}
| true |
a7dc5f79eb0d2b3c0a2402a876eb9f41e856b3fc | Java | axelFrau/aterlier_prog_poo | /Atelier_4/src/root/Forme.java | UTF-8 | 907 | 3.453125 | 3 | [] | no_license | package root;
public abstract class Forme {
/***************** Class and Static variables *****************/
protected static int counter = 0;
protected String identifier;
protected double surface;
/***************** Constructor *****************/
protected Forme(String name){
counter ++;
this.identifier = name + "_n°" + counter;
}
/***************** Getter and Setter *****************/
public String getIdentifier(){
return this.identifier;
}
public double getSurface(){
return this.surface;
}
public void setSurface(double surface){
this.surface = surface;
}
/***************** Class and Static method Method *****************/
protected abstract double calculSurface();
@Override
public String toString() {
return "Identifiant de l'objet : " + this.getIdentifier();
}
}
| true |
d5fe0ae9ce852bacde5879a250039ae2e9a0b7cc | Java | strugcoder/myRpc | /src/main/java/club/codermax/rpc/protocol/loadbalance/impl/RandomLoadStrategy.java | UTF-8 | 502 | 2.203125 | 2 | [] | no_license | package club.codermax.rpc.protocol.loadbalance.impl;
import club.codermax.rpc.framework.ServiceProvider;
import club.codermax.rpc.protocol.loadbalance.LoadStrategy;
import java.util.List;
import java.util.Random;
public class RandomLoadStrategy implements LoadStrategy {
@Override
public String select(List<String> providers) {
int m = providers.size();
Random r = new Random();
int index = r.nextInt(m);
return providers.get(index);
}
}
| true |
f361ed8b3358def2dcd876142ddb5c3735c87fd8 | Java | gkbamrah/Todo-list-application | /main/model/exceptions/TaskNotCompleteException.java | UTF-8 | 107 | 1.765625 | 2 | [] | no_license | package model.exceptions;
public class TaskNotCompleteException extends CannotDeleteTaskException {
}
| true |
833264e1df9d88ae7eda6fdda1f4206dfd7e56f7 | Java | JetBrains/intellij-community | /java/java-tests/testSrc/com/intellij/java/codeInsight/intention/ChangeUIDActionTest.java | UTF-8 | 541 | 1.632813 | 2 | [
"Apache-2.0"
] | permissive | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.codeInsight.intention;
import com.intellij.codeInsight.daemon.LightIntentionActionTestCase;
public class ChangeUIDActionTest extends LightIntentionActionTestCase {
@Override
protected boolean shouldBeAvailableAfterExecution() {
return true;
}
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/changeUid";
}
}
| true |
5524cc9446f15b7eeca307e2fb1f770783740541 | Java | TheCBProject/MinablesOverhaul | /src/main/java/teamasm/moh/client/render/tile/RenderTileDebug.java | UTF-8 | 3,066 | 2.03125 | 2 | [
"MIT"
] | permissive | package teamasm.moh.client.render.tile;
import codechicken.lib.colour.Colour;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.texture.TextureUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import teamasm.moh.client.OreDustTextureManager;
import teamasm.moh.reference.OreRegistry;
import teamasm.moh.reference.Reference;
import teamasm.moh.tile.TileDebug;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by covers1624 on 8/7/2016.
*/
public class RenderTileDebug extends TileEntitySpecialRenderer<TileDebug> {
@Override
public void renderTileEntityAt(TileDebug te, double x, double y, double z, float partialTicks, int destroyStage) {
render(x, y, z, 30, true);
}
public static void render(double x, double y, double z, int div, boolean label) {
TextureUtils.bindBlockTexture();
GlStateManager.pushMatrix();
Map<String, Colour> nameToColour = OreRegistry.INSTANCE.getOreColourMap();
String name = "oreCopper";
try {
int index = (int) Minecraft.getMinecraft().theWorld.getWorldTime() / div % nameToColour.size();
name = new ArrayList<String>(nameToColour.keySet()).get(index);
} catch (Exception ignored) {
}
TextureAtlasSprite icon = OreDustTextureManager.getSprite(new ResourceLocation(Reference.MOD_ID, "textures/items/ore/generated/" + name));
CCRenderState state = CCRenderState.instance();
VertexBuffer buffer = state.startDrawing(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_NORMAL);
buffer.setTranslation(x, y + 0.001, z);
buffer.pos(1, 0, 0).tex(icon.getMinU(), icon.getMinV()).normal(0, 1, 0).endVertex();
buffer.pos(0, 0, 0).tex(icon.getMinU(), icon.getMaxV()).normal(0, 1, 0).endVertex();
buffer.pos(0, 0, 1).tex(icon.getMaxU(), icon.getMaxV()).normal(0, 1, 0).endVertex();
buffer.pos(1, 0, 1).tex(icon.getMaxU(), icon.getMinV()).normal(0, 1, 0).endVertex();
buffer.setTranslation(0, 0, 0);
state.draw();
if (label){
RenderManager renderManager = Minecraft.getMinecraft().getRenderManager();
float viewY = renderManager.playerViewY;
float viewX = renderManager.playerViewX;
boolean thirdPerson = renderManager.options.thirdPersonView == 2;
EntityRenderer.func_189692_a(renderManager.getFontRenderer(), name, (float) x + 0.5F, (float) y + 1.5F, (float) z + 0.5F, 0, viewY, viewX, thirdPerson, false);
}
GlStateManager.popMatrix();
}
}
| true |
a32effd5b58325224fa8b900700d4ea25b5e723d | Java | hiopro2016/linkshow | /src/main/java/com/ddzhuan/manage/service/impl/UploadFileServiceImpl.java | UTF-8 | 2,758 | 2.078125 | 2 | [] | no_license | package com.ddzhuan.manage.service.impl;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.ddzhuan.manage.service.UploadFileService;
import com.ddzhuan.manage.tool.UploadFileTool;
@Service
public class UploadFileServiceImpl implements UploadFileService{
private Logger log = Logger.getLogger(UploadFileServiceImpl.class);
@Override
public String[] uploadMiaoTaskImageFile(List<Map<String, Object>> fileList, String dir) {
if(fileList == null || dir == null){
return null;
}
UploadFileTool ufTool = UploadFileTool.getInstance();
String[] fileUrl = new String[fileList.size()];
try{
String filePath = "miaotaskimg/" + dir ;
for(int i = 0; fileList != null && i < fileList.size(); i++){
InputStream flie = (InputStream)fileList.get(i).get("stream");
String filename = (String)fileList.get(i).get("filename");
fileUrl[i] = ufTool.upLoadWithUFilePut(flie, filePath , filename);
}
}catch(Exception ex){
log.error(ex);
}
return fileUrl;
}
@Override
public String[] uploadMiaoTaskApkFile(List<Map<String, Object>> fileList, String dir) {
if(fileList == null || dir == null){
return null;
}
UploadFileTool ufTool = UploadFileTool.getInstance();
String[] fileUrl = new String[fileList.size()];
try{
String filePath = "miaotaskapk/" + dir ;
for(int i = 0; fileList != null && i < fileList.size(); i++){
InputStream flie = (InputStream)fileList.get(i).get("stream");
String filename = (String)fileList.get(i).get("filename");
fileUrl[i] = ufTool.upLoadWithUFilePut(flie, filePath , filename);
}
}catch(Exception ex){
log.error(ex);
}
return fileUrl;
}
@Override
public String[] uploadMiaoTaskRecoveryAdjFile(List<Map<String, Object>> fileList, String dir) {
if(fileList == null || dir == null){
return null;
}
UploadFileTool ufTool = UploadFileTool.getInstance();
String[] fileUrl = new String[fileList.size()];
try{
String filePath = "recorveyadj/" + dir ;
for(int i = 0; fileList != null && i < fileList.size(); i++){
InputStream flie = (InputStream)fileList.get(i).get("stream");
String filename = (String)fileList.get(i).get("filename");
fileUrl[i] = ufTool.upLoadWithUFilePut(flie, filePath , filename);
}
}catch(Exception ex){
log.error(ex);
}
return fileUrl;
}
@Override
public boolean deleteUFile(List<String> uFileCdnUrls){
boolean flg = false;
try{
UploadFileTool ufTool = UploadFileTool.getInstance();
for(int i = 0; uFileCdnUrls != null && i < uFileCdnUrls.size(); i++){
ufTool.deleteWithUFileDelete(uFileCdnUrls.get(i));
}
}catch(Exception ex){
}
return flg;
}
}
| true |
4b040e0a9adddebd3cd05d74213c83d02f626262 | Java | HoelzelJon/MatchstickPuzzle | /src/jonathan/hoelzel/matchsticks/Util/Grid.java | UTF-8 | 3,266 | 3.046875 | 3 | [] | no_license | package jonathan.hoelzel.matchsticks.Util;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Grid<T> implements Iterable<Vector> {
private final List<List<T>> grid;
public Grid(T[][] arr) {
this(Arrays.stream(arr).map(Arrays::asList).collect(Collectors.toList()));
}
public Grid(List<List<T>> grid) {
List<Integer> sizes = grid.stream().map(List::size).collect(Collectors.toList());
int mySize = sizes.get(0);
for (int i : sizes) {
assert i == mySize;
}
this.grid = grid;
}
public static <T, U> Grid<T> transform(Grid<U> other, Function<U, T> aTransformation) {
return new Grid<>(Util.transform(other.grid, aTransformation));
}
public T get(Vector pos) {
return get(pos.getX(), pos.getY());
}
public T get(int x, int y) {
assert inBounds(x, y);
return grid.get(y).get(x);
}
public void put(Vector v, T t) {
put(v.getX(), v.getY(), t);
}
public void put(int x, int y, T t) {
assert inBounds(x, y);
grid.get(y).set(x, t);
}
public int width() {
return grid.get(0).size();
}
public int height() {
return grid.size();
}
public boolean containsAny(Predicate<T> filter) {
return grid.stream().anyMatch(aList -> aList.stream().anyMatch(filter));
}
public boolean inBounds(Vector pos) {
return inBounds(pos.getX(), pos.getY());
}
public boolean inBounds(int x, int y) {
return x >= 0 && x < width() && y >= 0 && y < height();
}
public Collection<Vector> getNeighborVectors(Vector pos) {
return streamNeighbors(pos).collect(Collectors.toList());
}
// includes orthogonal but not diagonal neighbors
public Collection<T> getNeighborValues(Vector pos) {
return streamNeighbors(pos)
.map(this::get)
.collect(Collectors.toList());
}
private Stream<Vector> streamNeighbors(Vector pos) {
return pos.getNeighbors().stream().filter(this::inBounds);
}
@Override
public Iterator<Vector> iterator() {
return new VectorRectangleIterator(width(), height());
}
public Optional<Vector> findAny(Predicate<T> predicate) {
for (Vector v : this) {
if (predicate.test(get(v))) {
return Optional.of(v);
}
}
return Optional.empty();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int y = 0; y < height(); y ++) {
for (int x = 0; x < width(); x ++) {
builder.append(get(x, y).toString() + " ");
}
builder.append("\n");
}
return builder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Grid<?> grid1 = (Grid<?>) o;
return Objects.equals(grid, grid1.grid);
}
@Override
public int hashCode() {
return Objects.hash(grid);
}
}
| true |
fa69d6797e304f4259a500ddf9d5613c01acc4e7 | Java | Mega343/FinalProject2 | /src/com/homework/corefinalproject/util/UserInputReader.java | UTF-8 | 820 | 2.8125 | 3 | [] | no_license | package com.homework.corefinalproject.util;
public class UserInputReader {
public static double parseDouble(String userInputText, String fieldName) {
double result = 0;
try {
result = Double.parseDouble(userInputText);
} catch (Exception e) {
throw new IllegalArgumentException(fieldName + ": value should be double: "
+ userInputText);
}
return result;
}
public static int parseInt(String userInputText, String fieldName) {
int result = 0;
try {
result = Integer.parseInt(userInputText);
} catch (Exception e) {
throw new IllegalArgumentException(fieldName + ": value should be int: "
+ userInputText);
}
return result;
}
} | true |
8effc8e747b74aa7614bf7614726dad195413c18 | Java | gan00000/qinquanfabu | /DownLoadCopyApp/src/com/egame/cn/DownLoadCopyAppActivity.java | UTF-8 | 6,232 | 2.046875 | 2 | [] | no_license | package com.egame.cn;
import java.io.File;
import com.brave.shine.sea.R;
import com.efun.core.db.EfunDatabase;
import com.efun.core.tools.ApkUtil;
import com.efun.core.tools.EfunLocalUtil;
import com.efun.download.EfunDownLoader;
import com.efun.download.listener.EfunDownLoadListener;
import com.efun.service.FileService;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class DownLoadCopyAppActivity extends BaseActivity {
protected static final String ALREADY_DOWNLOAD = "ALREADY_DOWNLOAD";
protected static final String ALREADY_DOWNLOAD_VALUE = "10";
static EfunDownLoader downLoader;
ProgressBar bar;
int fileSize_m = 0;
int downLoadedSize_m = 0;
private String obbNewFile = "";
private String remoteApkPath;
private TextView download_text_view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.copydownload);
Log.d("efun", "onCreate");
bar = (ProgressBar) this.findViewById(R.id.progressBar);
remoteApkPath = ResHelper.getInstallAppDownloadUrl(this);
download_text_view = (TextView) findViewById(R.id.progressBar_text);
download_text_view.setTextColor(Color.RED);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("efun", "onResume");
if (!TextUtils.isEmpty(ResHelper.getInstallAppPackageName(this))) {// 包名不一样的情形
if (ApkUtil.isInstallApp(this, ResHelper.getInstallAppPackageName(this))) {
startApp(this);// 包名不一样才会启动
} else {
//downApp(this);
askInstallGame();
}
} else {// 游戏包名跟本包名一致
if (!TextUtils.isEmpty(remoteApkPath)) {
//downApp(this);
askInstallGame();
}
}
if (bar != null) {
bar.setMax(fileSize_m);
bar.setProgress(downLoadedSize_m);
}
}
private void copyObbFile(Activity activity) {
obbNewFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + activity.getPackageName() + "/edown/" +
"fn." + EfunLocalUtil.getVersionCode(activity) + "." + activity.getPackageName() + ".apk";
String obbPath = getObbFilePath(activity);
File src = new File(obbPath);
new CopyFileTask(obbPath, obbNewFile){
protected void onPostExecute(String result) {
if ("1".equals(result)) {//复制成功
bar.setMax(100);
bar.setProgress(100);
//ApkUtil.installApk(MainActivity.this, obbNewFile);
installApp(DownLoadCopyAppActivity.this, obbNewFile);
}else{
downApp(DownLoadCopyAppActivity.this);
}
};
protected void onProgressUpdate(Integer[] values) {
if (bar != null) {
bar.setMax(values[0]);
bar.setProgress(values[1]);
}
};
}.asyncExcute();
}
protected void askInstallGame() {
String g = EfunDatabase.getSimpleString(this, EfunDatabase.EFUN_FILE, ALREADY_DOWNLOAD);
if (ALREADY_DOWNLOAD_VALUE.equals(g)) {
downApp(DownLoadCopyAppActivity.this);
}else{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setMessage("download and install game");
b.setNegativeButton("close", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
b.setPositiveButton("download", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
downApp(DownLoadCopyAppActivity.this);
EfunDatabase.saveSimpleInfo(DownLoadCopyAppActivity.this, EfunDatabase.EFUN_FILE, ALREADY_DOWNLOAD, ALREADY_DOWNLOAD_VALUE);
}
});
b.create().show();
}
}
protected void downApp(Context context) {
if (TextUtils.isEmpty(remoteApkPath)) {
return;
}
if (bar != null) {
bar.setVisibility(View.VISIBLE);
}
if (downLoader == null) {
downLoader = new EfunDownLoader();
}
initDownLoad(context);
downLoader.startDownLoad(context);
}
public void initDownLoad(final Context context){
final String saveDir = Environment.getExternalStorageDirectory().getPath() + "/edown";
final String apk_file_name = FileService.getFileName(remoteApkPath);
// 设置下载的路径
downLoader.setDownUrl(remoteApkPath);
// 设置下载后保全的路径
downLoader.setSaveDirectoryPath(saveDir);
downLoader.setDownLoadListener(new EfunDownLoadListener() {
@Override
public void update(int fileSize, int downLoadedSize) {
Log.i("down", "fileSize:" + fileSize + " downLoadedSize:" + downLoadedSize);
fileSize_m = fileSize;
downLoadedSize_m = downLoadedSize;
if (bar != null) {
bar.setMax(fileSize_m);
bar.setProgress(downLoadedSize_m);
}
float i =(float) downLoadedSize / (float)fileSize * 100;
float percent = (float)(Math.round(i * 100)) / 100;//Math.round为四舍五入算法
download_text_view.setText("downloading " + String.valueOf(percent) + "%");
}
@Override
public void finish() {
Log.i("efun", "finish download");
if (bar != null) {
bar.setMax(100);
bar.setProgress(100);
}
installApp(DownLoadCopyAppActivity.this, saveDir + File.separator + apk_file_name);
}
@Override
public void reachFile(int fileSize) {
Log.i("efun", "fileSize:" + fileSize);
if (bar != null) {
bar.setMax(fileSize_m);
}
}
@Override
public void unFinish() {
Log.i("efun", "unfinish download");
//Toast.makeText(getApplicationContext(), "download failed", Toast.LENGTH_SHORT).show();
}
@Override
public void lackStorageSpace() {
}
@Override
public void remoteFileNotFind() {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("efun", "onDestroy");
if (downLoader != null) {
downLoader.pauseDownLoad(this);
}
}
} | true |
2eee23eb538a5750478c0fcbc47638676ca019b4 | Java | JoeysWang/Leetcode | /src/main/java/test/CharTest.java | UTF-8 | 359 | 2.546875 | 3 | [] | no_license | package test;
public class CharTest {
public static void main(String[] args) {
char sperate = 9;
// String s = "\t";
// System.out.println(s.length());
// System.out.println(s.charAt(0)==sperate);
long l1 = 187_355_241_007_485L;
long l2 = 185_175_888_636_806L;
System.out.println((l1-l2)+"");
}
}
| true |
fe324eea425f51a933bd33802ead4c6a1f750e78 | Java | jandppw/ppwcode-recovered-from-google-code | /java/vernacular/persistence/trunk/src/main/java/org/ppwcode/vernacular/persistence_III/dao/RemoteAtomicStatelessCrudDao.java | UTF-8 | 11,921 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | /*<license>
Copyright 2005 - $Date$ by PeopleWare n.v..
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.
</license>*/
package org.ppwcode.vernacular.persistence_III.dao;
import static org.ppwcode.util.exception_III.ProgrammingErrorHelpers.dependency;
import static org.ppwcode.util.exception_III.ProgrammingErrorHelpers.unexpectedException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ppwcode.vernacular.exception_III.ExternalError;
import org.ppwcode.vernacular.exception_III.ApplicationException;
import org.ppwcode.vernacular.exception_III.handle.ExceptionHandler;
import org.ppwcode.vernacular.persistence_III.IdNotFoundException;
import org.ppwcode.vernacular.persistence_III.PersistentBean;
import org.ppwcode.vernacular.persistence_III.VersionedPersistentBean;
import org.ppwcode.vernacular.persistence_III.dao.AtomicStatelessCrudDao;
import org.ppwcode.vernacular.persistence_III.dao.RequiredTransactionStatelessCrudDao;
import org.toryt.annotations_I.Basic;
import org.toryt.annotations_I.Expression;
import org.toryt.annotations_I.MethodContract;
/**
* <p>JPA implementation of {@link AtomicStatelessCrudDao}. This delegates to an instance of
* {@link RequiredTransactionStatelessCrudDao}.</p>
* <p>This is a stateless session bean, whose first intention is remote use.
* Because we advise not to use the interface {@link AtomicStatelessCrudDao} directly in the API of your business
* application, you cannot use this class directly either. You should extend this class in your business application as
* follows:</p>
* <pre>
* package my.business.application_IV.businesslogic.jpa;
*
* ...
*
* @Stateless
* <var>@WebService</var>
* @TransactionManagement(TransactionManagementType.BEAN)
* public class RemoteStatelessCrudDao extends org.ppwcode.vernacular.persistence_III.dao.ejb3.RemoteStatelessCrudDao {
*
* // NOP
*
* }
* </pre>
* <p>Furthermore, you need to inject a {@link #getRequiredTransactionStatelessCrudDao() RequiredTransactionStatelessCrudDao}
* and an {@link #getExceptionHandler() ExceptionHandler}. The abstract methods {@link #isOperational()},
* {@link #beginTransaction()}, {@link #commitTransaction()}, and {@link #rollbackTransaction()} must be
* implemented. A subclass could do this by providing a {@link javax.transaction.UserTransaction} or
* {@link javax.persistence.EntityTransaction}, and implementing these methods by delegating the work to these
* specialized objects.</p>
* <p>That is why this class does not have the {@code @Stateless}, {@code @WebService} nor {@code @TransactionManagement}
* or {@code @TransactionAttribute} annotation (apart from infecting this library package with a dependency on EJB3 annotations).
* In this way you have the possibility to keep backward compatibility when your business application's semantics change, and the class
* / object model and data model change. In that case, you develop a new version in package {@code my.business.application_V}, introducing
* {@code my.business.application_V.businesslogic.jpa.JpaStatelessTransactionCrudDao} implementing a new remote interface. With that,
* your clients can now choose which version they want to use. From the old version, you keep the necessary classes, but since the
* database structure probably has changed, retrieving and updating data cannot easily happen the same way. In particular, your
* semantics (persistent bean subtypes) will probably no longer map to the database. This means that your original implementation of
* {@code my.business.application_IV.businesslogic.jpa.JpaStatelessTransactionCrudDao} with the old semantics (entities) will no
* longer work. By changing the implementation of {@code my.business.application_IV.businesslogic.jpa.JpaStatelessTransactionCrudDao}
* to map old semantic POJO's (now no longer entities) to new entities (if at all possible), you make the old API forward compatible
* with the new semantics. Because this is not always possible with all methods of this interface in all circumstances, all methods
* can throw a {@code NoLongerSupportedError}.</p>
*
* @mudo unit tests
*/
public abstract class RemoteAtomicStatelessCrudDao implements AtomicStatelessCrudDao {
private final static Log _LOG = LogFactory.getLog(RemoteAtomicStatelessCrudDao.class);
/*<property name="statelessCrudJoinTransactionDao">
-------------------------------------------------------------------------*/
@Basic
public final RequiredTransactionStatelessCrudDao getRequiredTransactionStatelessCrudDao() {
return $requiredTransactionStatelessCrudDao;
}
@MethodContract(
post = @Expression("statelessCrudJoinTransactionDao == _statelessCrudJoinTransactionDao")
)
public final void setStatelessCrudJoinTransactionDao(RequiredTransactionStatelessCrudDao requiredTransactionStatelessCrudDao) {
$requiredTransactionStatelessCrudDao = requiredTransactionStatelessCrudDao;
}
private RequiredTransactionStatelessCrudDao $requiredTransactionStatelessCrudDao;
/*</property>*/
/*<property name="exception handler">
-------------------------------------------------------------------------*/
@Basic
public final ExceptionHandler getExceptionHandler() {
return $exceptionHandler;
}
@MethodContract(
post = @Expression("exceptionHandler == _exceptionHandler")
)
public final void setExceptionHandler(ExceptionHandler exceptionHandler) {
$exceptionHandler = exceptionHandler;
}
private ExceptionHandler $exceptionHandler;
/*</property>*/
/**
* Returns true if this RemoteAtomicStatelessCrudDao is involved in an
* transaction (beginTransaction was called, but not yet rolled back
* or committed).
*/
@MethodContract(post = @Expression("result ? statelessCrudJoinTransactionDao != null && userTransaction != null && exceptionHandler != null"))
public abstract boolean isOperational();
/**
* Starts a transaction. Must only be called by this class
* (hence protected)
*/
protected abstract void beginTransaction();
/**
* Commits a transaction. Must only be called by this class
* (hence protected)
*/
protected abstract void commitTransaction();
/**
* Rolls back a transaction. Must only be called by this class
* (hence protected)
*/
protected abstract void rollbackTransaction();
public <_PersistentBean_ extends PersistentBean<?>> Set<_PersistentBean_>
retrieveAllPersistentBeans(Class<_PersistentBean_> persistentBeanType, boolean retrieveSubClasses) {
assert dependency(getExceptionHandler(), "exceptionHandler");
try {
beginTransaction();
Set<_PersistentBean_> result = getRequiredTransactionStatelessCrudDao().retrieveAllPersistentBeans(persistentBeanType, retrieveSubClasses);
commitTransaction();
return result;
}
catch (Throwable t) {
handleForNoException(t);
}
return null; // keep compiler happy
}
public <_VersionedPersistentBean_ extends VersionedPersistentBean<?, Timestamp>> Set<_VersionedPersistentBean_>
retrieveAllPersistentBeansChangedSince(Class<_VersionedPersistentBean_> persistentBeanType, boolean retrieveSubClasses, Timestamp since) {
assert dependency(getExceptionHandler(), "exceptionHandler");
try {
beginTransaction();
Set<_VersionedPersistentBean_> result = getRequiredTransactionStatelessCrudDao().retrieveAllPersistentBeansChangedSince(persistentBeanType, retrieveSubClasses, since);
commitTransaction();
return result;
}
catch (Throwable t) {
handleForNoException(t);
}
return null; // keep compiler happy
}
public <_Id_ extends Serializable, _PersistentBean_ extends PersistentBean<_Id_>>
_PersistentBean_ retrievePersistentBean(Class<_PersistentBean_> persistentBeanType, _Id_ id) throws IdNotFoundException {
assert dependency(getExceptionHandler(), "exceptionHandler");
try {
beginTransaction();
_PersistentBean_ result = getRequiredTransactionStatelessCrudDao().retrievePersistentBean(persistentBeanType, id);
commitTransaction();
return result;
}
catch (Throwable t) {
handleForIdNotFoudException(t);
}
return null; // keep compiler happy
}
public <_Id_ extends Serializable, _Version_ extends Serializable, _PB_ extends VersionedPersistentBean<_Id_, _Version_>>
_PB_ updatePersistentBean(_PB_ pb) throws ApplicationException {
assert dependency(getExceptionHandler(), "exceptionHandler");
try {
beginTransaction();
_PB_ result = getRequiredTransactionStatelessCrudDao().updatePersistentBean(pb);
commitTransaction();
return result;
}
catch (Throwable t) {
handleForApplicationException(t);
}
return null; // keep compiler happy
}
public <_Id_ extends Serializable, _Version_ extends Serializable, _PB_ extends VersionedPersistentBean<_Id_, _Version_>>
_PB_ createPersistentBean(_PB_ pb) throws ApplicationException {
assert dependency(getExceptionHandler(), "exceptionHandler");
try {
beginTransaction();
_PB_ result = getRequiredTransactionStatelessCrudDao().createPersistentBean(pb);
commitTransaction();
return result;
}
catch (Throwable t) {
handleForApplicationException(t);
}
return null; // keep compiler happy
}
public <_Id_ extends Serializable, _Version_ extends Serializable, _PB_ extends VersionedPersistentBean<_Id_, _Version_>>
_PB_ deletePersistentBean(_PB_ pb) throws ApplicationException {
try {
beginTransaction();
_PB_ result = getRequiredTransactionStatelessCrudDao().deletePersistentBean(pb);
commitTransaction();
return result;
}
catch (Throwable t) {
handleForApplicationException(t);
}
return null; // keep compiler happy
}
private void handleForNoException(Throwable t) throws ExternalError, AssertionError {
Throwable finalException = robustRollback(t);
try {
getExceptionHandler().handleException(finalException, _LOG);
}
catch (ApplicationException metaExc) {
unexpectedException(metaExc, "handleException can throw no ApplicationExceptions");
}
}
@SuppressWarnings("unchecked")
private void handleForIdNotFoudException(Throwable t) throws ExternalError, AssertionError, IdNotFoundException {
Throwable finalException = robustRollback(t);
try {
getExceptionHandler().handleException(finalException, _LOG, IdNotFoundException.class);
}
catch (IdNotFoundException infExc) {
throw infExc;
}
catch (ApplicationException metaExc) {
unexpectedException(metaExc, "handleException can throw no ApplicationExceptions");
}
}
@SuppressWarnings("unchecked")
private void handleForApplicationException(Throwable t) throws ExternalError, AssertionError, ApplicationException {
Throwable finalException = robustRollback(t);
getExceptionHandler().handleException(finalException, _LOG, ApplicationException.class);
}
private Throwable robustRollback(Throwable reasonForRollback) {
Throwable finalException = reasonForRollback;
try {
rollbackTransaction();
}
catch (Throwable exc) {
finalException = exc;
}
return finalException;
}
}
| true |
9705f1b1b3fa2ebd12afb9b5cd00ca93cf8ae4ea | Java | uo269412/IPS2020-PL61 | /src/sprint1/ui/ventanas/administracion/actividades/PlanificarActividadDialog.java | ISO-8859-1 | 17,488 | 2.171875 | 2 | [] | no_license | package sprint1.ui.ventanas.administracion.actividades;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import sprint1.business.Programa;
import sprint1.business.dominio.centroDeportes.actividades.Actividad;
import sprint1.business.dominio.centroDeportes.actividades.ActividadPlanificada;
import sprint1.business.dominio.centroDeportes.instalaciones.Instalacion;
import sprint1.business.dominio.centroDeportes.instalaciones.Recurso;
import sprint1.ui.ventanas.administracion.util.CalendarioAdmin;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ListSelectionModel;
import javax.swing.JScrollPane;
import java.awt.Toolkit;
public class PlanificarActividadDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JPanel pnActividadesPlanificadas;
private JList<ActividadPlanificada> listActividadesPlanificadas;
private JLabel lblDia;
private JPanel pnProgramarActividad;
private JLabel lblActividad;
private JComboBox<Actividad> cmbActividades;
private JLabel lblHora;
private JPanel pnHoras;
private JTextField txtHoraInicio;
private JTextField txtHoraFin;
private JLabel lblLimite;
private JTextField txtLimitePlazas;
private JPanel pnAadir;
private JButton btnAadir;
private JButton btnEliminar;
private JPanel pnBotones;
private JButton btnVolver;
private Programa programa;
private DefaultListModel<ActividadPlanificada> modeloLista;
private int dia;
private int mes;
private int ao;
private JButton btnNewButton;
private List<ActividadPlanificada> aEliminar;
private JLabel lblInstalacion;
private JComboBox<Instalacion> cmbInstalaciones;
private boolean updated = true;
DefaultComboBoxModel<Actividad> modeloBaseComboActividades;
private JScrollPane scrollPane;
// /**
// * Launch the application.
// */
// public static void main(String[] args) {
// try {
// AsignarActividadDialog dialog = new AsignarActividadDialog();
// dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// dialog.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* Create the dialog.
*/
public PlanificarActividadDialog(CalendarioAdmin parent, Programa p, int dia, int mes, int ao) {
setIconImage(Toolkit.getDefaultToolkit().getImage(PlanificarActividadDialog.class.getResource("/sprint1/ui/resources/titulo.png")));
setTitle("Centro de deportes: Asignar actividad " + dia + "/" + mes + "/" + ao);
this.programa = p;
this.dia = dia;
this.mes = mes;
this.ao = ao;
this.modeloLista = new DefaultListModel<ActividadPlanificada>();
this.modeloBaseComboActividades = new DefaultComboBoxModel<Actividad>(
programa.getActividades().toArray(new Actividad[programa.getActividades().size()]));
setBounds(100, 100, 760, 331);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new GridLayout(1, 0, 0, 0));
contentPanel.add(getPnProgramarActividad());
contentPanel.add(getPnActividadesPlanificadas());
getContentPane().add(getPnBotones(), BorderLayout.SOUTH);
aEliminar = new LinkedList<>();
}
private JPanel getPnActividadesPlanificadas() {
if (pnActividadesPlanificadas == null) {
pnActividadesPlanificadas = new JPanel();
pnActividadesPlanificadas.setLayout(new BorderLayout(0, 0));
pnActividadesPlanificadas.add(getLblDia(), BorderLayout.NORTH);
pnActividadesPlanificadas.add(getBtnEliminar(), BorderLayout.SOUTH);
pnActividadesPlanificadas.add(getScrollPane(), BorderLayout.CENTER);
}
return pnActividadesPlanificadas;
}
private JList<ActividadPlanificada> getListActividadesPlanificadas() {
if (listActividadesPlanificadas == null) {
mostrarActividadesPlanificadasDia();
listActividadesPlanificadas = new JList<ActividadPlanificada>();
listActividadesPlanificadas.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listActividadesPlanificadas.setModel(modeloLista);
}
return listActividadesPlanificadas;
}
private JLabel getLblDia() {
if (lblDia == null) {
lblDia = new JLabel("Actividades d\u00EDa:");
}
return lblDia;
}
private JPanel getPnProgramarActividad() {
if (pnProgramarActividad == null) {
pnProgramarActividad = new JPanel();
pnProgramarActividad.setLayout(new GridLayout(0, 1, 0, 0));
pnProgramarActividad.add(getLblActividad());
pnProgramarActividad.add(getCmbActividades());
pnProgramarActividad.add(getLblHora());
pnProgramarActividad.add(getPnHoras());
pnProgramarActividad.add(getLblLimite());
pnProgramarActividad.add(gettxtLimitePlazasPlazas());
pnProgramarActividad.add(getLblInstalacion());
pnProgramarActividad.add(getCmbInstalaciones());
pnProgramarActividad.add(getPnAadir());
}
return pnProgramarActividad;
}
private JLabel getLblActividad() {
if (lblActividad == null) {
lblActividad = new JLabel("Actividad a asignar:");
}
return lblActividad;
}
private JComboBox<Actividad> getCmbActividades() {
if (cmbActividades == null) {
cmbActividades = new JComboBox<Actividad>();
cmbActividades.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(updated) {
if(cmbActividades.getSelectedItem() != null) {
rellenarInstalacion();
}
}
}
});
cmbActividades.setFont(new Font("Tahoma", Font.PLAIN, 8));
cmbActividades.setModel(modeloBaseComboActividades);
}
return cmbActividades;
}
private JLabel getLblHora() {
if (lblHora == null) {
lblHora = new JLabel("Hora inicio/Hora fin (formato HH)");
}
return lblHora;
}
private JPanel getPnHoras() {
if (pnHoras == null) {
pnHoras = new JPanel();
pnHoras.add(getTxtHoraInicio());
pnHoras.add(getTxtHoraFin());
}
return pnHoras;
}
private JTextField getTxtHoraInicio() {
if (txtHoraInicio == null) {
txtHoraInicio = new JTextField();
txtHoraInicio.setColumns(10);
}
return txtHoraInicio;
}
private JTextField getTxtHoraFin() {
if (txtHoraFin == null) {
txtHoraFin = new JTextField();
txtHoraFin.setColumns(10);
}
return txtHoraFin;
}
private JLabel getLblLimite() {
if (lblLimite == null) {
lblLimite = new JLabel("Limite de plazas:");
}
return lblLimite;
}
private JTextField gettxtLimitePlazasPlazas() {
if (txtLimitePlazas == null) {
txtLimitePlazas = new JTextField();
txtLimitePlazas.setColumns(10);
}
return txtLimitePlazas;
}
private JPanel getPnAadir() {
if (pnAadir == null) {
pnAadir = new JPanel();
pnAadir.add(getBtnAadir());
}
return pnAadir;
}
private JButton getBtnAadir() {
if (btnAadir == null) {
btnAadir = new JButton("A\u00F1adir");
btnAadir.setMnemonic('d');
if(cmbInstalaciones.getModel().getSize() == 0) {
btnAadir.setEnabled(false);
} else {
btnAadir.setEnabled(true);
}
btnAadir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (checkHoraInicio() && checkHoraFin() && checkLimitePlazas() == 0) {
updated = false;
cmbInstalaciones.setEnabled(false);
aadirAModelo(crearPlanificada());
adaptarActividadesAInstalacion();
repintar();
} else if(checkLimitePlazas() == 1) {
JOptionPane.showMessageDialog(getMe(), "La aplicacin tiene menos recursos disponibles que las plazas que ests intentando aadir.\n"
+ "Mximos recursos disponibles ahora mismo en la instalacin: " + getMinRecursos());
}
}
});
btnAadir.setForeground(Color.WHITE);
btnAadir.setBackground(new Color(60, 179, 113));
}
return btnAadir;
}
private void repintar() {
txtHoraInicio.setBackground(Color.WHITE);
txtHoraInicio.setForeground(Color.BLACK);
txtHoraInicio.setText("");
txtHoraFin.setBackground(Color.WHITE);
txtHoraFin.setForeground(Color.BLACK);
txtHoraFin.setText("");
txtLimitePlazas.setBackground(Color.WHITE);
txtLimitePlazas.setForeground(Color.BLACK);
txtLimitePlazas.setText("");
}
private JButton getBtnEliminar() {
if (btnEliminar == null) {
btnEliminar = new JButton("Eliminar seleccionada");
btnEliminar.setMnemonic('E');
btnEliminar.setForeground(Color.WHITE);
btnEliminar.setBackground(new Color(255, 99, 71));
btnEliminar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
updated = false;
cmbInstalaciones.setEnabled(false);
cmbInstalaciones.setToolTipText("No puedes cambiar de instalacin hasta que no hayas aplicado los cambios");
int indiceAEliminar = listActividadesPlanificadas.getSelectedIndex();
aEliminar.add(modeloLista.get(indiceAEliminar));
modeloLista.remove(indiceAEliminar);
adaptarActividadesAInstalacion();
}
});
}
return btnEliminar;
}
private JPanel getPnBotones() {
if (pnBotones == null) {
pnBotones = new JPanel();
pnBotones.setLayout(new FlowLayout(FlowLayout.RIGHT));
pnBotones.add(getBtnVolver());
pnBotones.add(getBtnNewButton());
}
return pnBotones;
}
private JButton getBtnVolver() {
if (btnVolver == null) {
btnVolver = new JButton("Volver");
btnVolver.setMnemonic('V');
btnVolver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
getMe().dispose();
}
});
btnVolver.setBackground(Color.BLUE);
btnVolver.setForeground(Color.WHITE);
btnVolver.setActionCommand("Cancel");
}
return btnVolver;
}
private PlanificarActividadDialog getMe() {
return this;
}
private void aadirAModelo(ActividadPlanificada a) {
List<ActividadPlanificada> lista = new LinkedList<>();
for(int i = 0; i < modeloLista.getSize(); i++) {
lista.add(modeloLista.getElementAt(i));
}
lista.add(a);
lista.sort(new ComparePlanificadas());
modeloLista.clear();
for(ActividadPlanificada actividad: lista) {
modeloLista.add(modeloLista.size(), actividad);
}
}
public void mostrarActividadesPlanificadasDia() {
/*
try {
for (ActividadPlanificada a : programa.getActividadesPlanificadasInstalacionDia(((Instalacion)cmbInstalaciones.getSelectedItem()).getCodigo(), dia, mes, ao)) {
modeloLista.addElement(a);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this,
"Ha ocurrido un error cargando las actividades para este da, por favor contacte con el desarrollador");
}
*/
modeloLista.clear();
List<ActividadPlanificada> actividades = new LinkedList<>();
for (ActividadPlanificada a : programa.getActividadesPlanificadasInstalacionDia(((Instalacion)cmbInstalaciones.getSelectedItem()).getCodigo(), dia, mes, ao)) {
actividades.add(a);
}
actividades.sort(new ComparePlanificadas());
for(ActividadPlanificada a: actividades) {
modeloLista.addElement(a);
}
}
private boolean checkHoraInicio() {
if (txtHoraInicio.getText().length() > 2) {
txtHoraInicio.setBackground(Color.RED);
txtHoraInicio.setForeground(Color.WHITE);
return false;
}
try {
Integer.parseInt(txtHoraInicio.getText());
} catch (NumberFormatException e) {
return false;
}
return true;
}
private boolean checkHoraFin() {
if (txtHoraFin.getText().length() > 2) {
txtHoraFin.setBackground(Color.RED);
txtHoraFin.setForeground(Color.WHITE);
return false;
}
try {
Integer.parseInt(txtHoraFin.getText());
} catch (NumberFormatException e) {
return false;
}
return true;
}
private int checkLimitePlazas() {
if(txtLimitePlazas.getText().contentEquals("")) {
return 0;
}
else {
try {
int limitePlazas = Integer.parseInt(txtLimitePlazas.getText());
int minRecursos = getMinRecursos();
if(limitePlazas > minRecursos) {
return 1;
}
} catch (NumberFormatException e) {
txtLimitePlazas.setBackground(Color.RED);
txtLimitePlazas.setForeground(Color.WHITE);
return 2;
}
return 0;
}
}
private int getMinRecursos() {
int minRecursos = Integer.MAX_VALUE;
for(Recurso r: ((Actividad)cmbActividades.getSelectedItem()).getRecursos()) {
if(r.getUnidades() < minRecursos) {
minRecursos = r.getUnidades();
}
}
return minRecursos;
}
private ActividadPlanificada crearPlanificada() {
String codigoAAsignar = ((Actividad) cmbActividades.getSelectedItem()).getCodigo();
int limitePlazas;
if(txtLimitePlazas.getText().equals("")){
limitePlazas = Integer.MAX_VALUE;
}
else {
limitePlazas = Integer.parseInt(txtLimitePlazas.getText());
}
int horaInicio = Integer.parseInt(txtHoraInicio.getText());
int horaFin = Integer.parseInt(txtHoraFin.getText());
String codigoInstalacion = ((Instalacion)cmbInstalaciones.getSelectedItem()).getCodigoInstalacion();
return new ActividadPlanificada(codigoAAsignar, dia, mes, ao, limitePlazas, horaInicio, horaFin, codigoInstalacion);
}
private JButton getBtnNewButton() {
if (btnNewButton == null) {
btnNewButton = new JButton("Aplicar cambios");
btnNewButton.setBackground(new Color(0, 128, 0));
btnNewButton.setForeground(Color.WHITE);
btnNewButton.setMnemonic('A');
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
aplicarCambios();
updated = true;
cmbActividades.setModel(modeloBaseComboActividades);
cmbInstalaciones.setEnabled(true);
cmbInstalaciones.setToolTipText(null);
}
});
}
return btnNewButton;
}
private void aplicarCambios() {
try {
for (ActividadPlanificada a : aEliminar) {
programa.eliminarActividadPlanificada(a);
}
for (int i = 0; i < modeloLista.size(); i++) {
if( !programa.getActividadesPlanificadas().contains(modeloLista.getElementAt(i)))
programa.aadirActividadPlanificada(modeloLista.getElementAt(i));
}
modeloLista.clear();
mostrarActividadesPlanificadasDia();
} catch (SQLException e) {
JOptionPane.showMessageDialog(this,
"Ha ocurrido un error cargando las actividades para este da, por favor contacte con el desarrollador");
}
listActividadesPlanificadas.validate();
}
private JLabel getLblInstalacion() {
if (lblInstalacion == null) {
lblInstalacion = new JLabel("Instalaci\u00F3n:");
}
return lblInstalacion;
}
private void rellenarInstalacion() {
cmbInstalaciones.setEnabled(true);
Actividad a = programa.getActividades().get(cmbActividades.getSelectedIndex());
if(a.requiresRecursos()) {
boolean todosIguales = true;
String i = a.getRecursos().get(0).getInstalacion();
for(Recurso r: a.getRecursos()) {
if(r.getInstalacion().equals(i)) {
todosIguales = true;
} else {
todosIguales = false;
break;
}
}
if(todosIguales) {
try {
Instalacion inst = programa.obtenerInstalacionPorId(a.getRecursos().get(0).getInstalacion());
Instalacion[] arrayInst = new Instalacion[1];
arrayInst[0] = inst;
cmbInstalaciones.setModel(new DefaultComboBoxModel<Instalacion>(arrayInst));
} catch(SQLException e) {
JOptionPane.showMessageDialog(this, "Ha habido un problema con la base de datos asignando la instalacion"
+ ", pngase en contacto con el desarrollador");
}
} else {
cmbInstalaciones.setEnabled(false);
cmbInstalaciones.setToolTipText("No hay ninguna instalacin que tenga recursos para esta actividad");
btnAadir.setEnabled(false);
}
} else {
cmbInstalaciones.setModel(new DefaultComboBoxModel<Instalacion>(programa.getInstalacionesDisponibles().toArray(new Instalacion[programa.getInstalacionesDisponibles().size()])));
}
}
private JComboBox<Instalacion> getCmbInstalaciones() {
if (cmbInstalaciones == null) {
cmbInstalaciones = new JComboBox<Instalacion>();
rellenarInstalacion();
cmbInstalaciones.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
mostrarActividadesPlanificadasDia();
}
});
}
return cmbInstalaciones;
}
private void adaptarActividadesAInstalacion() {
Instalacion i = (Instalacion) cmbInstalaciones.getSelectedItem();
cmbActividades.setModel(new DefaultComboBoxModel<Actividad>(
programa.actividadesPorInstalacion(i.getCodigo()).toArray(new Actividad[programa.actividadesPorInstalacion(i.getCodigo()).size()])));
}
private class ComparePlanificadas implements Comparator<ActividadPlanificada> {
@Override
public int compare(ActividadPlanificada arg0, ActividadPlanificada arg1) {
return arg0.compareTo(arg1);
}
}
private JScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new JScrollPane();
scrollPane.add(getListActividadesPlanificadas());
scrollPane.setViewportView(getListActividadesPlanificadas());
}
return scrollPane;
}
} | true |
956986a9a5fd527f5e2ebaacf7cf213a4a52aa67 | Java | dearKundy/cranberry | /src/main/java/com/kundy/cranberry/javabasis/multithread/lock/TestReentrantLockMain.java | UTF-8 | 707 | 2.890625 | 3 | [] | no_license | package com.kundy.cranberry.javabasis.multithread.lock;
/**
* @author kundy
* @date 2020/7/21 6:55 PM
*/
public class TestReentrantLockMain {
public static void main(String[] args) {
ReentrantLockThread reentrantLockThread = new ReentrantLockThread("ReentrantLock测试对象1");
ReentrantLockThread reentrantLockThread2= new ReentrantLockThread("ReentrantLock测试对象2");
for (int i = 0; i < 10; i++) {
new Thread(()->{
reentrantLockThread.add();
}).start();
}
for (int i = 0; i < 10; i++) {
new Thread(()->{
reentrantLockThread2.add();
}).start();
}
}
}
| true |
b732ff15b0ad9d69695c5a8868ccc6356c58278f | Java | majbe/JavaDeluppgiftNote | /src/Note.java | UTF-8 | 1,618 | 3.375 | 3 | [] | no_license |
/**
*
* @author MikaelBergstrom
*/
public class Note {
//Deklarerar variabler
private String heading;
private String text;
private String signed;
private int numberOfChars;
private int numberOfWords;
private int priceClass;
public Note(String rubrik, String notistext, String underskrift) {
//Konstruktor for rubrik, notistext och underskrift
heading = rubrik;
text = notistext;
signed = underskrift;
numberOfWords = text.split(" ").length;
numberOfChars = text.length();
numberOfChars += (heading.length() + signed.length());
}
//Metod for att returnera notisens rubrik
public String getHeading()
{
return heading;
}
//Metod for att returnera notisens text
public String getText()
{
return text;
}
//Metod for att returnera notisens forfattare
public String getSigned()
{
return signed;
}
//Metod for att returnera antalet ord
public int getNumberOfWords()
{
return numberOfWords;
}
//Metod for att returnera antalet karaktarer
public int getNumberOfChars()
{
return numberOfChars;
}
//Metod for att returnera vilken prisklass texten hamnar i
public int getPriceClass()
{
if(numberOfChars >= 500)
{
priceClass = 3;
}
else if(numberOfChars <500 && numberOfChars >= 250)
{
priceClass = 2;
}
else if(numberOfChars < 250)
{
priceClass = 1;
}
return priceClass;
}
}
| true |
90f01b4682dc16d234fce1ca3679b5b8e9cce00f | Java | TheCahyag/BL4DEToys | /src/main/java/com/servegame/bl4de/BL4DEToys/EventHandlers/AbstractEventHandler.java | UTF-8 | 373 | 2.09375 | 2 | [] | no_license | package com.servegame.bl4de.BL4DEToys.EventHandlers;
import org.spongepowered.api.event.Event;
/**
* File: AbstractEventHandler.java
* @author Brandon Bires-Navel (brandonnavel@outlook.com)
*/
public interface AbstractEventHandler {
/* A purpose for this file hasn't been found yet,
I hope to use some kind of inheritance tho */
String toString();
void handle(Event event);
}
| true |
96d7160d00ff96c67985dcb571c25dde702b929e | Java | s19110/MASprojekt_koncowy | /src/GUI/DyrektorProblemyPanel.java | UTF-8 | 1,988 | 2.984375 | 3 | [] | no_license | package GUI;
import Controller.ProblemController;
import Controller.ProblemyDyrektorTableModel;
import Model.Nauczyciel;
import Model.Problem;
import Utils.WindowUtils;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Klasa zarządzająca oknem z listą problemów przekazaną wybranemu dyrektorowi
*/
public class DyrektorProblemyPanel {
public JPanel rootPanel;
private JTable problemyTable;
private JButton wybierzButton;
private JButton anulujButton;
private Nauczyciel wybranyDyrektor;
private ProblemyDyrektorTableModel tableModel;
public DyrektorProblemyPanel(Nauczyciel wybranyDyrektor){
this.wybranyDyrektor = wybranyDyrektor;
wybierzButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = problemyTable.getSelectedRow();
if(row >= 0){
otworzOknoSzczegolowProblemu(tableModel.getProblem(row));
}
}
});
anulujButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WindowUtils.disposeWindow(rootPanel);
}
});
}
private void createUIComponents() {
tableModel = new ProblemyDyrektorTableModel(ProblemController.getProblemy(wybranyDyrektor));
problemyTable = new JTable(tableModel);
problemyTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
/**
* Metoda otwierająca okno ze szczegółami wybranego problemu - dla dyrektora
* @param problem - problem wybrany z listy
*/
private void otworzOknoSzczegolowProblemu(Problem problem){
SwingUtilities.getWindowAncestor(rootPanel).dispose();
WindowUtils.createWindow("Problem",new ProblemDyrektorSzczegolyPanel(problem).rootPanel,JFrame.DISPOSE_ON_CLOSE);
}
}
| true |
93d6b5adc659d9a27b523d15513baa526c14c80e | Java | Dawidjuve/OCA_Exam | /src/chapter4/lambda/LambdaSearching.java | WINDOWS-1250 | 2,026 | 3.984375 | 4 | [] | no_license | package chapter4.lambda;
import java.util.ArrayList;
import java.util.List;
public class LambdaSearching {
public LambdaSearching() {
}
public static void main(String[] args) {
List<Animal> animals = new ArrayList<Animal>(); // list of animals
animals.add(new Animal("fish", false, true));
animals.add(new Animal("kangaroo", true, false));
animals.add(new Animal("rabbit", true, false));
animals.add(new Animal("turtle", false, true));
print(animals, a -> a.canHop());
print(animals, (a) -> {
return a.canHop();
});
print(animals, (a) -> a.canHop());
// print(animals, (a)-> { a.canHop();});
// print(animals, (a)-> return a.canHop(););
// print(animals, (a)-> a.canHop(););
print(animals, (a) -> {
System.out.println();
return a.canHop();
});
// Predicate & removeIf()
List<String> bunnies = new ArrayList<>();
bunnies.add("long ear");
bunnies.add("floppy");
bunnies.add("hoppy");
System.out.println(bunnies); // [long ear, floppy, hoppy]
bunnies.removeIf(s -> s.charAt(0) != 'h');
System.out.println(bunnies); // [hoppy]
}
public static void print(List<Animal> animals, CheckTrait x) {
for (Animal animal : animals) {
if (x.test(animal)) {
System.out.println(animal);
}
}
}
}
//Przykady poprawnych zapisw wyraenia lambda
//3: print(() -> true); // 0 parameters
//4: print(a -> a.startsWith("test")); // 1 parameter
//5: print((String a) -> a.startsWith("test")); // 1 parameter
//6: print((a, b) -> a.startsWith("test")); // 2 parameters
//7: print((String a, String b) -> a.startsWith("test")); // 2 parameters
//Przykady zych zapisw wyraenia lambda
//print(a, b -> a.startsWith("test")); // DOES NOT COMPILE
//print(a -> { a.startsWith("test"); }); // DOES NOT COMPILE
//print(a -> { return a.startsWith("test") }); // DOES NOT COMPILE
//Nie mona przeprowadza ponownej deklaracji zmiennej w ciele wyraenia lambda
//(a, b) -> { int a = 0; return 5;} // DOES NOT COMPILE
//(a, b) -> { int c = 0; return 5;} // COMPILE | true |
3ac53326d334005cc105888665a6e0a41e115df8 | Java | mhtpky/javaadvancehours | /src/day06_04april/Question05_Exception.java | UTF-8 | 531 | 2.765625 | 3 | [] | no_license | package day06_04april;
public class Question05_Exception {
public static void main(String[] args) {
/*
Motor isminde bir degisken olusturun ve sonra ki satirda
yine ayni isimde bir degisken olusturmaya calisin ve
eger bir hata alirsajiz bu hatayi handle edin
*/
/*String motor = " Ferrari motoru";
try {
String motor = "Tesla motoru"; // Ayni isimli 2. bir degisken olusturamayiz ve bunu Exception ile cozmemiz mumkun degildir
} catch (Exception e) {
e.printStackTrace();
}
*/
}
}
| true |
3968f826a4421f3ef2bc82e4b05e7f288c8f54e8 | Java | healthy183/springBoot | /spring_boot_freemarker/src/main/java/com/kang/boot/study/run/Application.java | UTF-8 | 1,139 | 1.914063 | 2 | [] | no_license | package com.kang.boot.study.run;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
@ComponentScan("com.kang")
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
private static class CustomizedContainer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/test404.ftl"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/testError.ftl"));
}
}
}
| true |
47053d98958888e063979e813fd41e78a68752f5 | Java | sayymon/CertificacaoOCJP | /src/br/certificacao/ocjp6/declaracaoInicializacaoEscopo/Arrays.java | ISO-8859-1 | 964 | 3.125 | 3 | [] | no_license | package br.certificacao.ocjp6.declaracaoInicializacaoEscopo;
/**
* <h1>Arrays</h1><br/>
* Arrays podem ser dos tipos (primitivos,Referencia ou arrays de arrays(Matrizes))
* <br/>
* <br/>
* Java verifica as posies a serem acessadas no array. caso seja feita referencia a uma posio invalida retornada a exceo ArrayIndexOfBounds
* Arrays so inicializados com os valores default :<br/>
* boolean = false;<br/>
* byte = 0;<br/>
* short = 0;<br/>
* int = 0;<br/>
* long = 0;<br/>
* float = 0;<br/>
* double = 0;<br/>
* char = '\u0000';<br/>
* Tipo Referencia = null;
*
* @author Saymon
*
*/
public class Arrays {
byte[] arrayBytes = new byte[126];
int[] arrayInteiros = {1,2,3,4,5,6};
public void acessandoPosicaoInvalida() throws ArrayIndexOutOfBoundsException{
for (byte i = 0; i <= 125; i++) {
arrayBytes[i] = i;
}
}
Double[][] arrayBidimensional = new Double[5][3];
}
| true |
3fe386ac4159d4ed141bafbef4c439f61d1a9e12 | Java | langwan1314/map_server | /map-mobile/src/main/java/com/youngo/mobile/controller/location/GoogleLocationHandler.java | UTF-8 | 3,617 | 2.40625 | 2 | [] | no_license | package com.youngo.mobile.controller.location;
import java.io.IOException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youngo.mobile.model.paperPlane.Address;
import com.youngo.mobile.model.paperPlane.AddressComponent;
import com.youngo.mobile.model.paperPlane.GoogleLocation;
import com.youngo.mobile.model.paperPlane.GoogleLocation.LocationType;
import com.youngo.mobile.model.paperPlane.GoogleLocationResult;
import com.youngo.mobile.model.paperPlane.GoogleLocationResult.GoogleLocationStatus;
public class GoogleLocationHandler implements ResponseHandler<Address> {
private ObjectMapper objectMapper = new ObjectMapper();//线程安全 但是否造成多线程竞争资源,需要考虑,能否避免资源竞争。
@Override
public Address handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
final StatusLine statusLine = response.getStatusLine();
final HttpEntity entity = response.getEntity();
try{
if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 400) {
//400是全局参数异常 按理来说正确的配置不会产生400错误
if (entity == null)
return null;
else{
byte[] bytes = EntityUtils.toByteArray(entity);
if(null != bytes){
String s = new String(bytes);
// System.out.println(s);
GoogleLocationResult result = this.objectMapper.readValue(bytes, 0, bytes.length, GoogleLocationResult.class);
if(GoogleLocationStatus.OK.name().equals(result.getStatus())){
GoogleLocation location = result.getResults().get(0);
List<AddressComponent> components = location.getAddress_components();
Address address = getAddress(components);
return address;
}
}
}
}else if(statusLine.getStatusCode() == 403){
//用户没有权限访问google接口,可能原因为tk失效或者 google改变tk策略。
//TODO
return null;
}else{
System.out.println(statusLine.getStatusCode());
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
}finally{
EntityUtils.consume(entity);
}
return null;
}
private Address getAddress(List<AddressComponent> components){
Address address = null;
if(null != components){
address = new Address();
String country = null;
String city = null;
String administrativeAreaLevel1 = null;
for(int i = 0, j = components.size(); i < j; i++){
AddressComponent component = components.get(i);
List<String> types = component.getTypes();
if(types.contains(LocationType.locality.name())){
city = component.getLong_name();
}else if(types.contains(LocationType.country.name())){
country = component.getLong_name();
}else if(types.contains(LocationType.administrative_area_level_1.name())){
administrativeAreaLevel1 = component.getLong_name();
}
if(null!= country && null != city){
break;
}
}
address.setCountry(country);
address.setCity(city == null ? administrativeAreaLevel1 : city);
}
return address;
}
}
| true |
2f31b19a1e9144732980233e477e4e357f6a101a | Java | Catfeeds/rog-backend | /src/main/java/com/rograndec/feijiayun/chain/business/goods/sale/controller/SpecialPriceStrategyController.java | UTF-8 | 8,076 | 2.109375 | 2 | [] | no_license | package com.rograndec.feijiayun.chain.business.goods.sale.controller;
import com.rograndec.feijiayun.chain.business.goods.sale.service.SpecialPriceStrategyService;
import com.rograndec.feijiayun.chain.business.goods.sale.vo.SpecialPriceStrategyVO;
import com.rograndec.feijiayun.chain.common.Result;
import com.rograndec.feijiayun.chain.common.SysCode;
import com.rograndec.feijiayun.chain.common.vo.UserVO;
import com.rograndec.feijiayun.chain.utils.string.ChineseString;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* Created by madong on 2017/9/5.
*/
@Api(value = "goods_sale_special", description = "商品管理-销售管理-特价设置服务接口", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/goods/sale/special")
@Validated
public class SpecialPriceStrategyController {
private static final Log logger = LogFactory.getLog(SpecialPriceStrategyController.class);
@Autowired
SpecialPriceStrategyService specialPriceStrategyService;
@ApiOperation(value="保存特价设置", notes = "保存特价设置 | 开发者:马东 | 已联调", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/saveSpecialPrice", method = RequestMethod.POST)
@ResponseBody
public Result saveSpecialPrice(HttpServletRequest request,
@ApiParam(value = "特价设置信息",required = true) @RequestBody SpecialPriceStrategyVO specialPriceStrategyVO){
Result result = new Result<>();
try{
HttpSession session = request.getSession(true);
UserVO loginUser = (UserVO) session.getAttribute("user");
if(StringUtils.isBlank(specialPriceStrategyVO.getCode())){
result.setBizCodeFallInfo(SysCode.FAIL.getCode(),"特价设置编码不能为空!");
return result;
}else if(ChineseString.isChinese(specialPriceStrategyVO.getCode())){
result.setBizCodeFallInfo(SysCode.FAIL.getCode(),"特价设置编码不能输入中文!");
return result;
}
specialPriceStrategyService.saveSpecialPrice(specialPriceStrategyVO,loginUser);
result.setBizCodeSuccessInfo(SysCode.SUCCESS, "保存特价设置成功!");
}catch(Exception e){
logger.error("保存特价设置错误:"+e.getMessage(),e);
result.setBizCodeFallInfo(SysCode.FAIL,e.getMessage());
return result;
}
return result;
}
@ApiOperation(value="修改特价设置", notes = "修改特价设置 | 开发者:马东 | 已联调", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/updateSpecialPrice", method = RequestMethod.POST)
@ResponseBody
public Result updateSpecialPrice(HttpServletRequest request,
@ApiParam(value = "特价设置信息",required = true) @RequestBody SpecialPriceStrategyVO specialPriceStrategyVO){
Result result = new Result<>();
try{
HttpSession session = request.getSession(true);
UserVO loginUser = (UserVO) session.getAttribute("user");
specialPriceStrategyService.updateSpecialPrice(specialPriceStrategyVO, loginUser);
result.setBizCodeSuccessInfo(SysCode.SUCCESS, "修改特价设置成功!");
}catch(Exception e){
logger.error("修改特价设置错误:"+e.getMessage(),e);
result.setBizCodeFallInfo(SysCode.FAIL,e.getMessage());
return result;
}
return result;
}
@ApiOperation(value="删除特价设置", notes = "删除特价设置 | 开发者:马东 | 已联调", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/deleteSpecialPrice", method = RequestMethod.GET)
@ResponseBody
public Result<String> deleteSpecialPrice(HttpServletRequest request,
@ApiParam(value = "需要删除的特价设置信息id",required = true) @RequestParam Long id){
Result<String> result = new Result<>();
try{
HttpSession session = request.getSession(true);
UserVO loginUser = (UserVO) session.getAttribute("user");
if(specialPriceStrategyService.canDeleteSpecialPrice(id, loginUser)){
int count = specialPriceStrategyService.deleteSpecialPrice(id, loginUser);
if(count == 0)
result.setBizCodeFallInfo(SysCode.FAIL.getCode(), "该特价设置已经不再系统中!");
else
result.setBizCodeSuccessInfo(SysCode.SUCCESS, "删除特价设置成功!");
}else {
result.setBizCodeFallInfo(SysCode.FAIL.getCode(), "该特价设置已管理商品,不能删除!");
}
}catch(Exception e){
logger.error("删除特价设置错误:"+e.getMessage(),e);
result.setBizCodeFallInfo(SysCode.FAIL);
return result;
}
return result;
}
@ApiOperation(value="获取所有特价设置", notes = "获取所有特价设置 | 开发者:马东 | 已联调", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/getSpecialPrice", method = RequestMethod.GET)
@ResponseBody
public Result<List<SpecialPriceStrategyVO>> getSpecialPrice(HttpServletRequest request,
@ApiParam(value = "待排序字段",required = false) @RequestParam(required = false) String orderName,
@ApiParam(value = "排序方式 升序ASC,降序DESC",required = false) @RequestParam(required = false) String orderType){
Result<List<SpecialPriceStrategyVO>> result = new Result<>();
try{
HttpSession session = request.getSession(true);
UserVO loginUser = (UserVO) session.getAttribute("user");
List<SpecialPriceStrategyVO> specialPriceStrategyVOList = specialPriceStrategyService.getSpecialPrice(loginUser,orderName,orderType);
result.setBizCodeSuccessInfo(SysCode.SUCCESS, specialPriceStrategyVOList);
}catch(Exception e){
logger.error("删除特价设置错误:"+e.getMessage(),e);
result.setBizCodeFallInfo(SysCode.FAIL);
return result;
}
return result;
}
@ApiOperation(value="检查特价设置编码是否重复", notes = "检查特价设置编码是否重复 | 开发者:马东 | 已联调", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/checkExistsCode", method = RequestMethod.GET)
@ResponseBody
public Result<String> checkExistsCode(HttpServletRequest request,
@ApiParam(value = "待检查编码",required = true) @RequestParam String code){
Result<String> result = new Result<>();
try{
HttpSession session = request.getSession(true);
UserVO loginUser = (UserVO) session.getAttribute("user");
Long count = specialPriceStrategyService.checkExistsCode(loginUser,code);
if(count.equals(0l))
result.setBizCodeSuccessInfo(SysCode.SUCCESS, "检查通过");
else
result.setBizCodeFallInfo(SysCode.FAIL.getCode(),"该编码已经存在,请重新输入!");
}catch(Exception e){
logger.error("检查特价设置编码是否重复:"+e.getMessage(),e);
result.setBizCodeFallInfo(SysCode.FAIL);
return result;
}
return result;
}
}
| true |
9d6d6a52ad78ea4161d3fdd76dc6108954be54d8 | Java | LukaszP12/HibernateAssociationsDemo1 | /src/main/java/CascadeRemoveApp.java | UTF-8 | 1,251 | 2.53125 | 3 | [] | no_license | import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import pl.strefakursow.entity.Company;
import pl.strefakursow.entity.CompanyDetail;
public class CascadeRemoveApp {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Company.class);
configuration.addAnnotatedClass(CompanyDetail.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session currentSession = sessionFactory.getCurrentSession();
currentSession.beginTransaction();
Company company = currentSession.get(Company.class, 48);
currentSession.remove(company);
// currentSession.refresh(); refresh() causes the data from DataBase to be read again into the object
// currentSession.detach(); if we detach the parent object from the session, then the child object also gets detached
// currentSession.merge(); if we add the parent object to the session, then the child object also gets merged
currentSession.getTransaction().commit();
sessionFactory.close();
}
}
| true |
abb2a80538eefd0eeb158f40885ab5db71c1f14a | Java | whatawurst/OpenCustomizationSelector | /src/com/sonymobile/customizationselector/CustomizationSelectorService.java | UTF-8 | 3,528 | 1.914063 | 2 | [] | no_license | package com.sonymobile.customizationselector;
import android.app.IntentService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.UserManager;
import android.provider.Settings.Secure;
public class CustomizationSelectorService extends IntentService {
private static final String TAG = CustomizationSelectorService.class.getSimpleName();
private static final String EVALUATE_ACTION = "evaluate_action";
public CustomizationSelectorService() {
super(CustomizationSelectorService.class.getName());
}
public static void evaluateCarrierBundle(Context context) {
synchronized (CustomizationSelectorService.class) {
try {
CSLog.logVersion(context, TAG);
CSLog.logSimValues(context, TAG);
if (!CommonUtil.isDirectBootEnabled()) {
UserManager userManager = context.getSystemService(UserManager.class);
if (userManager != null && !userManager.isUserUnlocked()) {
CSLog.d(TAG, "user is locked. private app data storage is not available.");
return;
}
}
Configurator configurator = new Configurator(context, CommonUtil.getCarrierBundle(context));
if (configurator.isNewConfigurationNeeded()) {
context.getPackageManager().setComponentEnabledSetting(new ComponentName(context, CustomizationSelectorActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
if (isUserSetupComplete(context)) {
CSLog.d(TAG, "isNewConfigurationNeeded - Need to reboot, starting dialog.");
context.startActivity(new Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_HOME).addFlags(270565376));
} else {
CSLog.d(TAG, "isNewConfigurationNeeded - Need to reboot, user setup not complete");
}
} else {
configurator.saveConfigurationKey();
CSLog.d(TAG, "isNewConfigurationNeeded - No new configuration.");
if (configurator.isFirstApply()) {
context.getPackageManager().setComponentEnabledSetting(new ComponentName(context, CustomizationSelectorActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
if (isUserSetupComplete(context)) {
context.startActivity(new Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_HOME).addFlags(270565376));
}
} else {
configurator.reApplyModem();
}
}
} catch (Exception e) {
CSLog.e(TAG, "evaluateCarrierBundle - ERROR: ", e);
}
}
}
private static boolean isUserSetupComplete(Context context) {
return Secure.getInt(context.getContentResolver(), Secure.USER_SETUP_COMPLETE, 0) != 0;
}
@Override
protected void onHandleIntent(Intent intent) {
if (EVALUATE_ACTION.equals(intent != null ? intent.getAction() : "")) {
evaluateCarrierBundle(this);
}
}
}
| true |
83e0a4d5fb3f9283c66d12657bc61993984329cb | Java | Guzalinuer822/JavaStudyByGuzal | /src/day39_finalKeyword/FinalMethods.java | UTF-8 | 815 | 4.21875 | 4 | [] | no_license | package day39_finalKeyword;
public class FinalMethods {
public void method1() {
System.out.println("Method 1");
}
public static void staticMethod(String word) {
System.out.println("Static Method");
}
}
class Sub extends FinalMethods{
@Override
public void method1() {
System.out.println("Method 1 in sub class");
}
//overload
public void method1(int x) {}
/* this overloading , we don't care return type,
* but this will give error
*
* public int method1(int x){
* }
*
* because i didn't write inside return keyword , i have to return int
*
* public int method1(int x){
*
* return x; // have to return, have to write something
* }
*
*/
public static void staticMethod(String word) {
System.out.println("Static Method in sub class");
}
} | true |
095c3272da555e6c9bce5d70d4caa5f13c62b7c8 | Java | mARk-LzZ/LzZ | /task2/multithreading.java | UTF-8 | 3,093 | 3.328125 | 3 | [] | no_license | package 第二次考核.task2;
import java.util.Scanner;
import java.util.concurrent.*;
public class multithreading {
public static void main(String[] args) throws ExecutionException, InterruptedException {
long begin=0 ;
long end=100000000 ;
//创建10个线程
thread callable1 = new thread(begin,end);
thread callable2 = new thread((end-begin) , end*2);
thread callable3 = new thread((end-begin)*2 , end*3);
thread callable4 = new thread((end-begin)*3 , end*4);
thread callable5 = new thread((end-begin)*4 , end*5);
thread callable6 = new thread((end-begin)*5 , end*6);
thread callable7 = new thread((end-begin)*6 , end*7);
thread callable8 = new thread((end-begin)*7 , end*8);
thread callable9 = new thread((end-begin)*8 , end*9);
thread callable10 = new thread((end-begin)*9 , end*10);
//接收10个线程传回来的futrue对象
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Long> future1 = executorService.submit(callable1);
Future<Long> future2 = executorService.submit(callable2);
Future<Long> future3 = executorService.submit(callable3);
Future<Long> future4 = executorService.submit(callable4);
Future<Long> future5 = executorService.submit(callable5);
Future<Long> future6 = executorService.submit(callable6);
Future<Long> future7 = executorService.submit(callable7);
Future<Long> future8 = executorService.submit(callable8);
Future<Long> future9 = executorService.submit(callable9);
Future<Long> future10 = executorService.submit(callable10);
//获取futrue的结果
long result1 = future1.get();
long result2 = future2.get();
long result3 = future3.get();
long result4 = future4.get();
long result5 = future5.get();
long result6 = future6.get();
long result7 = future7.get();
long result8 = future8.get();
long result9 = future9.get();
long result10 = future10.get();
long result = result1 + result2 +result3+result4+result5+result6+result7+result8+result9+result10;
System.out.println("result =" + result);
}
}
class thread implements Callable<Long> {
long begin ;
long end ;
long ans=0;
static Scanner scanner=new Scanner(System.in);
static int x=scanner.nextInt();
public thread(long begin, long end) {
this.begin=begin;
this.end=end;
}
@Override
public synchronized Long call() {
System.out.println("begin " + begin + " end " + end);
for (long i=begin; i < end; i++) {
if (contain(i, x)) ans+=i;
}
System.out.println("callable" + (end/100000000) + "'s result= " + ans);
return ans;
}
private static boolean contain ( long num, int x){
return String.valueOf(num).contains(String.valueOf(x));
}
}
| true |
bd4f19c9445cafe6f15025ced0012c5199e1b54f | Java | PabloValdivia/org.idempiere.pos | /src/org/adempiere/pos/command/CommandReverseSalesTransaction.java | UTF-8 | 3,096 | 1.765625 | 2 | [] | no_license | /** ****************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Copyright (C) 2003-2016 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
* ****************************************************************************/
package org.adempiere.pos.command;
import org.adempiere.pos.process.ReverseTheSalesTransaction;
import org.compiere.process.ProcessInfo;
import org.compiere.util.Trx;
import org.compiere.util.TrxRunnable;
import org.eevolution.service.dsl.ProcessBuilder;
/**
* Execute reversal sales transaction command
* eEvolution author Victor Perez <victor.perez@e-evolution.com>, Created by e-Evolution on 23/01/16.
*
* @contributor Ing. Victor Suarez - victor.suarez.is@gmail.com
* - Migration POS from ADempiere 3.9.0 to iDempiere ERP Plugin.
*/
public class CommandReverseSalesTransaction extends CommandAbstract implements Command {
public CommandReverseSalesTransaction(String command, String actionCommand) {
super.command = command;
super.event = actionCommand;
}
@Override
public void execute(CommandReceiver commandReceiver) {
Trx.run(new TrxRunnable() {
public void run(String trxName) {
//Reverse The Sales Transaction for Source Order
ProcessInfo processInfo = new ProcessInfo(commandReceiver.getEvent(), commandReceiver.getProcessId());
processInfo = ProcessBuilder
.create(commandReceiver.getCtx())
.process(processInfo.getAD_Process_ID())
.withTitle(processInfo.getTitle())
.withParameter(ReverseTheSalesTransaction.C_Order_ID, commandReceiver.getOrderId())
.withParameter(ReverseTheSalesTransaction.Bill_BPartner_ID, commandReceiver.getPartnerId())
.withParameter(ReverseTheSalesTransaction.IsCancelled, true)
.withParameter(ReverseTheSalesTransaction.IsShipConfirm, true)
.withoutTransactionClose()
.execute(trxName);
commandReceiver.setProcessInfo(processInfo);
}
});
}
}
| true |
f0490fae58068625c929ac9e12cfc69bc00a1d6c | Java | JohanAdam/Dagger2-Retrofit-Mvp | /app/src/main/java/io/reciteapp/recite/di/module/MainActivityModule.java | UTF-8 | 732 | 2.03125 | 2 | [] | no_license | package io.reciteapp.recite.di.module;
import dagger.Module;
import dagger.Provides;
import io.reciteapp.recite.data.sharedpref.SharedPreferencesManager;
import io.reciteapp.recite.di.scope.PerActivity;
import io.reciteapp.recite.main.MainContract;
import io.reciteapp.recite.main.MainDataManager;
import io.reciteapp.recite.main.MainPresenter;
@Module
public class MainActivityModule {
@Provides
@PerActivity
public MainContract.Model provideMainModel(SharedPreferencesManager sharedPreferencesManagerV) {
return new MainDataManager(sharedPreferencesManagerV);
}
@Provides
@PerActivity
public MainContract.Presenter provideMainPresenter(MainContract.Model model) {
return new MainPresenter(model);
}
}
| true |
10aff46b11a3db82a1f6e5ed029d7ac2fb3d2b58 | Java | mingtiandejiyi/HttpHelper | /src/main/java/com/zp/HttpHelper/HttpHelper.java | UTF-8 | 8,672 | 2.484375 | 2 | [
"MIT"
] | permissive | package com.zp.HttpHelper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.zp.HttpHelper.cache.CacheManager;
public class HttpHelper {
private static Logger logger = Logger.getLogger(HttpHelper.class);
private static final String CHARSET_UTF8 = "UTF-8";
@SuppressWarnings("unused")
private static final String CHARSET_GBK = "GBK";
// cache开关,true则开启自身缓存
private static CloseableHttpClient httpClient;
private boolean cacheswitch = false;
//懒汉式单例
private static HttpHelper instance = new HttpHelper();
private CacheManager cacheManager = CacheManager.getInstance();
Header[] cookieheaders = new Header[] {};
public CloseableHttpClient getHttpClient(){
return httpClient;
}
//私有构造函数,单例
private HttpHelper() {
httpClient = getCloseableHttpClient();
}
//缓存是否打开
public boolean isCacheing() {
return cacheswitch;
}
//打开缓存
public void openCache() {
cacheswitch = true;
}
//关闭缓存
public void stopCache() {
cacheswitch = false;
}
//对外开放的获取类的单独实例的接口
public static HttpHelper getHelper() {
return instance;
}
//设置cache保存时间,超时则刷新
public void setCacheAlivetime(long sec) {
if (cacheswitch) {
cacheManager.setAliveTime(sec);
}
}
/**
* 根据传入参数设置cookie
*
* @param url
* @param paramsMap
* @param charset
* @return
* @throws IOException
*/
public void getCookie(String url, Map<String, String> paramsMap,
String charset) throws IOException {
if (url == null || url.isEmpty()) {
return;
}
// 如果传入编码则使用传入的编码,否则utf8
charset = (charset == null ? CHARSET_UTF8 : charset);
// 将map转成List<NameValuePair>
List<NameValuePair> params = getParamsList(paramsMap);
UrlEncodedFormEntity entity = null;
HttpPost post = null;
CloseableHttpResponse response = null;
try {
entity = new UrlEncodedFormEntity(params, charset);
post = new HttpPost(url);
// 设置post的参数
post.setEntity(entity);
response = httpClient.execute(post);
// 保存response的名称为Set-Cookie的headers
cookieheaders = response.getHeaders("Set-Cookie");
// cookie = set_cookie.substring(0, set_cookie.indexOf(";"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
}
return;
}
public void setCookies(Header[] headers){
cookieheaders=headers;
}
/**
* get方法,参数需自己构建到url中,如果需要cookie则用getcookie方法设置
*
* @param url
* 地址
* @param charset
* 默认utf8,可为空
* @return
* @throws IOException
*/
public String get(String url, String charset) throws IOException {
if (url == null || url.isEmpty()) {
return null;
}
// 如果缓存中有,则直接取出并返回
if (cacheswitch == true) {
Object cacheObj = cacheManager.get(url);
if (cacheObj != null) {
return (String) cacheObj;
}
}
charset = (charset == null ? CHARSET_UTF8 : charset);
HttpGet get = new HttpGet(url);
if (cookieheaders != null && cookieheaders.length > 0) {
for (Header header : cookieheaders) {
get.addHeader(header);
}
}
CloseableHttpResponse response = null;
String res = null;
try {
response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
logger.info("GET:" + url);
res = EntityUtils.toString(entity, charset);
// 放入缓存
if (cacheswitch) {
cacheManager.put(url, res);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
}
return res;
}
/**
* 对应cookie是单独设置的网站,通过某些办法把cookie的头信息提取出来,然后传到这里
* @param url
* @param charset
* @param cookie
* @return
* @throws IOException
*/
public String get(String url, String charset, String cookie) throws IOException {
if (url == null || url.isEmpty()) {
return null;
}
// 如果缓存中有,则直接取出并返回
if (cacheswitch == true) {
Object cacheObj = cacheManager.get(url);
if (cacheObj != null) {
return (String) cacheObj;
}
}
charset = (charset == null ? CHARSET_UTF8 : charset);
HttpGet get = new HttpGet(url);
if (cookieheaders != null && cookieheaders.length > 0) {
for (Header header : cookieheaders) {
get.addHeader(header);
}
}
get.addHeader("cookie", cookie);
CloseableHttpResponse response = null;
String res = null;
try {
response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
logger.info("GET:" + url);
res = EntityUtils.toString(entity, charset);
// 放入缓存
if (cacheswitch) {
cacheManager.put(url, res);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
}
return res;
}
/**
* 只传一个网址的get
*
* @param url
* @return
* @throws IOException
*/
public String get(String url) throws IOException {
return get(url, null);
}
public String post(String url, Map<String, String> map) throws IOException {
return post(url, map, null);
}
/**
* post方法,如果需要cookie则用getcookie方法设置
*
* @param url
* @param paramsMap
* @param charset
* @return
* @throws IOException
*/
public String post(String url, Map<String, String> paramsMap, String charset)
throws IOException {
if (url == null || url.isEmpty()) {
return null;
}
List<NameValuePair> params = getParamsList(paramsMap);
UrlEncodedFormEntity formEntity = null;
HttpPost post = null;
CloseableHttpResponse response = null;
String res = null;
try {
charset = (charset == null ? CHARSET_UTF8 : charset);
formEntity = new UrlEncodedFormEntity(params, charset);
post = new HttpPost(url);
post.setEntity(formEntity);
if (cookieheaders != null && cookieheaders.length > 0) {
for (Header header : cookieheaders) {
post.addHeader(header);
}
}
response = httpClient.execute(post);
res = EntityUtils.toString(response.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
}
return res;
}
/**
* 获取httpclien,关于httpclient的设置可以在这里进行
*
* @param charset
* @return
*/
private CloseableHttpClient getCloseableHttpClient() {
CloseableHttpClient httpclient = HttpClients.createDefault();
return httpclient;
}
public void closeClient() throws IOException {
httpClient.close();
}
/**
* 将传入的键/值对参数转换为NameValuePair参数集
*
* @param paramsMap
* 参数集, 键/值对
* @return NameValuePair参数集
*/
private List<NameValuePair> getParamsList(Map<String, String> paramsMap) {
if (paramsMap == null || paramsMap.size() == 0) {
return new ArrayList<NameValuePair>();
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> map : paramsMap.entrySet()) {
params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
}
if(params==null){
return new ArrayList<NameValuePair>();
}
return params;
}
}
| true |
ac629477c5c5bec20f8fb153f278b960aa61b0b1 | Java | deepsharma951/adEsale | /src/main/java/com/org/abde/service/LoginService.java | UTF-8 | 304 | 1.914063 | 2 | [] | no_license | package com.org.abde.service;
import java.util.List;
import com.org.abde.beans.User;
public interface LoginService {
List<User> listAllUser();
long saveOrUpdate(User user);
User findUserByID(int id);
void deleteUser(long id);
User findByusername(String username, String password);
}
| true |
1e7ebe9b7f4525f2370b18a58a57a0fab6c1eea2 | Java | lalabib/a14-android-fundamental-labs | /navigation/LatihanNavigationComponent/java/app/src/main/java/com/dicoding/picodiploma/mynavigation/DetailCategoryFragment.java | UTF-8 | 1,899 | 2.125 | 2 | [] | no_license | package com.dicoding.picodiploma.mynavigation;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class DetailCategoryFragment extends Fragment {
public DetailCategoryFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail_category, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView tvCategoryName = view.findViewById(R.id.tv_category_name);
TextView tvCategoryDescription = view.findViewById(R.id.tv_category_description);
// String dataName = getArguments().getString(CategoryFragment.EXTRA_NAME);
// long dataDescription = getArguments().getLong(CategoryFragment.EXTRA_STOCK);
String dataName = DetailCategoryFragmentArgs.fromBundle(getArguments()).getName();
Long dataDescription = DetailCategoryFragmentArgs.fromBundle(getArguments()).getStock();
tvCategoryName.setText(dataName);
tvCategoryDescription.setText("Stock : "+dataDescription);
Button btnProfile = view.findViewById(R.id.btn_profile);
btnProfile.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.action_detailCategoryFragment_to_homeFragment, null)
);
}
}
| true |
ac1ff312538bb2a98e10068137d1453c9ff384dd | Java | alexbajzat/nature-escape-android | /app/src/main/java/com/bjz/naturescape/service/LoginService.java | UTF-8 | 340 | 1.90625 | 2 | [] | no_license | package com.bjz.naturescape.service;
import com.bjz.naturescape.model.request.LoginRequest;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
/**
* Created by bjz on 10/23/2017.
*/
public interface LoginService {
@POST(value = "/login")
Call<Void> loginAccount(@Body LoginRequest loginRequest);
}
| true |
12dc52464163cde142e1ba523d23d41fb06609bb | Java | mdatsev/elsys_homeworks | /oop/oop2017-2018/practice/07-postfix-calculator/test/org/elsys/postfix/DuplicateTest.java | UTF-8 | 493 | 2.328125 | 2 | [
"Unlicense"
] | permissive | package org.elsys.postfix;
import org.junit.Test;
public class DuplicateTest extends CalculatorAbstractTest {
@Test
public void test() {
input("10");
input("dup");
inputCtrlC();
runCalculator();
assertCalculatorLastValue(10);
assertCalculatorStackSize(2);
}
@Test
public void testDuplicateAndNegate() {
input("10");
input("dup");
input("neg");
input("dup");
inputCtrlC();
runCalculator();
assertCalculatorLastValue(-10);
assertCalculatorStackSize(3);
}
}
| true |
2049a2bd212a088bc0951f1f63eba93224269310 | Java | warchiefmarkus/WurmServerModLauncher-0.43 | /TOOLS/server/1.0/com/sun/tools/xjc/generator/unmarshaller/automaton/AutomatonToGraphViz.java | UTF-8 | 5,095 | 2.265625 | 2 | [
"IJG"
] | permissive | /* */ package 1.0.com.sun.tools.xjc.generator.unmarshaller.automaton;
/* */
/* */ import com.sun.tools.xjc.generator.unmarshaller.automaton.Alphabet;
/* */ import com.sun.tools.xjc.generator.unmarshaller.automaton.Automaton;
/* */ import com.sun.tools.xjc.generator.unmarshaller.automaton.State;
/* */ import com.sun.tools.xjc.generator.unmarshaller.automaton.Transition;
/* */ import java.io.BufferedOutputStream;
/* */ import java.io.BufferedReader;
/* */ import java.io.File;
/* */ import java.io.IOException;
/* */ import java.io.InputStreamReader;
/* */ import java.io.PrintStream;
/* */ import java.io.PrintWriter;
/* */ import java.text.MessageFormat;
/* */ import java.util.Iterator;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class AutomatonToGraphViz
/* */ {
/* 28 */ private static final PrintStream debug = null;
/* */
/* */
/* */ private static String getStateName(Automaton a, State s) {
/* 32 */ return "\"s" + a.getStateNumber(s) + (s.isListState ? "*" : "") + '"';
/* */ }
/* */
/* */
/* */
/* */ private static String getColor(Alphabet a) {
/* 38 */ if (a instanceof Alphabet.EnterElement) return "0";
/* 39 */ if (a instanceof Alphabet.EnterAttribute) return "0.125";
/* 40 */ if (a instanceof Alphabet.LeaveAttribute) return "0.25";
/* 41 */ if (a instanceof Alphabet.LeaveElement) return "0.375";
/* 42 */ if (a instanceof Alphabet.Child) return "0.5";
/* 43 */ if (a instanceof Alphabet.SuperClass) return "0.625";
/* 44 */ if (a instanceof Alphabet.External) return "0.625";
/* 45 */ if (a instanceof Alphabet.Dispatch) return "0.625";
/* 46 */ if (a instanceof Alphabet.EverythingElse) return "0.625";
/* 47 */ if (a instanceof Alphabet.Text) return "0.75";
/* 48 */ if (a instanceof Alphabet.Interleave) return "0.875";
/* 49 */ throw new InternalError(a.getClass().getName());
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static void convert(Automaton a, File target) throws IOException, InterruptedException {
/* 58 */ System.err.println("generating a graph to " + target.getPath());
/* */
/* */
/* 61 */ Process proc = Runtime.getRuntime().exec(new String[] { "dot", "-Tgif", "-o", target.getPath() });
/* */
/* 63 */ PrintWriter out = new PrintWriter(new BufferedOutputStream(proc.getOutputStream()));
/* */
/* */
/* 66 */ out.println("digraph G {");
/* 67 */ out.println("node [shape=\"circle\"];");
/* */
/* 69 */ Iterator itr = a.states();
/* 70 */ while (itr.hasNext()) {
/* 71 */ State s = itr.next();
/* 72 */ if (s.isFinalState()) {
/* 73 */ out.println(getStateName(a, s) + " [shape=\"doublecircle\"];");
/* */ }
/* 75 */ if (s.getDelegatedState() != null) {
/* 76 */ out.println(MessageFormat.format("{0} -> {1} [style=dotted];", new Object[] { getStateName(a, s), getStateName(a, s.getDelegatedState()) }));
/* */ }
/* */
/* */
/* */
/* */
/* 82 */ Iterator jtr = s.transitions();
/* 83 */ while (jtr.hasNext()) {
/* 84 */ Transition t = jtr.next();
/* */
/* 86 */ String str = MessageFormat.format("{0} -> {1} [ label=\"{2}\",color=\"{3} 1 .5\",fontcolor=\"{3} 1 .3\" ];", new Object[] { getStateName(a, s), getStateName(a, t.to), getAlphabetName(a, t.alphabet), getColor(t.alphabet) });
/* */
/* */
/* */
/* */
/* */
/* */
/* 93 */ out.println(str);
/* 94 */ if (debug != null) debug.println(str);
/* */
/* */ }
/* */ }
/* 98 */ out.println("}");
/* 99 */ out.flush();
/* 100 */ out.close();
/* */
/* 102 */ BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
/* */ while (true) {
/* 104 */ String s = in.readLine();
/* 105 */ if (s == null)
/* 106 */ break; System.out.println(s);
/* */ }
/* 108 */ in.close();
/* */
/* 110 */ proc.waitFor();
/* */ }
/* */
/* */
/* */
/* */ private static String getAlphabetName(Automaton a, Alphabet alphabet) {
/* 116 */ String s = alphabet.toString();
/* 117 */ if (alphabet instanceof Alphabet.Interleave) {
/* 118 */ s = s + " ->";
/* 119 */ Alphabet.Interleave ia = (Alphabet.Interleave)alphabet;
/* 120 */ for (int i = 0; i < ia.branches.length; i++)
/* 121 */ s = s + " " + a.getStateNumber((ia.branches[i]).initialState);
/* */ }
/* 123 */ return s;
/* */ }
/* */ }
/* Location: C:\Users\leo\Desktop\server.jar!\1.0\com\sun\tools\xjc\generato\\unmarshaller\automaton\AutomatonToGraphViz.class
* Java compiler version: 2 (46.0)
* JD-Core Version: 1.1.3
*/ | true |
4e7920cbd3d6e9bba67b407165a12e261dbafd9a | Java | yitzackRabin/Datastructures | /src/hashtable/SecondaryHash.java | UTF-8 | 195 | 1.96875 | 2 | [] | no_license | /**
* Simple interface file for double hashing
*
* @author RABIN
*/
package hashtable;
public interface SecondaryHash {
// A method for a second hash function
public int hashCode2();
}
| true |
225614cc9e8a76144edc977232306f299a38545b | Java | AnanthaRajuC/JavaConcepts | /VariableTypes/src/vtPackage/VariableTypes.java | UTF-8 | 681 | 3.625 | 4 | [
"MIT"
] | permissive | /**
* @author anantharaju
* Variable is name of reserved area allocated in memory
*/
package vtPackage;
public class VariableTypes
{
int data=50; //Instance variable - A variable that is declared inside the class but outside the method
//Instance variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is created.
static int m=100; //Static variable - A variable that is declared as static is called static variable. It cannot be local.
public static void main(String[] args)
{
int n=90; //Local variable - A variable that is declared inside the method
System.out.println(m);
System.out.println(n);
}
}
| true |
a05e2a69ae352b145af8215801ddf4ddb91f6a57 | Java | luccas-freitas/school-registration | /br/edu/ifpr/utils/validators/RgValidator.java | UTF-8 | 236 | 2.109375 | 2 | [] | no_license | package br.edu.ifpr.utils.validators;
import java.util.regex.Pattern;
public final class RgValidator {
public static boolean validateRg(final String rg) {
if(Pattern.matches("(\\d{9})", rg))
return true;
return false;
}
}
| true |
b189de4659c0e485eab495a3894110560618499e | Java | datonli/moead_spark | /src/mr_partition/MapClass.java | UTF-8 | 1,649 | 2.359375 | 2 | [] | no_license | package mr_partition;
import java.io.IOException;
import moead.MOEAD;
import mop.MopData;
import mop.MopDataPop;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import mop.AMOP;
import mop.CMOP;
import problems.AProblem;
import problems.DTLZ1;
import utilities.WrongRemindException;
import utilities.StringJoin;
public class MapClass extends MapReduceBase implements Mapper<Object, Text, Text, Text> {
private static int innerLoop = 1;
Text weightVector = new Text();
Text indivInfo = new Text();
public static void setInnerLoop(int innerLoopTime){
innerLoop = innerLoopTime;
}
public void map(Object key, Text value, OutputCollector<Text, Text> output, Reporter reporter)
throws IOException{
String paragraph = value.toString();
System.out.println("paragraph is \n" + paragraph);
int popSize = 351;
int neighbourSize = 20;
AProblem problem = DTLZ1.getInstance();
AMOP mop = CMOP.getInstance(popSize, neighbourSize, problem);
MopDataPop mopData = new MopDataPop(mop);
System.out.println("map begin ... ");
mopData.clear();
try {
mopData.line2mop(paragraph);
MOEAD.moead(mopData.mop,innerLoop);
weightVector.set("111111111");
indivInfo.set(mopData.idealPoint2Line() + "#" + StringJoin.join(",",mopData.mop.partitionArr));
output.collect(weightVector, indivInfo);
System.out.println("output collect ~!~");
for (int i = 0; i < mopData.mop.chromosomes.size(); i++) {
weightVector.set(mopData.weight2Line(i));
indivInfo.set(mopData.mop2Line(i));
output.collect(weightVector, indivInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
bd0532c9c88bb2bf2d8fdc27a2c9fcee63082c38 | Java | chrisp-cbh/FitnesseTables | /src/main/java/FileUtilities.java | UTF-8 | 754 | 3.25 | 3 | [] | no_license | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class FileUtilities {
private File theFile;
public boolean createFile(String path) throws Exception{
makeSureFileDoesntExist(path);
theFile.createNewFile();
return theFile.exists();
}
public void initialiseFileObject(String path) {
theFile = new File(path);
}
public boolean appendTextToFile(String text,String path) throws FileNotFoundException{
PrintWriter writer = new PrintWriter(path);
writer.print(text);
writer.close();
return true;
}
public boolean makeSureFileDoesntExist(String path){
initialiseFileObject(path);
if(theFile.exists()){
theFile.delete();
}
return !theFile.exists();
}
}
| true |
a12d103b641ed524d5dc7eb772d0ae9388af7544 | Java | Game-Designing/Custom-Football-Game | /sources/p005cm/aptoide/p006pt/home/apps/C3548Ja.java | UTF-8 | 493 | 1.585938 | 2 | [
"MIT"
] | permissive | package p005cm.aptoide.p006pt.home.apps;
import p026rx.p027b.C0129b;
/* renamed from: cm.aptoide.pt.home.apps.Ja */
/* compiled from: lambda */
public final /* synthetic */ class C3548Ja implements C0129b {
/* renamed from: a */
private final /* synthetic */ AppsPresenter f6930a;
public /* synthetic */ C3548Ja(AppsPresenter appsPresenter) {
this.f6930a = appsPresenter;
}
public final void call(Object obj) {
this.f6930a.mo14730a((App) obj);
}
}
| true |
d78cebe9991e6c69c3b858106f05123ac1d10a5b | Java | dharapshah/50JavaAssignments | /src/com/wbl/oops/Overloading.java | UTF-8 | 678 | 3.953125 | 4 | [] | no_license | package com.wbl.oops;
// a class having multiple methods like below, having same name (i.e add-method name) but diff parameters (i.e int, double, etc) is know as overloading
public class Overloading {
public static int add (int a, int b){
return (a+b);
}
public static double add (double a, double b){
return (a+b);
}
public static String add(String a, String b){
return (a+b);
}
public static void main(String[] args) {
System.out.println(add(4,8)); // whenever you are passing 2 integers it will by default know to call add int method
System.out.println(add("Hello ", "world"));// same for integer
}
}
| true |
6f19197d22bd0447302578f954992da54e3b9252 | Java | hjc851/SourceCodePlagiarismDetectionDataset | /Entire Dataset/1-45/read/DepositoryAccomplishment.java | UTF-8 | 775 | 2.28125 | 2 | [
"MIT"
] | permissive | package read;
import throughputMaterials.FissionableCavil;
public class DepositoryAccomplishment extends read.SeminarRead {
private throughputMaterials.FissionableCavil discipline = null;
public static final java.lang.String SeemedMurder = "DID_REMOVE";
public DepositoryAccomplishment(
double beginning, String scoop, int resources, FissionableCavil subjugate) {
this.juncture = (beginning);
this.learn = (scoop);
this.tonnage = (resources);
this.discipline = (subjugate);
}
public synchronized int capable() {
return this.tonnage;
}
private int tonnage = 0;
public synchronized throughputMaterials.FissionableCavil place() {
return this.discipline;
}
public static final java.lang.String LikedProvide = "DID_ADD";
}
| true |
f2fd805137f83d16a5bde281991ece286246ad6d | Java | kailaisi/databindingTest | /app/src/main/java/com/tcsl/databindingtest/lib/httpLoader/ResultCallback.java | UTF-8 | 913 | 2.140625 | 2 | [] | no_license | package com.tcsl.databindingtest.lib.httpLoader;
import com.google.gson.internal.$Gson$Types;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Request;
/**
* 描述:
* <p/>作者:wjx
* <p/>创建时间: 2017/3/9 14:07
*/
public abstract class ResultCallback<T> {
Type mType;
public ResultCallback() {
mType = getTypeParame(getClass());
}
public Type getTypeParame(Class<?> clazz) {
Type superclass = clazz.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
}
public abstract void onSuccess(T result);
public abstract void onError(Request request, Exception e);
}
| true |
0293589991a96bb23291bd509eb7be0b71a87ae8 | Java | NemanjaTck/GoaiFrameworkNeuroph | /src/org/goai/classification/samples/UniversalEvaluator.java | UTF-8 | 3,599 | 2.78125 | 3 | [] | no_license | package org.goai.classification.samples;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.goai.classification.api.ClassificationProblem;
import org.goai.classification.api.Classifier;
import org.goai.classification.eval.ClassifierEvaluationBase;
import org.goai.classification.impl.WekaClassifier;
import weka.core.Instance;
import weka.core.Instances;
/**
*
* @author vladimir
*/
public class UniversalEvaluator extends ClassifierEvaluationBase <double[], String, weka.classifiers.Classifier, Instances> {
String[] classNames; // temprary solution before we support column names in dataset
public UniversalEvaluator(weka.classifiers.Classifier classifierSrc, Instances problemSrc) {
super(classifierSrc, problemSrc);
}
/**
* Creates and trains Weka classifier with an instance of MultilayerPerception classifier
* and iris data set
* @return Classifier
*/
@Override
public Classifier createClassifier(weka.classifiers.Classifier wekaClassifier) {
try {
// Inicialize GOAI Classifier with Weka classifier
Classifier<double[], String> goaiClassifier = new WekaClassifier(wekaClassifier);
//Process data from Map
goaiClassifier.buildClassifier(makeMapOutOfInstances(super.getProblemSrc()));
return goaiClassifier;
} catch (Exception ex) {
Logger.getLogger(UniversalEvaluator.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Creates HashMap out of Weka data set
* @return HashMap
*/
@Override
public ClassificationProblem createClassificationProblem(Instances wekaDataset) {
try {
// Convert Weka data set to HashMap
HashMap<double[], String> classificationMap = makeMapOutOfInstances(wekaDataset);
return new ClassificationProblem("Iris", classificationMap);
} catch (Exception ex) {
Logger.getLogger(UniversalEvaluator.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Converts Weka data set to HashMap
* @param jmlDataset Dataset to be converted
* @return HashMap
*/
private HashMap<double[], String> makeMapOutOfInstances(Instances wekaDataset) {
//Get class index in given dataset
int classIndex = wekaDataset.classIndex();
//class index has to be set
if(classIndex < 0){
throw new RuntimeException("Class index has to be set!");
}
//map for instances values
HashMap<double[], String> itemClassMap = new HashMap<double[],String>();
//iterate through dataset
for(Instance dataRow: wekaDataset){
//initialize double array for values
double[] mapKey = new double[wekaDataset.numAttributes()-1];
//fill double array with values from instances
for(int i = 0; i < wekaDataset.numAttributes()-1; i++){
mapKey[i] = dataRow.value(i);
}
//Get class attribute as string value
String clazz = dataRow.toString(dataRow.attribute(classIndex));
//put entry in Map
itemClassMap.put(mapKey, clazz);
}
return itemClassMap;
}
public void setClassNames(String[] classNames) {
this.classNames = classNames;
}
}
| true |
546518691fd841220c5b90e73f9b9dc9993c0faa | Java | vanduc1102/spring-boot-2-skeleton | /src/main/java/com/wizeline/skeleton/controller/OverrideErrorWhitelabelController.java | UTF-8 | 1,074 | 1.945313 | 2 | [] | no_license | package com.wizeline.skeleton.controller;
import com.wizeline.skeleton.dto.response.GenericResponse;
import com.wizeline.skeleton.util.ResponseBodyBuilder;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import springfox.documentation.annotations.ApiIgnore;
@ApiIgnore
@Controller
public class OverrideErrorWhitelabelController implements ErrorController {
private static final String ERROR_PATH = "/error";
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
@RequestMapping(value = ERROR_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
public GenericResponse<String> handleError() {
return ResponseBodyBuilder.notFoundHandler();
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
}
| true |
97bf6ee6389d35b47c1e0d95a72328cc5aa0e1a6 | Java | TheShermanTanker/Server-1.16.3 | /io/netty/handler/codec/http/DefaultHttpRequest.java | UTF-8 | 2,783 | 2.515625 | 3 | [] | no_license | package io.netty.handler.codec.http;
import io.netty.util.internal.ObjectUtil;
public class DefaultHttpRequest extends DefaultHttpMessage implements HttpRequest {
private static final int HASH_CODE_PRIME = 31;
private HttpMethod method;
private String uri;
public DefaultHttpRequest(final HttpVersion httpVersion, final HttpMethod method, final String uri) {
this(httpVersion, method, uri, true);
}
public DefaultHttpRequest(final HttpVersion httpVersion, final HttpMethod method, final String uri, final boolean validateHeaders) {
super(httpVersion, validateHeaders, false);
this.method = ObjectUtil.<HttpMethod>checkNotNull(method, "method");
this.uri = ObjectUtil.<String>checkNotNull(uri, "uri");
}
public DefaultHttpRequest(final HttpVersion httpVersion, final HttpMethod method, final String uri, final HttpHeaders headers) {
super(httpVersion, headers);
this.method = ObjectUtil.<HttpMethod>checkNotNull(method, "method");
this.uri = ObjectUtil.<String>checkNotNull(uri, "uri");
}
@Deprecated
@Override
public HttpMethod getMethod() {
return this.method();
}
@Override
public HttpMethod method() {
return this.method;
}
@Deprecated
@Override
public String getUri() {
return this.uri();
}
@Override
public String uri() {
return this.uri;
}
@Override
public HttpRequest setMethod(final HttpMethod method) {
if (method == null) {
throw new NullPointerException("method");
}
this.method = method;
return this;
}
@Override
public HttpRequest setUri(final String uri) {
if (uri == null) {
throw new NullPointerException("uri");
}
this.uri = uri;
return this;
}
@Override
public HttpRequest setProtocolVersion(final HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + this.method.hashCode();
result = 31 * result + this.uri.hashCode();
result = 31 * result + super.hashCode();
return result;
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof DefaultHttpRequest)) {
return false;
}
final DefaultHttpRequest other = (DefaultHttpRequest)o;
return this.method().equals(other.method()) && this.uri().equalsIgnoreCase(other.uri()) && super.equals(o);
}
public String toString() {
return HttpMessageUtil.appendRequest(new StringBuilder(256), this).toString();
}
}
| true |
4950e9c271f5439ea73a66c92d0d33765cee8bb9 | Java | kayazas123/microframeworks | /todo-backend-test/src/test/java/nl/jaapcoomans/demo/microframeworks/todo/test/BladeTodoBackendTest.java | UTF-8 | 725 | 1.90625 | 2 | [
"MIT"
] | permissive | package nl.jaapcoomans.demo.microframeworks.todo.test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.images.builder.ImageFromDockerfile;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.nio.file.Paths;
@Testcontainers
class BladeTodoBackendTest extends BaseTodoBackendTest {
private static ImageFromDockerfile bladeImage = new ImageFromDockerfile().withFileFromPath(".", Paths.get("../blade"));
@Container
private static GenericContainer bladeContainer = new GenericContainer(bladeImage).withExposedPorts(8080);
@Override
GenericContainer getContainer() {
return bladeContainer;
}
}
| true |
24a9d80d9f098a1d58ac57be61e52a8f3a0865a1 | Java | inspire-software/geda-genericdto | /core/src/test/java/com/inspiresoftware/lib/dto/geda/assembler/examples/complex/multidescriptors/dto/CustomerOrderDeliveryDetailDTOImpl.java | UTF-8 | 1,046 | 1.953125 | 2 | [] | no_license | /*
* This code is distributed under The GNU Lesser General Public License (LGPLv3)
* Please visit GNU site for LGPLv3 http://www.gnu.org/copyleft/lesser.html
*
* Copyright Denis Pavlov 2009
* Web: http://www.genericdtoassembler.org
* SVN: https://svn.code.sf.net/p/geda-genericdto/code/trunk/
* SVN (mirror): http://geda-genericdto.googlecode.com/svn/trunk/
*/
package com.inspiresoftware.lib.dto.geda.assembler.examples.complex.multidescriptors.dto;
import com.inspiresoftware.lib.dto.geda.annotations.Dto;
import com.inspiresoftware.lib.dto.geda.annotations.DtoField;
import java.math.BigDecimal;
@Dto
public class CustomerOrderDeliveryDetailDTOImpl implements CustomerOrderDeliveryDetailDTO {
private static final long serialVersionUID = 20120812L;
@DtoField(value = "qty")
private BigDecimal qty;
/** {@inheritDoc} */
public BigDecimal getQty() {
return qty;
}
/** {@inheritDoc} */
public void setQty(final BigDecimal qty) {
this.qty = qty;
}
}
| true |
7ca80008bde2ea4200cae44736e551f6888a05da | Java | iamaga/java_test | /sxtoa/src/com/liu/service/impl/PaymentServiceImpl.java | UTF-8 | 1,433 | 2.03125 | 2 | [] | no_license | package com.liu.service.impl;
import com.liu.mapper.PaymentMapper;
import com.liu.pojo.NV;
import com.liu.pojo.Payment;
import com.liu.service.PaymentService;
import com.liu.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class PaymentServiceImpl implements PaymentService {
@Override
public int addPayment(Payment payment) {
SqlSession session = MybatisUtil.getSession();
PaymentMapper mapper = session.getMapper(PaymentMapper.class);
int i = mapper.addPayment(payment);
session.commit();
MybatisUtil.closed();
return i;
}
@Override
public List<Payment> findPaymentByCondition(String startDate, String endDate, String realname) {
SqlSession session = MybatisUtil.getSession();
PaymentMapper mapper = session.getMapper(PaymentMapper.class);
List<Payment> payments = mapper.findPaymentByCondition(startDate, endDate, realname);
session.commit();
MybatisUtil.closed();
return payments;
}
@Override
public List<NV> findPaymentByDate(String startDate, String endDate) {
SqlSession session = MybatisUtil.getSession();
PaymentMapper mapper = session.getMapper(PaymentMapper.class);
List<NV> payments = mapper.findPaymentByDate(startDate, endDate);
session.commit();
MybatisUtil.closed();
return payments;
}
}
| true |
293c4446eb2e4d4b8731144a50a63955755a1efd | Java | BankaiNoJutsu/sbrw-mp-sync-2018 | /br/com/sbrw/mp/handler/race/PlayerInfoBeforeHandler.java | UTF-8 | 3,319 | 2.09375 | 2 | [] | no_license | /*
* This file is part of the Soapbox Race World MP source code.
* If you use any of this code for third-party purposes, please provide attribution.
* Original source code by Nilzao, 2018
*/
package br.com.sbrw.mp.handler.race;
import br.com.sbrw.mp.pktvo.IPkt;
import br.com.sbrw.mp.pktvo.race.MainRacePacket;
import br.com.sbrw.mp.pktvo.race.player.PlayerInfo;
import br.com.sbrw.mp.pktvo.race.player.PlayerMainPkt;
import br.com.sbrw.mp.protocol.MpAllTalkers;
import br.com.sbrw.mp.protocol.MpSession;
import br.com.sbrw.mp.protocol.MpSessions;
import br.com.sbrw.mp.protocol.MpTalker;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import java.util.Iterator;
import java.util.Map;
public class PlayerInfoBeforeHandler extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
DatagramPacket datagramPacket = (DatagramPacket)msg;
ByteBuf buf = (ByteBuf)datagramPacket.content();
if (isPlayerInfoPacket(buf)) {
MpTalker mpTalker = MpAllTalkers.get(datagramPacket);
if (mpTalker != null) {
MainRacePacket mainPacket = (MainRacePacket)mpTalker.getMainPacket();
mainPacket.parsePlayerInfo(buf);
playerInfoBeforeOk(mpTalker);
}
}
super.channelRead(ctx, msg);
}
private void playerInfoBeforeOk(MpTalker mpTalker) {
MpSession mpSession = MpSessions.get(mpTalker);
Map<Integer, MpTalker> mpTalkersTmp = mpSession.getMpTalkers();
if (isAllPlayerInfoBeforeOk(mpSession)) {
Iterator<Map.Entry<Integer, MpTalker>> iterator = mpTalkersTmp.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, MpTalker> next = iterator.next();
MpTalker mpTalkerTmp = next.getValue();
mpTalkerTmp.broadcastToSession(sendPlayerInfo(mpTalkerTmp));
}
}
}
private boolean isAllPlayerInfoBeforeOk(MpSession mpSession) {
Map<Integer, MpTalker> mpTalkersTmp = mpSession.getMpTalkers();
Iterator<Map.Entry<Integer, MpTalker>> iterator = mpTalkersTmp.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, MpTalker> next = iterator.next();
MpTalker mpTalker = next.getValue();
MainRacePacket mainPacket = (MainRacePacket)mpTalker.getMainPacket();
if (!mainPacket.isPlayerInfoOk())
return false;
}
return true;
}
private boolean isPlayerInfoPacket(ByteBuf buf) {
return (buf.getByte(0) == 1 && buf
.getByte(6) == -1 && buf
.getByte(7) == -1 && buf
.getByte(8) == -1 && buf
.getByte(9) == -1);
}
private byte[] sendPlayerInfo(MpTalker mpTalker) {
MainRacePacket mainPacket = (MainRacePacket)mpTalker.getMainPacket();
PlayerMainPkt playerMainPkt = mainPacket.getPlayerMainPkt();
PlayerInfo playerInfo = new PlayerInfo();
playerInfo.setPlayerInfo(mainPacket.getSbrwParser().getPlayerInfo());
playerInfo.setPlayerStatePos(mainPacket.getSbrwParser().getCarState());
playerMainPkt.setPlayerInfo(playerInfo);
return mpTalker.getMainPacket((IPkt)playerMainPkt);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.err.println(cause.getMessage());
}
}
| true |
9cebc82cfcfdba567dc532d07e0b70e9672947c6 | Java | antoinecronier/pokeAndroid | /src/com/antoinecronier/pokebattle/view/poketypepokemon/PokeTypePokemonListAdapter.java | UTF-8 | 4,738 | 2.265625 | 2 | [] | no_license | /**************************************************************************
* PokeTypePokemonListAdapter.java, pokebattle Android
*
* Copyright 2016
* Description :
* Author(s) : Harmony
* Licence :
* Last update : May 25, 2016
*
**************************************************************************/
package com.antoinecronier.pokebattle.view.poketypepokemon;
import com.antoinecronier.pokebattle.R;
import android.database.Cursor;
import android.view.ViewGroup;
import android.widget.TextView;
import com.antoinecronier.pokebattle.entity.PokeTypePokemon;
import com.antoinecronier.pokebattle.harmony.view.HarmonyCursorAdapter;
import com.antoinecronier.pokebattle.harmony.view.HarmonyViewHolder;
import com.antoinecronier.pokebattle.provider.contract.PokeTypePokemonContract;
import com.antoinecronier.pokebattle.provider.contract.PokeTypeContract;
import com.antoinecronier.pokebattle.provider.contract.PokeZoneContract;
/**
* List adapter for PokeTypePokemon entity.
*/
public class PokeTypePokemonListAdapter extends HarmonyCursorAdapter<PokeTypePokemon> {
/**
* Constructor.
* @param ctx context
*/
public PokeTypePokemonListAdapter(android.content.Context context) {
super(context);
}
/**
* Constructor.
* @param ctx context
* @param cursor cursor
*/
public PokeTypePokemonListAdapter(android.content.Context context, Cursor cursor) {
super(context, cursor);
}
@Override
protected PokeTypePokemon cursorToItem(Cursor cursor) {
return PokeTypePokemonContract.cursorToItem(cursor);
}
@Override
protected String getColId() {
return PokeTypePokemonContract.COL_ID;
}
@Override
protected HarmonyViewHolder<PokeTypePokemon> getNewViewHolder(
android.content.Context context,
Cursor cursor, ViewGroup group) {
return new ViewHolder(context, group);
}
/** Holder row. */
private class ViewHolder extends HarmonyViewHolder<PokeTypePokemon> {
/**
* Constructor.
*
* @param context The context
* @param parent Optional view to be the parent of the generated hierarchy
*/
public ViewHolder(android.content.Context context, ViewGroup parent) {
super(context, parent, R.layout.row_poketypepokemon);
}
/**
* Populate row with a {@link PokeTypePokemon}.
*
* @param model {@link PokeTypePokemon} data
*/
public void populate(final PokeTypePokemon model) {
TextView nomView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_nom);
TextView attaqueView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_attaque);
TextView attaque_speView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_attaque_spe);
TextView defenceView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_defence);
TextView defence_speView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_defence_spe);
TextView vitesseView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_vitesse);
TextView pvView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_pv);
TextView pokedexView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_pokedex);
TextView evolueView = (TextView) this.getView().findViewById(
R.id.row_poketypepokemon_evolue);
if (model.getNom() != null) {
nomView.setText(model.getNom());
}
attaqueView.setText(String.valueOf(model.getAttaque()));
attaque_speView.setText(String.valueOf(model.getAttaque_spe()));
defenceView.setText(String.valueOf(model.getDefence()));
defence_speView.setText(String.valueOf(model.getDefence_spe()));
vitesseView.setText(String.valueOf(model.getVitesse()));
pvView.setText(String.valueOf(model.getPv()));
pokedexView.setText(String.valueOf(model.getPokedex()));
if (model.getEvolue() != null) {
evolueView.setText(
String.valueOf(model.getEvolue().getId()));
}
}
}
}
| true |
896102d0b5f588395e9c162c9d50be24330a36e1 | Java | Swop4a/link-rest | /link-rest/src/main/java/com/nhl/link/rest/runtime/protocol/IIncludeParser.java | UTF-8 | 327 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | package com.nhl.link.rest.runtime.protocol;
import com.nhl.link.rest.protocol.Include;
import java.util.List;
/**
* Parsing of Include query parameter from string value.
*
* @since 2.13
*/
public interface IIncludeParser {
List<Include> fromStrings(List<String> values);
Include oneFromString(String value);
}
| true |
06d1ce82d4f5c09f08ad03a36162adfa93ea5e98 | Java | danielgoncharov/algorithm-playground | /src/main/java/com/daniel/goncharov/algorithm/playground/interviewbit/dp/DungeonPrincess.java | UTF-8 | 1,700 | 3.4375 | 3 | [] | no_license | package com.daniel.goncharov.algorithm.playground.interviewbit.dp;
import java.util.ArrayList;
public class DungeonPrincess {
public int calculateMinimumHP(ArrayList<ArrayList<Integer>> matrix) {
for (int i = matrix.size() - 1; i >= 0; i--) {
ArrayList<Integer> row = matrix.get(i);
for (int j = row.size() - 1; j >= 0; j--) {
if (i == matrix.size() - 1 && j == row.size() - 1) {
setLastItem(row, j);
} else {
setOtherItem(matrix, i, j);
}
}
}
return matrix.get(0).get(0);
}
private void setLastItem(ArrayList<Integer> row, int j) {
int item = row.get(j);
if (item <= 0) {
row.set(j, Math.abs(item) + 1);
}
}
private void setOtherItem(ArrayList<ArrayList<Integer>> matrix, int i, int j) {
ArrayList<Integer> row = matrix.get(i);
int item = row.get(j);
int minItem = Math.min(getFromBottom(matrix, i, j), getFromRight(matrix, i, j));
if (item <= 0) {
row.set(j, Math.abs(item) + minItem);
} else if (item - minItem >= 0) {
row.set(j, 1);
} else {
row.set(j, Math.abs(item - minItem));
}
}
private int getFromBottom(ArrayList<ArrayList<Integer>> matrix, int i, int j) {
if (i + 1 == matrix.size()) return Integer.MAX_VALUE;
else return matrix.get(i + 1).get(j);
}
private int getFromRight(ArrayList<ArrayList<Integer>> matrix, int i, int j) {
if (j + 1 == matrix.get(0).size()) return Integer.MAX_VALUE;
else return matrix.get(i).get(j + 1);
}
}
| true |
a5136335253459c4b4915919501977932eae530d | Java | lixianch/Java | /src/test/java/activiti/gateway/ExclusiveGateWayProcessTest.java | UTF-8 | 1,207 | 2.140625 | 2 | [] | no_license | package activiti.gateway;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.repository.Deployment;
import org.junit.Test;
/**
* Created by lixianch on 2018/9/30.
*/
public class ExclusiveGateWayProcessTest {
private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
@Test
public void testDeploy() {
Deployment deploy = processEngine.getRepositoryService()
.createDeployment().addClasspathResource("GatewayProcess.bpmn20.xml")
.key("ExclusiveGateWay").name("ExclusiveGateway")
.deploy();
System.out.println("发布流程,Id: " + deploy.getId() + ",key: " + deploy.getKey() + ",name: " + deploy.getName());
}
@Test
public void startProcess() {
processEngine.getRuntimeService().startProcessInstanceByKey("GatewayProcess");
}
@Test
public void processTask() {
String taskId = "77505";
processEngine.getTaskService().setVariableLocal(taskId,"localcount",30);
processEngine.getTaskService().setVariable(taskId,"money",250);
processEngine.getTaskService().complete(taskId);
}
}
| true |
8fa69ae3711719fb656af3cfee95c9ff95298c57 | Java | evgeniy-fitsner/riot | /common/src/org/riotfamily/common/web/mvc/interceptor/RequestInterceptorAdapter.java | UTF-8 | 1,422 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.riotfamily.common.web.mvc.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Abstract adapter class for the RequestInterceptor interface, for simplified
* implementation of pre-only/post-only interceptors.
*/
public class RequestInterceptorAdapter implements RequestInterceptor {
/**
* This implementation returns <code>true</code>.
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
return true;
}
/**
* This implementation is empty.
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
}
/**
* This implementation is empty.
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
}
}
| true |
06658110f9c4aabb966a31269998d503bf30c167 | Java | Dante-101/PoolUp | /src/com/example/firstapp/LoaderActivity.java | UTF-8 | 3,608 | 2.296875 | 2 | [] | no_license | package com.example.firstapp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.example.connections.ConnectionsManager;
import com.example.connections.HitClient;
import com.example.datatypes.Record;
import com.google.gson.Gson;
public class LoaderActivity extends ListActivity implements OnClickListener, OnInitListener {
Button btn;
HitClient client = new HitClient();
String uri=ConnectionsManager.db_url+"users.json";
ProgressDialog dialog;
TextView heading;
TextToSpeech tts;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_loader);
tts = new TextToSpeech(this,this);
}
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onClick(View view){
}
public List<String> getPotentialDrivers()
{
List<String> output = new ArrayList<String>();
try {
String json =client.sendGetRequest(uri, null, null);
JSONObject js = new JSONObject(json);
Iterator it = js.keys();
while(it.hasNext())
{
String name = (String)it.next();
JSONObject res = (JSONObject)js.get(name);
output.add(res.toString().toString());
}
return output;
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
public void clickUser(Record record) {
Log.i("came","here");
tts.speak(record.getUserId()+" has been sent a bid", TextToSpeech.QUEUE_FLUSH, null);
}
public void submit(View view) {
new LongOperation(this).execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
ListActivity activity;
private Context context;
List<String> messages;
public LongOperation(ListActivity activity) {
this.activity = activity;
context = activity;
messages = new ArrayList<String>();
}
@Override
protected String doInBackground(String... params) {
messages = getPotentialDrivers();
return "Executed";
}
@Override
protected void onPostExecute(String result) {
List<Record> titles = new ArrayList<Record>(messages.size());
Gson gson = new Gson();
for (String msg : messages){
Record rec = gson.fromJson(msg,Record.class);
titles.add(rec);
}
ArrayAdapter<Record> adapter =new InteractiveArrayAdapter(activity,titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
}
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(activity, "Working..", "Downloading Data...", true, false);
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
} | true |
aea2e5c88bcdeedfbc2da97d1a3079cf7eb0ce2b | Java | wpelaez55/ExposingIndustryMediocrity | /com.citi.mobile.co/Sources/ny0k/bG.java | UTF-8 | 21,185 | 1.617188 | 2 | [
"MIT"
] | permissive | package ny0k;
import android.util.Log;
import android.widget.BaseAdapter;
import com.konylabs.android.KonyMain;
import com.konylabs.api.ui.LuaWidget;
import com.konylabs.api.ui.eO;
import com.konylabs.api.ui.iq;
import com.konylabs.vm.LuaNil;
import com.konylabs.vm.LuaTable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
public abstract class bG extends bO {
private static int al;
public static int f4585d;
protected static int f4586e;
protected static int f4587f;
protected static int f4588g;
protected ArrayList f4589a;
private BaseAdapter ak;
private int am;
private int an;
private bH ao;
protected ArrayList f4590b;
protected cj f4591c;
protected int f4592h;
static {
f4585d = 0;
al = 1;
f4586e = 1000;
f4587f = 1001;
f4588g = 1002;
}
public bG(LuaTable luaTable, LuaTable luaTable2, LuaTable luaTable3, long j) {
super(luaTable, luaTable2, luaTable3, j);
this.ak = null;
this.f4589a = new ArrayList();
this.f4590b = new ArrayList();
this.f4592h = f4588g;
this.am = 0;
this.an = 1;
this.Y = new Vector(1);
this.f4591c = new cj(this.f4590b, this.Y);
m4833i();
}
private int m4885a(Object obj) {
int indexOf = this.f4589a.indexOf(obj);
if (indexOf != -1) {
return indexOf;
}
this.f4589a.add(obj);
return this.f4589a.size() - 1;
}
private void m4886a(Vector vector, int i, int i2, bT bTVar) {
Vector vector2;
int size = vector.size();
Vector vector3 = bTVar.f2147g;
if (vector3 == null) {
vector3 = new Vector(size);
bTVar.f2147g = vector3;
vector2 = vector3;
} else {
vector2 = vector3;
}
int size2 = vector2.size();
int i3 = i2 + 1;
int i4 = 0;
while (i4 < size) {
int i5;
LuaTable luaTable = (LuaTable) vector.elementAt(i4);
if (luaTable.map.size() != 0) {
Hashtable hashtable = luaTable.map;
Object b = m4810b(hashtable);
LuaTable a = bO.m4760a(hashtable, (eO) b);
bH bHVar = new bH(this);
bHVar.f2133b = i2;
bHVar.f2134c = i;
bHVar.f2135d = size2 + i4;
bHVar.f2136e = m4885a(b);
bI bIVar = new bI(this, b, luaTable, bHVar, m4831h(luaTable), a);
bHVar.f2132a = bIVar;
if (i2 == -1) {
this.f4590b.add(bHVar);
i5 = i3;
} else {
this.f4590b.add(i3, bHVar);
i5 = i3 + 1;
}
vector2.add(bIVar);
} else {
i5 = i3;
}
i4++;
i3 = i5;
}
}
private void m4887a(bH bHVar, int i, int i2, int i3) {
int b;
Object obj = null;
if (i3 == 0) {
if (this.ab) {
bHVar.f2133b = ((bJ) this.Y.get(i)).f3319a.f2133b;
}
b = this.f4591c.m2171b(i, i2);
if (b >= 0 && b <= this.f4590b.size()) {
this.f4590b.add(b, bHVar);
b++;
} else {
return;
}
} else if (i3 == this.an) {
b = this.f4591c.m2171b(i, i2);
if (b >= 0 && b < this.f4590b.size() && this.f4590b.remove(b) != null) {
obj = 1;
}
if (obj == null) {
return;
}
} else {
return;
}
int size = this.f4590b.size();
for (int i4 = b; i4 < size; i4++) {
bH bHVar2 = (bH) this.f4590b.get(i4);
if (bHVar2.f2134c != i || bHVar2.f2135d < i2) {
if (bHVar2.f2134c > i) {
if (i3 == 0) {
bHVar2.f2133b++;
} else if (i3 == this.an) {
bHVar2.f2133b--;
}
}
} else if (i3 == 0) {
bHVar2.f2135d++;
} else if (i3 == this.an) {
bHVar2.f2135d--;
}
}
}
private void m4888c(int i, int i2) {
int size = this.Y.size();
while (i < size) {
bJ bJVar = (bJ) this.Y.get(i);
bH bHVar = bJVar.f3319a;
bHVar.f2133b = i2;
bHVar.f2134c = i;
Vector vector = bJVar.g;
int size2 = vector.size();
for (int i3 = 0; i3 < size2; i3++) {
bH bHVar2 = ((bI) vector.get(i3)).f3317a;
bHVar2.f2133b = i2;
bHVar2.f2134c = i;
}
i2 += size2 + 1;
i++;
}
}
private void m4889h(int i) {
e_();
m4893a(i);
}
private void m4890l() {
if (this.f4590b != null) {
this.ao = null;
ArrayList arrayList = this.f4590b;
int size = arrayList.size();
for (int i = 0; i < size; i++) {
bH bHVar = (bH) arrayList.get(i);
bHVar.f2137f = false;
Object obj = bHVar.f2132a;
if (obj instanceof bI) {
ci ciVar = ((bI) obj).f3318b;
if (ciVar != null) {
ciVar.f2279c = null;
}
}
}
}
}
private void m4891m() {
if (this.ah != null && !this.ah.isEmpty() && this.Y != null && !this.Y.isEmpty()) {
HashMap hashMap = this.ah;
Iterator it = hashMap.keySet().iterator();
Integer num;
bT bTVar;
if (this.S == 1) {
if (it.hasNext()) {
num = (Integer) it.next();
if (num.intValue() < this.Y.size()) {
Integer num2 = (Integer) hashMap.get(num);
if (num2 != null) {
bTVar = (bT) this.Y.get(num.intValue());
if (num2.intValue() < bTVar.f2147g.size()) {
bH bHVar = ((bI) bTVar.f2147g.get(num2.intValue())).f3317a;
bHVar.f2137f = true;
this.ao = bHVar;
}
}
}
}
} else if (this.S == 2) {
Vector vector = this.Y;
while (it.hasNext()) {
num = (Integer) it.next();
if (num.intValue() < vector.size()) {
ArrayList arrayList = (ArrayList) hashMap.get(num);
if (arrayList != null) {
bTVar = (bT) vector.get(num.intValue());
int size = arrayList.size();
for (int i = 0; i < size; i++) {
Integer num3 = (Integer) arrayList.get(i);
if (num3.intValue() < bTVar.f2147g.size()) {
((bI) bTVar.f2147g.get(num3.intValue())).f3317a.f2137f = true;
}
}
}
}
}
}
}
}
private void m4892n() {
if (this.af != -1 && this.ag != -1 && this.Y != null && this.af < this.Y.size()) {
bJ bJVar = (bJ) this.Y.get(this.af);
if (this.ag < bJVar.g.size()) {
bH bHVar = ((bI) bJVar.g.get(this.ag)).f3317a;
bHVar.f2137f = true;
this.ao = bHVar;
}
}
}
protected abstract void m4893a(int i);
public final void m4894a(BaseAdapter baseAdapter) {
this.ak = baseAdapter;
}
public final void m4895a(LuaTable luaTable, int i) {
if (i >= 0) {
bJ bJVar = null;
int size = this.Y.size();
int i2 = i < size ? i : size;
size = this.f4590b.size();
super.m4800a(luaTable, i);
int abs = Math.abs(size - this.f4590b.size());
int size2 = luaTable.list.size() + i;
if (size2 < this.Y.size()) {
bJ bJVar2 = (bJ) this.Y.get(size2 - 1);
m4888c(size2, (bJVar2.g.size() + bJVar2.f3319a.f2133b) + 1);
bJVar = bJVar2;
}
if (this.E == KONY_WIDGET_RESTORE) {
size2 = f_();
size = ((bH) this.f4590b.get(size2)).f2134c;
if (bJVar != null) {
if (this.f4592h == f4586e) {
size2 = size >= i2 ? (abs - 1) + size2 : size2;
} else if (this.f4592h == f4587f) {
size2 = size >= i2 ? size2 + abs : size2 + 1;
} else if (size >= i2) {
size2 += abs;
}
} else if (this.f4592h == f4587f) {
if (size > i2) {
size2 += abs;
} else if (size < i2) {
size2++;
}
}
m4889h(size2);
}
} else if (KonyMain.f3659g) {
Log.d("LuaSegUI2", "Invalid sectionIndex: " + i + " to add section at");
}
}
public final void m4896a(LuaTable luaTable, Vector vector, int i, int i2) {
bH bHVar = new bH(this, i2, i);
Hashtable hashtable = luaTable.map;
Object b = m4810b(hashtable);
if (b != this.X) {
cr.m2212c(this, b);
}
LuaTable luaTable2 = luaTable;
bI bIVar = new bI(this, b, luaTable2, bHVar, m4831h(luaTable), bO.m4760a(hashtable, (eO) b));
bHVar.f2132a = bIVar;
bHVar.f2136e = m4885a(b);
if (i < vector.size()) {
vector.add(i, bIVar);
} else {
vector.add(bIVar);
}
m4887a(bHVar, i2, i, 0);
if (this.E == KONY_WIDGET_RESTORE) {
int f_ = f_();
if (this.f4592h == f4586e) {
f_ = 0;
} else if (f_ >= this.f4591c.m2171b(i2, i)) {
f_++;
}
m4889h(f_);
}
}
protected void m4897a(Object obj, Object obj2) {
if (obj == P || obj == R || obj == C || obj == Q) {
m4912e();
}
super.m4804a(obj, obj2);
if (obj == k || obj == i || obj == j || obj == l || obj == p || obj == m) {
m4889h(f_());
} else if (obj == u || obj == t || obj == q) {
m4912e();
}
}
public final void m4898a(Vector vector) {
super.m4805a(vector);
if (this.E == KONY_WIDGET_RESTORE) {
m4889h(0);
}
}
protected void m4899a(Vector vector, int i) {
int size = vector.size();
this.Y.ensureCapacity(size);
int size2 = this.Y.size();
if (i == -1 || i >= size2) {
i = size2;
}
if (this.Y == null || this.Y.isEmpty()) {
size2 = 0;
} else {
size2 = this.Y.size();
bJ bJVar;
if (i >= size2) {
bJVar = (bJ) this.Y.get(size2 - 1);
size2 = bJVar.f3319a != null ? (bJVar.g.size() + bJVar.f3319a.f2133b) + 1 : 0;
} else {
bJVar = (bJ) this.Y.get(i);
size2 = bJVar.f3319a != null ? bJVar.f3319a.f2133b : 0;
}
}
int i2 = 0;
int i3 = size2;
while (i2 < size) {
LuaTable luaTable = (LuaTable) vector.elementAt(i2);
if (luaTable.list.size() != 0) {
Object obj;
bT bTVar;
LuaNil luaNil = luaTable.list.get(0);
if (luaNil != LuaNil.nil) {
bT bJVar2;
Object obj2;
Integer.valueOf(0);
bH bHVar = new bH(this);
if (luaNil instanceof String) {
String str = (String) luaNil;
LuaTable luaTable2 = null;
if (luaTable.list.size() > 2) {
obj = luaTable.list.get(2);
if (obj instanceof LuaTable) {
luaTable2 = (LuaTable) obj;
}
}
bJVar2 = new bJ(this, str, bHVar, 0, luaTable2);
obj2 = "title";
} else if (luaNil instanceof LuaTable) {
Hashtable hashtable = ((LuaTable) luaNil).map;
obj2 = m4797a(hashtable);
bJVar2 = new bJ(this, obj2, (LuaTable) luaNil, bHVar, al, bO.m4760a(hashtable, (eO) obj2));
} else {
bJVar2 = new bJ(this, " ", bHVar, 0, null);
obj2 = "title";
}
bHVar.f2133b = i3;
bHVar.f2134c = i;
bHVar.f2132a = bJVar2;
bHVar.f2136e = m4885a(obj2);
this.f4590b.add(i3, bHVar);
bTVar = bJVar2;
} else {
bTVar = new bJ(this);
}
obj = luaTable.list.get(1);
if (obj != null) {
m4886a(((LuaTable) obj).list, i, i3, bTVar);
size2 = (bTVar.g.size() + 1) + i3;
} else {
size2 = i3;
}
this.Y.add(i, bTVar);
} else {
size2 = i3;
}
i++;
i2++;
i3 = size2;
}
}
public final void m4900a(Vector vector, int i, int i2) {
LuaWidget luaWidget = ((bI) vector.elementAt(i)).c;
if (!(luaWidget == null || luaWidget == this.X)) {
cr.m2209b((LuaWidget) this, luaWidget);
if (this.ai != null) {
this.ai.remove(luaWidget);
}
}
int b = this.f4591c.m2171b(i2, i);
m4887a(null, i2, i, this.an);
vector.removeElementAt(i);
if (this.E == KONY_WIDGET_RESTORE) {
int f_ = f_();
if (this.f4592h == f4586e) {
f_ = 0;
} else if ((this.f4592h == f4588g || this.f4592h == f4587f) && f_ >= b) {
f_--;
}
m4889h(f_);
}
}
protected final void m4901a(bS bSVar, LuaTable luaTable) {
if (this.E == KONY_WIDGET_RESTORE) {
m4912e();
}
}
public final boolean m4902a(int i, int i2) {
if (this.S == 1) {
bH bHVar = ((bI) ((bT) this.Y.get(i)).f2147g.get(i2)).f3317a;
if (!bHVar.f2137f) {
if (this.ao != null) {
this.ao.f2137f = false;
}
bHVar.f2137f = true;
}
this.ao = bHVar;
return true;
} else if (this.S != 2) {
return true;
} else {
bH bHVar2 = ((bI) ((bT) this.Y.get(i)).f2147g.get(i2)).f3317a;
boolean z = !bHVar2.f2137f;
bHVar2.f2137f = z;
return z;
}
}
public final void m4903b(int i) {
if (this.Y != null && i >= 0 && i < this.Y.size()) {
int size = ((bT) this.Y.get(i)).f2147g.size();
if (size > 0) {
bH bHVar = ((bI) ((bT) this.Y.get(i)).f2147g.get(size - 1)).f3317a;
size = this.f4591c.m2171b(bHVar.f2134c, bHVar.f2135d);
} else {
size = -1;
}
super.m4812b(i);
ArrayList arrayList = null;
bJ bJVar = (bJ) this.Y.remove(i);
eO eOVar = bJVar.d;
if (!(eOVar == null || eOVar == this.Z)) {
arrayList = new ArrayList();
arrayList.add(eOVar);
if (this.ai != null) {
this.ai.remove(eOVar);
}
}
int i2 = bJVar.f3319a.f2133b;
if (size == -1) {
size = i2;
}
this.f4590b.remove(bJVar.f3319a);
int size2 = bJVar.g.size();
Vector vector = bJVar.g;
ArrayList arrayList2 = arrayList;
int i3 = 0;
while (i3 < size2) {
ArrayList arrayList3;
bI bIVar = (bI) vector.get(i3);
this.f4590b.remove(bIVar.f3317a);
eO eOVar2 = bIVar.c;
if (eOVar2 == null || eOVar2 == this.X) {
arrayList3 = arrayList2;
} else {
arrayList3 = arrayList2 == null ? new ArrayList() : arrayList2;
arrayList3.add(eOVar2);
if (this.ai != null) {
this.ai.remove(eOVar2);
}
}
i3++;
arrayList2 = arrayList3;
}
if (arrayList2 != null) {
cr.m2206a((LuaWidget) this, arrayList2);
}
m4888c(i, i2);
if (this.E == KONY_WIDGET_RESTORE) {
int f_ = f_();
if (this.f4592h == f4586e) {
f_ = 0;
} else if ((this.f4592h == f4588g || this.f4592h == f4587f) && f_ >= r1) {
f_ -= size2;
}
m4889h(f_);
}
}
}
public final void m4904b(LuaTable luaTable) {
super.m4813b(luaTable);
if (this.E == KONY_WIDGET_RESTORE) {
int f_ = f_();
if (this.f4592h == f4586e) {
f_ = 0;
} else if (this.f4592h == f4587f) {
f_++;
}
m4889h(f_);
}
}
public void m4905b(Vector vector) {
int i;
bT bJVar;
int size = this.Y.size();
if (size == 0) {
i = 0;
bJVar = new bJ(this);
this.Y.add(bJVar);
} else {
i = size - 1;
bJ bJVar2 = (bJ) this.Y.elementAt(i);
}
m4886a(vector, i, -1, bJVar);
}
public final boolean m4906b(int i, int i2) {
return ((bI) ((bT) this.Y.get(i)).f2147g.get(i2)).f3317a.f2137f;
}
protected final void m4907c(int i) {
if (this.S != i) {
m4890l();
}
super.m4817c(i);
}
protected final void m4908c(LuaTable luaTable) {
super.m4818c(luaTable);
m4890l();
m4891m();
}
public void cleanup() {
super.cleanup();
if (this.S == 1 || this.S == 2) {
m4890l();
this.V = null;
}
this.ak = null;
}
protected void m4909d() {
if ((this.Y != null ? this.Y.size() : 0) == 0) {
LuaNil table = super.getTable(r);
if (!(table == LuaNil.nil || table == null)) {
m4835j((LuaTable) table);
}
} else {
e_();
}
if (this.S == 1 || this.S == 2) {
m4891m();
}
}
protected final void m4910d(LuaTable luaTable) {
super.m4821d(luaTable);
m4890l();
if (this.S == 1) {
m4892n();
} else {
m4891m();
}
}
protected final bH m4911e(int i) {
if (this.ab) {
i = this.f4591c.m2169a(i, this.ab);
}
return (this.f4590b == null || i >= this.f4590b.size()) ? null : (bH) this.f4590b.get(i);
}
protected void m4912e() {
if (this.ak != null) {
this.ak.notifyDataSetChanged();
}
}
protected final void m4913e(LuaTable luaTable) {
super.m4823e(luaTable);
m4890l();
m4891m();
}
protected abstract void e_();
public void m4914f() {
if (this.f4590b != null) {
this.f4590b.clear();
}
if (this.f4589a != null) {
this.f4589a.clear();
}
super.m4824f();
if (this.E == KONY_WIDGET_RESTORE) {
m4912e();
}
}
protected final void m4915f(LuaTable luaTable) {
super.m4825f(luaTable);
m4890l();
if (this.S == 1) {
m4892n();
} else {
m4891m();
}
}
protected abstract int f_();
protected final iq m4916g() {
return new bK(this);
}
protected final void m4917g(LuaTable luaTable) {
super.m4829g(luaTable);
m4890l();
}
protected final bT m4918h() {
return new bJ(this);
}
public void handleOrientationChange(int i) {
super.handleOrientationChange(i);
m4889h(f_());
}
}
| true |
24df6c61f55ddb5a163b54557f445e0975d65179 | Java | TianGuisen/mvvmDemo | /app/src/main/java/tgs/com/mvvm/core/retrofit/RetrofitUtil.java | UTF-8 | 3,323 | 2.375 | 2 | [] | no_license | package tgs.com.mvvm.core.retrofit;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import tgs.com.mvvm.MyApplication;
import tgs.com.mvvm.RetrofitService;
import tgs.com.mvvm.constant.NetConstant;
/**
* Created by 田桂森 on 2016/11/30.
*/
public class RetrofitUtil {
private static RetrofitService stringService;
private static RetrofitService gsonService;
private static RetrofitService createRetrofit(RetrofitParams params) {
File cacheDir = new File(MyApplication.getAppContext().getCacheDir(), "response");
//缓存的最大尺寸10m
Cache cache = new Cache(cacheDir, 1024 * 1024 * 10);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
for (Interceptor interceptor : params.interceptors) {
builder.addInterceptor(interceptor);
}
builder.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.MINUTES)
.writeTimeout(15, TimeUnit.MINUTES)
.cache(cache);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(params.baseUrl)
.addConverterFactory(params.converterFactory)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(builder.build())
.build();
return retrofit.create(RetrofitService.class);
}
private static class RetrofitParams {
private List<Interceptor> interceptors = new ArrayList();
private String baseUrl = NetConstant.BASE_URL;
private Converter.Factory converterFactory = ScalarsConverterFactory.create();
}
public static RetrofitService getString() {
if (stringService == null) {
synchronized (RetrofitUtil.class) {
if (stringService == null) {
RetrofitParams retrofitParams = new RetrofitParams();
retrofitParams.interceptors.add(new ParamInterceptor());
retrofitParams.interceptors.add(new LoggerInterceptor2());
stringService = createRetrofit(retrofitParams);
}
}
}
return stringService;
}
public static RetrofitService getJson() {
if (gsonService == null) {
synchronized (RetrofitUtil.class) {
if (gsonService == null) {
RetrofitParams retrofitParams = new RetrofitParams();
retrofitParams.interceptors.add(new ParamInterceptor());
retrofitParams.interceptors.add(new CacheInterceptor());
retrofitParams.interceptors.add(new LoggerInterceptor2());
retrofitParams.converterFactory = FastJsonConverterFactory.create();
gsonService = createRetrofit(retrofitParams);
}
}
}
return gsonService;
}
}
| true |
128fa38472c9c36b9b8bcdf9606dc69a6a474e63 | Java | NPashaO/Uncontested_Testing_Team | /url-shrtnr-guitarosexuals/src/test/java/shortener/database/tables/AliasTableTest.java | UTF-8 | 2,214 | 2.703125 | 3 | [] | no_license | package shortener.database.tables;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import shortener.TestUtils;
import shortener.database.entities.Alias;
import shortener.exceptions.database.UniqueViolation;
public class AliasTableTest {
private static final String TEST_ROOT_DIRECTORY = "table-test-db";
private final AliasTable table = new AliasTable(Path.of(TEST_ROOT_DIRECTORY));
@AfterAll
static void purgeRootDirectory() {
TestUtils.purgeDirectory(new File(TEST_ROOT_DIRECTORY));
}
@BeforeEach
void setupRootDirectory() throws IOException {
TestUtils.purgeDirectory(new File(TEST_ROOT_DIRECTORY));
Files.createDirectory(Path.of(TEST_ROOT_DIRECTORY));
AliasTable.init(Path.of(TEST_ROOT_DIRECTORY));
}
@Test
void initCorrectlyCreatesNeededFiles() throws IOException {
TestUtils.purgeDirectory(new File(TEST_ROOT_DIRECTORY));
Files.createDirectory(Path.of(TEST_ROOT_DIRECTORY));
AliasTable.init(Path.of(TEST_ROOT_DIRECTORY));
// Check the filesystem
Assertions.assertThat(Files.exists(Path.of(TEST_ROOT_DIRECTORY, table.getTableName())))
.isTrue();
}
@Test
void prepareRecordForCreationThrowsIfSimilarAliasExists() throws IOException {
Files.write(table.getWritableFilePath(), "test|https://example.com|1\n".getBytes(),
StandardOpenOption.APPEND);
Assertions.assertThatThrownBy(() -> {
table.prepareRecordForCreation(new Alias("test", "https://example.com", 1L));
}).isInstanceOf(UniqueViolation.class);
}
@Test
void serializeWorksCorrectly() {
Assertions.assertThat(table.serialize(new Alias("al", "https://example.com", 1L)))
.isEqualTo("al|https://example.com|1");
}
@Test
void deserializeWorksCorrectly() {
Assertions.assertThat(table.deserialize("al|https://example.com|1"))
.isEqualTo(new Alias("al", "https://example.com", 1L));
}
}
| true |
082d402c12a96449c9a0ebd3f81b038ec91fcf98 | Java | JobanCai/study | /src/main/java/com/joban/study/design/media/Colleague.java | UTF-8 | 279 | 2.53125 | 3 | [] | no_license | package com.joban.study.design.media;
public abstract class Colleague {
private int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public abstract void setNumber(int number, Media media);
}
| true |
fdd2fc1160071c3fc8ad72b76bd8ce4e0d4582a6 | Java | Nyaungbinhla/spring-hadoop | /spring-hadoop-store/src/main/java/org/springframework/data/hadoop/store/expression/MapPartitionKeyPropertyAccessor.java | UTF-8 | 4,863 | 1.742188 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.hadoop.store.expression;
import java.util.Map;
import org.springframework.asm.MethodVisitor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.CompilablePropertyAccessor;
import org.springframework.expression.spel.support.ReflectivePropertyAccessor;
/**
* A {@link PropertyAccessor} reading values from a backing {@link Map} used by a
* partition key.
*
* @author Janne Valkealahti
*
*/
public class MapPartitionKeyPropertyAccessor extends ReflectivePropertyAccessor {
private final static Class<?>[] CLASSES = new Class<?>[] { Map.class };
private final static String mapClassDescriptor = "java/util/Map";
private volatile String typeDescriptor;
@Override
public Class<?>[] getSpecificTargetClasses() {
return CLASSES;
}
@Override
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
boolean containsKey = ((Map<?, ?>) target).containsKey(name);
if (containsKey) {
this.typeDescriptor = CodeFlow.toDescriptorFromObject(((Map<?, ?>) target).get(name));
}
return containsKey;
}
@Override
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
Map<?, ?> map = (Map<?, ?>) target;
Object value = map.get(name);
if (value == null && !map.containsKey(name)) {
throw new MapAccessException(name);
}
return new TypedValue(value);
}
@Override
public PropertyAccessor createOptimalAccessor(EvaluationContext evalContext, Object target, String name) {
return new MapOptimalPropertyAccessor(this.typeDescriptor);
}
public static class MapOptimalPropertyAccessor implements CompilablePropertyAccessor {
private final String typeDescriptor;
public MapOptimalPropertyAccessor(String typeDescriptor) {
this.typeDescriptor = typeDescriptor;
}
@Override
public Class<?>[] getSpecificTargetClasses() {
throw new UnsupportedOperationException("Should not be called on an MessageOptimalPropertyAccessor");
}
@Override
public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
return true;
}
@Override
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
return new TypedValue(((Map<?,?>) target).get(name));
}
@Override
public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
throw new UnsupportedOperationException("Should not be called on an MessageOptimalPropertyAccessor");
}
@Override
public void write(EvaluationContext context, Object target, String name, Object newValue)
throws AccessException {
throw new UnsupportedOperationException("Should not be called on an MessageOptimalPropertyAccessor");
}
@Override
public boolean isCompilable() {
return true;
}
@Override
public Class<?> getPropertyType() {
return Object.class;
}
@Override
public void generateCode(String propertyName, MethodVisitor mv, CodeFlow cf) {
String descriptor = cf.lastDescriptor();
if (descriptor == null) {
cf.loadTarget(mv);
}
if (descriptor == null || !mapClassDescriptor.equals(descriptor.substring(1))) {
mv.visitTypeInsn(CHECKCAST, mapClassDescriptor);
}
mv.visitLdcInsn(propertyName);
mv.visitMethodInsn(INVOKEINTERFACE, mapClassDescriptor, "get",
"(Ljava/lang/Object;)Ljava/lang/Object;", true);
if (typeDescriptor != null) {
CodeFlow.insertCheckCast(mv, typeDescriptor);
}
}
}
/**
* Exception thrown from {@code read} in order to reset a cached
* PropertyAccessor, allowing other accessors to have a try.
*/
@SuppressWarnings("serial")
private static class MapAccessException extends AccessException {
private final String key;
public MapAccessException(String key) {
super(null);
this.key = key;
}
@Override
public String getMessage() {
return "Map does not contain a value for key '" + this.key + "'";
}
}
}
| true |
a55702c22a32343882aae87d551187d6383c18b4 | Java | bug123luo/gunlocation | /src/main/java/com/tct/codec/pojo/DeviceBulletCountReplyMessage.java | UTF-8 | 342 | 1.6875 | 2 | [
"Apache-2.0"
] | permissive | package com.tct.codec.pojo;
public class DeviceBulletCountReplyMessage extends SimpleMessage {
private DeviceBulletCountReplyBody messageBody;
public DeviceBulletCountReplyBody getMessageBody() {
return messageBody;
}
public void setMessageBody(DeviceBulletCountReplyBody messageBody) {
this.messageBody = messageBody;
}
}
| true |
f63f4954cdf2d76d4a6e5d4c6aefe7fdd83c2f61 | Java | arpitmittal99635/OSS | /eclipselink.runtime-2.5.0/moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/events/descriptor/PostBuildEventTestCases.java | UTF-8 | 2,686 | 1.789063 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* dmccann - 1.0M9 - Initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.oxm.events.descriptor;
import java.util.ArrayList;
import org.eclipse.persistence.oxm.platform.XMLPlatform;
import org.eclipse.persistence.testing.oxm.OXTestCase.Platform;
import org.eclipse.persistence.testing.oxm.events.Address;
import org.eclipse.persistence.testing.oxm.events.Employee;
import org.eclipse.persistence.testing.oxm.mappings.XMLMappingTestCases;
import org.w3c.dom.Document;
public class PostBuildEventTestCases extends XMLMappingTestCases {
static Integer EMPLOYEE_POST_BUILD = new Integer(0);
static Integer ADDRESS_POST_BUILD = new Integer(1);
EmployeeProject project;
public PostBuildEventTestCases(String name) throws Exception {
super(name);
project = new EmployeeProject();
setProject(project);
setControlDocument("org/eclipse/persistence/testing/oxm/events/composite_object.xml");
}
public void setUp() throws Exception {
super.setUp();
project.setup();
}
public void xmlToObjectTest(Object testObject) throws Exception {
super.xmlToObjectTest(testObject);
assertTrue("Employee post build event did not occur as expected", project.events.contains(EMPLOYEE_POST_BUILD));
assertTrue("Address post build event did not occur as expected", project.events.contains(ADDRESS_POST_BUILD));
}
public Object getControlObject() {
Employee employee = new Employee();
Address address = new Address();
address.street = "2201 Riverside Drive";
employee.address = address;
if (platform == Platform.SAX) {
employee.anyCollection = new ArrayList(); // initialize list for equality check
}
return employee;
}
public static void main(String[] args) {
junit.textui.TestRunner.main(new String[] { "-c", "org.eclipse.persistence.testing.oxm.events.descriptor.PostBuildEventTestCases" });
}
}
| true |
99a20ab670b87ef3acac807ffd0ff423145dd98e | Java | cha63506/CompSecurity | /Shopping/offerup_source/src/com/offerup/android/activities/bk.java | UTF-8 | 1,031 | 1.546875 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.offerup.android.activities;
import android.content.DialogInterface;
import android.support.v4.e.a;
import com.offerup.android.utils.n;
// Referenced classes of package com.offerup.android.activities:
// br, ChatActivity
final class bk
implements android.content.DialogInterface.OnClickListener
{
private android.app.AlertDialog.Builder a;
private ChatActivity b;
bk(ChatActivity chatactivity, android.app.AlertDialog.Builder builder)
{
b = chatactivity;
a = builder;
super();
}
public final void onClick(DialogInterface dialoginterface, int i)
{
dialoginterface.dismiss();
if (android.support.v4.e.a.b(b))
{
b.a(new br(b, b), new Object[0]);
return;
} else
{
n.a(a);
return;
}
}
}
| true |
0459fbc971cc7fd01618761cf1cd32f2a4a14f11 | Java | zhangchunling/JavaEE_CodeNote | /src/com/study/网络编程/TCP协议网络编程/Demo/Server.java | UTF-8 | 2,280 | 3.28125 | 3 | [] | no_license | package com.study.网络编程.TCP协议网络编程.Demo;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* TCP Server
* @author 矫迩
* HTTP(HyperText Transfer Protocol):超文本传输协议:规定好了数据格式
* HTML语言 (超级文本标记语言)
*/
public class Server {
// 1.请求协议
public static void main(String[] args) throws Exception {
//创建服务器套接字
ServerSocket server = new ServerSocket(20000);//指定端口号创建服务器
//这儿接收时会出现等待,当客户端访问时,会返回与客户端Socket对应的Socket
Socket socket = server.accept();
//接收客户端输入流
InputStream inputStream = socket.getInputStream();
int read;
System.out.println("来自客户端的数据:");
while((read=inputStream.read()) != -1) {
System.out.print((char)read);
}
socket.close();
inputStream.close();
server.close();
}
}
/**请求协议:共三部分*//*客户端输入网址:http://192.168.1.254:123/后会收到如下——请求协议*/
/*1.请求头 请求行
//GET / HTTP/1.1 GET:请求方式 HTTP/1.1:请求版本
*/
/*2.消息报头 key:value 冒号前面是key,后面是值
//Accept: text/html, application/xhtml+xml,
//Accept-Language: zh-CN
//User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0) Trident:内核
//Accept-Encoding: gzip, deflate X //有了这行,服务器发给客户端的是压缩包
//Host: 192.168.1.254:123
//DNT: 1 DNT(do not track)
//Connection: Keep-Alive
// 这儿有个换行不能漏掉了,所以在客户端写请求协议时,上面一行要加两个\r\n
*/
/*3.请求正文
内容……*/
/**请求协议*/
/*以网址http://192.168.1.254:123/324324/fasfasdfasfasffa/fasfasd访问时,加粗部分自动加到GET与HTTP/1.1之间*/
//GET /324324/fasfasdfasfasffa/fasfasd HTTP/1.1
//Accept: text/html, application/xhtml+xml, */*
//Accept-Language: zh-CN
//User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
//Accept-Encoding: gzip, deflate
//Host: 192.168.1.254:123
//DNT: 1
//Connection: Keep-Alive
| true |
a07b7673d9d113c4c2f13937757b708cf15f90c9 | Java | oxford-fumble/anathema | /Namegenerator/src/net/sf/anathema/namegenerator/presenter/model/INameGeneratorModel.java | UTF-8 | 478 | 2.078125 | 2 | [] | no_license | package net.sf.anathema.namegenerator.presenter.model;
import net.sf.anathema.lib.control.ChangeListener;
import net.sf.anathema.lib.util.Identifier;
import java.util.Set;
public interface INameGeneratorModel {
void addGeneratorTypeChangeListener(ChangeListener listener);
Set<Identifier> getGeneratorTypes();
Identifier getSelectedGeneratorType();
void setGeneratorType(Identifier selectedGeneratorType);
String[] generateNames(int count);
} | true |
bc1df22546f139bf954e8b2a5263bb910bb90e9e | Java | ivanteejj/main | /src/test/java/seedu/address/testutil/TeacherBuilder.java | UTF-8 | 4,770 | 2.875 | 3 | [
"MIT"
] | permissive | package seedu.address.testutil;
import seedu.address.model.modelObjectTags.*;
import seedu.address.model.modelStaff.Staff;
import seedu.address.model.tag.Tag;
import seedu.address.model.util.SampleDataUtil;
import java.util.HashSet;
import java.util.Set;
/**
* A utility class to help with building Teacher objects.
*/
public class TeacherBuilder {
public static final String DEFAULT_NAME = "Alice Pauline";
public static final String DEFAULT_LEVEL = "TEACHER";
public static final String DEFAULT_ID = "120";
public static final String DEFAULT_GENDER = "f";
public static final String DEFAULT_PHONE = "85355255";
public static final String DEFAULT_EMAIL = "alice@gmail.com";
public static final String DEFAULT_SALARY = "1000";
public static final String DEFAULT_ASSIGNEDCOURSES = "";
public static final String DEFAULT_ADDRESS = "123, Jurong West Ave 6, #08-111";
private Name name;
private Staff.Level level;
private ID id;
private Gender gender;
private Phone phone;
private Email email;
private Salary salary;
private Address address;
private Set<ID> assignedCourses;
private Set<Tag> tags;
public TeacherBuilder() {
name = new Name(DEFAULT_NAME);
id = new ID(DEFAULT_ID);
gender = new Gender(DEFAULT_GENDER);
if (DEFAULT_LEVEL.equals("TEACHER")) {
level = Staff.Level.TEACHER;
} else {
level = Staff.Level.ADMIN;
}
phone = new Phone(DEFAULT_PHONE);
email = new Email(DEFAULT_EMAIL);
salary = new Salary(DEFAULT_SALARY);
assignedCourses = new HashSet<>();
address = new Address(DEFAULT_ADDRESS);
tags = new HashSet<>();
}
/**
* Initializes the TeacherBuilder with the data of {@code teacherToCopy}.
*/
public TeacherBuilder(Staff teacherToCopy) {
name = teacherToCopy.getName();
level = teacherToCopy.getLevel();
phone = teacherToCopy.getPhone();
email = teacherToCopy.getEmail();
salary = teacherToCopy.getSalary();
assignedCourses = teacherToCopy.getAssignedCoursesID();
address = teacherToCopy.getAddress();
tags = new HashSet<>(teacherToCopy.getTags());
}
/**
* Sets the {@code Name} of the {@code Teacher} that we are building.
*/
public TeacherBuilder withName(String name) {
this.name = new Name(name);
return this;
}
/**
* Sets the {@code ID} of the {@code Teacher} that we are building.
*/
public TeacherBuilder withID(String id) {
this.id = new ID(id);
return this;
}
/**
* Sets the {@code Level} of the {@code Staff} that we are building.
*/
public TeacherBuilder withLevel(String level) {
level = level.trim().toUpperCase();
if (level.equals("TEACHER")) {
this.level = Staff.Level.TEACHER;
} else if (level.equals("ADMIN")) {
this.level = Staff.Level.ADMIN;
}
return this;
}
/**
* Sets the {@code Gender} of the {@code Staff} that we are building.
*/
public TeacherBuilder withGender(String gender) {
this.gender = new Gender(gender);
return this;
}
/**
* Parses the {@code tags} into a {@code Set<Tag>} and set it to the {@code Teacher} that we are building.
*/
public TeacherBuilder withTags(String... tags) {
this.tags = SampleDataUtil.getTagSet(tags);
return this;
}
/**
* Sets the {@code AssignedCourses} of the {@code Teacher} that we are building.
*/
public TeacherBuilder withAssignedCourses(String assignedCourses) {
this.assignedCourses = SampleDataUtil.getIDSet(assignedCourses);
return this;
}
/**
* Sets the {@code Address} of the {@code Teacher} that we are building.
*/
public TeacherBuilder withAddress(String address) {
this.address = new Address(address);
return this;
}
/**
* Sets the {@code Phone} of the {@code Teacher} that we are building.
*/
public TeacherBuilder withPhone(String phone) {
this.phone = new Phone(phone);
return this;
}
/**
* Sets the {@code Email} of the {@code Teacher} that we are building.
*/
public TeacherBuilder withEmail(String email) {
this.email = new Email(email);
return this;
}
/**
* Sets the {@code Salary} of the {@code Teacher} that we are building.
*/
public TeacherBuilder withSalary(String salary) {
this.salary = new Salary(salary);
return this;
}
public Staff build() {
return new Staff(name, id, gender, level, phone, email, salary, address, tags);
}
}
| true |
c693471126c378da8fc7daf61198d70773f3e09c | Java | xiaobxia/haze_api | /gringotts-core/src/main/java/com/vxianjin/gringotts/web/dao/impl/PublicAboutDao.java | UTF-8 | 810 | 2.046875 | 2 | [] | no_license | package com.vxianjin.gringotts.web.dao.impl;
import com.vxianjin.gringotts.web.dao.IPublicAboutDao;
import com.vxianjin.gringotts.web.pojo.PublicAbout;
import org.springframework.stereotype.Repository;
@Repository
public class PublicAboutDao extends BaseDao implements IPublicAboutDao {
/**
* 新增关于
*/
public int searchPublicAbout(PublicAbout about) {
return this.getSqlSessionTemplate().insert("searchPublicAbout", about);
}
/**
* 查询关于
*/
public PublicAbout selectPublicAbout() {
return this.getSqlSessionTemplate().selectOne("selectPublicAbout");
}
/**
* 修改关于
*/
public int updatePublicAbout(PublicAbout about) {
return this.getSqlSessionTemplate().update("updatePublicAbout", about);
}
}
| true |
3ebb4eb3a3c1ab68d98177b2b399361ac3c25d15 | Java | sspringday/springboot-mybatis | /src/main/java/com/ergou/springbootmybatis/web/json/DefaultResponseJson.java | UTF-8 | 4,684 | 2.515625 | 3 | [] | no_license | package com.ergou.springbootmybatis.web.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import java.util.Date;
import java.util.List;
/**
* @author 程二狗
* @since 2019/6/25 0025 17:04
*/
public class DefaultResponseJson implements ResponseJson {
private static SerializeConfig mapping = new SerializeConfig();
static {
mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
}
/** 状态码 **/
private int errCode;
/** 返回值说明 **/
private String errMsg;
/** 返回数据 **/
private Object data;
/** 总数 **/
private Long total;
/** 当前页数 **/
private Integer pageNum;
/** 每页条数 **/
private Integer pageSize;
/** 总页数 **/
private Integer totalPage;
/** 当前服务器时间**/
// private String serverTime = DateTimeHelper.formatDateTimetoString(new Date());
/** 额外信息 **/
private Object extra;
private Object error;
public void setData(Object data) {
this.data = data;
}
public DefaultResponseJson() {
this.setData("");
this.errCode = 200;
}
public DefaultResponseJson(Object data) {
this.setData(data);
this.errCode = 200;
}
public DefaultResponseJson(int errCode, String errMsg) {
super();
this.errCode = errCode;
this.errMsg = errMsg;
}
public DefaultResponseJson(int errCode, String errMsg, Object data) {
super();
this.setData(data);
this.errCode = errCode;
this.errMsg = errMsg;
}
public DefaultResponseJson(int errCode) {
super();
this.errCode = errCode;
}
public <T> DefaultResponseJson(List<Object> data, Long total, Integer pageNum, Integer numPerPage) {
super();
this.errCode = 200;
this.data = data;
this.total = total;
this.pageNum = pageNum;
this.pageSize = numPerPage;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public Object getExtra() {
return extra;
}
public void setExtra(Object extra) {
this.extra = extra;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public int getErrCode() {
return errCode;
}
public void setErrCode(int errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public Object getData() {
return data;
}
// public void setData(Object data) {
// if (null != data) {
// if(data instanceof PageInfo) {
// PageInfo<?> pageInfo = (PageInfo<?>) data;
// this.data = pageInfo.getList();
// this.total = pageInfo.getTotal();
// this.pageNum = pageInfo.getPageNum();
// this.pageSize = pageInfo.getPageSize();
// this.totalPage = pageInfo.getPages();
// }else {
// this.data = data;
// }
// }
// }
// public String getServerTime() {
// return serverTime;
// }
//
// public void setServerTime(String serverTime) {
// this.serverTime = serverTime;
// }
public static DefaultResponseJson warn(String errMsg){
return new DefaultResponseJson(300, errMsg);
}
/**
* 成功的返回方法
*/
public static DefaultResponseJson ok(){
return new DefaultResponseJson();
}
/**
* 成功的返回方法
*/
public static DefaultResponseJson ok(Object data){
return new DefaultResponseJson(data);
}
public String toJson() {
return JSON.toJSONString(this, mapping);
}
@Override
public String toString() {
return "DefaultResponseJson [errCode=" + errCode + ", errMsg=" + errMsg + ", data=" + data + "]";
}
public Object getError() {
return error;
}
public void setError(Object error) {
this.error = error;
}
}
| true |
8ac89f9fe95405b55325599be0b6ebc4e8aa15ad | Java | bilalbenma/Onto-Metrics | /src/de/edu/rostock/ontologymetrics/owlapi/ontology/metric/basemetric/graphbasemetric/graphmetric/AverageBreadthMetric.java | UTF-8 | 829 | 2.421875 | 2 | [] | no_license | package de.edu.rostock.ontologymetrics.owlapi.ontology.metric.basemetric.graphbasemetric.graphmetric;
import java.util.Set;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLOntology;
import de.edu.rostock.ontologymetrics.owlapi.ontology.metric.basemetric.graphbasemetric.GraphBaseLevelsMetric;
public class AverageBreadthMetric extends GraphMetric {
public AverageBreadthMetric(OWLOntology pOntology) {
super(pOntology);
}
@Override
public Float getValue() {
int breadth = 0;
Set<Set<OWLClass>> levels = new GraphBaseLevelsMetric(ontology)
.getValue();
for (Set<OWLClass> path : levels) {
breadth = breadth + path.size();
}
return (float) breadth / (float) levels.size();
}
@Override
public String toString() {
return "Average depth";
}
}
| true |
80677c1fea7c1c57567ed1ee94db54769767f942 | Java | clachic00/AIA | /java_project/MyPhoneBook/src/versionA5/PhoneCompanyInfor.java | UTF-8 | 385 | 2.734375 | 3 | [] | no_license | package versionA5;
public class PhoneCompanyInfor extends PhoneInfor {
String company;
PhoneCompanyInfor(String name, String phoneNumber, String address, String email, String company) {
super(name, phoneNumber, address, email);
this.company = company;
}
@Override
public void showData() {
super.showInfo();
System.out.println("회사 : " + this.company);
}
}
| true |
e3601251c46047ed7f15563c5dbb044e0f20a150 | Java | FeraFLN/war | /src/main/java/com/ferafln/war/territorio/util/Props.java | UTF-8 | 1,180 | 2.5 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ferafln.war.territorio.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
*
* @author feraf
*/
public class Props {
public static Properties getProperties(String path) {
InputStream file = null;
Properties properties = null;
try {
properties = new Properties();
file = new FileInputStream(path);
properties.load(file);
file.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
//TODO treat exception
} catch (IOException ex) {
//TODO treat exception
ex.printStackTrace();
} finally {
try {
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return properties;
}
public static Properties getProperties(PropFilesEnum path) {
return getProperties(path.getPath());
}
}
| true |
9e822229faaaadf8660aff1f94e84721eeb65141 | Java | flozano/lucene-problems | /lucene-problems/lucene-query-parse/src/test/java/com/kii/testcase/lucenequery/QueryParseProblemTest.java | UTF-8 | 5,165 | 2.5 | 2 | [] | no_license | package com.kii.testcase.lucenequery;
import org.apache.lucene.search.Query;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
public class QueryParseProblemTest {
@Rule
public TestName name = new TestName();
public void check(Query oldStyle, Query newStyle) {
System.out.println("====================================");
System.out.println("Test " + name.getMethodName() + ": "
+ oldStyle.equals(newStyle));
System.out.println("Old = " + oldStyle);
System.out.println("New = " + newStyle);
Assert.assertEquals("Test " + name, oldStyle, newStyle);
}
@Test
public void testJapaneseAndQueryWithDefaultAnd() {
String query = "_deleted:true AND title:東京";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testJapaneseAndQueryWithDefaultOr() {
String query = "_deleted:true AND title:東京";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
@Test
public void testJapaneseQueryWithDefaultAnd() {
String query = "_deleted:true title:東京";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testJapaneseQueryWithDefaultOr() {
String query = "_deleted:true title:東京";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
@Test
public void testEnglishAndQueryWithDefaultAnd() {
String query = "_deleted:true AND title:Tokyo";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testEnglishAndQueryWithDefaultOr() {
String query = "_deleted:true AND title:Tokyo";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
@Test
public void testEnglishQueryWithDefaultAnd() {
String query = "_deleted:true title:Tokyo";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testEnglishParenthesisQueryWithDefaultOr() {
String query = "_deleted:true (title:Tokyo)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
@Test
public void testEnglishParenthesisAndQueryWithDefaultAnd() {
String query = "_deleted:true AND (title:Tokyo)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testEnglishAndParenthesisQueryWithDefaultOr() {
String query = "_deleted:true AND (title:Tokyo)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
@Test
public void testEnglishParenthesisQueryWithDefaultAnd() {
String query = "_deleted:true (title:Tokyo)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testEnglishQueryWithDefaultOr() {
String query = "_deleted:true title:Tokyo";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
@Test
public void testJapaneseAndParenthesisQueryWithDefaultAnd() {
String query = "_deleted:true AND (title:東京)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testJapaneseAndParenthesisQueryWithDefaultOr() {
String query = "_deleted:true AND (title:東京)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
@Test
public void testJapaneseParenthesisQueryWithDefaultAnd() {
String query = "_deleted:true (title:東京)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, true);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, true);
check(oldStyle, newStyle);
}
@Test
public void testJapaneseParenthesisQueryWithDefaultOr() {
String query = "_deleted:true (title:東京)";
Query oldStyle = ParserUtil.parseWithQueryParser(query, false);
Query newStyle = ParserUtil.parseWithStandardQueryParser(query, false);
check(oldStyle, newStyle);
}
}
| true |
9227c997d2427fe3f511b4af11289124a61fc428 | Java | marianaNamubiru/I-Doctor | /app/src/main/java/com/example/i_doctor/helpers/MyPreferenceManager.java | UTF-8 | 3,764 | 2.484375 | 2 | [] | no_license | package com.example.i_doctor.helpers;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
public class MyPreferenceManager {
private String TAG = MyPreferenceManager.class.getSimpleName();
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file title
private static final String PREF_NAME = "androidhive_gcm";
// All Shared Preferences Keys
private static final String KEY_USER_ID = "user_id";
private static final String KEY_FIRSTNAME = "FirstName";
private static final String KEY_LASTNAME = "LastName";
private static final String KEY_USERNAME = "username";
private static final String KEY_COUNTRY = "Country";
private static final String KEY_PHONECONTACT = "PhoneContact";
private static final String KEY_Date_of_birth = "Date_of_birth";
private static final String KEY_EMAILADDRESS = "EmailAddress";
private static final String KEY_GENDER = "Gender";
private static final String KEY_HOSPITAL = "Hospital";
private static final String KEY_ADDRESS = "Address";
// Constructor
public MyPreferenceManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void storeUser(User user) {
editor.putString(KEY_USER_ID, user.getId());
editor.putString(KEY_FIRSTNAME, user.getFirstName());
editor.putString(KEY_LASTNAME, user.getLastName());
editor.putString(KEY_USERNAME, user.getusername());
editor.putString(KEY_COUNTRY, user.getCountry());
editor.putString(KEY_PHONECONTACT, user.getPhoneContact());
editor.putString(KEY_Date_of_birth, user.getDate_of_birth());
editor.putString(KEY_EMAILADDRESS, user.getEmailAddress());
editor.putString(KEY_GENDER, user.getGender());
editor.putString(KEY_HOSPITAL, user.getHospital());
editor.putString(KEY_ADDRESS, user.getAddress());
editor.commit();
Log.e(TAG, "User is stored in shared preferences. " + user.getFirstName() + ", " + user.getLastName()
+ "," + user.getusername()+ "," + user.getCountry()+ "," + user.getPhoneContact() + "," + user.getDate_of_birth()
+ "," +user.getEmailAddress()+ "," +user.getGender() + "," + user.getHospital() + "," + user.getAddress() );
}
public User getUser() {
if (pref.getString(KEY_USER_ID, null) != null) {
String id, FirstName, LastName, username,Country,PhoneContact,Date_of_birth,EmailAddress,Gender,
Hospital,Address;
id = pref.getString(KEY_USER_ID, null);
FirstName = pref.getString(KEY_FIRSTNAME, null);
LastName = pref.getString(KEY_LASTNAME, null);
username = pref.getString(KEY_USERNAME, null);
Country = pref.getString(KEY_COUNTRY, null);
PhoneContact = pref.getString(KEY_PHONECONTACT, null);
Date_of_birth = pref.getString(KEY_Date_of_birth, null);
EmailAddress = pref.getString(KEY_EMAILADDRESS, null);
Gender = pref.getString(KEY_GENDER, null);
Hospital = pref.getString(KEY_HOSPITAL, null);
Address = pref.getString(KEY_ADDRESS, null);
User user = new User(id, FirstName, LastName,username,Country,PhoneContact,Date_of_birth,EmailAddress,Gender,Hospital,Address);
return user;
}
return null;
}
public void clear() {
editor.clear();
editor.commit();
}
}
| true |
bdb43ad440ceb887b280744f6bcd4ae11ef9e5b5 | Java | Excombatient/Minas | /Minas/src/minas/leerTXT.java | UTF-8 | 2,075 | 2.6875 | 3 | [] | no_license | package minas;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
*
* @author JJ
*/
public class leerTXT{
private static final String FILENAME = "puntuacion.txt";
public static void EndStage(StageManage<Stage> primaryStage) {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Scene scene = new Scene(grid, 300, 275);
primaryStage.getMainStage().setScene(scene);
Text scenetitle = new Text("Puntuacion de Usuarios");
scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
grid.add(scenetitle,0,0,1, 1);
ArrayList<String> jugadores = new ArrayList<String>();
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
jugadores.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("hola"+jugadores);
String listString = "";
for (String s : jugadores){
listString += s + "\n";
}
System.out.println(listString);
Text area = new Text(listString);
grid.add(area,0,5, 4, 4);
}
}
| true |
61872f71dc7560f2fd8d396df61f09dee15e42f2 | Java | ithub-moscow/course_java_2 | /lambda.expressions/src/main/java/ru/course/stream/api/homework/Task1.java | UTF-8 | 1,008 | 3.40625 | 3 | [] | no_license | package ru.course.stream.api.homework;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.BinaryOperator;
public class Task1 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("sdfghjkl");
list.add("sdfghjdfghj");
list.add("kjhgfdoiuytr");
list.add("wertyuiocvbfghjk");
Comparator<String> cmp = (s1, s2) -> Integer.compare(s2.length(), s1.length());
Collections.max(list, cmp);
list.stream()
.sorted(cmp)
.findFirst();
list.stream().max(cmp);
BinaryOperator<String> func = (max, item) -> {
if(max.length() > item.length())
return max;
else
return item;
};
list.stream()
.reduce((max, item) ->
max.length() < item.length() ? item : max);
}
}
| true |
2863fe07305ad8358d6e873f5e359987df29130a | Java | linsir6/WeChat_java | /com/tencent/mm/modelsfs/g.java | UTF-8 | 9,800 | 1.921875 | 2 | [] | no_license | package com.tencent.mm.modelsfs;
import java.util.EnumSet;
final class g {
public enum a {
NOESCAPE,
PATHNAME,
PERIOD,
LEADING_DIR,
CASEFOLD
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
static boolean a(java.lang.String r9, int r10, java.lang.String r11, int r12, java.util.EnumSet<com.tencent.mm.modelsfs.g.a> r13) {
/*
L_0x0000:
r0 = r9.length();
if (r10 < r0) goto L_0x0022;
L_0x0006:
r0 = com.tencent.mm.modelsfs.g.a.LEADING_DIR;
r0 = r13.contains(r0);
if (r0 == 0) goto L_0x0018;
L_0x000e:
r0 = r11.charAt(r12);
r1 = 47;
if (r0 != r1) goto L_0x0018;
L_0x0016:
r0 = 1;
L_0x0017:
return r0;
L_0x0018:
r0 = r11.length();
if (r12 != r0) goto L_0x0020;
L_0x001e:
r0 = 1;
goto L_0x0017;
L_0x0020:
r0 = 0;
goto L_0x0017;
L_0x0022:
r0 = r10 + 1;
r1 = r9.charAt(r10);
switch(r1) {
case 42: goto L_0x0223;
case 63: goto L_0x0034;
case 91: goto L_0x00e8;
case 92: goto L_0x01db;
default: goto L_0x002b;
};
L_0x002b:
r10 = r0;
L_0x002c:
r0 = r11.length();
if (r12 < r0) goto L_0x01f6;
L_0x0032:
r0 = 0;
goto L_0x0017;
L_0x0034:
r1 = r11.length();
if (r12 < r1) goto L_0x003c;
L_0x003a:
r0 = 0;
goto L_0x0017;
L_0x003c:
r1 = r11.charAt(r12);
r2 = 47;
if (r1 != r2) goto L_0x004e;
L_0x0044:
r1 = com.tencent.mm.modelsfs.g.a.PATHNAME;
r1 = r13.contains(r1);
if (r1 == 0) goto L_0x004e;
L_0x004c:
r0 = 0;
goto L_0x0017;
L_0x004e:
r1 = a(r11, r12, r13);
if (r1 == 0) goto L_0x0056;
L_0x0054:
r0 = 0;
goto L_0x0017;
L_0x0056:
r12 = r12 + 1;
r10 = r0;
goto L_0x0000;
L_0x005a:
r0 = r9.length();
if (r10 >= r0) goto L_0x006c;
L_0x0060:
r0 = r9.charAt(r10);
r1 = 42;
if (r0 != r1) goto L_0x006d;
L_0x0068:
r10 = r10 + 1;
r1 = r0;
goto L_0x005a;
L_0x006c:
r0 = r1;
L_0x006d:
r1 = a(r11, r12, r13);
if (r1 == 0) goto L_0x0075;
L_0x0073:
r0 = 0;
goto L_0x0017;
L_0x0075:
r1 = r9.length();
if (r10 != r1) goto L_0x009b;
L_0x007b:
r0 = com.tencent.mm.modelsfs.g.a.PATHNAME;
r0 = r13.contains(r0);
if (r0 == 0) goto L_0x0098;
L_0x0083:
r0 = com.tencent.mm.modelsfs.g.a.LEADING_DIR;
r0 = r13.contains(r0);
if (r0 != 0) goto L_0x0094;
L_0x008b:
r0 = 47;
r0 = r11.indexOf(r0, r12);
r1 = -1;
if (r0 != r1) goto L_0x0096;
L_0x0094:
r0 = 1;
goto L_0x0017;
L_0x0096:
r0 = 0;
goto L_0x0017;
L_0x0098:
r0 = 1;
goto L_0x0017;
L_0x009b:
r1 = 47;
if (r0 != r1) goto L_0x00c5;
L_0x009f:
r0 = com.tencent.mm.modelsfs.g.a.PATHNAME;
r0 = r13.contains(r0);
if (r0 == 0) goto L_0x00c5;
L_0x00a7:
r0 = 47;
r12 = r11.indexOf(r0, r12);
r0 = -1;
if (r12 != r0) goto L_0x0000;
L_0x00b0:
r0 = 0;
goto L_0x0017;
L_0x00b3:
r0 = r11.charAt(r12);
r1 = 47;
if (r0 != r1) goto L_0x00c3;
L_0x00bb:
r0 = com.tencent.mm.modelsfs.g.a.PATHNAME;
r0 = r13.contains(r0);
if (r0 != 0) goto L_0x00e5;
L_0x00c3:
r12 = r12 + 1;
L_0x00c5:
r0 = r11.length();
if (r12 >= r0) goto L_0x00e5;
L_0x00cb:
r0 = com.tencent.mm.modelsfs.g.a.PERIOD;
r0 = r13.contains(r0);
if (r0 == 0) goto L_0x00dc;
L_0x00d3:
r13 = java.util.EnumSet.copyOf(r13);
r0 = com.tencent.mm.modelsfs.g.a.PERIOD;
r13.remove(r0);
L_0x00dc:
r0 = a(r9, r10, r11, r12, r13);
if (r0 == 0) goto L_0x00b3;
L_0x00e2:
r0 = 1;
goto L_0x0017;
L_0x00e5:
r0 = 0;
goto L_0x0017;
L_0x00e8:
r2 = r11.length();
if (r12 < r2) goto L_0x00f1;
L_0x00ee:
r0 = 0;
goto L_0x0017;
L_0x00f1:
r2 = r11.charAt(r12);
r3 = 47;
if (r2 != r3) goto L_0x0104;
L_0x00f9:
r2 = com.tencent.mm.modelsfs.g.a.PATHNAME;
r2 = r13.contains(r2);
if (r2 == 0) goto L_0x0104;
L_0x0101:
r0 = 0;
goto L_0x0017;
L_0x0104:
r2 = a(r11, r12, r13);
if (r2 == 0) goto L_0x010d;
L_0x010a:
r0 = 0;
goto L_0x0017;
L_0x010d:
r3 = r11.charAt(r12);
r2 = r9.length();
if (r0 < r2) goto L_0x0120;
L_0x0117:
r10 = -1;
L_0x0118:
r2 = -1;
if (r10 == r2) goto L_0x002b;
L_0x011b:
if (r10 != 0) goto L_0x01d7;
L_0x011d:
r0 = 0;
goto L_0x0017;
L_0x0120:
r2 = r9.charAt(r0);
r4 = 33;
if (r2 == r4) goto L_0x012c;
L_0x0128:
r4 = 94;
if (r2 != r4) goto L_0x0148;
L_0x012c:
r2 = 1;
r8 = r2;
L_0x012e:
if (r8 == 0) goto L_0x0220;
L_0x0130:
r2 = r0 + 1;
L_0x0132:
r4 = com.tencent.mm.modelsfs.g.a.CASEFOLD;
r4 = r13.contains(r4);
if (r4 == 0) goto L_0x013e;
L_0x013a:
r3 = java.lang.Character.toLowerCase(r3);
L_0x013e:
r4 = 0;
r5 = r2;
L_0x0140:
r2 = r9.length();
if (r5 < r2) goto L_0x014b;
L_0x0146:
r10 = -1;
goto L_0x0118;
L_0x0148:
r2 = 0;
r8 = r2;
goto L_0x012e;
L_0x014b:
r10 = r5 + 1;
r2 = r9.charAt(r5);
r5 = 93;
if (r2 == r5) goto L_0x01d2;
L_0x0155:
r5 = 92;
if (r2 != r5) goto L_0x021d;
L_0x0159:
r5 = com.tencent.mm.modelsfs.g.a.NOESCAPE;
r5 = r13.contains(r5);
if (r5 != 0) goto L_0x021d;
L_0x0161:
r5 = r10 + 1;
r2 = r9.charAt(r10);
L_0x0167:
r6 = 47;
if (r2 != r6) goto L_0x0175;
L_0x016b:
r6 = com.tencent.mm.modelsfs.g.a.PATHNAME;
r6 = r13.contains(r6);
if (r6 == 0) goto L_0x0175;
L_0x0173:
r10 = 0;
goto L_0x0118;
L_0x0175:
r6 = com.tencent.mm.modelsfs.g.a.CASEFOLD;
r6 = r13.contains(r6);
if (r6 == 0) goto L_0x0181;
L_0x017d:
r2 = java.lang.Character.toLowerCase(r2);
L_0x0181:
r6 = r9.charAt(r5);
r7 = 45;
if (r6 != r7) goto L_0x01cc;
L_0x0189:
r6 = r5 + 1;
r7 = r9.length();
if (r6 >= r7) goto L_0x01cc;
L_0x0191:
r6 = r5 + 1;
r7 = r9.charAt(r6);
r6 = 93;
if (r7 == r6) goto L_0x01cc;
L_0x019b:
r6 = r5 + 2;
r5 = 92;
if (r7 != r5) goto L_0x021b;
L_0x01a1:
r5 = com.tencent.mm.modelsfs.g.a.NOESCAPE;
r5 = r13.contains(r5);
if (r5 != 0) goto L_0x021b;
L_0x01a9:
r2 = r9.length();
if (r6 < r2) goto L_0x01b2;
L_0x01af:
r10 = -1;
goto L_0x0118;
L_0x01b2:
r5 = r6 + 1;
r2 = r9.charAt(r6);
L_0x01b8:
r6 = com.tencent.mm.modelsfs.g.a.CASEFOLD;
r6 = r13.contains(r6);
if (r6 == 0) goto L_0x0219;
L_0x01c0:
r6 = java.lang.Character.toLowerCase(r7);
L_0x01c4:
if (r2 > r3) goto L_0x0140;
L_0x01c6:
if (r3 > r6) goto L_0x0140;
L_0x01c8:
r2 = 1;
r4 = r2;
goto L_0x0140;
L_0x01cc:
if (r2 != r3) goto L_0x0140;
L_0x01ce:
r2 = 1;
r4 = r2;
goto L_0x0140;
L_0x01d2:
if (r4 != r8) goto L_0x0118;
L_0x01d4:
r10 = 0;
goto L_0x0118;
L_0x01d7:
r12 = r12 + 1;
goto L_0x0000;
L_0x01db:
r2 = com.tencent.mm.modelsfs.g.a.NOESCAPE;
r2 = r13.contains(r2);
if (r2 != 0) goto L_0x002b;
L_0x01e3:
r1 = r9.length();
if (r0 < r1) goto L_0x01ee;
L_0x01e9:
r1 = 92;
r10 = r0;
goto L_0x002c;
L_0x01ee:
r10 = r0 + 1;
r1 = r9.charAt(r0);
goto L_0x002c;
L_0x01f6:
r0 = r11.charAt(r12);
if (r1 == r0) goto L_0x0215;
L_0x01fc:
r0 = com.tencent.mm.modelsfs.g.a.CASEFOLD;
r0 = r13.contains(r0);
if (r0 == 0) goto L_0x0212;
L_0x0204:
r0 = java.lang.Character.toLowerCase(r1);
r1 = r11.charAt(r12);
r1 = java.lang.Character.toLowerCase(r1);
if (r0 == r1) goto L_0x0215;
L_0x0212:
r0 = 0;
goto L_0x0017;
L_0x0215:
r12 = r12 + 1;
goto L_0x0000;
L_0x0219:
r6 = r7;
goto L_0x01c4;
L_0x021b:
r5 = r6;
goto L_0x01b8;
L_0x021d:
r5 = r10;
goto L_0x0167;
L_0x0220:
r2 = r0;
goto L_0x0132;
L_0x0223:
r10 = r0;
goto L_0x005a;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.modelsfs.g.a(java.lang.String, int, java.lang.String, int, java.util.EnumSet):boolean");
}
private static boolean a(String str, int i, EnumSet<a> enumSet) {
if (i > str.length() - 1) {
return false;
}
if ((i == 0 || (enumSet.contains(a.PATHNAME) && str.charAt(i - 1) == '/')) && str.charAt(i) == '.' && enumSet.contains(a.PERIOD)) {
return true;
}
return false;
}
}
| true |
8c2e9870700710986cef69adef25e4d96245ad67 | Java | tomcatx7/utils | /TimeUtil.java | UTF-8 | 1,578 | 3.296875 | 3 | [] | no_license | package util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class TimeUtil {
public static String format(Long time) {
if (time == null) {
return null;
} else {
long hour = time / (60 * 60 * 1000);
long minute = (time - hour * 60 * 60 * 1000) / (60 * 1000);
long second = (time - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;
return (hour == 0 ? "00" : (hour > 10 ? hour : ("0" + hour))) + ":" + (minute == 0 ? "00" : (minute > 10 ? minute : ("0" + minute))) + ":" + (second == 0 ? "00" : (second > 10 ? second : ("0" + second)));
}
}
/**
* 时间为秒
* Long类型时间转换成视频时长
*/
public static String formatTime(Long time) {
if (time == null) {
return null;
} else {
long hour = time / (60 * 60);
long minute = (time - hour * 60 * 60) / 60;
long second = time - hour * 60 * 60 - minute * 60;
return (hour == 0 ? "00" : (hour > 10 ? hour : ("0" + hour))) + ":" + (minute == 0 ? "00" : (minute > 10 ? minute : ("0" + minute))) + ":" + (second == 0 ? "00" : (second > 10 ? second : ("0" + second)));
}
}
public static void main(String[] args) {
Executors.newFixedThreadPool(5);
Long time = 73796L;
String format = TimeUtil.format(time);
System.out.println(format);
}
}
| true |
83c1080f2f8387cd775461f6ba6b024a33871f62 | Java | gzstyp/spring_security_frontend_backend | /src/main/java/com/fwtai/config/AuthLoginFilter.java | UTF-8 | 2,276 | 2.453125 | 2 | [] | no_license | package com.fwtai.config;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 登录认证器
* @作者 田应平
* @版本 v1.0
* @创建时间 2020-11-21 19:23
* @QQ号码 444141300
* @Email service@dwlai.com
* @官网 http://www.fwtai.com
*/
public class AuthLoginFilter extends UsernamePasswordAuthenticationFilter{
private AuthenticationManager authenticationManager;
public AuthLoginFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
super.setFilterProcessesUrl("/auth/login");
}
@Override
public Authentication attemptAuthentication(final HttpServletRequest request,final HttpServletResponse response) throws AuthenticationException{
// 从输入流中获取到登录的信息
/*try {
final LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword())
);
} catch (final IOException e) {
e.printStackTrace();
return null;
}*/
return null;
}
// 成功验证后调用的方法
// 如果验证成功,就生成token并返回
@Override
protected void successfulAuthentication(final HttpServletRequest request,final HttpServletResponse response,final FilterChain chain,final Authentication authResult) throws IOException, ServletException{
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
response.getWriter().write("authentication failed, reason: " + failed.getMessage());
}
} | true |
c7da5ad65f715d89b090c1151c39f1863774fe97 | Java | rzndev/compiler | /src/main/java/ru/tokenizer/CsvParser.java | UTF-8 | 1,397 | 3.078125 | 3 | [] | no_license | package ru.tokenizer;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
/**
* Получение токена CSV
*/
public class CsvParser {
private static final int DEFAULT_BUFFER_CAPACITY = 65536;
/**
* Источник данных
*/
private Reader reader;
/**
* Буфер исходных данных
*/
private CharBuffer charBuffer;
/**
* Позиция последнего символа в буфере
*/
private int lastPosition;
/**
* Емкость буфера
*/
private int bufferCapacity;
/**
* Порядковый номер элемента в строке
*/
private int sequenceNumber;
public int getBufferCapacity() {
return bufferCapacity;
}
public void setBufferCapacity(int bufferCapacity) {
this.bufferCapacity = bufferCapacity;
}
public CsvParser() {
this.bufferCapacity = DEFAULT_BUFFER_CAPACITY;
}
/**
* Инициализация парсера
*/
public void Init(Reader reader) {
charBuffer = CharBuffer.allocate(bufferCapacity);
this.reader = reader;
}
private void fetchData() {
try {
lastPosition = reader.read(charBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
72f6752b624f3531ee588f9d0d23549cba59ecf3 | Java | pswainuu/Hello_world | /src/test/java/com/caiofilipini/upload/handler/DetailsHandlerTest.java | UTF-8 | 2,151 | 2.390625 | 2 | [] | no_license | package com.caiofilipini.upload.handler;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import com.caiofilipini.upload.handler.DetailsHandler;
import com.caiofilipini.upload.progress.InProgress;
import com.caiofilipini.upload.progress.UploadProgress;
public class DetailsHandlerTest {
private HttpServletRequest request;
private HttpServletResponse response;
private DetailsHandler detailsHandler;
@Before
public void createSubject() {
detailsHandler = new DetailsHandler();
}
@Before
public void createRequestAndResponse() throws Exception {
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
response = mock(HttpServletResponse.class);
request = mock(HttpServletRequest.class);
when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher);
}
@Test
public void shouldMakeFilePathAndDetailsAvailableForRendering() throws Exception {
setupPostRequest("29", "Everyone has sounds to share.");
detailsHandler.doPost(request, response);
verify(request).setAttribute("filePath", "/files/29.mp3");
verify(request).setAttribute("details", "Everyone has sounds to share.");
}
@Test
public void shouldRedirectToDetailsPage() throws Exception {
setupPostRequest("57", "Everyone has sounds to share.");
detailsHandler.doPost(request, response);
verify(request).getRequestDispatcher("/WEB-INF/jsp/details.jsp");
}
private void setupPostRequest(String uid, String details) {
when(request.getParameter("uid")).thenReturn(uid);
when(request.getParameter("details")).thenReturn(details);
UploadProgress progress = new UploadProgress(42L, 42L);
progress.fileAvailableAt("/files/" + uid + ".mp3");
InProgress.store(uid, progress);
}
}
| true |
5f05dcbb07779de753737d3abec471e35f103163 | Java | maiphong0411/OOLT.20202.20184172.MaiThePhong | /Lab09/AimsProject/src/main/java/hust/soict/hedspi/gui/javafx/JavaFXAims.java | UTF-8 | 875 | 2.390625 | 2 | [] | no_license | package hust.soict.hedspi.gui.javafx;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.fxml.FXMLLoader;
public class JavaFXAims extends Application {
private static Stage stg;
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Main.fxml"));
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
}
public void changeScene(String fxml) throws IOException {
Parent pane = FXMLLoader.load(getClass().getResource(fxml));
stg.getScene().setRoot(pane);
}
public static void main(String[] args) {
launch(args);
}
} | true |
cd731fffe38a3941d508b866bc2008f3b3ce505b | Java | mutyalu38/InstaMoneyWebApp | /src/main/java/com/gtids/InstaMoney/model/LoansCustomerOccupationDTO.java | UTF-8 | 173 | 1.796875 | 2 | [] | no_license | package com.gtids.InstaMoney.model;
public interface LoansCustomerOccupationDTO {
String getBeneficiary_lineofactivity();
int getCountOfBeneficiary_lineofactivity();
}
| true |