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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b690da3a78e510270b83f1ab0deca4c11f87ec6b | Java | jansomers/gs-android | /app/src/main/java/br/com/managersystems/guardasaude/exams/exammenu/report/ReportInteractor.java | UTF-8 | 3,234 | 2.328125 | 2 | [] | no_license | package br.com.managersystems.guardasaude.exams.exammenu.report;
import android.content.Intent;
import android.util.Log;
import br.com.managersystems.guardasaude.exams.domain.Exam;
import br.com.managersystems.guardasaude.exams.domain.ReportResponse;
import br.com.managersystems.guardasaude.exams.mainmenu.examoverview.ExamApi;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* This class is an implementation of the IReportInteractor
*
* Authors:
* @author Jan Somers
* @author Thanee Stevens
*
* Also see:
* @see IReportInteractor
*/
public class ReportInteractor implements IReportInteractor {
private final String BASE_URL = "https://guardasaude.com.br/";
OnReportRetrievedListener reportListener;
ExamApi examApi;
public ReportInteractor(OnReportRetrievedListener reportListener) {
this.reportListener = reportListener;
examApi = initiateRetrofit();
}
/**
* Initiates the retrofit instances for the ExamApi.
* @return ExamApi instance representing the client.
*/
private ExamApi initiateRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(ExamApi.class);
}
@Override
public void getReport(final String examIdentification, final String token, final String user) {
if (examApi == null) initiateRetrofit();
Log.d(getClass().getSimpleName(), "making the getReport call");
Call<ReportResponse> call = examApi.getReport(user, token, examIdentification);
call.enqueue(new Callback<ReportResponse>() {
@Override
public void onResponse(Call<ReportResponse> call, Response<ReportResponse> response) {
if (response.body().getReportContent()==null) {
Log.d(getClass().getSimpleName(), "report response body was empty.. alerting listener!");
reportListener.onFailure();
} else {
Log.d(getClass().getSimpleName(), "report response successful... notifying listener!");
reportListener.onReportSuccess(response.body().getReportContent());
}
}
@Override
public void onFailure(Call<ReportResponse> call, Throwable t) {
Log.d(getClass().getSimpleName(), "Report call failed... alerting listener!");
reportListener.onFailure();
}
});
}
@Override
public void getExam(Intent intent) {
Log.d(getClass().getSimpleName(), "Interactor is retrieving the exam...");
Exam exam = intent.getParcelableExtra("exam");
if (exam.getIdentification().isEmpty()) {
Log.d(getClass().getSimpleName(), "Exam has no identification.. alerting listener!");
reportListener.onFailure();
} else {
Log.d(getClass().getSimpleName(), "Exam was retrieved successfully... notifying listener!");
reportListener.onExamReceived(exam);
}
}
}
| true |
0402be4f1d38734fa182cbfa55df3771a50cac12 | Java | Artsiomas/QA01-onl | /src/HW5/ClassWork.java | UTF-8 | 211 | 2.40625 | 2 | [] | no_license | package HW5;
public class ClassWork {
public static void main(String[] args) {
/* Car car = new Car(10);
car.setModel("Audi");
car.setSpeed(250);
car.setPrice(25720);
*/
}
}
| true |
d03101d241b6e62e3e46eb7c533fd33bb22b2a19 | Java | taobupt/LeetcodeReview | /src/main/java/_04_19/FourHundredTwentySixToFourHundredThirtyFive.java | UTF-8 | 1,899 | 3.34375 | 3 | [] | no_license | package _04_19;
import common.Interval;
import java.util.Arrays;
import java.util.Comparator;
/**
* Created by tao on 5/23/17.
*/
public class FourHundredTwentySixToFourHundredThirtyFive {
//432 All O`one Data Structure 不太会
//434
public int countSegments(String s) {
String []args = s.split("\\s+");
int cnt=0;
for(String arg:args){
if(arg.length()!=0)
cnt++;
}
return cnt;
}
//space;
public int countSegmentsWithSpace(String s){
char []ss=s.toCharArray();
int n=ss.length;
int cnt=0,i=0;
while(i<n){
while(i<n && Character.isSpaceChar(ss[i]))
i++;
if(i<n)// 为什么放在这里呢?若是放下面的话,就会少算一个,为啥判断小于n呢,不判断就会出现corn case
cnt++;
while(i<n && !Character.isSpaceChar(ss[i]))
i++;
}
return cnt;
}
// non-overlapping interval
//没啥印象
//先排序,发现有重叠就删之。
public int eraseOverlapIntervals(Interval[] intervals) {
Arrays.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if(o1.start!=o2.start)
return o1.start-o2.start;
else
return o1.end-o2.end;
}
});
int cnt=0,n=intervals.length;
if(n<=1)
return 0;
int end=intervals[0].end;
for(int i=1;i<n;++i){
if(intervals[i].start<end){
cnt++;
end=Math.min(end,intervals[i].end);//漏掉了,唉
continue;
}else{
end=Math.max(end,intervals[i].end);
}
}
return cnt;
}
}
| true |
68dac51ab47e5204513e98261d85c26a32a9f159 | Java | k0ksi/Java | /Java-Collections-Basics-Homework/src/CardsFrequencies.java | UTF-8 | 882 | 3.3125 | 3 | [] | no_license | import java.text.NumberFormat;
import java.util.LinkedHashMap;
import java.util.Scanner;
import java.util.Map.Entry;
public class CardsFrequencies {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] cards = input.replaceAll("[♥♣♦♠]", "").split("\\s+");
int n = cards.length;
LinkedHashMap<String, Double> cardMap = new LinkedHashMap<String, Double>();
Double count = 0.0;
for (String card : cards) {
count = cardMap.get(card);
if(count == null) {
count = 0.0;
}
cardMap.put(card, count + 1);
}
for(Entry<String, Double> entry : cardMap.entrySet()) {
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
System.out.println(entry.getKey() + " -> " + defaultFormat.format(entry.getValue() / n));
}
}
}
| true |
4091b9f1d9353851b39b6de1ade4e95d42f478cf | Java | johnson28/SeikaiEntityHibernateMavenWebapp | /seikai-entity-hibernate Maven Webapp/src/main/java/seikai/entity/hibernate/impl/AbstractHibernateGenericRecordDaoImpl.java | UTF-8 | 5,549 | 2.046875 | 2 | [] | no_license | package seikai.entity.hibernate.impl;
import static org.hibernate.criterion.Restrictions.eq;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Projections;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.orm.hibernate4.HibernateOperations;
import org.springframework.orm.hibernate4.HibernateTemplate;
import seikai.entity.base.RecordDto;
import seikai.entity.data.impl.AbstractGenericRecordDaoImpl;
import seikai.entity.hibernate.HibernateGenericRecordDao;
public abstract class AbstractHibernateGenericRecordDaoImpl<Entity extends RecordDto, EntityHistory extends RecordDto, Id extends Serializable>
extends AbstractGenericRecordDaoImpl<Entity, EntityHistory, Id> implements
HibernateGenericRecordDao<Entity, EntityHistory, Id> {
private HibernateTemplate hibernateTemplate;
@Autowired
@Required
@Override
public final void setSessionFactory(final SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
protected final HibernateOperations getHibernateTemplate() {
return hibernateTemplate;
}
protected Session getCurrentSession() {
return hibernateTemplate.getSessionFactory().getCurrentSession();
}
protected final AuditReader getAuditReader() {
return AuditReaderFactory.get(getCurrentSession());
}
@Override
@SuppressWarnings({ "unchecked" })
public final Id save(final Entity entity) throws Exception {
Id id = (Id) hibernateTemplate.save(entity);
copyEntity(entity);
return id;
}
@Override
public final void saveOrUpdate(final Entity entity) throws Exception {
hibernateTemplate.saveOrUpdate(entity);
copyEntity(entity);
}
@Override
public final Entity get(final Id id) {
return hibernateTemplate.get(getEntityClass(), id);
}
@Override
public final Entity load(final Id id) {
return hibernateTemplate.load(getEntityClass(), id);
}
@Override
public final void refresh(final Entity entity) {
hibernateTemplate.refresh(entity);
}
@Override
@SuppressWarnings("unchecked")
public final List<Entity> findAll() {
return getCurrentSession().createCriteria(getEntityClass()).list();
}
@Override
@SuppressWarnings("unchecked")
public final List<Entity> findAllEnable() {
return getCurrentSession().createCriteria(getEntityClass()).add(eq("dataEnabled", true)).list();
}
@Override
public final List<Entity> findByExample(final Entity exampleEntity) {
return hibernateTemplate.findByExample(exampleEntity);
}
@Override
public final List<Entity> findByExample(final Entity exampleEntity, final int firstResult, final int maxResults) {
return hibernateTemplate.findByExample(exampleEntity, firstResult, maxResults);
}
@Override
public final List<Entity> findByRestrictions(final Map<String, Serializable> params) {
try {
Entity exampleEntity = getEntityClass().newInstance();
BeanUtils.populate(exampleEntity, params);
return findByExample(exampleEntity);
} catch (Exception e) {
throw new DataRetrievalFailureException(e.getMessage(), e);
}
}
@Override
public final List<Entity> findByRestrictions(final Map<String, Serializable> params, final int firstResult,
final int maxResults) {
try {
Entity exampleEntity = getEntityClass().newInstance();
BeanUtils.populate(exampleEntity, params);
return findByExample(exampleEntity, firstResult, maxResults);
} catch (Exception e) {
throw new DataRetrievalFailureException(e.getMessage(), e);
}
}
@Override
public final void update(final Entity entity) throws Exception {
hibernateTemplate.update(entity);
copyEntity(entity);
}
@Override
public final void delete(Entity entity) throws Exception {
entity.setDataEnabled(false);
update(entity);
}
@Override
public final void delete(Id id) throws Exception {
Entity entity = get(id);
if (entity != null) {
delete(entity);
}
}
@Override
public final int countAll() {
return ((Long) getCurrentSession().createCriteria(getEntityClass()).setProjection(Projections.rowCount())
.uniqueResult()).intValue();
}
@Override
public final int countByExample(final Entity exampleEntity) {
return ((Long) getCurrentSession().createCriteria(getEntityClass()).add(Example.create(exampleEntity))
.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}
@Override
public final int countByRestrictions(final Map<String, Serializable> params) {
try {
Entity exampleEntity = getEntityClass().newInstance();
BeanUtils.populate(exampleEntity, params);
return countByExample(exampleEntity);
} catch (Exception e) {
throw new DataRetrievalFailureException(e.getMessage(), e);
}
}
private void copyEntity(final Entity entity) throws Exception {
EntityHistory entityHistory = getEntityHistoryClass().newInstance();
BeanUtils.copyProperties(entityHistory, entity);
entityHistory.setId(null);
entityHistory.setCreateDate(new Date());
entityHistory.setRecordId(entity.getId());
saveHistory(entityHistory);
}
private final void saveHistory(final EntityHistory entityHistory) {
hibernateTemplate.save(entityHistory);
}
}
| true |
f4bc847de8f2d7114127b6710db79db94bc1900a | Java | elliotcho/LeetCode-Questions | /ApplyDiscountEverynOrders.java | UTF-8 | 929 | 3.203125 | 3 | [] | no_license | class Cashier {
int customerCount=0;
int n;
int discount;
HashMap<Integer, Integer> map;
public Cashier(int n, int discount, int[] products, int[] prices) {
this.n=n;
this.discount=discount;
map=new HashMap<>();
for(int i=0;i<products.length;i++){
map.put(products[i], prices[i]);
}
}
public double getBill(int[] product, int[] amount) {
customerCount++;
double total=0;
for(int i=0;i<product.length;i++){
total+=map.get(product[i])*amount[i];
}
return (customerCount%n ==0) ? total-(discount*total)/100: total;
}
}
/**
* Your Cashier object will be instantiated and called as such:
* Cashier obj = new Cashier(n, discount, products, prices);
* double param_1 = obj.getBill(product,amount);
*/ | true |
a0825cf81a011a62c34381bd11260ff62da94743 | Java | bjyu/dulgi-1 | /com.example.dulgi.MainActivity/src/com/example/dulgi/MainActivity.java | UHC | 1,908 | 2.328125 | 2 | [] | no_license | package com.example.dulgi;
import com.y2util.AndroidUtil;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
// Activity resource ID
final static int ID_ACTIVITY_ALARM_EDIT = 100;
ArrayList <Alarm> mAlarms;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onButtonEvent ();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.activity_main, menu);
return false;
}
public void onButtonEvent () {
Button btn = (Button)findViewById(R.id.btnNew);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AndroidUtil.showLogI(getClass().getName(), " ˶");
Intent i = new Intent(MainActivity.this, AlarmEdit.class);
i.putExtra("alarmData", new Alarm ());
startActivityForResult(i, ID_ACTIVITY_ALARM_EDIT);
XmlDocument doc = new XmlDocument ();
doc.load (MainActivity.this);
}
});
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ID_ACTIVITY_ALARM_EDIT) {
if (resultCode == RESULT_OK) {
Alarm al = (Alarm) data.getSerializableExtra("alarmData");
XmlDocument doc = new XmlDocument ();
doc.save (this, al);
AndroidUtil.showToast(this, " ˶ Ϸ");
} else {
AndroidUtil.showToast(this, "");
}
}
}
}
| true |
ee395277a61fb11cb44e60c55ea9536c43e4028e | Java | benmcclelland/dbviz | /src/gui/models/Table.java | UTF-8 | 1,240 | 2.671875 | 3 | [] | no_license | package gui.models;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Table implements Serializable {
private static final long serialVersionUID = -2525495695287221814L;
private String name;
private List<String> keys;
private List<String> columns;
private List<String> types;
public Table(){
name = "";
keys = new ArrayList<String>();
columns = new ArrayList<String>();
types = new ArrayList<String>();
}
public Table(String s, List<String> keyList, List<String> columnList, List<String> typeList) {
name = s;
if (keyList == null) {
keyList = new ArrayList<String>();
} else {
keys = keyList;
}
if (columnList == null) {
columns = new ArrayList<String>();
} else {
columns = columnList;
}
if (typeList == null) {
types = new ArrayList<String>();
} else {
types = typeList;
}
}
public String getName() {
return name;
}
public List<String> getKeys() {
return keys;
}
public List<String> getColumns() {
return columns;
}
public List<String> getTypes() {
return types;
}
public void setName(String s) {
name = s;
}
public void setKeys(List<String> list) {
if (list != null) {
keys = list;
}
}
}
| true |
16ce0f173b865f16442cfd885a06f03de82b3288 | Java | chedbrandh/gibberish | /src/test/java/com/chedbrandh/gibberish/exceptions/IllegalPhraseExceptionTest.java | UTF-8 | 1,222 | 2.5625 | 3 | [
"MIT"
] | permissive | package com.chedbrandh.gibberish.exceptions;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IllegalPhraseExceptionTest {
@Test
public void testConstructor() throws Exception {
IllegalPhraseException underTest =
new IllegalPhraseException("foo phrase", "foo message");
assertEquals("foo phrase", underTest.getPhrase());
assertEquals("foo message", underTest.getMessage());
}
@Test
public void testExpectedLeading() throws Exception {
IllegalPhraseException underTest =
IllegalPhraseException.expectedLeading("foo phrase", "");
assertEquals("foo phrase", underTest.getPhrase());
}
@Test
public void testExpectedTrailing() throws Exception {
IllegalPhraseException underTest =
IllegalPhraseException.expectedTrailing("foo phrase", "");
assertEquals("foo phrase", underTest.getPhrase());
}
@Test
public void testExpectedSeparator() throws Exception {
IllegalPhraseException underTest =
IllegalPhraseException.expectedSeparator("foo phrase", "");
assertEquals("foo phrase", underTest.getPhrase());
}
}
| true |
c35afe65afb0382aa4f2a224580d142901e8d5f0 | Java | rcoolboy/guilvN | /app/src/main/java/com/qiyukf/unicorn/p213f/p214a/p222f/C2606b.java | UTF-8 | 1,185 | 1.6875 | 2 | [] | no_license | package com.qiyukf.unicorn.p213f.p214a.p222f;
import android.content.Context;
import android.text.TextUtils;
import com.qiyukf.unicorn.C2364R;
import com.qiyukf.unicorn.p213f.p214a.AbstractC2597e;
import com.qiyukf.unicorn.p213f.p214a.p218b.AbstractC2548a;
import com.qiyukf.unicorn.p213f.p214a.p218b.AbstractC2549b;
@AbstractC2549b(mo35941a = 26)
/* renamed from: com.qiyukf.unicorn.f.a.f.b */
public class C2606b extends AbstractC2597e {
@AbstractC2548a(mo35940a = "sessionid")
/* renamed from: a */
public long f5317a;
@AbstractC2548a(mo35940a = "message")
/* renamed from: b */
public String f5318b;
/* renamed from: a */
public final void mo36153a(long j) {
this.f5317a = j;
}
/* renamed from: a */
public final void mo36154a(String str) {
this.f5318b = str;
}
@Override // com.qiyukf.unicorn.api.msg.attachment.MsgAttachment, com.qiyukf.unicorn.p213f.p214a.AbstractC2558d
public String getContent(Context context) {
if (!TextUtils.isEmpty(this.f5318b)) {
return this.f5318b;
}
return "[" + context.getString(C2364R.string.ysf_msg_quit_session_tips) + "]";
}
}
| true |
499d00e9457a2888dbccfe9ccca9ffc6a386456d | Java | bigrichteam-frontend/MusicApp | /src/main/test/com/riches/honour/mapper/AdevertMapperTest.java | UTF-8 | 1,480 | 2.328125 | 2 | [] | no_license | package com.riches.honour.mapper;
import com.riches.honour.bean.Advert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* @author 王志坚
* @createTime 2019.07.08.20:55
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class AdevertMapperTest {
@Autowired
AdevertMapper adevertMapper;
@Test
public void addadevert(){
Advert advert = new Advert();
Date now = new Date();
advert.setCreateTime(now);
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.add(Calendar.DATE,1);
advert.setEndTime(cal.getTime());
advert.setPic("test");
advert.setName("八个核桃");
int flag = adevertMapper.insertSelective(advert);
}
@Test
public void query(){
Advert advert = new Advert();
advert.setName("六个核桃");
int count = adevertMapper.selectCount(advert);
System.out.println("count = " + count);
List<Advert> adverts = adevertMapper.select(advert);
if(adverts!=null){
for (Advert advert1 : adverts) {
System.out.println("advert1 = " + advert1);
}
}
}
} | true |
cb166a05ea459bcffe8668ee3a918ef28ddabee3 | Java | arameshraju/caremanager-app | /src/main/java/com/bao/caremanager/app/service/CareServiceImpl.java | UTF-8 | 847 | 2.25 | 2 | [] | no_license | package com.bao.caremanager.app.service;
import com.bao.caremanager.app.data.CareBaseMapper;
import com.bao.caremanager.app.model.Doctor;
import com.bao.caremanager.app.model.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
@Component
public class CareServiceImpl implements CareService{
@Autowired
CareBaseMapper mapper;
@Override
public List<HashMap> getDoctor() {
return mapper.getDoctor();
}
@Override
public void InsertDoctor(Doctor doc) {
System.out.print(doc.getName());
mapper.insertDoctor(doc);
}
@Override
public void insertPatient(Patient patient) {
System.out.print(patient.getName());
mapper.insertPatient(patient);
}
}
| true |
bdc7afc47f150a74a89fdb6718c9a9d9ad7e8f03 | Java | anicloud/ccyl-law-popularization | /commons/src/main/java/com/ani/ccyl/leg/commons/dto/AwardDto.java | UTF-8 | 1,535 | 2.265625 | 2 | [] | no_license | package com.ani.ccyl.leg.commons.dto;
import com.ani.ccyl.leg.commons.enums.AwardTypeEnum;
import java.io.Serializable;
/**
* Created by lihui on 17-12-28.
*/
public class AwardDto implements Serializable {
private static final long serialVersionUID = 2112431259790987270L;
private AwardTypeEnum awardType;
private Boolean isUsedUp;
private Integer score;
private Integer myScore;
private Integer awardCount;
public AwardDto() {
}
public AwardDto(AwardTypeEnum awardType, Boolean isUsedUp, Integer score, Integer myScore,Integer awardCount) {
this.awardType = awardType;
this.isUsedUp = isUsedUp;
this.score = score;
this.myScore = myScore;
this.awardCount = awardCount;
}
public Integer getMyScore() {
return myScore;
}
public void setMyScore(Integer myScore) {
this.myScore = myScore;
}
public AwardTypeEnum getAwardType() {
return awardType;
}
public void setAwardType(AwardTypeEnum awardType) {
this.awardType = awardType;
}
public Boolean getUsedUp() {
return isUsedUp;
}
public void setUsedUp(Boolean usedUp) {
isUsedUp = usedUp;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public Integer getAwardCount() {
return awardCount;
}
public void setAwardCount(Integer awardCount) {
this.awardCount = awardCount;
}
}
| true |
c01e5db95b89c079a399e42bc1bb599a1fefb1da | Java | amrutachavan/Reliable-Data-Transfer-Protocol | /src/fcntcp.java | UTF-8 | 1,582 | 2.9375 | 3 | [] | no_license | import java.net.InetAddress;
/*
* @author Amruta Chavan agc9066
*
* This class is to run the main program
* */
public class fcntcp {
public static void main(String []args){
String opt = args[0];
int p=1;
switch(opt){
//if server is to be started
case ("-s") :
int srvPort;
boolean quiet=false;
srvPort=Integer.parseInt(args[args.length-1]);
if(args[p].equals("-q")){
quiet=true;
}
UDPReceiver udpServer;
try{
String tsIp = InetAddress.getLocalHost().getHostAddress();
System.out.println("\nTHE IP OF MAIN SERVER IS::"+tsIp+"\n");
}catch(Exception e){}
udpServer = new UDPReceiver(srvPort,quiet);
Thread udp = new Thread(udpServer);
udp.start();
break;
//if client is to be started
case("-c"):
String fname=null,serverAdd=null;
int servPort;
int time=1000;
boolean q=false;
serverAdd=args[args.length-2];
servPort=Integer.parseInt(args[args.length-1]);
if(args[p].equals("-f")){
fname=args[p+1];
p+=2;
}
if(args[p].equals("-t")){
time=Integer.parseInt(args[p+1]);
p+=2;
}
if(args[p].equals("-q")){
q=true;
}
//creste client object
UDPSender tC1 = new UDPSender(serverAdd,servPort,fname,time,q);
tC1.Type=1;
Thread t1 =new Thread(tC1);
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tC1.Type=2;
Thread t2 = new Thread(tC1);
t2.start();
break;
}
}
}
| true |
0a02e7205524feb5c858c86467d6088de7745d63 | Java | NikitaDergunov/CourseworkServlet | /src/MHServlet.java | UTF-8 | 1,768 | 2.328125 | 2 | [] | no_license | import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MHServlet extends HttpServlet{
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
resp.setContentType("text/html");
ServletContext context=getServletContext();
MedicalHistoryDao MH = (MedicalHistoryDao) context.getAttribute("MH");
MH.init(req,resp, context);
if (req.getParameter("MHIns") != null){
String[] ins = new String[3];
ins[0] = "'" + req.getParameter("MHHistory") + "'";
ins[1] = req.getParameter("MHPatientID");
ins[2] ="'" + req.getParameter("MHDateOfAdmission") + "'";
MH.insertInto(ins);
MH.outputTable();
resp.sendRedirect( req.getContextPath() + "/MH");
}
else if (req.getParameter("MHDel") != null) {
int del = Integer.parseInt(req.getParameter("textarea1"));
MH.deleteByID(del);
MH.outputTable();
resp.sendRedirect( req.getContextPath() + "/MH");
}
else{
MH.outputTable();
resp.sendRedirect(req.getContextPath() + "/MH");}
}
catch (Exception e){
}
}
} | true |
17fc1ee89bf6b63924117f2b2d15ff2c04790dca | Java | nonamejx/NemApp | /app/src/main/java/com/nicest/nemapp/MainActivity.java | UTF-8 | 682 | 1.921875 | 2 | [] | no_license | package com.nicest.nemapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.nicest.nemapp.data.local.db.DbHelper;
import com.nicest.nemapp.utils.AppLogger;
import javax.inject.Inject;
public class MainActivity extends AppCompatActivity {
@Inject
DbHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((NemApp) getApplication()).getAppComponent().inject(this);
AppLogger.d("Data", dbHelper);
Log.d(MainActivity.class.getName(), dbHelper + "");
}
}
| true |
1e59e1a7f6737a2bd1be5a4831b5f845043efebf | Java | chongbo2013/Features | /FloatMultiTask/alps/packages/apps/FloatMultiTask/src/com/mlt/floatmultitask/NoteContent.java | UTF-8 | 1,152 | 2.4375 | 2 | [] | no_license | package com.mlt.floatmultitask;
/**
* filename:NoteContent.java
* Copyright MALATA ,ALL rights reserved.
* 15-7-20
* author: laiyang
*
* java bean,to save note
*
* Modification History
* -----------------------------------
*
* -----------------------------------
*/
public class NoteContent {
/** note id in db */
private int id;
/** note content */
private String content;
/** write note time */
private String time;
public NoteContent(int id, String content, String time) {
this.id = id;
this.content = content;
this.time = time;
}
public NoteContent(String content, String time) {
this.content = content;
this.time = time;
}
public NoteContent() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
| true |
ee1c7fd942e91375b6fe91d6bd610f7b94321260 | Java | efernasier/phone-shop | /src/main/java/com/gnaderi/interview/phoneshop/config/ShoppingRuleConfiguration.java | UTF-8 | 467 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | package com.gnaderi.interview.phoneshop.config;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShoppingRuleConfiguration {
@Bean
public KieContainer kieContainer() {
KieServices kieServices = KieServices.Factory.get();
return kieServices.getKieClasspathContainer();
}
} | true |
5b43b9c9d37ea163e35d78953f982053732acd93 | Java | mnq-naqui/CoreJava | /InnerClasses/src/anonymous/innerclass/Manger15.java | UTF-8 | 438 | 2.65625 | 3 | [] | no_license | package anonymous.innerclass;
public class Manger15 {
/*I you want to initialize NSM inside AIC use IIB not const coz we cannot
* incorporate const iinside AIC as AIC has no name*/
public static void main(String[] args) {
D d1=new D(){
{
System.out.println("AIC-IIB");
}
};
System.out.println("=======================================");
D d2=new D(14){
{
System.out.println("AIC-IIB");
}
};
}
}
| true |
7401c75cb100678af28f49707edc58eaa741a04f | Java | 0713mingyu/ssafy-firstproject | /Backend/itda_test/src/main/java/com/ssafy/itda/itda_test/service/IStackService.java | UTF-8 | 478 | 2.015625 | 2 | [] | no_license | package com.ssafy.itda.itda_test.service;
import java.util.List;
import com.ssafy.itda.itda_test.model.JobStack;
import com.ssafy.itda.itda_test.model.MyStack;
import com.ssafy.itda.itda_test.model.Stack;
public interface IStackService {
void createStack(String s);
void createMyStack(MyStack ms);
void createJobStack(JobStack js);
List<Stack> getAllStacks();
List<Stack> getJobStacks(int jid);
List<Stack> getMyStacks(int uid);
void deleteMyStack(MyStack newms);
}
| true |
9ad22e1da741fc8f545550104f7201081ffbce40 | Java | leandrodpereira/ltp-iv | /Polimorfismo/src/br/fepi/si/polimorficos/Quadrado.java | UTF-8 | 536 | 2.953125 | 3 | [] | no_license | package br.fepi.si.polimorficos;
public class Quadrado extends DuasDimensoes {
private double lado;
public Quadrado(String cor, int espessuraDaBorda, double lado) {
super(cor, espessuraDaBorda);
this.lado = lado;
}
@Override
public void calculoDeArea() {
System.out.println(Math.pow(lado,2));
}
public double getLado() {
return lado;
}
public void setLado(double lado) {
this.lado = lado;
}
@Override
public String toString() {
return "Quadrado [lado=" + lado + " " + super.toString() + "]";
}
}
| true |
07356dcd21ee925ff40a7f3b31f7a1af7f1b0ec2 | Java | jasonC5/mybatisGenerator-new | /src/main/java/com/dxh/mem/mapper/BalanceConsumeBatchMapper.java | UTF-8 | 1,433 | 1.664063 | 2 | [] | no_license | package com.dxh.mem.mapper;
import com.dxh.mem.entity.BalanceConsumeBatch;
public interface BalanceConsumeBatchMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table balanceconsumebatch
*
* @mbggenerated Fri Aug 28 17:31:02 GMT+08:00 2020
*/
int insert(BalanceConsumeBatch record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table balanceconsumebatch
*
* @mbggenerated Fri Aug 28 17:31:02 GMT+08:00 2020
*/
int insertSelective(BalanceConsumeBatch record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table balanceconsumebatch
*
* @mbggenerated Fri Aug 28 17:31:02 GMT+08:00 2020
*/
BalanceConsumeBatch selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table balanceconsumebatch
*
* @mbggenerated Fri Aug 28 17:31:02 GMT+08:00 2020
*/
int updateByPrimaryKeySelective(BalanceConsumeBatch record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table balanceconsumebatch
*
* @mbggenerated Fri Aug 28 17:31:02 GMT+08:00 2020
*/
int updateByPrimaryKey(BalanceConsumeBatch record);
} | true |
c2bd6db968a39c6e5dae1a336a95c69d6195efa6 | Java | bergerm/BGFinder | /app/src/main/java/com/bgonline/bgfinder/ForgotPasswordFragment.java | UTF-8 | 3,935 | 2.109375 | 2 | [] | no_license | package com.bgonline.bgfinder;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
/**
* Created by Manu on 10/24/2016.
*/
public class ForgotPasswordFragment extends SynchronizedLoadFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onChangeFragment(Fragment newFragment);
}
private static final String TAG = "BGFinderForgotPasswordFragment";
private FirebaseAuth mAuth;
public static ForgotPasswordFragment newInstance() {
return new ForgotPasswordFragment();
}
public ForgotPasswordFragment() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View forgotPasswordView = inflater.inflate(R.layout.forgot_password, container, false);
mAuth = FirebaseAuth.getInstance();
final ViewGroup exContainer = container;
final Button resetPasswordButton = (Button)forgotPasswordView.findViewById(R.id.reset_password_button);
resetPasswordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = ((EditText)forgotPasswordView.findViewById(R.id.email)).getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(exContainer.getContext(), "Enter your registered email id", Toast.LENGTH_SHORT).show();
return;
}
final ProgressBar progressBar = (ProgressBar) forgotPasswordView.findViewById(R.id.forgot_password_progressBar);
progressBar.setVisibility(View.VISIBLE);
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getActivity(), "We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show();
mCallback.onChangeFragment(new LogInFragment());
} else {
Toast.makeText(getActivity(), "Failed to send reset email!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
}
});
final Button backButton = (Button)forgotPasswordView.findViewById(R.id.forgot_password_back_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCallback.onChangeFragment(new LogInFragment());
}
});
return forgotPasswordView;
}
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
}
| true |
f45bcc9c0696fd8e212a0b3e98db5ae244932aaf | Java | huynhnhatthiep/ftcoffee | /ftCoffee/src/main/java/com/ft/coffee/dao/ProductDao.java | UTF-8 | 852 | 1.945313 | 2 | [] | no_license | package com.ft.coffee.dao;
import java.util.List;
import com.ft.coffee.entities.DVT;
import com.ft.coffee.entities.PriceList;
import com.ft.coffee.entities.Product;
import com.ft.coffee.entities.ProductGroup;
public interface ProductDao {
public void addProduct(Product product);
public void deleteProduct(String idProduct);
public Product updateProduct (Product product);
public Product getProduct(String idProduct);
public boolean findProduct(String idProduct);
public List< Product > loadIdGrouProducts(String idGroup);
public List< Product > searchNameProducts(String nameProduct);
public List<PriceList> loadListProduct();
public List<Product> showProducts();
public List<ProductGroup> getOptionProductGroup();
public List<DVT> getOptionDVT();
public void delete(String idProduct);
public boolean find(String idProduct);
}
| true |
4e09a3d4d4604c17e84330a39aaa4ad69569cb30 | Java | Surine/YCHybridFlutter | /YCAndroid/app/src/main/java/com/ycbjie/ycandroid/AndroidSecondActivity.java | UTF-8 | 1,029 | 2.234375 | 2 | [
"Apache-2.0"
] | permissive | package com.ycbjie.ycandroid;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* @author yc
*/
public class AndroidSecondActivity extends AppCompatActivity {
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android);
TextView tv = findViewById(R.id.tv);
ArrayList<String> params = getIntent().getStringArrayListExtra("yc");
if (params!=null && params.size()>0) {
Toast.makeText(this, "逗比" + params.get(0), Toast.LENGTH_SHORT).show();
tv.setText("flutter 传参集合:" + params.get(0));
}else {
Toast.makeText(this, "逗比,没有接收到数据", Toast.LENGTH_SHORT).show();
}
}
}
| true |
316dbeea9a03b35de869d38394b08ead75aa685a | Java | jiajinshuo/java_demo | /JavaSenior/src/com/duothread/ThreadTest.java | UTF-8 | 552 | 3.109375 | 3 | [] | no_license | package com.duothread;
/**
* @author jiajinshuo
* @create 2020-01-03 17:09
*/
public class ThreadTest {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
MyThread myThread1 = new MyThread();
myThread1.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName()+"\t"+i);
}
}
}
}
| true |
b2b0528571ad91d618f23646d387ce7376c9c67f | Java | udap/myriadapi | /src/main/java/io/chainmind/myriadapi/domain/CodeName.java | UTF-8 | 651 | 2.375 | 2 | [] | no_license | package io.chainmind.myriadapi.domain;
public enum CodeName {
// common codes
MIXED,
ID,
NAME,
// codes for account
CELLPHONE,
EMAIL,
SOURCE_ID, // external account id
// codes for organization
CODE, // organization code
LICENSE,
UPCODE, // unionpay merchant code
WPCODE, // wechat pay merchant code
APCODE; // alipay merchant code
/**
* Returns an integer representing the meta type of the CodeName
* @return 0 for common type, 1 for account code type, 2 for organization code type
*/
public int getMetaType() {
if (this.ordinal() > 5)
return 2;
else if (this.ordinal() > 2)
return 1;
else
return 0;
}
}
| true |
ebf16aa48edce77f76cf543f841c1bfc81778a68 | Java | vikaskundarapu/microservices | /create-sentences-using-ribbon-feign-hystrix/myspring-cloud-eureka-verb-service/src/main/java/com/vikas/springboot/eurekaverb/MyspringCloudEurekaVerbServiceApplication.java | UTF-8 | 468 | 1.578125 | 2 | [] | no_license | package com.vikas.springboot.eurekaverb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class MyspringCloudEurekaVerbServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MyspringCloudEurekaVerbServiceApplication.class, args);
}
}
| true |
e52d391519fc764b64b552a5a9f57b74c7cb73b8 | Java | maxandersen/jbang | /src/test/java/dev/jbang/cli/TestEditWithPackage.java | UTF-8 | 2,529 | 2.5 | 2 | [
"MIT"
] | permissive | package dev.jbang.cli;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.io.FileMatchers.aReadableFile;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import dev.jbang.BaseTest;
import dev.jbang.source.RunContext;
import dev.jbang.source.ScriptSource;
import dev.jbang.source.Source;
import dev.jbang.source.TestScript;
public class TestEditWithPackage extends BaseTest {
final String classA = "//SOURCES person/B.java\n"
+ "\n"
+ "import person.B;\n"
+ "\n"
+ "public class A {\n"
+ " \n"
+ " public static void main(String args[]) {\n"
+ " new B();\n"
+ " }\n"
+ "}\n";
final String classB = "package person ;\n"
+ "\n"
+ "//SOURCES model/C.java\n"
+ "\n"
+ "import person.model.C;\n"
+ "\n"
+ "public class B {\n"
+ " \n"
+ " public B() {\n"
+ " new C();\n"
+ " }\n"
+ "}\n";
final String classC = " package person.model;\n"
+ "\n"
+ "public class C {\n"
+ " public C() {}\n"
+ "}\n";
@Test
void testEditPackage() throws IOException {
Path mainPath = TestScript.createTmpFileWithContent("", "A.java", classA);
Path BPath = TestScript.createTmpFileWithContent(mainPath.getParent(), "person", "B.java", classB);
Path CPath = TestScript.createTmpFileWithContent(BPath.getParent(), "model", "C.java", classC);
assertTrue(mainPath.toFile().exists());
RunContext ctx = RunContext.empty();
ScriptSource src = (ScriptSource) Source.forResource(mainPath.toString(), ctx);
File project = new Edit().createProjectForEdit(src, ctx, false);
assertTrue(new File(project, "src/A.java").exists());
assertTrue(new File(project, "src/person/B.java").exists());
assertTrue(new File(project, "src/person/model/C.java").exists());
File javaC = new File(project, "src/person/model/C.java");
// first check for symlink. in some cases on windows (non admin privileg)
// symlink cannot be created, as fallback a hardlink will be created.
assertTrue(Files.isSymbolicLink(javaC.toPath()) || javaC.exists());
assertTrue(Files.isSameFile(javaC.toPath(), CPath));
Arrays .asList("A.java", "person/B.java", "person/model/C.java")
.forEach(f -> {
File java = new File(project, "src/" + f);
assertThat(f + " not found", java, aReadableFile());
});
}
}
| true |
89e34f14c9a9c2507eb7d94ffc777d176d4ca9a6 | Java | SDLMiniProject/PPMS | /app/src/main/java/comsdlminiproject/httpsgithub/ppms/SuccessfullyLoggedIn.java | UTF-8 | 3,574 | 1.875 | 2 | [] | no_license | package comsdlminiproject.httpsgithub.ppms;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
public class SuccessfullyLoggedIn extends AppCompatActivity {
Button btnOpenMap,btnGetLatestPetrolPrice,btnTallyAccount,btnViewRecords,btnOpenCctv,btnOpenFirebase;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.logoutmenu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.LOGOUT:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(getApplicationContext(),ActivityLogIn.class));
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_successfully_logged_in);
btnOpenMap= findViewById(R.id.btnOpenMap);
btnOpenMap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent= new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=Nearest petrol pump"));
startActivity(intent);
}
});
btnGetLatestPetrolPrice=findViewById(R.id.btnGetLatestPetrolPrice);
btnGetLatestPetrolPrice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent= new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.bankbazaar.com/fuel/petrol-price-pune.html?ck=Y%2BziX71XnZjIM9ZwEflsyDYlRL7gaN4W0xhuJSr9Iq7aMYwRm2IPACTQB2XBBtGG&rc=1"));
startActivity(intent);
}
});
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnTallyAccount= findViewById(R.id.btnTallyAccount);
btnTallyAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent= new Intent(getApplicationContext(),InputData.class);
startActivity(intent);
}
});
/*btnViewRecords = findViewById(R.id.btnViewRecords);
btnViewRecords.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Data.class));
}
});*/
btnOpenCctv= findViewById(R.id.btnOpenCctv);
btnOpenCctv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.mcu.iVMSHD");
startActivity(intent);
}
});
btnOpenFirebase = findViewById(R.id.btnOpenFirebase);
btnOpenFirebase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),DataRetrieved.class));
}
});
}
}
| true |
606e7bacb4489ebe4f5cd0f2da4615fe737d6277 | Java | AxelEj/interlude | /auth/la2/auth/net/server/InitPacket.java | UTF-8 | 989 | 2.265625 | 2 | [] | no_license | package la2.auth.net.server;
import net.io.SendablePacket;
import la2.auth.AuthClient;
public class InitPacket extends SendablePacket {
private int session;
private byte[] publicKey;
private byte[] blowfishKey;
public InitPacket(AuthClient client) {
this(client.getScrambledKeyPair()._scrambledModulus,client.getBlowfishKey(),client.getSession());
}
public InitPacket(byte[] publicKey, byte[] blowfishKey, int session) {
this.session = session;
this.publicKey = publicKey;
this.blowfishKey = blowfishKey;
}
@Override
public void write() {
writeB(0x00);
writeDW(session); // session id
writeDW(0x0000c621); // protocol revision
writeB(publicKey); // RSA Public Key
writeDW(0x29DD954E);
writeDW(0x77C39CFC);
writeDW(0x97ADB620);
writeDW(0x07BDE0F7);
writeB(blowfishKey); // BlowFish key
writeB(0x00);
}
}
| true |
a600481b302c94051c164b30612539a61bb9c397 | Java | viktorsadikovic/soa-application | /auth-service/src/main/java/mk/ukim/finki/authservice/service/UserService.java | UTF-8 | 291 | 2.0625 | 2 | [] | no_license | package mk.ukim.finki.authservice.service;
import mk.ukim.finki.authservice.model.User;
import java.util.List;
public interface UserService{
List<User> findAll();
User findByUsername(String username);
boolean existsByUsername(String username);
User register(User user);
}
| true |
a5dd1bc136210f7ff72b2ccd40b55da27299406e | Java | qichangjian/springBootLearn | /src/main/java/ch3/taskexecutor/Main.java | UTF-8 | 995 | 3.171875 | 3 | [] | no_license | package ch3.taskexecutor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Spring是通过任务执行器(TaskExecutor)l来实现多线程和并发编程。
* 使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。
* 实际开发中任务一般是非阻碍的,也就是异步的,
* 所以我们要在配置类中通过@EnableAsync开启对异步任务的支持,
* 并通过在实际执行的Bean的方法中使用@Async注解来声明其是一个异步任务
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
for (int i = 0; i < 10; i++) {
asyncTaskService.executeAsynoTask(i);
asyncTaskService.executeAsynoTaskPlus(i);
}
context.close();
}
}
| true |
fe2c287e4d90e02df11a408713f1be96ade1b9ba | Java | ConstancyZ/Constancy | /mpdemo/src/main/java/com/mpdemo/controller/UserController.java | UTF-8 | 7,665 | 2.34375 | 2 | [] | no_license | package com.mpdemo.controller;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mpdemo.dao.TKUserMapper;
import com.mpdemo.entity.TKUser;
import com.mpdemo.service.TKUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.xml.ws.WebEndpoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private TKUserMapper tkUserMapper;
@RequestMapping("/getUser")
public TKUser getUser () {
return tkUserMapper.selectById(736);
}
@RequestMapping("/addUser")
public Long addUser () {
TKUser tkUser = new TKUser();
tkUser.setMobile("12345678965");
tkUser.setEmail("@163.com");
tkUser.setKdgtTabId(Long.parseLong("62"));
tkUser.setAddress("hujian");
tkUserMapper.insert(tkUser);
return tkUser.getId();
}
@RequestMapping("/updateUser")
public void updateUser(){
TKUser tkUser = new TKUser();
tkUser.setId(Long.parseLong("736"));
tkUser.setEmail("@163.com");
tkUserMapper.updateById(tkUser);//根据id进行更新,没有传值的属性就不会更新
//tkUserMapper.;//根据id进行更新,没传值的属性就更新为null
}
@RequestMapping("/selectByCondition")
public List<TKUser> selectByCondition(){
/*
查询条件用map集合封装,columnMap,写的是数据表中的列名,
而非实体类的属性名。比如属性名为lastName,数据表中字段为last_name,
这里应该写的是last_name。selectByMap方法返回值用list集合接收
*/
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("mobile","13882985800");//写表中的列名
columnMap.put("name","Zay");
// 查询出满足columnMap条件的所有user
List<TKUser> tkUsers = tkUserMapper.selectByMap(columnMap);
return tkUsers;
}
@RequestMapping("/selectByIds")
public List<TKUser> selectByIds(){
/*
通过id批量查询
*/
List<Integer> idList = new ArrayList<>();
idList.add(734);
idList.add(735);
idList.add(736);
// 查询出满足columnMap条件的所有user
List<TKUser> tkUsers = tkUserMapper.selectBatchIds(idList);
return tkUsers;
}
@RequestMapping("/selectByPage")
public List<TKUser> selectByPage(){
/*分页查询
selectPage方法就是分页查询,在page中传入分页信息,后
者为null的分页条件,这里先让其为null,讲了条件构造器再说其用法。
这个分页其实并不是物理分页,而是内存分页。也就是说,查询的时候
并没有limit语句。等配置了分页插件后才可以实现真正的分页。
*/
// 查询出满足columnMap条件的所有user
List<TKUser> tkUsers = (List<TKUser>) tkUserMapper.selectPage(new Page<>(1,2),null);
return tkUsers;
}
@RequestMapping("/deleteByCondition")
public void deleteByCondition(){
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("mobile","13882985800");//写表中的列名
columnMap.put("name","Zay");
tkUserMapper.deleteByMap(columnMap);
// 按id批量删除与selectByIds一致
}
/**
* 条件构造器(EntityWrapper):
* 以上基本的 CRUD 操作,我们仅仅需要继承一个 BaseMapper 即可实现大部分单表 CRUD 操作。
* BaseMapper 提供了多达 17 个方法供使用, 可以极其方便的实现单一、批量、分页等操作,
* 极大的减少开发负担。但是mybatis-plus的强大不限于此,请看如下需求该如何处理:
* 需求:
* 我们需要分页查询 tb_employee 表中,年龄在 18~50 之间性别为男且姓名为 xx 的所有用户
* 这时候我们该如何实现上述需求呢?
* 使用MyBatis : 需要在 SQL 映射文件中编写带条件查询的 SQL,并用PageHelper 插件完成分页.
* 实现以上一个简单的需求,往往需要我们做很多重复单调的工作。
* 使用MP: 依旧不用编写 SQL 语句,MP 提供了功能强大的条件构造器 ------ EntityWrapper。
*
* 接下来就直接看几个案例体会EntityWrapper的使用。
*/
// 查询gender为0且名字中带有老师、或者邮箱中带有a的用户:
@RequestMapping("selectByEntityWrapper")
public IPage<TKUser> selectByEntityWrapper(){
// 分页查询园所id在1-100之间,state在1,性别为男的用户
IPage<TKUser> tkUsers = tkUserMapper.selectPage(new Page<TKUser>(1,3),
new QueryWrapper<TKUser>()
.between("kdgt_tab_id",1,100)
.eq("state",1)
.eq("sex","男"));
return tkUsers;
/*
由此案例可知,分页查询和之前一样,new 一个page对象传入分页信息即可。至于分页条件,
new 一个QueryWrapper对象,调用该对象的相关方法即可。between方法三个参数,
分别是column、value1、value2,该方法表示column的值要在value1和value2之间;
eq是equals的简写,该方法两个参数,column和value,表示column的值和value要相等。
注意column是数据表对应的字段,而非实体类属性字段。
*/
}
// 模糊查询
@RequestMapping("selectByLike")
public List<TKUser> selectByLike(){
List<TKUser> tkUsers = tkUserMapper.selectList(
new QueryWrapper<TKUser>()
.eq("state",1)
.like("mobile","138")
.or()
.like("name","Zay")
);
return tkUsers;
}
// 查询state为1,根据birthdate排序,简单分页
@RequestMapping("selectByOrder")
public List<TKUser> selectByOrder() {
List<TKUser> tkUsers = tkUserMapper.selectList(
new QueryWrapper<TKUser>()
.eq("state",1)
.orderByDesc("birthdate")
.last("limit 1,3"));
return tkUsers;
/*
简单分页是指不用page对象进行分页。orderBy方法就是根据传入的column进行升序排序,
若要降序,可以使用orderByDesc方法,也可以如案例中所示用last方法;last方法就是
将last方法里面的value值追加到sql语句的后面,在该案例中,最后的sql语句就变为
select ······ order by desc limit 1, 3,追加了desc limit 1,3所以可以进行降序排序和分页。
*/
}
/*
根据条件更新
*/
@RequestMapping("/updateByCondition")
public void updateByCondition(){
TKUser tkUser = new TKUser();
tkUser.setName("zyh");
tkUserMapper.update(tkUser,
new UpdateWrapper<TKUser>()
.eq("mobile","13882985800")
);
// 吧mobile13882985800的用户name改成zyh
}
}
| true |
ea0396e524324c4335252217e4c947606713ed83 | Java | amgrim07/USB_SCM_TRABAJO | /src/test/java/co/edu/usbcali/bank/repository/TransactionRepositoryTest.java | UTF-8 | 4,987 | 2.5 | 2 | [] | no_license | package co.edu.usbcali.bank.repository;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Date;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import co.edu.usbcali.bank.domain.Account;
import co.edu.usbcali.bank.domain.Transaction;
import co.edu.usbcali.bank.domain.TransactionType;
import co.edu.usbcali.bank.domain.Users;
// indica que es una calse Junit combinada con Spring
@SpringBootTest
// el rollback false, indica que no debe de hacer rollback al finalzar el metodo
@Rollback(false)
class TransactionRepositoryTest {
//Siempre se recomienda usar el Log de slf4j, para el manejo de los LOGS
final static Logger log = LoggerFactory.getLogger(TransactionRepositoryTest.class);
@Autowired
TransactionRepository transactionRepository;
static Long transactionID = 0L;
@Autowired
TransactionTypeRepository transactionTypeRepository;
Long transactionTypeID = 1L;
@Autowired
AccountRepository accountRepository;
String accountId = "4640-0341-9387-5781";
@Autowired
UsersRepository userRepository;
String userId = "cfaier0@cafepress.com";
// el @Test indica al JUnit que es un metod Test que se debe de ejecutar
@Test
// el @DisplayName indica al JUnit el nombre de la prueba que se debe desplegar
@DisplayName("Save")
@Transactional(readOnly = false)
void atest() {
log.info("Se ejecuto el Test Save");
Optional<Transaction> transactionOptional = transactionRepository.findById(transactionID);
assertFalse(transactionOptional.isPresent(), "El registeredAccount ya existe");
Optional<TransactionType> transactionTypeOptional = transactionTypeRepository.findById(transactionTypeID);
assertTrue(transactionTypeOptional.isPresent(), "El TransactionType existe");
Optional<Account> accountOptional = accountRepository.findById(accountId);
assertTrue(accountOptional.isPresent(), "La Cuenta no existe");
Optional<Users> usersOptional = userRepository.findById(userId);
assertTrue(usersOptional.isPresent(), "El Users no existe");
Transaction transaction = new Transaction();
transaction.setAccount(accountOptional.get());
transaction.setAmount(200000D);
transaction.setDate(new Date());
transaction.setTransactionType(transactionTypeOptional.get());
transaction.setUsers(usersOptional.get());
transaction = transactionRepository.save(transaction);
transactionID = transaction.getTranId();
log.info("Id "+transactionID);
}
@Test
@DisplayName("findByID")
@Transactional(readOnly = false)
void btest() {
log.info("Se ejecuto el Test find_by_ID");
// el java.util.Optional es adicionado el Java 8 para realizar el manejo de los NullPointerException, esto es programacion Funcional
Optional<Transaction> transactionOptional = transactionRepository.findById(transactionID);
// funcional
assertTrue(transactionOptional.isPresent(), "El Transaction no existe");
}
@Test
@DisplayName("Update")
@Transactional(readOnly = false)
void ctest() {
log.info("Se ejecuto el Test Update");
// el java.util.Optional es adicionado el Java 8 para realizar el manejo de los NullPointerException, esto es programacion Funcional
Optional<Transaction> transactionOptional = transactionRepository.findById(transactionID);
// funcional
assertTrue(transactionOptional.isPresent(), "La Transaction no existe");
// Programacacion interactiva
transactionOptional.ifPresent(transaction ->{
transaction.setAmount(10000D);
transaction.setDate(new Date());
transactionRepository.save(transaction);
}
);
}
@Test
@DisplayName("Delete")
@Transactional(readOnly = false)
void dtest() {
log.info("Se ejecuto el Test Delete");
Optional<Transaction> transactionOptional = transactionRepository.findById(transactionID);
// funcional
assertTrue(transactionOptional.isPresent(), "La Transaction no existe");
// Programacacion interactiva
transactionOptional.ifPresent(transaction ->{
transactionRepository.delete(transaction);
}
);
}
// el beforeEach indica al JUnit que de ejecutar este metodo antes de cada metodo @test que se ejecute
@BeforeEach
void beforeEach()
{
log.info("Se ejecuto el metodo beforeEach");
assertNotNull(transactionRepository, "el transactionRepository es null");
}
// el afterEach indica al JUnit que de ejecutar este metodo despues de cada metodo @test que se ejecute
@AfterEach
void afterEach()
{
log.info("Se ejecuto el metodo afterEach");
}
}
| true |
56a073809a045f091a69d903047bb8f927db483d | Java | ArthurMaker/HeadsLeaderBoards | /HeadLeaderBoards/src/main/java/com/headleaderboards/headleaderboards/commands/DeleteCommand.java | UTF-8 | 1,319 | 2.78125 | 3 | [] | no_license | package com.headleaderboards.headleaderboards.commands;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.headleaderboards.headleaderboards.HeadLeaderBoards;
public class DeleteCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length != 2) {
sender.sendMessage(ChatColor.RED + "USAGE: /hbl delete <leaderboard name>");
return true;
}
List<String> lbs = (HeadLeaderBoards.get().getConfig().getStringList("leaderboards"));
String hlbname = args[1].toLowerCase();
if (lbs.contains(hlbname)) {
lbs.remove(hlbname);
HeadLeaderBoards.get().getConfig().set("leaderboards", lbs);
HeadLeaderBoards.get().fileClass.getCustomConfig().set(hlbname, null);
HeadLeaderBoards.get().fileClass.saveCustomConfig();
HeadLeaderBoards.get().saveConfig();
sender.sendMessage(ChatColor.GREEN + "Leaderboard " + hlbname + " Has Been Removed!");
return true;
} else {
sender.sendMessage(ChatColor.RED + "ERROR: There is No Leaderboard With That Name!");
return true;
}
}
}
| true |
a4f2f760b6291cc49dafc123b420d51b3d9d848b | Java | fossabot/BrainySnake | /core/src/de/adesso/brainysnake/ApplicationController.java | UTF-8 | 734 | 2.3125 | 2 | [
"MIT"
] | permissive | package de.adesso.brainysnake;
import com.badlogic.gdx.Game;
import de.adesso.brainysnake.screenmanagement.ScreenManager;
import de.adesso.brainysnake.screenmanagement.ScreenType;
public class ApplicationController extends Game {
@Override
public void create() {
ScreenManager screenManager = ScreenManager.getINSTANCE();
screenManager.initialize(this);
screenManager.showScreen(ScreenType.MAIN_MENU);
}
@Override
public void pause() {
super.pause();
}
@Override
public void resume() {
super.resume();
}
@Override
public void render() {
super.render();
}
@Override
public void dispose() {
super.dispose();
}
}
| true |
52e755a224c7e91dab0ddf2310e6aec789ea6c0b | Java | c0mpiler/org.eclipse.stem | /org.eclipse.stem/analysis/org.eclipse.stem.analysis/src/org/eclipse/stem/analysis/provider/AnalysisItemProviderAdapterFactory.java | UTF-8 | 10,364 | 1.609375 | 2 | [] | no_license | package org.eclipse.stem.analysis.provider;
/*******************************************************************************
* Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018
* IBM Corporation, BfR, and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.edit.provider.ChangeNotifier;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IChangeNotifier;
import org.eclipse.emf.edit.provider.IDisposable;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.INotifyChangedListener;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.stem.analysis.util.AnalysisAdapterFactory;
/**
* This is the factory that is used to provide the interfaces needed to support Viewers.
* The adapters generated by this factory convert EMF adapter notifications into calls to {@link #fireNotifyChanged fireNotifyChanged}.
* The adapters also support Eclipse property sheets.
* Note that most of the adapters are shared among multiple instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class AnalysisItemProviderAdapterFactory extends AnalysisAdapterFactory implements ComposeableAdapterFactory, IChangeNotifier, IDisposable {
/**
* This keeps track of the root adapter factory that delegates to this adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComposedAdapterFactory parentAdapterFactory;
/**
* This is used to implement {@link org.eclipse.emf.edit.provider.IChangeNotifier}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IChangeNotifier changeNotifier = new ChangeNotifier();
/**
* This keeps track of all the supported types checked by {@link #isFactoryForType isFactoryForType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<Object> supportedTypes = new ArrayList<Object>();
/**
* This constructs an instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AnalysisItemProviderAdapterFactory() {
supportedTypes.add(IEditingDomainItemProvider.class);
supportedTypes.add(IStructuredItemContentProvider.class);
supportedTypes.add(ITreeItemContentProvider.class);
supportedTypes.add(IItemLabelProvider.class);
supportedTypes.add(IItemPropertySource.class);
}
/**
* This keeps track of the one adapter used for all {@link org.eclipse.stem.analysis.ErrorFunction} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ErrorFunctionItemProvider errorFunctionItemProvider;
/**
* This creates an adapter for a {@link org.eclipse.stem.analysis.ErrorFunction}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createErrorFunctionAdapter() {
if (errorFunctionItemProvider == null) {
errorFunctionItemProvider = new ErrorFunctionItemProvider(this);
}
return errorFunctionItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.eclipse.stem.analysis.ThresholdErrorFunction} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ThresholdErrorFunctionItemProvider thresholdErrorFunctionItemProvider;
/**
* This creates an adapter for a {@link org.eclipse.stem.analysis.ThresholdErrorFunction}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createThresholdErrorFunctionAdapter() {
if (thresholdErrorFunctionItemProvider == null) {
thresholdErrorFunctionItemProvider = new ThresholdErrorFunctionItemProvider(this);
}
return thresholdErrorFunctionItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.eclipse.stem.analysis.ReferenceScenarioDataMap} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ReferenceScenarioDataMapItemProvider referenceScenarioDataMapItemProvider;
/**
* This creates an adapter for a {@link org.eclipse.stem.analysis.ReferenceScenarioDataMap}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createReferenceScenarioDataMapAdapter() {
if (referenceScenarioDataMapItemProvider == null) {
referenceScenarioDataMapItemProvider = new ReferenceScenarioDataMapItemProvider(this);
}
return referenceScenarioDataMapItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.eclipse.stem.analysis.SimpleErrorFunction} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SimpleErrorFunctionItemProvider simpleErrorFunctionItemProvider;
/**
* This creates an adapter for a {@link org.eclipse.stem.analysis.SimpleErrorFunction}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createSimpleErrorFunctionAdapter() {
if (simpleErrorFunctionItemProvider == null) {
simpleErrorFunctionItemProvider = new SimpleErrorFunctionItemProvider(this);
}
return simpleErrorFunctionItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.eclipse.stem.analysis.ErrorResult} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ErrorResultItemProvider errorResultItemProvider;
/**
* This creates an adapter for a {@link org.eclipse.stem.analysis.ErrorResult}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createErrorResultAdapter() {
if (errorResultItemProvider == null) {
errorResultItemProvider = new ErrorResultItemProvider(this);
}
return errorResultItemProvider;
}
/**
* This keeps track of the one adapter used for all {@link org.eclipse.stem.analysis.CompoundErrorFunction} instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CompoundErrorFunctionItemProvider compoundErrorFunctionItemProvider;
/**
* This creates an adapter for a {@link org.eclipse.stem.analysis.CompoundErrorFunction}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter createCompoundErrorFunctionAdapter() {
if (compoundErrorFunctionItemProvider == null) {
compoundErrorFunctionItemProvider = new CompoundErrorFunctionItemProvider(this);
}
return compoundErrorFunctionItemProvider;
}
/**
* This returns the root adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComposeableAdapterFactory getRootAdapterFactory() {
return parentAdapterFactory == null ? this : parentAdapterFactory.getRootAdapterFactory();
}
/**
* This sets the composed adapter factory that contains this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParentAdapterFactory(ComposedAdapterFactory parentAdapterFactory) {
this.parentAdapterFactory = parentAdapterFactory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isFactoryForType(Object type) {
return supportedTypes.contains(type) || super.isFactoryForType(type);
}
/**
* This implementation substitutes the factory itself as the key for the adapter.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Adapter adapt(Notifier notifier, Object type) {
return super.adapt(notifier, this);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object adapt(Object object, Object type) {
if (isFactoryForType(type)) {
Object adapter = super.adapt(object, type);
if (!(type instanceof Class<?>) || (((Class<?>)type).isInstance(adapter))) {
return adapter;
}
}
return null;
}
/**
* This adds a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void addListener(INotifyChangedListener notifyChangedListener) {
changeNotifier.addListener(notifyChangedListener);
}
/**
* This removes a listener.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void removeListener(INotifyChangedListener notifyChangedListener) {
changeNotifier.removeListener(notifyChangedListener);
}
/**
* This delegates to {@link #changeNotifier} and to {@link #parentAdapterFactory}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void fireNotifyChanged(Notification notification) {
changeNotifier.fireNotifyChanged(notification);
if (parentAdapterFactory != null) {
parentAdapterFactory.fireNotifyChanged(notification);
}
}
/**
* This disposes all of the item providers created by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void dispose() {
if (errorFunctionItemProvider != null) errorFunctionItemProvider.dispose();
if (thresholdErrorFunctionItemProvider != null) thresholdErrorFunctionItemProvider.dispose();
if (referenceScenarioDataMapItemProvider != null) referenceScenarioDataMapItemProvider.dispose();
if (simpleErrorFunctionItemProvider != null) simpleErrorFunctionItemProvider.dispose();
if (errorResultItemProvider != null) errorResultItemProvider.dispose();
if (compoundErrorFunctionItemProvider != null) compoundErrorFunctionItemProvider.dispose();
}
}
| true |
82ae4706ae94761de208d05ac9a13211f1afa6ac | Java | OOPteam10/Iteration3 | /src/main/model/Managers/WaterwayAdjacencyManager.java | UTF-8 | 363 | 2.265625 | 2 | [] | no_license | package model.Managers;
import model.TileSubsystem.HexSide;
import model.TileSubsystem.Waterway;
/**
* Created by hankerins on 4/9/17.
*/
public class WaterwayAdjacencyManager extends AdjacencyManager<Waterway, HexSide, Waterway> {
@Override
public Adjacency<HexSide, Waterway> getAdjacency(Waterway l){
return getManagerMap().get(l);
}
}
| true |
2f795756d66b05499d3151ae0b1d12d4811ead54 | Java | bryant1410/LoonAndroid3 | /LoonAndroid_4_demo/src/com/android/demo/activity/PullHorizontalScrollViewActivity.java | UTF-8 | 1,143 | 2.140625 | 2 | [] | no_license | package com.android.demo.activity;
import android.app.Activity;
import android.widget.HorizontalScrollView;
import com.example.loonandroid2.R;
import com.loonandroid.pc.annotation.InBack;
import com.loonandroid.pc.annotation.InLayer;
import com.loonandroid.pc.annotation.InPullRefresh;
import com.loonandroid.pc.annotation.InUI;
import com.loonandroid.pc.annotation.InView;
import com.loonandroid.pc.annotation.Init;
import com.loonandroid.pc.refresh.Pull;
import com.loonandroid.pc.refresh.PullToRefreshBase;
@InLayer(R.layout.activity_horizontalscrollview)
public class PullHorizontalScrollViewActivity extends Activity {
@InView(pull = true, down = true)
HorizontalScrollView pull_refresh_horizontalscrollview;
private PullToRefreshBase<?> pullToRefreshBase;
@Init
void init() {
System.out.println(pull_refresh_horizontalscrollview.getChildCount());
}
@InPullRefresh
@InBack
public void refresh(PullToRefreshBase<?> refreshView, Pull type) throws InterruptedException {
pullToRefreshBase = refreshView;
Thread.sleep(4000);
getData();
}
@InUI
public void getData() {
pullToRefreshBase.onRefreshComplete();
}
}
| true |
e30bb05c1d16ecf3c3bd631b0906f42edcb5727f | Java | jlf1997/learngit | /boot/iot-master -yx/src/main/java/com/cimr/master/sysmanage/service/PermissionService.java | UTF-8 | 1,369 | 1.859375 | 2 | [] | no_license | package com.cimr.sysmanage.service;
import java.util.List;
import java.util.Set;
import com.cimr.comm.base.BaseService;
import com.cimr.sysmanage.model.Permission;
import com.cimr.util.PageData;
public interface PermissionService extends BaseService<Permission, String> {
/**
* 根据用户ID获取用户菜单,返回的是经过去重后的菜单ID集合
* @param paramString
* @return
*/
Set<String> findPermissionByUserId(String paramString);
/**
* 根据用户ID获取用户菜单,返回的是经过去重后的菜单对象集合
* @param paramString
* @return
*/
List<Permission> getPermissionListByUserId(String paramString);
List<Permission> getPermissionListWithName(String menuName, String type, String userId);
PageData<Permission> getPermissionListWithName(String menuName, String type, String userId, int page, int limit);
List<Permission> getPermissionsByKey(String key, String type);
List<Permission> getMenuList();
List<Permission> getMenuListByUserId(String userId);
List<Permission> getMenuListByUsername(String username);
List<Permission> getMenuListByRoleId(String roleId);
List<Permission> getOperationListByUserId(String userId);
List<Permission> getOperationListByUsername(String username);
List<Permission> getOperationListByRoleId(String roleId);
int deleteByPermissionId(String permissionId);
}
| true |
28c094a0bcae0169169738e3225eaeafa09184bd | Java | TofuDelivery/VK_bot | /src/main/java/com/company/Inventory/CoinsPouch.java | UTF-8 | 865 | 3.21875 | 3 | [] | no_license | package com.company.Inventory;
public class CoinsPouch {
private int gold;
private int silver;
private int copper;
public CoinsPouch(int gold, int silver, int copper){
this.gold = gold;
this.silver = silver;
this.copper = copper;
}
public int getGold(){
return gold;
}
public void addGold(int gold) {
this.gold += gold;
}
public int getSilver() {
return silver;
}
public void addSilver(int silver) {
this.silver = this.silver + silver;
}
public int getCopper() {
return copper;
}
public void addCopper(int copper) {
this.copper += copper;
}
public String getStringCoins(){
return String.format("Ваши деньги:%nЗолото: %d%nСеребро: %d%nМедь: %d", gold, silver, copper);
}
}
| true |
8b267bbcb920f91c8dc7f5c252f85ffa8e47ffb9 | Java | valentinmanea/travel | /src/main/java/com/travel/assistant/proxy/dto/HotelOfferDto.java | UTF-8 | 352 | 1.8125 | 2 | [] | no_license | package com.travel.assistant.proxy.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class HotelOfferDto {
public String id;
public String rateCode;
@JsonProperty("room")
public RoomDto roomDto;
@JsonProperty("guests")
public HotelGuestsDto hotelGuestDto;
@JsonProperty("price")
public HotelPriceDto hotelPriceDto;
}
| true |
d11d9633face2532ce335c1b17a3f25b9c81a4ea | Java | lousongtao/digitalmenu | /server/src/main/java/com/shuishou/digitalmenu/indent/views/MakeOrderResult.java | UTF-8 | 300 | 1.875 | 2 | [] | no_license | package com.shuishou.digitalmenu.indent.views;
import com.shuishou.digitalmenu.views.ObjectResult;
public class MakeOrderResult extends ObjectResult {
public int data;
public MakeOrderResult(String result, boolean success, int sequence) {
super(result, success);
this.data = sequence;
}
}
| true |
56ca81821f147ecbcf19a49f0f8c18aa67ec3851 | Java | furkantan-java/mycodes | /src/day11/LogicalOperators.java | UTF-8 | 3,074 | 3.28125 | 3 | [] | no_license | package day11;
public class LogicalOperators {
public static void main(String[] args) {
// eger x 60dan buyukse (int x = 70) yani soyle desek 60< x< 100 --> true <100 cok sacma olur boyle desek
//Java icin nasil deriz bunu x> 60 && x <100 yazariz
// && bunun adi ampersand yani & 1 boyle desekde olur ayni anlam. __>logical and operator
//boylelikle java diliyle isleme dogru diyoruz.
// yani int x = 70; x> 60 && x <100; that means true;
//eger iki islemde birbirini tutyorsa true yanlissa false
// false true
// int x = 10; x> 60 && x <100 ; false
// true false
//int x = 110; x> 60 && x <100 ; false
//mesela bu ornegi passport login example da dusun; eger username yanlissa passport dogru olsa bile
// sisteme giremiyorsun! kesinlikle bunun icin.
// || 2 pipe yada | 1 pipe icin;
// herhangi bir durumda birinin cevabi dogruysa sonuc dogru ornek; sut almak istiyorsun iki markete gittin
//eger bir marketden bukursan sut almis olursun
// ornek; int x = 70; x>10 || x<5 --> true
//System.out.println("truth table");
//System.out.println(true && true);
//System.out.println(false && true);
// System.out.println(true && false) ;
//System.out.println(false && false);
//System.out.println("truth table");
//System.out.println("result of true && true is" + (true && true) ); // parantez icinde olmasina dikkat et
//System.out.println("result of false && true is" + (false && true) );
//System.out.println("result of true && false is" + (true && false) );
//System.out.println("result of false && false is" + (false && false) );
//password ve user name buna harika bir ornek!
//System.out.println( "TRUTH TABLE ||");
//System.out.println( "RESULT OF true || true is " + (true || true) );
//System.out.println( "RESULT OF false || true is " + (false || true) );
// at least one is true yes
//System.out.println( "RESULT OF true || false is " + (true || false) );
// at least one side is true yes result is true
//System.out.println( "RESULT OF false || false is " + (false || false) );
// false
//int num = 80;
// System.out.println(num > 100 && num< 100) ;
//System.out.println("the result is " + (true && true));
//System.out.println(num < 100 && num> 60);
//int x = 55; // bundan sonra print statemnt alk ikinci asama icin
// System.out.println( x>100 || x<10 );
//System.out.println( x>10 && x<60 );
// System.out.println( x == 50 || x == 51 || x == 55 );// false || false ->false || true --> true
//System.out.println( true || false || false ); // -->true
//System.out.println(true && true && false); // -->false
// "&& means and" "|| means or"
int x =55 ;
System.out.println(x >50 && x != 52 || x == 57);
}
}
| true |
84e053b95605a540dcfe9f8fb01b4a75888431eb | Java | eddmanea199/CarSales | /src/main/java/com/sda/carsales/services/UserService.java | UTF-8 | 581 | 2.21875 | 2 | [] | no_license | package com.sda.carsales.services;
import com.sda.carsales.models.User;
import com.sda.carsales.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired private BCryptPasswordEncoder encoder;
@Autowired private UserRepository userRepository;
public void save(User user) {
user.setPassword(encoder.encode(user.getPassword()));
userRepository.save(user);
}
}
| true |
154dc4b61ee056321173ec6791d900bcc0424380 | Java | mathgladiator/adama-lang | /common/src/test/java/org/adamalang/common/ProtectedUUIDTests.java | UTF-8 | 740 | 1.929688 | 2 | [
"MIT"
] | permissive | /*
* This file is subject to the terms and conditions outlined in the
* file 'LICENSE' (it's dual licensed) located in the root directory
* near the README.md which you should also read. For more information
* about the project which owns this file, see https://www.adama-platform.com/ .
*
* (c) 2021 - 2023 by Adama Platform Initiative, LLC
*/
package org.adamalang.common;
import org.junit.Assert;
import org.junit.Test;
public class ProtectedUUIDTests {
@Test
public void coverage() {
try {
ProtectedUUID.encode(null);
} catch (RuntimeException re) {
Assert.assertTrue(re.getCause() instanceof NullPointerException);
}
for (int k = 0; k < 1000; k++) {
ProtectedUUID.generate();
}
}
}
| true |
511851949ab331b2e80bf253ec84762b483f1791 | Java | Ashaupperla/oosw_creativework2 | /view/HomeScreen.java | UTF-8 | 2,015 | 2.59375 | 3 | [] | no_license | package view;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import controller.LogoutButtonListener;
import model.DataBase;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Font;
public class HomeScreen {
private StateContext context;
private JFrame window;
private int userSerialID;
private HomeCanvas canvas;
private JButton logoutButton = new JButton("Log out");
private JTextArea loginIdButton = new JTextArea("User Details:");
private JTextArea loginIdField = new JTextArea("");
public HomeScreen(StateContext context, int userSerialID) {
this.window = context.window;
this.context = context;
this.userSerialID = userSerialID;
}
public void init() {
Container cp = window.getContentPane();
loginIdButton.setEditable(false);
loginIdField.setEditable(false);
loginIdButton.setFont(loginIdButton.getFont().deriveFont(Font.BOLD));
loginIdField.setText(DataBase.database.get(this.userSerialID).getDisplayData());
JPanel southPanel = new JPanel();
southPanel.add(logoutButton);
cp.add(BorderLayout.SOUTH, southPanel);
canvas = new HomeCanvas();
canvas.setLayout(new GridLayout(0, 2));
// canvas.setPreferredSize(new Dimension (200,100));
canvas.add(loginIdButton);
canvas.add(loginIdField);
cp.add(BorderLayout.CENTER, canvas);
LogoutButtonListener listener = new LogoutButtonListener(this);
logoutButton.addActionListener(listener);
}
public StateContext getContext() {
return context;
}
public JButton getLogoutButton() {
return logoutButton;
}
public JFrame getWindow() {
return window;
}
public HomeCanvas getCanvas() {
return canvas;
}
public JTextArea getLoginIdField() {
return loginIdField;
}
}
| true |
783757b6335bfa58ba7eaa60e48836c13c2f98ce | Java | ADINISairam/upload | /src/main/java/lasflores/controller/RetailerController.java | UTF-8 | 1,568 | 2.109375 | 2 | [] | no_license | package lasflores.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import lasflores.model.Retailer;
import lasflores.service.RetailerRegService;;
@Controller
@RequestMapping("/retailerReg")
public class RetailerController
{
@Autowired
private RetailerRegService RetailerRegService;
@GetMapping("/showFormRetailer")
public String showFormForAdd(ModelMap theModel) {
Retailer theRetailer=new Retailer();
//addAttribute will include all the property of NewUserReg
theModel.addAttribute("retailerReg", theRetailer);
return "NewRetailerReg-form";
}
@PostMapping("/saveNewRetailerReg")
public String saveNewUserReg(@ModelAttribute("retailerReg") Retailer theRetailer)
{ RetailerRegService.saveRetailer(theRetailer);
return "redirect:/RetailerReg/list";
}
@GetMapping("/list")
public String listNewUserRegs(ModelMap theModel)
{
List<Retailer>theRetailer=RetailerRegService.getRetailerReg();
theModel.addAttribute("retailerReg",theRetailer);
return "list-RetailerUser";
}
}
| true |
19a23a0768029faef80535edca08c7acf02881ac | Java | findfly12345/console | /src/main/java/com/allcheer/bpos/entity/TblMerFileInfoDO.java | UTF-8 | 16,606 | 1.984375 | 2 | [] | no_license | package com.allcheer.bpos.entity;
public class TblMerFileInfoDO {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.INST_ID
*
* @mbggenerated
*/
private String instId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.MER_ID
*
* @mbggenerated
*/
private String merId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.INST_MER_ID
*
* @mbggenerated
*/
private String instMerId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.PIC_ADDRESS1
*
* @mbggenerated
*/
private String picAddress1;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.PIC_ADDRESS2
*
* @mbggenerated
*/
private String picAddress2;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS3
*
* @mbggenerated
*/
private String picAddress3;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS4
*
* @mbggenerated
*/
private String picAddress4;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.PIC_ADDRESS5
*
* @mbggenerated
*/
private String picAddress5;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS6
*
* @mbggenerated
*/
private String picAddress6;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS7
*
* @mbggenerated
*/
private String picAddress7;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS8
*
* @mbggenerated
*/
private String picAddress8;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.PIC_ADDRESS9
*
* @mbggenerated
*/
private String picAddress9;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS10
*
* @mbggenerated
*/
private String picAddress10;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS11
*
* @mbggenerated
*/
private String picAddress11;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS12
*
* @mbggenerated
*/
private String picAddress12;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.
PIC_ADDRESS13
*
* @mbggenerated
*/
private String picAddress13;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_MER_FILE_INFO.PIC_ADDRESS15
*
* @mbggenerated
*/
private String picAddress15;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.INST_ID
*
* @return the value of TBL_MER_FILE_INFO.INST_ID
*
* @mbggenerated
*/
public String getInstId() {
return instId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.INST_ID
*
* @param instId the value for TBL_MER_FILE_INFO.INST_ID
*
* @mbggenerated
*/
public void setInstId(String instId) {
this.instId = instId == null ? null : instId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.MER_ID
*
* @return the value of TBL_MER_FILE_INFO.MER_ID
*
* @mbggenerated
*/
public String getMerId() {
return merId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.MER_ID
*
* @param merId the value for TBL_MER_FILE_INFO.MER_ID
*
* @mbggenerated
*/
public void setMerId(String merId) {
this.merId = merId == null ? null : merId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.INST_MER_ID
*
* @return the value of TBL_MER_FILE_INFO.INST_MER_ID
*
* @mbggenerated
*/
public String getInstMerId() {
return instMerId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.INST_MER_ID
*
* @param instMerId the value for TBL_MER_FILE_INFO.INST_MER_ID
*
* @mbggenerated
*/
public void setInstMerId(String instMerId) {
this.instMerId = instMerId == null ? null : instMerId.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS1
*
* @return the value of TBL_MER_FILE_INFO.PIC_ADDRESS1
*
* @mbggenerated
*/
public String getPicAddress1() {
return picAddress1;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS1
*
* @param picAddress1 the value for TBL_MER_FILE_INFO.PIC_ADDRESS1
*
* @mbggenerated
*/
public void setPicAddress1(String picAddress1) {
this.picAddress1 = picAddress1 == null ? null : picAddress1.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS2
*
* @return the value of TBL_MER_FILE_INFO.PIC_ADDRESS2
*
* @mbggenerated
*/
public String getPicAddress2() {
return picAddress2;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS2
*
* @param picAddress2 the value for TBL_MER_FILE_INFO.PIC_ADDRESS2
*
* @mbggenerated
*/
public void setPicAddress2(String picAddress2) {
this.picAddress2 = picAddress2 == null ? null : picAddress2.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS3
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS3
*
* @mbggenerated
*/
public String getPicAddress3() {
return picAddress3;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS3
*
* @param
picAddress3 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS3
*
* @mbggenerated
*/
public void setPicAddress3(String picAddress3) {
this.picAddress3 = picAddress3 == null ? null : picAddress3.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS4
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS4
*
* @mbggenerated
*/
public String getPicAddress4() {
return picAddress4;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS4
*
* @param
picAddress4 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS4
*
* @mbggenerated
*/
public void setPicAddress4(String picAddress4) {
this.picAddress4 = picAddress4 == null ? null : picAddress4.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS5
*
* @return the value of TBL_MER_FILE_INFO.PIC_ADDRESS5
*
* @mbggenerated
*/
public String getPicAddress5() {
return picAddress5;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS5
*
* @param picAddress5 the value for TBL_MER_FILE_INFO.PIC_ADDRESS5
*
* @mbggenerated
*/
public void setPicAddress5(String picAddress5) {
this.picAddress5 = picAddress5 == null ? null : picAddress5.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS6
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS6
*
* @mbggenerated
*/
public String getPicAddress6() {
return picAddress6;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS6
*
* @param
picAddress6 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS6
*
* @mbggenerated
*/
public void setPicAddress6(String picAddress6) {
this.picAddress6 = picAddress6 == null ? null : picAddress6.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS7
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS7
*
* @mbggenerated
*/
public String getPicAddress7() {
return picAddress7;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS7
*
* @param
picAddress7 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS7
*
* @mbggenerated
*/
public void setPicAddress7(String picAddress7) {
this.picAddress7 = picAddress7 == null ? null : picAddress7.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS8
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS8
*
* @mbggenerated
*/
public String getPicAddress8() {
return picAddress8;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS8
*
* @param
picAddress8 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS8
*
* @mbggenerated
*/
public void setPicAddress8(String picAddress8) {
this.picAddress8 = picAddress8 == null ? null : picAddress8.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS9
*
* @return the value of TBL_MER_FILE_INFO.PIC_ADDRESS9
*
* @mbggenerated
*/
public String getPicAddress9() {
return picAddress9;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS9
*
* @param picAddress9 the value for TBL_MER_FILE_INFO.PIC_ADDRESS9
*
* @mbggenerated
*/
public void setPicAddress9(String picAddress9) {
this.picAddress9 = picAddress9 == null ? null : picAddress9.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS10
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS10
*
* @mbggenerated
*/
public String getPicAddress10() {
return picAddress10;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS10
*
* @param
picAddress10 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS10
*
* @mbggenerated
*/
public void setPicAddress10(String picAddress10) {
this.picAddress10 = picAddress10 == null ? null : picAddress10.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS11
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS11
*
* @mbggenerated
*/
public String getPicAddress11() {
return picAddress11;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS11
*
* @param
picAddress11 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS11
*
* @mbggenerated
*/
public void setPicAddress11(String picAddress11) {
this.picAddress11 = picAddress11 == null ? null : picAddress11.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS12
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS12
*
* @mbggenerated
*/
public String getPicAddress12() {
return picAddress12;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS12
*
* @param
picAddress12 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS12
*
* @mbggenerated
*/
public void setPicAddress12(String picAddress12) {
this.picAddress12 = picAddress12 == null ? null : picAddress12.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS13
*
* @return the value of TBL_MER_FILE_INFO.
PIC_ADDRESS13
*
* @mbggenerated
*/
public String getPicAddress13() {
return picAddress13;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.
PIC_ADDRESS13
*
* @param
picAddress13 the value for TBL_MER_FILE_INFO.
PIC_ADDRESS13
*
* @mbggenerated
*/
public void setPicAddress13(String picAddress13) {
this.picAddress13 = picAddress13 == null ? null : picAddress13.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS15
*
* @return the value of TBL_MER_FILE_INFO.PIC_ADDRESS15
*
* @mbggenerated
*/
public String getPicAddress15() {
return picAddress15;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_MER_FILE_INFO.PIC_ADDRESS15
*
* @param picAddress15 the value for TBL_MER_FILE_INFO.PIC_ADDRESS15
*
* @mbggenerated
*/
public void setPicAddress15(String picAddress15) {
this.picAddress15 = picAddress15 == null ? null : picAddress15.trim();
}
} | true |
1a4cf686a916b1dcbbb354c5e58fb38dd987cf7f | Java | janbodnar/Java-Course | /day1/ContinueStatementEx.java | UTF-8 | 362 | 3.25 | 3 | [] | no_license | package com.zetcode;
public class ContinueStatementEx {
public static void main(String[] args) {
int num = 0;
while (num < 100) {
num++;
if ((num % 2) == 0) {
continue;
}
System.out.print(num + " ");
}
System.out.print('\n');
}
}
| true |
c7f5dee8187527d6b8e4c50c91c40a80851b0f97 | Java | matzora/TPM1Agile2 | /java/src/test/test.java | UTF-8 | 264 | 1.554688 | 2 | [] | no_license | package test;
import controller.APIController;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
APIController api = new APIController();
api.sendRequest("http://jsonplaceholder.typicode.com/posts/1");
}
}
| true |
66c7aebedb062e8afbe4b0e0c8be1efe122ab29d | Java | raghavb1/oval-search-platform | /OvalSearch/src/main/java/com/ovalsearch/dao/IEntityDao.java | UTF-8 | 762 | 2.09375 | 2 | [] | no_license | package com.ovalsearch.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.stereotype.Repository;
import com.ovalsearch.entity.BaseEntity;
@Repository
public interface IEntityDao {
public <T extends BaseEntity> void saveOrUpdate(T object);
public <T extends BaseEntity> void delete(T object);
public <T extends BaseEntity> T findById(Class<T> objectClass, Long id);
public <T extends BaseEntity> List<T> findAll(Class<T> objectClass);
public <T extends BaseEntity> List<T> findAllEnabledObjects(Class<T> objectClass);
public <T extends BaseEntity> Long getMaxId(Class<T> objectClass);
public void flush();
public void clear();
public EntityManager getEntityManager();
}
| true |
2ba6e89bed5466610bacee5f0b499c4998eee29a | Java | afaulconbridge/JAChemKit | /src/main/java/jachemkit/webapp/PopulateRunner.java | UTF-8 | 2,506 | 2.71875 | 3 | [
"MIT"
] | permissive | package jachemkit.webapp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import jachemkit.hashchem.model.NeoAtom;
import jachemkit.hashchem.model.NeoMolecule;
import jachemkit.hashchem.repo.MoleculeRepository;
import jachemkit.hashchem.service.MoleculeEqualityService;
@Component
public class PopulateRunner implements ApplicationRunner {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private MoleculeRepository moleculeRepository;
@Autowired
private MoleculeEqualityService moleculeEqualityTester;
@Autowired
private ObjectMapper objectMapper;
@Override
public void run(ApplicationArguments args) throws Exception {
//ensure there is some basic molecules in the repos
//create what we want to be there
Set<NeoMolecule> wantedMolecules = new HashSet<>();
for (int i = 0; i < 10; i++) {
Random rng = new Random(i);
//warm up the randomness a bit
for (int j=0; j < rng.nextInt(10); j++) {
rng.nextInt();
}
List<Integer> element = new ArrayList<>();
for (int j=0; j < 4; j++) {
element.add(rng.nextInt(8));
}
//convert to json
String value = objectMapper.writeValueAsString(element);
//create the molecule
NeoMolecule mol = new NeoMolecule(new NeoAtom(value));
wantedMolecules.add(mol);
}
//for each thing that is there, remove its partner from the wanted
for (NeoMolecule mol : moleculeRepository.findAtoms()) {
//make sure we get it in sufficient depth
mol = moleculeRepository.findOne(mol.getNeoId(), 3);
Iterator<NeoMolecule> wantedIterator = wantedMolecules.iterator();
while (wantedIterator.hasNext()) {
NeoMolecule wanted = wantedIterator.next();
if (moleculeEqualityTester.areEqual(wanted, mol)) {
wantedIterator.remove();
break;
}
}
}
//add what is left
Iterator<NeoMolecule> wantedIterator = wantedMolecules.iterator();
while (wantedIterator.hasNext()) {
log.info("Adding new atomic molecule");
NeoMolecule wanted = wantedIterator.next();
moleculeRepository.save(wanted);
}
}
}
| true |
ddac186393e1b860d255615ac97db233c5131fd3 | Java | devanshah1/Distributed-Systems-Assignments-and-Labs | /Labs/Lab 2/Final Submission/DistributedSystems - Lab 2 - Task 2 Implement Election/src/ElectionImplementation.java | UTF-8 | 5,732 | 3.390625 | 3 | [] | no_license | import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
/**
* This class contains the method implementation that are defined in ElectionInterface.
* @author Devan Shah 100428864
*
*/
public class ElectionImplementation extends UnicastRemoteObject implements ElectionInterface
{
// Default serialization ID
private static final long serialVersionUID = 1L ;
/*
* Stores the votes that are casted will contain:
* Integer - voters ID
* String - the candidate's name they voted for.
*/
public Map <Integer, String> votesCasted ;
/**
* Constructor of the class that is used to initialize the votesCasted
* as a HashMap of integers and strings.
* @throws RemoteException
*/
public ElectionImplementation () throws RemoteException
{
super () ;
votesCasted = new HashMap <Integer, String>() ;
}
/**
* This function is used to cast a vote, this is called remotely.
* The function also performs a verification task to make sure that
* the same voter's number is not used to cast a vote.
*/
@Override
public boolean vote ( String candidateName, int voterNumber )
{
// Only add the vote into the main hashmap if the voter's number does not already exist.
if ( votesCasted.containsKey ( voterNumber ) )
{
System.out.println ( "Sorry You can only Vote Once, you voter ID is: " + voterNumber + "\n" ) ;
// Return false when the voter has already voted.
return false ;
}
else {
// Add the users vote into the main HashMap
votesCasted.put ( new Integer ( voterNumber ), candidateName ) ;
System.out.println ( "Vote for \"" + candidateName + "\" successfully casted by \"" + voterNumber + "\"" ) ;
}
// return true on a successful vote cast
return true ;
}
/**
* This function is used to return the casted results for all the candidates.
* Following are the steps that the performed by this function:
* 1. Iterate through the votesCasted hashmap
* 2. Build the candidateResultsHolder hashmap with distinct candidates name
* and the gather now many votes where for that candidate.
* 3. Iterate through the candidateResultsHolder hashmap that was build and
* make store the results as a ElectionResults method in vector candidateResults.
* 4. Return the candidateResults vector.
*/
@Override
public Vector<Object> result () throws RemoteException
{
// Declare vector and HashMap
Vector <Object> candidateResults = new Vector<Object>() ;
Map <String, Integer> candidateResultsHolder = new HashMap <String, Integer>() ;
// Build the votesCasted Iterator to retrieve results from the HashMap
Iterator <Entry <Integer, String>> castedVotesIterator = votesCasted.entrySet().iterator() ;
// Loop through the iterator and build the candidateResultsHolder HashMap
while ( castedVotesIterator.hasNext() )
{
// Construct the Entry to get the reference to the elements.
Entry <Integer, String> castedVotesEntry = castedVotesIterator.next() ;
/*
* Check the candidate value in HashMap castedVotesEntry and add them to candidateResultsHolder HashMap
* make sure that when adding the candidate values into candidateResultsHolder that they are distinct only.
* When a duplicate value is detected in castedVotesEntry HashMap increment the candidateResultsHolder
* Hashmap value for the candidate key in question.
*/
if ( candidateResultsHolder.containsKey ( castedVotesEntry.getValue() ) )
{
// Increment the value in candidateResultsHolder for the candidate in question by 1.
candidateResultsHolder.put ( castedVotesEntry.getValue(), ( candidateResultsHolder.get ( castedVotesEntry.getValue() ) + 1 ) ) ;
}
else {
// A new candidate has been detected create a new entry in the candidateResultsHolder HashMap
candidateResultsHolder.put ( castedVotesEntry.getValue(), new Integer (1) ) ;
}
}
// Build the candidateResults Iterator to retrieve results from the HashMap
Iterator <Entry <String, Integer>> candidateResultsIterator = candidateResultsHolder.entrySet().iterator() ;
// Loop through the iterator and build the candidateResults vectors
while ( candidateResultsIterator.hasNext() )
{
// Construct the Entry to get the reference to the elements.
Entry <String, Integer> candidateResultEntry = candidateResultsIterator.next() ;
// Construct an object of ElectionResults with the information from the candidateResultsHolder HashMap.
ElectionResults resultsAdd = new ElectionResults ( candidateResultEntry.getKey(), candidateResultEntry.getValue() ) ;
// Add the elements to the vector.
candidateResults.addElement ( resultsAdd ) ;
}
System.out.println ( "The total number of candidates being returned to client: " + candidateResults.size () ) ;
// return the candidateResults vector
return candidateResults ;
}
}
| true |
48abcbf3dd1db01cd337e2ec1b2b664e9e34d64a | Java | steeck1/Java-Fun | /main.java | UTF-8 | 7,391 | 2.15625 | 2 | [] | no_license |
import java.awt.Color;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.Timer;
import javax.swing.AbstractAction;
import javax.swing.JLabel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class main extends javax.swing.JFrame {
public main() {
initComponents();
series1 = new XYSeries("b/w usage in kbps");
dataset = createDataset();
chart = createChart(dataset);
chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
// chartPanel.setLayout();
chartPanel.add(current_bandwidth_label);
setContentPane(chartPanel);
pmt = new PacketMonitoringThread();
pmt.start();
Action updateCursorAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int current_bandwidth = new Integer((int) TcpPacketCapturer.getPacketSizeTillNowAndResetSize());
qe.add(current_bandwidth);
current_bandwidth_label.setText("" + current_bandwidth);
if (qe.size() > 20) {
System.out.println(qe.poll());
}
dataset = createDataset();
chart = createChart(dataset);
chartPanel = new ChartPanel(chart);
// getContentPane().repaint();
// SwingUtilities.updateComponentTreeUI(chartPanel);
}
};
new Timer(1000, updateCursorAction).start();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSeparator1 = new javax.swing.JSeparator();
jToolBar1 = new javax.swing.JToolBar();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jToolBar1.setRollover(true);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(203, 203, 203)
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(113, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main f = new main();
f.setVisible(true);
}
});
}
private XYDataset createDataset() {
series1.clear();
Iterator it = qe.iterator();
// System.out.println("Initial Size of Queue :" + qe.size());
double a = 1.0;
while (it.hasNext()) {
Integer iteratorValue = (Integer) it.next();
series1.add(a++, ((double) iteratorValue) / 1024);
}
final XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series1);
return dataset;
}
private JFreeChart createChart(final XYDataset dataset) {
// create the chart...
final JFreeChart chart = ChartFactory.createXYLineChart(
"B/W Usage in kbps ", // chart title
"Seconds", // x axis label
"Usage", // y axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
chart.setBackgroundPaint(Color.white);
// final StandardLegend legend = (StandardLegend) chart.getLegend();
// legend.setDisplaySeriesShapes(true);
// get a reference to the plot for further customisation...
final XYPlot plot = chart.getXYPlot();
plot.setBackgroundPaint(Color.lightGray);
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
//
final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setSeriesLinesVisible(1, true);
// renderer.setSeriesShapesVisible(1, false);
plot.setRenderer(renderer);
// change the auto tick unit selection to integer units only...
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// OPTIONAL CUSTOMISATION COMPLETED.
return chart;
}
PacketMonitoringThread pmt = null;
public XYSeries series1 = null;
XYDataset dataset = null;
JFreeChart chart = null;
ChartPanel chartPanel = null;
Queue<Integer> qe = new LinkedList<Integer>();
static JLabel current_bandwidth_label = new JLabel("0");
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JToolBar jToolBar1;
// End of variables declaration//GEN-END:variables
}
| true |
ce462243437cfec1d8554bfe362af84ba4fb7223 | Java | javalite/javalite-examples | /activeweb-lessc/src/main/java/app/controllers/BootstrapController.java | UTF-8 | 387 | 1.90625 | 2 | [
"Apache-2.0"
] | permissive | package app.controllers;
import org.javalite.activeweb.AppController;
import org.javalite.activeweb.controllers.AbstractLesscController;
import java.io.File;
/**
* @author Igor Polevoy on 7/28/14.
*/
public class BootstrapController extends AbstractLesscController {
@Override
protected File getLessFile() {
return new File("src/main/webapp/less/bootstrap.less");
}
}
| true |
6c8ce4e9d1d625c9d6090a07767ea6b2f98052b9 | Java | sajidit/Sonica | /app/src/main/java/sonica/it/com/sonica/service/SonicaQuestionService.java | UTF-8 | 373 | 1.695313 | 2 | [] | no_license | package sonica.it.com.sonica.service;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import sonica.it.com.sonica.bean.Question;
import sonica.it.com.sonica.bean.ResponseBody;
/**
* Created by SajidA on 02/11/2016.
*/
public interface SonicaQuestionService {
@GET("/_ah/api/questions/v1/questions")
Call<ResponseBody> listRepos();
}
| true |
9228b34e8c4b7e47d22a94eb720d611ea8c288ce | Java | LczjTeam/Lczj | /src/main/java/jx/lczj/controller/BrandController.java | UTF-8 | 2,264 | 2.09375 | 2 | [] | no_license | package jx.lczj.controller;
import jx.lczj.anotation.Privilege;
import jx.lczj.dao.BrandDao;
import jx.lczj.model.T_brand;
import jx.lczj.service.AdminService;
import jx.lczj.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* Created by 14260 on 2018/6/10.
*/
@Controller
@RequestMapping("brand")
public class BrandController {
@Autowired
BrandService brandService;
/**
* 加载所有品牌信息
*/
@RequestMapping("/list")
@ResponseBody
public List<T_brand> list(){
return brandService.loadList();
}
/**
* 加载镜片品牌信息
*/
@RequestMapping("/list1")
@ResponseBody
public List<T_brand> list1(HttpServletRequest request){
return brandService.loadList1(request);
}
/**
* 加载镜框品牌信息
*/
@RequestMapping("/list2")
@ResponseBody
public List<T_brand> list2(){
return brandService.loadList2();
}
/**
* 添加品牌信息
* @param brand
* @param name
* @param company
* @return
*/
@Privilege(value = "品牌管理")
@RequestMapping("/add")
@ResponseBody
public boolean add(int brand,String name,String company,int type,int recommend){
return brandService.add(brand,name,company,type,recommend);
}
/**
* 更新品牌信息
* @param brand
* @param name
* @param company
* @return
*/
@Privilege(value = "品牌管理")
@RequestMapping("/update")
@ResponseBody
public boolean update(int brand,String name,String company,int type,int recommend){
return brandService.update(brand,name,company,type,recommend);
}
/**
* 删除品牌信息
* @param brand
* @return
*/
@Privilege(value = "品牌管理")
@RequestMapping("/delete")
@ResponseBody
public boolean delete(String brand){
return brandService.delete(brand);
}
}
| true |
078ef38907af59bad127bf1ac0583777e7768dc8 | Java | shpunishment/mall | /mall-back-api/src/main/java/com/shpun/mall/back/controller/MallFileServerController.java | UTF-8 | 1,045 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | package com.shpun.mall.back.controller;
import com.shpun.mall.common.service.MallFileServerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* @Description:
* @Author: sun
* @Date: 2020/8/29 13:43
*/
@Api(tags = "文件服务器控制器")
@RequestMapping("/api/file")
@RestController
public class MallFileServerController {
@Autowired
private MallFileServerService fileServerService;
@ApiOperation("上传文件")
@PostMapping("/upload")
public Integer upload(@RequestParam(value = "file") MultipartFile file) {
return fileServerService.saveUploadFile(file);
}
}
| true |
d9fbb522a1cade24e4105c383bdd303f7c4c91ec | Java | JobDiangkinay/Project1Revature | /src/main/java/com/revature/entities/EmployeeDao.java | UTF-8 | 9,946 | 2.53125 | 3 | [] | no_license | package com.revature.entities;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import com.revature.models.Employee;
import com.revature.models.Reimbursement;
public class EmployeeDao implements Dao{
private Connection connection;
public EmployeeDao(Connection connection) {
this.connection = connection;
}
public boolean checkLogIn(String userName, String password) throws SQLException {
int count = 0;
try {
PreparedStatement pStatement = connection
.prepareStatement("select * from accountcredentials where username = ?");
pStatement.setString(1, userName);
ResultSet resultSet = pStatement.executeQuery();
while (resultSet.next()) {
count++;
byte[] hashPassword = resultSet.getBytes("password");
byte[] hashSalt = resultSet.getBytes("saltpass");
try {
MessageDigest md;
md = MessageDigest.getInstance("SHA-512");
md.update(hashSalt);
byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));
if(Arrays.equals(hashedPassword, hashPassword)) {
return true;
}else {
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return false;
}
public Employee getEmployeeObject(String userName) throws SQLException {
int count = 0;
Employee curEmp = null;
try {
PreparedStatement pStatement = connection.prepareStatement(
"select * from persons join accountcredentials on persons.username = accountcredentials.username where persons.username = ?");
pStatement.setString(1, userName);
ResultSet resultSet = pStatement.executeQuery();
while (resultSet.next()) {
String username = resultSet.getString("username");
String passWord = resultSet.getString("password");
String usertype = resultSet.getString("usertype");
String firstName = resultSet.getString("firstname");
String lastName = resultSet.getString("lastname");
String phoneNumber = resultSet.getString("phonenumber");
String eMail = resultSet.getString("emailadd");
count++;
curEmp = new Employee(username, passWord, usertype, firstName, lastName, phoneNumber, eMail);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
if (count == 1) {
return curEmp;
}
return curEmp;
}
public ArrayList<Employee> getAllEmployees() {
ArrayList<Employee> allEmp = new ArrayList<>();
try {
PreparedStatement pStatement = connection.prepareStatement(
"select * from persons join accountcredentials on persons.username = accountcredentials.username where accountcredentials.usertype = 'EMPLOYEE'");
ResultSet resultSet = pStatement.executeQuery();
while (resultSet.next()) {
String username = resultSet.getString("username");
String passWord = resultSet.getString("password");
String usertype = resultSet.getString("usertype");
String firstName = resultSet.getString("firstname");
String lastName = resultSet.getString("lastname");
String phoneNumber = resultSet.getString("phonenumber");
String eMail = resultSet.getString("emailadd");
allEmp.add(new Employee(username, passWord, usertype, firstName, lastName, phoneNumber, eMail));
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return allEmp;
}
public ArrayList<Reimbursement> getEmployeeReim(String curUsername) {
ArrayList<Reimbursement> allReimburse = new ArrayList<>();
try {
PreparedStatement pStatement = connection
.prepareStatement("select * from reimbursements where username = ?");
pStatement.setString(1, curUsername);
ResultSet resultSet = pStatement.executeQuery();
while (resultSet.next()) {
String reimId = resultSet.getString("pid");
double amount = resultSet.getDouble("amount");
String reimType = resultSet.getString("reimbursementtype");
String reimStatus = resultSet.getString("reimbursementstatus");
String reimDate = resultSet.getString("creationdate");
String reimDesc = resultSet.getString("reimbursementdesc");
String userName = resultSet.getString("username");
String reimBase64 = resultSet.getString("reimbase64");
String adminName = resultSet.getString("reimadmin");
allReimburse.add(new Reimbursement(reimId, reimType, reimStatus, reimDate, reimDesc, amount, userName,
reimBase64, adminName));
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return allReimburse;
}
public ArrayList<Reimbursement> getAllReim() {
ArrayList<Reimbursement> allReimburse = new ArrayList<>();
try {
PreparedStatement pStatement = connection.prepareStatement("select * from reimbursements");
ResultSet resultSet = pStatement.executeQuery();
while (resultSet.next()) {
String reimId = resultSet.getString("pid");
double amount = resultSet.getDouble("amount");
String reimType = resultSet.getString("reimbursementtype");
String reimStatus = resultSet.getString("reimbursementstatus");
String reimDate = resultSet.getString("creationdate");
String reimDesc = resultSet.getString("reimbursementdesc");
String userName = resultSet.getString("username");
String reimBase64 = resultSet.getString("reimbase64");
String adminName = resultSet.getString("reimadmin");
allReimburse.add(new Reimbursement(reimId, reimType, reimStatus, reimDate, reimDesc, amount, userName,
reimBase64, adminName));
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return allReimburse;
}
public boolean updateReimStatus(String reimId, boolean Accept, String adminName) {
boolean status = false;
int iD = Integer.parseInt(reimId);
boolean isAccepted = Accept;
try {
if (isAccepted) {
PreparedStatement pStatement = connection.prepareStatement(
"update reimbursements set reimbursementstatus = 'Approved', reimadmin = ? where pid = ? ");
pStatement.setString(1, adminName);
pStatement.setInt(2, iD);
pStatement.executeUpdate();
status = true;
} else {
PreparedStatement pStatement = connection.prepareStatement(
"update reimbursements set reimbursementstatus = 'Denied', reimadmin = ? where pid = ? ");
pStatement.setString(1, adminName);
pStatement.setInt(2, iD);
pStatement.executeUpdate();
status = false;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return status;
}
public boolean updateEmpInfo(String userName, String editType, String editValue) {
boolean status = false;
try {
if (editType.equals("eMail")) {
PreparedStatement pStatement = connection
.prepareStatement("update persons set emailadd = ? where username = ? ");
pStatement.setString(1, editValue);
pStatement.setString(2, userName);
pStatement.executeUpdate();
status = true;
} else if (editType.equals("phoneNumber")) {
PreparedStatement pStatement = connection
.prepareStatement("update persons set phonenumber = ? where username = ? ");
pStatement.setString(1, editValue);
pStatement.setString(2, userName);
pStatement.executeUpdate();
status = true;
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return status;
}
public boolean submitNewRequest(Reimbursement e) {
boolean status = false;
try {
PreparedStatement pStatement = connection.prepareStatement(
"insert into reimbursements(username, amount, reimbursementtype, reimbursementstatus, reimbursementdesc, creationdate, reimbase64) values(?, ?, ?, ?, ?, ?,?)");
pStatement.setString(1, e.getUserId());
pStatement.setDouble(2, e.getAmount());
pStatement.setString(3, e.getReimbursementType());
pStatement.setString(4, e.getStatus());
pStatement.setString(5, e.getReimbursementDesc());
pStatement.setString(6, e.getDateCreated());
pStatement.setString(7, e.getImageBase64());
// byte[] bytes = e.getImageBase64().getBytes();
// pStatement.setBytes(7, bytes);
pStatement.executeUpdate();
status = true;
} catch (SQLException ex) {
ex.printStackTrace();
return status;
}
return status;
}
public void insertEmployee(Employee addEmp) {
try {
PreparedStatement pStatement = connection
.prepareStatement("insert into accountcredentials(usertype, username, password, saltpass) values(?, ?, ?, ?)");
pStatement.setString(1, addEmp.getUserType());
pStatement.setString(2, addEmp.getUserName());
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
MessageDigest md;
try {
// Creates hashed password
md = MessageDigest.getInstance("SHA-512");
md.update(salt);
// This is stored in database in user
byte[] hashedPassword = md.digest(addEmp.getPassword().getBytes(StandardCharsets.UTF_8));
pStatement.setBytes(3, hashedPassword);
pStatement.setBytes(4, salt);
} catch (Exception ex) {
}
pStatement.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
}
insertPerson(addEmp);
}
public void insertPerson(Employee addEmp) {
try {
PreparedStatement pStatement = connection.prepareStatement(
"insert into persons(username, emailadd, phonenumber, lastname, firstname) values(?, ?, ?, ?, ?)");
pStatement.setString(1, addEmp.getUserName());
pStatement.setString(2, addEmp.geteMail());
pStatement.setString(3, addEmp.getPhoneNumber());
pStatement.setString(4, addEmp.getLastName());
pStatement.setString(5, addEmp.getFirstName());
pStatement.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| true |
3793f85bf32e0a6dd27085cf23b6d1049a8fb76d | Java | ZeeNzY/Assignment5 | /src/main/java/ac/za/cput/projects/service/impl/EmployeeServiceImp.java | UTF-8 | 1,326 | 2.46875 | 2 | [] | no_license | package ac.za.cput.projects.service.impl;
import ac.za.cput.projects.domain.Persons.AgencyEmployee;
import ac.za.cput.projects.repository.EmployeeRepository;
import ac.za.cput.projects.repository.impl.EmployeeRepoImp;
import ac.za.cput.projects.service.EmployeeService;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class EmployeeServiceImp implements EmployeeService {
private EmployeeRepository repository;
private static EmployeeServiceImp service = null;
private EmployeeServiceImp(){
this.repository = EmployeeRepoImp.getEmployeeRepository();
}
public static EmployeeServiceImp getService(){
if (service == null) service = new EmployeeServiceImp();
return service;
}
@Override
public AgencyEmployee create(AgencyEmployee agencyEmployee) {
return repository.create(agencyEmployee);
}
@Override
public AgencyEmployee update(AgencyEmployee agencyEmployee) {
return repository.update(agencyEmployee);
}
@Override
public void delete(String s) {
repository.delete(s);
}
@Override
public AgencyEmployee read(String s) {
return repository.read(s);
}
@Override
public Set<AgencyEmployee> getAll() {
return repository.getAll();
}
}
| true |
3aa7fd6407b1b87a08f70a16b0a3eb9e243dc3ed | Java | shawnThottan/AmbulanceDriverApp | /app/src/main/java/com/example/android/ambulancedriverapp/details.java | UTF-8 | 4,256 | 2 | 2 | [] | no_license | package com.example.android.ambulancedriverapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class details extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
final TextView si = (TextView)findViewById(R.id.Si);
final TextView no = (TextView)findViewById(R.id.No);
final TextView ti = (TextView)findViewById(R.id.Ti);
final TextView start = (TextView)findViewById(R.id.Start);
final TextView end = (TextView)findViewById(R.id.End);
final TextView dest = (TextView)findViewById(R.id.dest);
final Button B = (Button)findViewById(R.id.Location);
String username;
Bundle extras=getIntent().getExtras();
username=extras.getString("username");
final int nu=extras.getInt("no");
final Intent i = new Intent(getApplicationContext(),location.class);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Log/Ambulance/"+username);
ref.addChildEventListener(new ChildEventListener() {
int n=0;
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
n++;
if(n == nu) {
if (dataSnapshot != null) {
timeEnded tE = dataSnapshot.getValue(timeEnded.class);
String t;
end.setText("End: "+tE.date+" | "+ tE.month+" | "+ tE.year+" || "+ tE.hour+" : "+ tE.minute);
start.setText("Start: "+tE.dates+" | "+ tE.months+" | "+ tE.years+" || "+ tE.hours+" : "+ tE.minutes);
t="Not Specified";
if(tE.ti==1)
t="Neural";
if(tE.ti==2)
t="Pregnancy";
if(tE.ti==3)
t="Heart Attack";
if(tE.ti==4)
t="Vehicle Accident";
if(tE.ti==5)
t="Head Injury";
if(tE.ti==6)
t="Other";
ti.setText("Type: "+t);
t="Low";
if(tE.si==2)
t="Medium";
if(tE.si==3)
t="High";
if(tE.dest==1)
dest.setText("The patient was taken elsewhere due to high criticality.");
si.setText("Severity: "+t);
no.setText("Number: "+tE.no);
i.putExtra("lat",tE.lat);
i.putExtra("lon",tE.lon);
i.putExtra("late",tE.late);
i.putExtra("lone",tE.lone);
i.putExtra("stime","Starting Time: "+tE.hours+":"+tE.minutes);
i.putExtra("etime","Ending Time: "+tE.hour+":"+tE.minute);
}
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
B.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(i);
}
});
}
}
| true |
8f5c73d774ed10db8a27743dd14809ace421acba | Java | awwolfe/MorphPotion | /src/main/java/gamecycles/morphpotion/init/PotionTypeEntry.java | UTF-8 | 248 | 2.28125 | 2 | [] | no_license | package gamecycles.morphpotion.init;
import net.minecraft.potion.PotionType;
public class PotionTypeEntry{
public int level;
public PotionType type;
public PotionTypeEntry(int level,PotionType type){
this.level=level;
this.type=type;
}
}
| true |
7315f1dc0b535d70cf110a538715c32056747f4b | Java | TimBishop42/trade-integrity-checker | /src/main/java/com/crypto/tradeintegritychecker/model/response/trades/TradeResult.java | UTF-8 | 298 | 1.765625 | 2 | [] | no_license | package com.crypto.tradeintegritychecker.model.response.trades;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
@Data
public class TradeResult {
@JsonProperty("instrument_name")
private String instrumentName;
List<TradesData> data;
}
| true |
6ba5791c4feddb3779c9793370aa3f4a437816c4 | Java | mateusteixeira/digital-wallet | /src/test/java/br/com/dwallet/service/WalletAccountServiceTest.java | UTF-8 | 5,646 | 2.046875 | 2 | [] | no_license | package br.com.dwallet.service;
import br.com.dwallet.exception.WalletAccountNotFoundException;
import br.com.dwallet.model.User;
import br.com.dwallet.model.WalletAccount;
import br.com.dwallet.model.dto.WalletAccountDTO;
import br.com.dwallet.model.repository.WalletAccountRepository;
import br.com.dwallet.translator.WalletAccountTranslator;
import br.com.dwallet.validator.WalletAccountValidator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class WalletAccountServiceTest {
private static final String ID_WALLET_ACCOUNT = "aqsw";
@Mock
private UserService userService;
@Mock
private WalletAccountValidator walletAccountValidator;
@Mock
private WalletAccountRepository walletAccountRepository;
@Mock
private WalletAccountTranslator walletAccountTranslator;
@InjectMocks
private WalletAccountService walletAccountService;
@BeforeEach
public void before() {
MockitoAnnotations.openMocks(this);
}
@Test
public void should_save_new_walletAccount() {
WalletAccountDTO walletAccountDTO = WalletAccountDTO.builder().idUser("3232").build();
WalletAccount walletAccount = mock(WalletAccount.class);
when(userService.getUserOrThrowNotFoundException("3232")).thenReturn(User.builder().build());
when(walletAccountTranslator.fromDTO(walletAccountDTO)).thenReturn(walletAccount);
when(walletAccountRepository.save(walletAccount)).thenReturn(walletAccount);
when(walletAccountTranslator.toDTO(walletAccount)).thenReturn(walletAccountDTO);
WalletAccountDTO walletAccountCreatedDTO = walletAccountService.createWalletAccount(walletAccountDTO);
assertNotNull(walletAccountCreatedDTO);
verify(walletAccountValidator).validateWalletAccountExists(walletAccount);
verify(walletAccountRepository).save(walletAccount);
}
@Test
public void should_get_walletAccount_by_id() {
WalletAccount walletAccount = WalletAccount.builder().build();
WalletAccountDTO walletAccountDTO = WalletAccountDTO.builder().build();
when(walletAccountRepository.findById(ID_WALLET_ACCOUNT)).thenReturn(Optional.of(walletAccount));
when(walletAccountTranslator.toDTO(walletAccount)).thenReturn(walletAccountDTO);
WalletAccountDTO walletAccountFindDTO = walletAccountService.getWalletAccountById(ID_WALLET_ACCOUNT);
assertNotNull(walletAccountFindDTO);
verify(walletAccountRepository).findById(ID_WALLET_ACCOUNT);
verify(walletAccountTranslator).toDTO(walletAccount);
}
@Test
public void should_throws_exception_when_get_walletAccount_by_id_not_found() {
when(walletAccountRepository.findById(ID_WALLET_ACCOUNT)).thenReturn(Optional.empty());
assertThrows(WalletAccountNotFoundException.class, () -> walletAccountService.getWalletAccountById(ID_WALLET_ACCOUNT));
verify(walletAccountRepository).findById(ID_WALLET_ACCOUNT);
verify(walletAccountTranslator, never()).toDTO(any());
}
@Test
public void should_get_all_walletAccounts() {
WalletAccount walletAccount = WalletAccount.builder().build();
WalletAccountDTO walletAccountDTO = WalletAccountDTO.builder().build();
PageImpl<WalletAccount> walletAccounts = new PageImpl<>(List.of(walletAccount));
when(walletAccountRepository.findAll(Pageable.unpaged())).thenReturn(walletAccounts);
when(walletAccountTranslator.toDTO(walletAccount)).thenReturn(walletAccountDTO);
List<WalletAccountDTO> allWalletAccounts = walletAccountService.getAllWalletAccounts(Pageable.unpaged());
assertNotNull(allWalletAccounts);
assertEquals(1, allWalletAccounts.size());
verify(walletAccountRepository).findAll(any(Pageable.class));
verify(walletAccountTranslator).toDTO(walletAccount);
}
@Test
public void should_update_walletAccount() {
WalletAccount walletAccount = mock(WalletAccount.class);
WalletAccountDTO walletAccountDTO = mock(WalletAccountDTO.class);
when(walletAccountRepository.findById(ID_WALLET_ACCOUNT)).thenReturn(Optional.of(walletAccount));
walletAccountService.updateWalletAccount(walletAccountDTO, ID_WALLET_ACCOUNT);
verify(walletAccountRepository).findById(ID_WALLET_ACCOUNT);
verify(walletAccountRepository).save(walletAccount);
}
@Test
public void should_not_update_walletAccount_when_walletAccount_not_found() {
when(walletAccountRepository.findById(ID_WALLET_ACCOUNT)).thenReturn(Optional.empty());
assertThrows(WalletAccountNotFoundException.class, () -> walletAccountService.getWalletAccountById(ID_WALLET_ACCOUNT));
verify(walletAccountRepository).findById(ID_WALLET_ACCOUNT);
verify(walletAccountRepository, never()).save(any());
}
@Test
public void should_delete_walletAccount_by_id() {
walletAccountService.deleteWalletAccount(ID_WALLET_ACCOUNT);
verify(walletAccountRepository).deleteById(ID_WALLET_ACCOUNT);
}
@Test
public void should_delete_all_walletAccounts() {
walletAccountService.deleteAllWalletAccounts();
verify(walletAccountRepository).deleteAll();
}
} | true |
37bbe6aa068247ece5f120610e8d085eab04a8f3 | Java | oyjy2018/lz-scf | /scfcloud-model/src/main/java/com/zhjs/scfcloud/model/mapper/BusinessFileCfgMapper.java | UTF-8 | 620 | 1.796875 | 2 | [] | no_license | package com.zhjs.scfcloud.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhjs.scfcloud.model.entity.BusinessFileCfg;
/**
* 业务文件配置表 Mapper 接口
* @author:dailongting
* @date:2019-06-21 15:33
*/
public interface BusinessFileCfgMapper extends BaseMapper<BusinessFileCfg> {
int deleteByPrimaryKey(Long id);
int insert(BusinessFileCfg record);
int insertSelective(BusinessFileCfg record);
BusinessFileCfg selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(BusinessFileCfg record);
int updateByPrimaryKey(BusinessFileCfg record);
} | true |
4174b28cb596ff065b2a88d35d05e89bc4dc9365 | Java | kdw912001/homework | /JAVA/day20Silsub/src/day20/silsub1/TestMyNote.java | UTF-8 | 910 | 3.40625 | 3 | [] | no_license | package day20.silsub1;
import java.util.Scanner;
public class TestMyNote {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu() {
MyNote mn = new MyNote();
do {
int no;
System.out.print("****** MyNote *******\r\n" +
"\r\n" +
" 1. 노트 새로 만들기 //MyNote의 fileSave()\r\n" +
" 2. 노트 열기 //MyNote의 fileOpen()\r\n" +
" 3. 노트 열어서 수정하기 //MyNote의 fileEdit()\r\n" +
" 4. 끝내기 //main() 으로 리턴\r\n" +
"\r\n" +
" 메뉴 선택 :");
no=sc.nextInt();
switch(no) {
case 1: mn.fileSave(); break;
case 2: mn.fileOpen(); break;
case 3: mn.fileEdit(); break;
case 4: System.out.print("종료 합니다"); return;
default : System.out.println("잘못 입력하셨습니다"); break;
}
}while(true);
}
}
| true |
d4321f3c252b13d5b5707b1855bd48df3ec88f62 | Java | rscarberry-wa/clodhopper | /clodhopper-examples/src/main/java/org/battelle/clodhopper/examples/kmeans/SimpleKMeansDemo.java | UTF-8 | 6,688 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | package org.battelle.clodhopper.examples.kmeans;
import java.io.File;
import java.util.List;
import org.battelle.clodhopper.Cluster;
import org.battelle.clodhopper.distance.EuclideanDistanceMetric;
import org.battelle.clodhopper.kmeans.KMeansClusterer;
import org.battelle.clodhopper.kmeans.KMeansParams;
import org.battelle.clodhopper.seeding.KMeansPlusPlusSeeder;
import org.battelle.clodhopper.task.TaskEvent;
import org.battelle.clodhopper.task.TaskListener;
import org.battelle.clodhopper.task.TaskOutcome;
import org.battelle.clodhopper.tuple.ArrayTupleListFactory;
import org.battelle.clodhopper.tuple.TupleIO;
import org.battelle.clodhopper.tuple.TupleList;
import org.battelle.clodhopper.tuple.TupleListFactory;
/**
* A very simple demonstration of how to run k-means clustering on
* data contained in a csv file. The csv file is specified as the first
* argument to main. The clustering results are output to stdout.
*
* @author Randy Scarberry
*
*/
public class SimpleKMeansDemo {
public static void main(String[] args) {
// This example expects you to provide the name of a csv file containing the data
// you wish to cluster. Each line of the csv file should contain a row of numbers.
// Each row should contain the same count of numbers.
//
if (args.length != 1) {
System.err.printf("Usage: java %s <input csv file>\n", SimpleKMeansDemo.class.getName());
System.exit(-1);
}
// Since this is a simple example, wrap it all in an all-emcompassing try-catch.
//
try {
//
// Step 1. Read the data in the file into a TupleList.
//
// First, create a TupleListFactory. For this example, just use
// a simple ArrayTupleListFactory. This factory produces ArrayTupleLists, which
// use a 1-D array of doubles to house the data.
//
TupleListFactory tupleListFactory = new ArrayTupleListFactory();
// Call TupleIO to read it. It doesn't matter what name is given to the TupleList.
//
TupleList tuples = TupleIO.loadCSV(new File(args[0]), "myData", tupleListFactory);
//
// Step 2. Configure the k-mean parameters object.
//
// For this example, arbitrarily choose the square root of the number
// of tuples as the number of clusters.
//
int numClusters = (int) Math.sqrt(tuples.getTupleCount());
// Since k-means has many parameters, it's easiest to use the nested builder class.
KMeansParams.Builder builder = new KMeansParams.Builder();
// Generate the parameters object.
//
KMeansParams params = builder.clusterCount(numClusters)
.clusterSeeder(new KMeansPlusPlusSeeder(new EuclideanDistanceMetric()))
.distanceMetric(new EuclideanDistanceMetric())
.workerThreadCount(Runtime.getRuntime().availableProcessors())
.build();
// Notice that k-means++ seeding was used, so you may think of this
// as k-means++ instead of k-means. The only difference is how the initial seeds
// are chosen.
// Now instantiate k-means.
KMeansClusterer kMeans = new KMeansClusterer(tuples, params);
// Register a TaskListener that will output messages to System.out.
// In graphical applications, you would use the task events to
// display progress and status messages, and to know when k-means was
// done.
//
kMeans.addTaskListener(new TaskListener() {
@Override
public void taskBegun(TaskEvent e) {
// The initial event.
System.out.println(e.getMessage());
}
@Override
public void taskMessage(TaskEvent e) {
// Status messages as the task proceeds.
System.out.printf("\t ... %s\n", e.getMessage());
}
@Override
public void taskProgress(TaskEvent e) {
// This could be used to drive a progress bar,
// but we will ignore for this example.
}
@Override
public void taskPaused(TaskEvent e) {
// Ignore -- no provision in this example for pause
// to be triggered.
}
@Override
public void taskResumed(TaskEvent e) {
// Also ignore for this example.
}
@Override
public void taskEnded(TaskEvent e) {
// The final event.
System.out.println(e.getMessage());
}
});
// Launch k-means on a new thread. (We could be REALLY simple and call k-means.run()...)
//
Thread t = new Thread(kMeans);
t.start();
// Just join the thread to wait for it to finish.
t.join();
// Check that k-means succeeded.
if (kMeans.getTaskOutcome() == TaskOutcome.SUCCESS) {
// All the clusterers extend AbstractClusterer, which is a
// Future<List<Cluster>> and has a blocking get(). Since kMeans has been
// verified to have finished successfully, we can confidently call get().
//
List<Cluster> clusters = kMeans.get();
// Print results to System.out.
//
final int clusterCount = clusters.size();
System.out.printf("\nK-Means Generated %d Clusters\n\n", clusterCount);
for (int i=0; i<clusterCount; i++) {
Cluster c = clusters.get(i);
StringBuilder sb = new StringBuilder("Cluster " + (i+1) + ": ");
final int memberCount = c.getMemberCount();
for (int j=0; j<memberCount; j++) {
if (j > 0) {
sb.append(", ");
}
sb.append(c.getMember(j));
}
System.out.println(sb.toString());
}
} else if (kMeans.getTaskOutcome() == TaskOutcome.ERROR) {
System.out.printf("K-Means ended with the following error: %s\n", kMeans.getErrorMessage());
} else {
// The only other TaskOutcome is TaskOutcome.CANCELLED, but this
// program does not provide a way to cancel. Therefore, if we're here,
// there must be a bug.
System.out.printf("K-Means ended with the unexpected outcome of: %s\n", kMeans.getTaskOutcome());
}
// The most likely scenario is someone running this on such a huge file
// of data, an OutOfMemoryError results. No fear, though. ClodHopper can
// handle really large amounts of data by using an FSTupleListFactory instead
// of an ArrayTupleListFactory.
//
} catch (Throwable t) {
t.printStackTrace();
}
}
}
| true |
823827cec633803bc4b10f971885443b5d76cb6b | Java | yblsy/tools | /unifytools/src/main/java/personal/tools/DateUtils.java | UTF-8 | 6,307 | 2.921875 | 3 | [] | no_license | package personal.tools;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author 刘晨
* @create 2018-04-19 14:58
* To change this template use File | Settings | Editor | File and Code Templates.
**/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils{
private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
public static Date getDateStart(Date date) {
if(date==null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date= sdf.parse(formatDate(date, "yyyy-MM-dd")+" 00:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static Date getDateEnd(Date date) {
if(date==null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date= sdf.parse(formatDate(date, "yyyy-MM-dd") +" 23:59:59");
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 判断字符串是否是日期
* @param timeString
* @return
*/
public static boolean isDate(String timeString){
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
format.setLenient(false);
try{
format.parse(timeString);
}catch(Exception e){
return false;
}
return true;
}
/**
* 格式化时间
* @param timestamp
* @return
*/
public static String dateFormat(Date timestamp){
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(timestamp);
}
/**
* 获取系统时间Timestamp
* @return
*/
public static Timestamp getSysTimestamp(){
return new Timestamp(new Date().getTime());
}
/**
* 获取系统时间Date
* @return
*/
public static Date getSysDate(){
return new Date();
}
/**
* 生成时间随机数
* @return
*/
public static String getDateRandom(){
String s=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
return s;
}
public static boolean isCurrentDate(java.util.Date date, String patten) {
return formatDate(new java.util.Date(), patten).compareTo(formatDate(date, patten)) == 0;
}
public static String getBetweenTime(java.util.Date beforeTime, java.util.Date afterTime) {
long ms = afterTime.getTime() - beforeTime.getTime();
long ss = 1000L;
long mi = ss * 60L;
long hh = mi * 60L;
long dd = hh * 24L;
String result = "";
if(ms % dd > 0L && ms > 0L) {
result = result + (ms - ms % dd) / dd + "天";
ms %= dd;
}
if(ms % hh > 0L && ms > 0L) {
result = result + (ms - ms % hh) / hh + "时";
ms %= hh;
}
if(ms % mi > 0L && ms > 0L) {
result = result + (ms - ms % mi) / mi + "分";
ms %= mi;
}
if(ms % ss > 0L && ms > 0L) {
result = result + (ms - ms % ss) / ss + "秒";
long var10000 = ms % ss;
}
return result;
}
}
| true |
be9b23a9ea82ce1b3cf4286d6dadb7603652541e | Java | atrifonova/experiments | /spring/src/test/java/rmi/server/ServerTest.java | UTF-8 | 307 | 1.671875 | 2 | [] | no_license | package rmi.server;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author youmoo
* @since 2014-04-06 5:40 PM
*/
public class ServerTest {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring/spring-rmi-server.xml");
}
}
| true |
d0cbaf94a61b2ea35562348ced85679a28a2f417 | Java | GrantBParker/Generics | /Generics/Boat.java | UTF-8 | 860 | 2.921875 | 3 | [] | no_license |
public class Boat implements Measurable{
private String name;
private double weight;
private double length;
public Boat() {
}
public Boat(String name, double weight, double length) {
this.name = name;
this.weight = weight;
this.length = length;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
@Override
public String toString() {
return "Boat [name=" + name + ", weight=" + weight + ", length=" + length + "]";
}
@Override
public int getMeasure() {
return 0;
}
}
| true |
1ae04132d5085a74754b3e5ac67a0cb6ee5f88b1 | Java | TheGreatTuna/netcracker.application | /src/main/java/com/gmail/netcracker/application/utilites/scheduling/jobs/EventNotificationJob.java | UTF-8 | 673 | 2.171875 | 2 | [] | no_license | package com.gmail.netcracker.application.utilites.scheduling.jobs;
import com.gmail.netcracker.application.dto.model.Event;
import com.gmail.netcracker.application.utilites.EmailConstructor;
import lombok.Setter;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
@Setter
public class EventNotificationJob extends QuartzJobBean {
private EmailConstructor emailConstructor;
private Event event;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
emailConstructor.notifyAboutEvent(event);
}
}
| true |
75fd39d1c7fea985637d0b553a2600ebbdfc9acf | Java | shixiuyuan/taotao | /taotao-manager/taotao-manager-service/src/main/java/com/taotao/service/PictureService.java | UTF-8 | 263 | 1.8125 | 2 | [] | no_license | package com.taotao.service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;
/**
* Created by xy on 2017/5/27.
*/
public interface PictureService {
Map uploadPitcture(MultipartFile uploadFile);
}
| true |
5724bacc47720a696594f14e23d832681d0c12d6 | Java | relentlesscoder/Leetcode | /src/org/wshuai/algorithm/binarytree/BinaryTreeDepthFirstTraversalRecursive.java | UTF-8 | 1,423 | 3.3125 | 3 | [] | no_license | package org.wshuai.algorithm.binarytree;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Wei on 8/30/16.
*/
public class BinaryTreeDepthFirstTraversalRecursive {
public static List<Integer> inOrderTraversal(BinaryTreeNode root) {
List<Integer> lst = new ArrayList<Integer>();
inOrderTraversalHelper(root, lst);
return lst;
}
private static void inOrderTraversalHelper(BinaryTreeNode root, List<Integer> lst) {
if (root == null) {
return;
}
inOrderTraversalHelper(root.left, lst);
lst.add(root.value);
inOrderTraversalHelper(root.right, lst);
}
public static List<Integer> preOrderTraversal(BinaryTreeNode root) {
List<Integer> lst = new ArrayList<Integer>();
preOrderTraversalHelper(root, lst);
return lst;
}
private static void preOrderTraversalHelper(BinaryTreeNode root, List<Integer> lst) {
if (root == null) {
return;
}
lst.add(root.value);
preOrderTraversalHelper(root.left, lst);
preOrderTraversalHelper(root.right, lst);
}
public static List<Integer> postOrderTraversal(BinaryTreeNode root) {
List<Integer> lst = new ArrayList<Integer>();
postOrderTraversalHelper(root, lst);
return lst;
}
private static void postOrderTraversalHelper(BinaryTreeNode root, List<Integer> lst) {
if (root == null) {
return;
}
postOrderTraversalHelper(root.left, lst);
postOrderTraversalHelper(root.right, lst);
lst.add(root.value);
}
}
| true |
d26f1e6f053349ac119906abead4e519f1929643 | Java | krnets/codewars-practice | /7kyu/Exclamation marks series 3 - Remove all exclamation marks from sentence except at the end/SolutionTest.java | UTF-8 | 552 | 2.5625 | 3 | [] | no_license | import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Test
public void testBasic() {
assertEquals("nothing to do", R.removeBang("nothing to do"));
assertEquals("should remove bangs from the end of words", "No seriously Seriously Wow", R.removeBang("No seriously! Seriously!! Wow"));
assertEquals("should remove bangs from the end of words only", "!!No seriously !Seriously !!Wow", R.removeBang("!!No! seriously! !Seriously!! !!Wow!"));
}
} | true |
797e12bb0bc6e3ac297da21216b7c188d71094bf | Java | kmarabet/mssc-bread-service | /src/main/java/guru/springframework/msscbreadservice/web/mappers/BreadMapper.java | UTF-8 | 431 | 1.78125 | 2 | [] | no_license | package guru.springframework.msscbreadservice.web.mappers;
import guru.springframework.msscbreadservice.domain.Bread;
import guru.springframework.msscbreadservice.web.model.BreadDto;
import org.mapstruct.Mapper;
@Mapper(uses = {DateMapper.class})
public interface BreadMapper {
BreadDto breadToBreadDto(Bread bread);
Bread breadDtoToBread(BreadDto breadDto);
BreadDto breadToBreadDtoWithInventory(Bread bread);
}
| true |
9d3a31a77d1d544d6603289cfb17ad575dced7cd | Java | hw233/cq_game-java | /src/main/java/com/junyou/bus/branchtask/configure/OpenConditionFactory.java | UTF-8 | 519 | 2.046875 | 2 | [] | no_license | package com.junyou.bus.branchtask.configure;
import com.junyou.utils.common.CovertObjectUtil;
public class OpenConditionFactory {
public static IOpenCondition createOpenCondition(int conditionType,Object conditionParams){
switch (conditionType) {
case ConditionType.HERO_LEVEL:
return new LevelOpen(CovertObjectUtil.object2int(conditionParams));
case ConditionType.ZHIXIAN_RENWU:
return new ZhiXianOpen(CovertObjectUtil.object2int(conditionParams));
default:
break;
}
return null;
}
}
| true |
a95374b97b578a0dd28f4985879db9cc897ef390 | Java | fermadeiral/StyleErrors | /ibinti-bugvm/b6428f98237d32ec9d9e706ffe652052ed608be5/194/Function.java | UTF-8 | 7,079 | 2.15625 | 2 | [] | no_license | /*
* Copyright (C) 2012 RoboVM AB
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
package com.bugvm.compiler.llvm;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @version $Id$
*/
public class Function {
private final String name;
private final Linkage linkage;
private final FunctionAttribute[] attributes;
private final ParameterAttribute[][] parameterAttributes;
private final String section;
private final FunctionType type;
private final Map<Label, BasicBlock> basicBlockMap = new HashMap<Label, BasicBlock>();
private final List<BasicBlock> basicBlockList = new ArrayList<BasicBlock>();
private final Map<String, Variable> variablesMap = new HashMap<String, Variable>();
private int counter = 0;
private final String[] parameterNames;
public Function(Linkage linkage, FunctionAttribute[] attributes, String section, String name, FunctionType type, String ... parameterNames) {
this.linkage = linkage;
this.attributes = attributes;
this.section = section;
this.name = name;
this.type = type;
if (parameterNames == null || parameterNames.length == 0 && type.getParameterTypes().length > 0) {
parameterNames = new String[type.getParameterTypes().length];
for (int i = 0; i < parameterNames.length; i++) {
parameterNames[i] = "p" + i;
}
}
this.parameterNames = parameterNames;
this.parameterAttributes = new ParameterAttribute[type.getParameterTypes().length][];
}
public FunctionRef ref() {
return new FunctionRef(this);
}
public String getName() {
return name;
}
public FunctionType getType() {
return type;
}
public VariableRef getParameterRef(int index) {
return new VariableRef(parameterNames[index], type.getParameterTypes()[index]);
}
public VariableRef[] getParameterRefs() {
VariableRef[] result = new VariableRef[parameterNames.length];
for (int i = 0; i < result.length; i++) {
result[i] = getParameterRef(i);
}
return result;
}
public String[] getParameterNames() {
return parameterNames.clone();
}
public void setParameterAttributes(int paramIndex, ParameterAttribute ... attributes) {
parameterAttributes[paramIndex] = attributes.clone();
}
String getLabel(BasicBlock bb) {
return "label" + basicBlockList.indexOf(bb);
}
String getLabel(BasicBlockRef ref) {
return getLabel(basicBlockMap.get(ref.getLabel()));
}
public BasicBlock newBasicBlock(Label label) {
BasicBlock block = basicBlockMap.get(label);
if (block != null) {
throw new IllegalArgumentException("BasicBlock with label " + label + " already exists");
}
block = new BasicBlock(this, label);
basicBlockMap.put(label, block);
basicBlockList.add(block);
return block;
}
public BasicBlockRef newBasicBlockRef(Label label) {
return new BasicBlockRef(this, label);
}
public BasicBlock getCurrentBasicBlock() {
if (basicBlockList.isEmpty()) {
return newBasicBlock(new Label());
}
return basicBlockList.get(basicBlockList.size() - 1);
}
public List<BasicBlock> getBasicBlocks() {
return basicBlockList;
}
public BasicBlock getBasicBlock(Label label) {
return basicBlockMap.get(label);
}
public Variable newVariable(Type type) {
return newVariable("t" + (counter++), type);
}
public Variable newVariable(String name, Type type) {
if (variablesMap.containsKey(name)) {
throw new IllegalArgumentException("Variable with name '" + name + "' already exists");
}
Variable v = new Variable(name, type);
variablesMap.put(name, v);
return v;
}
public BasicBlock getDefinedIn(VariableRef ref) {
Variable var = new Variable(ref);
for (BasicBlock bb : basicBlockList) {
if (bb.getWritesTo().contains(var)) {
return bb;
}
}
throw new IllegalStateException("Variable " + var + " not defined");
}
public Instruction add(Instruction instruction) {
getCurrentBasicBlock().add(instruction);
return instruction;
}
public void write(Writer writer) throws IOException {
Type returnType = type.getReturnType();
Type[] parameterTypes = type.getParameterTypes();
writer.write("define ");
if (linkage != null) {
writer.write(linkage.toString());
writer.write(' ');
}
writer.write(returnType.toString());
writer.write(" @\"");
writer.write(name);
writer.write("\"(");
for (int i = 0; i < parameterTypes.length; i++) {
if (i > 0) {
writer.write(", ");
}
writer.write(parameterTypes[i].toString());
if (parameterAttributes[i] != null) {
for (ParameterAttribute attrib : parameterAttributes[i]) {
writer.write(' ');
writer.write(attrib.toString());
}
}
writer.write(" %");
writer.write(parameterNames[i]);
}
if (type.isVarargs()) {
writer.write(", ...");
}
writer.write(")");
if (attributes != null && attributes.length > 0) {
for (FunctionAttribute attr : attributes) {
writer.write(' ');
writer.write(attr.toString());
}
}
if (section != null) {
writer.write(" section \"");
writer.write(section);
writer.write('"');
}
writer.write(" {\n");
for (BasicBlock bb : basicBlockList) {
writer.write(bb.toString());
}
writer.write("}\n");
}
@Override
public String toString() {
StringWriter sw = new StringWriter();
try {
write(sw);
} catch (IOException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
}
| true |
d15f33eb7fecca912ee70aeb3a8b0d24c0a745bc | Java | Pelayo-Torre/DLP | /src/ast/DefFuncion.java | UTF-8 | 1,204 | 2.75 | 3 | [] | no_license | package ast;
import java.util.List;
import tipo.Tipo;
import tipo.TipoFuncion;
import visitor.Visitor;
public class DefFuncion extends AbstractDefinicion {
private String nombre;
private TipoFuncion tipoFuncion;
private List<Sentencia> sentencias;
public DefFuncion(int line, int column, String nombre, TipoFuncion tipoFuncion, List<Sentencia> sentencias) {
super(line, column);
this.nombre = nombre;
this.tipoFuncion = tipoFuncion;
this.sentencias = sentencias;
}
@Override
public String getNombre() {
return nombre;
}
@Override
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List<Sentencia> getSentencias() {
return sentencias;
}
public void setSentencias(List<Sentencia> sentencias) {
this.sentencias = sentencias;
}
@Override
public String toString() {
return "DefFuncion [nombre=" + nombre + ", tipoFuncion=" + tipoFuncion + ", sentencias=" + sentencias + "]";
}
@Override
public Object accept(Visitor visitor, Object param) {
return visitor.visit(this, param);
}
@Override
public Tipo getTipo() {
return tipoFuncion;
}
@Override
public void setTipo(Tipo tipo) {
this.tipoFuncion = (TipoFuncion) tipo;
}
}
| true |
0aac4d1b4fe7c57f4e84402dc9562c58dbd90f72 | Java | homacs/org.cakelab.jdoxml | /src/org/cakelab/jdoxml/impl/dochandler/ImageHandler.java | UTF-8 | 1,052 | 2.25 | 2 | [] | no_license | package org.cakelab.jdoxml.impl.dochandler;
import org.cakelab.jdoxml.api.IDocImage;
import org.cakelab.jdoxml.impl.Log;
import org.cakelab.jdoxml.impl.basehandler.BaseHandler;
import org.cakelab.jdoxml.impl.basehandler.IBaseHandler;
import org.xml.sax.Attributes;
/** Node representing an image.
*
*/
// children: -
public class ImageHandler extends BaseHandler<ImageHandler> implements IDocImage {
private IBaseHandler m_parent;
private String m_name;
private String m_caption;
public ImageHandler(IBaseHandler parent)
{
m_parent = parent;
addEndHandler("image", this, "endImage");
}
public void startImage(Attributes attrib) {
m_name = attrib.getValue("name");
m_curString = "";
m_parent.setDelegate(this);
}
public void endImage() {
m_caption = m_curString;
Log.debug(2, "image name=`%s' caption=`%s'\n", m_name, m_caption);
m_parent.setDelegate(null);
}
// IDocImage
public Kind kind() {
return Kind.Image;
}
public String name() {
return m_name;
}
public String caption() {
return m_caption;
}
} | true |
04b681856297cf83e2173fed28f2bb95e335a929 | Java | javagurulv/CampaignManager | /core/src/main/java/lv/javaguru/campaignmanager/core/commands/campaigns/task/CreateTaskCampaignHandler.java | UTF-8 | 1,201 | 2.21875 | 2 | [] | no_license | package lv.javaguru.campaignmanager.core.commands.campaigns.task;
import lv.javaguru.campaignmanager.api.dto.campaigns.task.TaskCampaignDTO;
import lv.javaguru.campaignmanager.core.DomainCommandHandler;
import lv.javaguru.campaignmanager.core.domain.TaskCampaign;
import lv.javaguru.campaignmanager.core.services.campaigns.task.TaskCampaignFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
class CreateTaskCampaignHandler
implements DomainCommandHandler<CreateTaskCampaignCommand, CreateTaskCampaignResult> {
@Autowired private TaskCampaignFactory factory;
@Autowired private TaskCampaignConverter converter;
@Override
public CreateTaskCampaignResult execute(CreateTaskCampaignCommand command) {
TaskCampaign taskCampaign = factory.create(
command.getCampaignGroupId(),
command.getTitle()
);
TaskCampaignDTO taskCampaignDTO = converter.convert(taskCampaign);
return new CreateTaskCampaignResult(taskCampaignDTO);
}
@Override
public Class getCommandType() {
return CreateTaskCampaignCommand.class;
}
}
| true |
c017794de24fd13a8cdfa1fe9c26980ed092c2f2 | Java | ferjuarezlp/carassyst | /app/src/main/java/com/underapps/carassist/adapters/ExpenseAdapter.java | UTF-8 | 2,722 | 2.34375 | 2 | [] | no_license | package com.underapps.carassist.adapters;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.underapps.carassist.R;
import com.underapps.carassist.models.Expense;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by Nilesh Jarad on 18-06-2015.
*/
public class ExpenseAdapter extends RecyclerView.Adapter<ExpenseAdapter.ViewHolder> {
private final List<Expense> expensesCard;
private Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.textViewDescription)
TextView textViewDescription;
@Bind(R.id.textViewAmount)
TextView textViewAmount;
@Bind(R.id.textViewCategory)
TextView textViewCategory;
@Bind(R.id.card_view)
CardView cardView;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public ExpenseAdapter(Context context, List<Expense> expenses) {
this.context = context;
this.expensesCard = expenses;
}
public long getID(int position) {
return expensesCard.get(position).getId();
}
public void removeItem(int position) {
expensesCard.remove(position);
notifyItemRemoved(position);
// for (int i = 0; i < visitingCards.size(); i++) {
//// if (visitingCards.get(i).getNo() == id) {
////// visitingCards.remove(i);
//// notifyDataSetChanged();
//// return;
//// }
// }
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.expense_card, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String[] categories = context.getResources().getStringArray(R.array.categories);
String formattedString = String.format( "%.2f", expensesCard.get(position).getAmount());
holder.textViewAmount.setText("" + formattedString);
holder.textViewDescription.setText("" + expensesCard.get(position).getDescription());
holder.textViewCategory.setText("" + categories[expensesCard.get(position).getCategory_id()]);
}
@Override
public int getItemCount() {
return expensesCard.size();
}
}
| true |
27aab9ce8342849321ec5df4c0e40a5bfd44838d | Java | Darako/CV | /Facturame/src/interfacesGraficas/VentanaEmpresa.java | ISO-8859-1 | 4,865 | 2.46875 | 2 | [] | no_license | package interfacesGraficas;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import factorias.FactoriaCRUD;
import factorias.FactoriaEmpresa;
import factorias.FactoriaVehiculo;
import operacionesCRUD.CRUDempresa;
import pojo.Empresa;
import util.UtilVentanas;
/**
* Ventana para la inserccin de datos de empresas.
*/
/**
*
* @author Jorge Gonzlez Rodrguez y Javier Ruiz Rodrguez
*
*/
public class VentanaEmpresa extends JFrame {
private JPanel contentPane;
private JTextField textNombre;
private JTextField textNif;
private JTextField textDireccion;
private JTextField textTelefono;
private JTextField textMail;
private JButton buttonAceptar;
private JButton buttonBorrar;
private FactoriaEmpresa fe;
private FactoriaCRUD fc;
private ArrayList<JTextField> textos = new ArrayList<JTextField>();
public VentanaEmpresa(VentanaGestion gestion) {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
formWindowClosing(gestion);
}
});
setTitle("Facturame --- Empresa");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 482, 185);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel labelNombre = new JLabel("Nombre:");
labelNombre.setBounds(10, 10, 50, 20);
contentPane.add(labelNombre);
textNombre = new JTextField();
textNombre.setBounds(70, 10, 120, 20);
contentPane.add(textNombre);
textNombre.setColumns(10);
JLabel labelNif = new JLabel("NIF:");
labelNif.setBounds(10, 40, 61, 20);
contentPane.add(labelNif);
textNif = new JTextField();
textNif.setColumns(10);
textNif.setBounds(70, 40, 120, 20);
contentPane.add(textNif);
JLabel labelDireccion = new JLabel("Direcci\u00F3n:");
labelDireccion.setBounds(210, 10, 61, 20);
contentPane.add(labelDireccion);
textDireccion = new JTextField();
textDireccion.setColumns(10);
textDireccion.setBounds(281, 10, 120, 20);
contentPane.add(textDireccion);
JLabel labelTelefono = new JLabel("Tel\u00E9fono:");
labelTelefono.setBounds(210, 40, 61, 20);
contentPane.add(labelTelefono);
textTelefono = new JTextField();
textTelefono.setColumns(10);
textTelefono.setBounds(281, 40, 120, 20);
contentPane.add(textTelefono);
JLabel labelMail = new JLabel("Mail:");
labelMail.setBounds(210, 71, 61, 20);
contentPane.add(labelMail);
textMail = new JTextField();
textMail.setColumns(10);
textMail.setBounds(281, 71, 120, 20);
contentPane.add(textMail);
buttonAceptar = new JButton("ACEPTAR");
buttonAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
crearEmpresa();
} catch (SQLException sqle) {
UtilVentanas.Alertas.mostrar(UtilVentanas.Alertas.ERROR_SQL,sqle.toString());
} catch (IOException ioe) {
UtilVentanas.Alertas.mostrar(UtilVentanas.Alertas.ERROR_IOE,ioe.toString());
}
}
});
buttonAceptar.setBounds(70, 108, 201, 25);
contentPane.add(buttonAceptar);
buttonBorrar = new JButton("");
buttonBorrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UtilVentanas.borrarTextos(textos);
}
});
buttonBorrar.setIcon(new ImageIcon("images\\papelera_16.png"));
buttonBorrar.setBounds(314, 108, 25, 25);
contentPane.add(buttonBorrar);
textos.add(textNombre);
textos.add(textNif);
textos.add(textDireccion);
textos.add(textTelefono);
textos.add(textMail);
this.fe = new FactoriaEmpresa();
this.fc = new FactoriaCRUD();
}
private void formWindowClosing(VentanaGestion gestion) {
this.setVisible(false);
gestion.setVisible(true);
}
private void crearEmpresa() throws SQLException, IOException{
if(UtilVentanas.textosIncompletos(textos)){
Empresa empresa = fe.crearEmpresa();
empresa.setNif(textNif.getText());
empresa.setEmpresa(textNombre.getText());
empresa.setDireccion(textDireccion.getText());
empresa.setnTelefono(Integer.parseInt(textTelefono.getText()));
empresa.setEmail(textMail.getText());
fc.crearCRUD(FactoriaCRUD.TIPO_EMPRESA).insertarActualizar(empresa, true);
UtilVentanas.Alertas.mostrar(UtilVentanas.Alertas.EXITO_INSERT, "empresa");
} else {
UtilVentanas.Alertas.mostrar(UtilVentanas.Alertas.ERROR_CAMPOS_INCOMPLETOS,"");
}
}
}
| true |
9bc713dd2d0372c46a44bb96d23cc1266599cce9 | Java | LuisClase/Boletin | /boletin7/src/ejercicio3/FrameEjer3.java | UTF-8 | 16,132 | 2.78125 | 3 | [] | no_license | package ejercicio3;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FrameEjer3 extends JFrame implements ActionListener,ItemListener{
//Propiedades
private JTextField txtNombre;
private JTextField txtApellidos;
private JTextField txtDNI;
private JTextField txtEdad;
private JLabel lblNombre;
private JLabel lblApellidos;
private JLabel lblDNI;
private JLabel lblEdad;
private JLabel lblSexo;
private JRadioButton sexMasc;
private JRadioButton sexFem;
private ButtonGroup GroupSexo;
private JButton btnAñadir;
private JButton btnVisualizar;
private JButton btnCerrar;
private JButton btnAceptar;
private JButton btnCancelar;
private JButton btnSiguiente;
private JButton btnAnterior;
private JButton btnAñadirDatos;
private sexo EnumSexo;
private Persona persona;
private ArrayList<Persona> collection;
private RandomAccessFile fileRand=null;
private File f=new File("/home/alumnoinfo/Escritorio/prueba/datos.txt");
private int cont=-1;
//Constructor
public FrameEjer3(){
super("Formulario Datos Personales");
this.setLayout(null);
//lblNombre
lblNombre=new JLabel("Nombre");
lblNombre.setSize(lblNombre.getPreferredSize());
lblNombre.setLocation(10,10);
add(lblNombre);
//txtNombre
txtNombre=new JTextField("Nombre");
txtNombre.setToolTipText("Campo para poner el nombre");
txtNombre.setSize(txtNombre.getPreferredSize());
txtNombre.setLocation(10,10+lblNombre.getHeight());
txtNombre.setEnabled(false);
add(txtNombre);
//lblApellido
lblApellidos=new JLabel("Apellidos");
lblApellidos.setSize(lblApellidos.getPreferredSize());
lblApellidos.setLocation(20+lblNombre.getWidth(),10);
add(lblApellidos);
//txtApellido
txtApellidos=new JTextField("Apellidos ");
txtApellidos.setToolTipText("Campo para rellenar con el apellido");
txtApellidos.setSize(txtApellidos.getPreferredSize());
txtApellidos.setLocation(20+txtNombre.getWidth(),10+lblApellidos.getHeight());
txtApellidos.setEnabled(false);
add(txtApellidos);
//lblDNI
lblDNI=new JLabel("nº DNI");
lblDNI.setSize(lblDNI.getPreferredSize());
lblDNI.setLocation(10,50);
add(lblDNI);
//txtDNI
txtDNI=new JTextField("Num DNI");
txtDNI.setToolTipText("Inserte su DNI sin letra");
txtDNI.setSize(txtDNI.getPreferredSize());
txtDNI.setLocation(10,50+lblDNI.getHeight());
txtDNI.setEnabled(false);
add(txtDNI);
//lblEdad
lblEdad=new JLabel("Edad");
lblEdad.setSize(lblEdad.getPreferredSize());
lblEdad.setLocation(30+lblDNI.getWidth(),50);
add(lblEdad);
//txtEdad
txtEdad=new JTextField("Edad");
txtEdad.setToolTipText("Escriba aqui su Edad actual");
txtEdad.setSize(txtEdad.getPreferredSize());
txtEdad.setLocation(15+txtDNI.getWidth(),50+lblEdad.getHeight());
txtEdad.setEnabled(false);
add(txtEdad);
//lblSexo
lblSexo=new JLabel("Sexo");
lblSexo.setSize(lblSexo.getPreferredSize());
lblSexo.setLocation(10,90);
add(lblSexo);
//sexMasc
sexMasc= new JRadioButton("Masculino");
sexMasc.setToolTipText("Seleccione esto si es un Hombre");
sexMasc.setSize(sexMasc.getPreferredSize());
sexMasc.setLocation(10,110);
sexMasc.addItemListener(this);
sexMasc.setEnabled(false);
add(sexMasc);
//sexFem
sexFem=new JRadioButton("Femenino");
sexFem.setToolTipText("Seleccione si es una Mujer");
sexFem.setSize(sexFem.getPreferredSize());
sexFem.setLocation(10,130);
sexFem.addItemListener(this);
sexFem.setEnabled(false);
add(sexFem);
//GroupSexo
GroupSexo=new ButtonGroup();
GroupSexo.add(sexMasc);
GroupSexo.add(sexFem);
sexMasc.setSelected(true);
//btnAñadir
btnAñadir=new JButton("Añadir Datos");
btnAñadir.setToolTipText("Añadir nuevos datos a la base de datos");
btnAñadir.setSize(btnAñadir.getPreferredSize());
btnAñadir.setLocation(10,160);
btnAñadir.addActionListener(this);
add(btnAñadir);
//btnVisualizar
btnVisualizar=new JButton("Visualizar");
btnVisualizar.setToolTipText("Presione para ver la base de datos");
btnVisualizar.setSize(btnVisualizar.getPreferredSize());
btnVisualizar.setLocation(20+btnAñadir.getWidth(),160);
btnVisualizar.addActionListener(this);
add(btnVisualizar);
//btnCerrar
btnCerrar=new JButton("Cerrar Prog");
btnCerrar.setToolTipText("Presione para cerrar el programa");
btnCerrar.setSize(btnCerrar.getPreferredSize());
btnCerrar.setLocation(30+btnAñadir.getWidth()+btnVisualizar.getWidth(),160);
btnCerrar.addActionListener(this);
add(btnCerrar);
//btnAceptar
btnAceptar= new JButton("Aceptar");
btnAceptar.setToolTipText("Presionar para añadir a la base de datos");
btnAceptar.setSize(btnAñadir.getSize());
btnAceptar.setLocation(btnAñadir.getLocation());
btnAceptar.setVisible(false);
btnAceptar.addActionListener(this);
add(btnAceptar);
//btnCancelar
btnCancelar= new JButton("Cancelar");
btnCancelar.setToolTipText("Presionar para volver atras");
btnCancelar.setSize(btnCerrar.getSize());
btnCancelar.setLocation(btnCerrar.getLocation());
btnCancelar.setVisible(false);
btnCancelar.addActionListener(this);
add(btnCancelar);
//btnSiguiente
btnSiguiente=new JButton("Siguiente");
btnSiguiente.setToolTipText("Presione para ver la Siguiente persona");
btnSiguiente.setSize(btnSiguiente.getPreferredSize());
btnSiguiente.setLocation(10,200);
btnSiguiente.addActionListener(this);
add(btnSiguiente);
//btnAnterior
btnAnterior=new JButton("Anterior");
btnAnterior.setToolTipText("Presione para ver la persona Anterior");
btnAnterior.setSize(btnAnterior.getPreferredSize());
btnAnterior.setLocation(20+btnSiguiente.getWidth(),200);
btnAnterior.addActionListener(this);
add(btnAnterior);
//btnAñadirDatos
btnAñadirDatos=new JButton("Cargar Datos");
btnAñadirDatos.setToolTipText("Presione para cargar datos desde un archivo de texto");
btnAñadirDatos.setSize(btnAñadirDatos.getPreferredSize());
btnAñadirDatos.setLocation(10, 240);
btnAñadirDatos.addActionListener(this);
add(btnAñadirDatos);
//collection
collection=new ArrayList<Persona>();
//LeerArchivo
//File f=new File("/home/alumnoinfo/Escritorio/prueba/datos.txt");
if(f.exists()){
System.err.println("Existe");
try{
fileRand=new RandomAccessFile(f, "r");
String temp="";
while(fileRand.getFilePointer()!=fileRand.length()){
Persona p1=new Persona();
System.err.println("Nueva persona");
p1.setNombre(fileRand.readUTF());
System.err.println("Nombre añadido");
p1.setApellido(fileRand.readUTF());
System.err.println("Apellido añadido");
p1.setDNI(fileRand.readUTF());
System.err.println("dni añadido");
temp=fileRand.readUTF();
System.err.println("temp creado");
if(temp.contains("MASCULINO")){
p1.setSexo1(EnumSexo.MASCULINO);
System.err.println("masculino añadido");
}
else{
p1.setSexo1(EnumSexo.FEMENINO);
System.err.println("femenino añadido");
}
p1.setEdad(Integer.parseInt(fileRand.readUTF()));
System.err.println("edad añadida");
collection.add(p1);
System.err.println("persona añadida");
}
fileRand.close();
System.err.println("Datos cargados con exito");
}
catch(FileNotFoundException e){
System.err.println("Archivo datos.txt no encontrado");
}
catch(IOException e){
System.err.println("Error leyendo datos");
e.getMessage();
}
}
else{
System.err.println("No existe");
}
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int res = JOptionPane
.showConfirmDialog(null, "Deseas cerrar el programa?",
"Eventos Teclado", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (res == JOptionPane.OK_OPTION){
e.getWindow().dispose();
if(f.exists()){
try{
fileRand=new RandomAccessFile(f, "rw");
for(int i=0;i<collection.size();i++){
System.err.println("dentro for");
fileRand.writeUTF(collection.get(i).getNombre());
fileRand.writeUTF(collection.get(i).getApellido());
fileRand.writeUTF(collection.get(i).getDNI());
if(collection.get(i).getSexo1()==sexo.MASCULINO){
fileRand.writeUTF("MASCULINO");
}
else{
fileRand.writeUTF("FEMENINO");
}
fileRand.writeUTF(String.format("%d",collection.get(i).getEdad()));
}
fileRand.close();
System.err.println("Fuera for");
}
catch(FileNotFoundException e2){
System.err.println("archivo no encontrado, btnAñadir");
}
catch(IOException e2){
System.err.println("Fallo escribiendo, btnAñadir");
}
}
}
}
});
}
//Metodos
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnAñadirDatos){
FileNameExtensionFilter filtro=new FileNameExtensionFilter("Texto", "txt");
JFileChooser fc=new JFileChooser();
fc.addChoosableFileFilter(filtro);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int respuesta=fc.showOpenDialog(this);
if(respuesta==JFileChooser.APPROVE_OPTION){
File f=new File(fc.getSelectedFile().getPath());
if(f.exists()){
System.err.println("Existe");
try{
fileRand=new RandomAccessFile(f, "r");
String temp="";
while(fileRand.getFilePointer()!=fileRand.length()){
Persona p1=new Persona();
System.err.println("Nueva persona");
p1.setNombre(fileRand.readUTF());
System.err.println("Nombre añadido");
p1.setApellido(fileRand.readUTF());
System.err.println("Apellido añadido");
p1.setDNI(fileRand.readUTF());
System.err.println("dni añadido");
temp=fileRand.readUTF();
System.err.println("temp creado");
if(temp.contains("MASCULINO")){
p1.setSexo1(EnumSexo.MASCULINO);
System.err.println("masculino añadido");
}
else{
p1.setSexo1(EnumSexo.FEMENINO);
System.err.println("femenino añadido");
}
p1.setEdad(Integer.parseInt(fileRand.readUTF()));
System.err.println("edad añadida");
collection.add(p1);
System.err.println("persona añadida");
}
fileRand.close();
System.err.println("Datos cargados con exito");
}
catch(FileNotFoundException e2){
System.err.println("Archivo datos.txt no encontrado");
}
catch(IOException e2){
System.err.println("Error leyendo datos");
e2.getMessage();
}
}
}
}
if(e.getSource()==btnAñadir){
btnAñadir.setVisible(false);
btnAceptar.setVisible(true);
btnCancelar.setVisible(true);
btnCerrar.setVisible(false);
btnSiguiente.setEnabled(false);
btnAnterior.setEnabled(false);
sexMasc.setEnabled(true);
sexFem.setEnabled(true);
for(int i=0;i<getContentPane().getComponentCount();i++){
if(getContentPane().getComponent(i).getClass()==JTextField.class){
((JTextField)getContentPane().getComponent(i)).setText("");
((JTextField)getContentPane().getComponent(i)).setEnabled(true);
}
}
}
if(e.getSource()==btnAceptar){
if(txtNombre.getText().trim().equals("")){
JOptionPane.showMessageDialog(this, "No ha introducido nombre",
"Error con el nombre",JOptionPane.WARNING_MESSAGE);
}else{
try{
int edad=0;
if(txtEdad.getText().trim().equals("Edad") || txtEdad.getText().trim().equals("")){
txtEdad.setText("0");
}
char letraDNI=persona.letraDNI(txtDNI.getText());
try{
edad=Integer.parseInt(txtEdad.getText());
if(edad>=0){
persona=new Persona(txtNombre.getText().trim(),txtApellidos.getText().trim(),txtDNI.getText().trim()+letraDNI,EnumSexo,edad);
boolean repetido=false;
for(int i=0 ;i<collection.size() && !repetido;i++){
//System.out.println("bucle for");
//System.out.printf("%s\n%s", persona.numeroDNI(),collection.get(i).numeroDNI());
if(persona.numeroDNI().equals(collection.get(i).numeroDNI())){
//System.out.println("if");
JOptionPane.showMessageDialog(this, "DNI repetido","DNI repetido",JOptionPane.WARNING_MESSAGE);
repetido=true;
}
else{
repetido=false;
}
}
if(!repetido){
collection.add(persona);
JOptionPane.showMessageDialog(this, "Datos añadidos correctamente","Datos añadidos",JOptionPane.INFORMATION_MESSAGE);
btnAñadir.setVisible(true);
btnAceptar.setVisible(false);
btnCancelar.setVisible(false);
btnCerrar.setVisible(true);
btnSiguiente.setEnabled(true);
btnAnterior.setEnabled(true);
txtApellidos.setText("Apellidos");
txtNombre.setText("Nombre");
txtDNI.setText("Num DNI");
txtEdad.setText("Edad");
for(int i=0 ;i<getContentPane().getComponentCount();i++){
if(getContentPane().getComponent(i).getClass()==JTextField.class){
((JTextField)getContentPane().getComponent(i)).setEnabled(false);
}
}
}
}
else{
JOptionPane.showMessageDialog(this, "La edad no puede ser negativa","Benjamin Button",JOptionPane.WARNING_MESSAGE);
}
}
catch (NumberFormatException e2){
JOptionPane.showMessageDialog(this, "Solo numeros para la edad,gracias","Problemas de edad",JOptionPane.WARNING_MESSAGE);
}
}
catch(FormatterClosedException e3){
JOptionPane.showMessageDialog(this, "Formato DNI no valido",
"Error con el DNI",JOptionPane.WARNING_MESSAGE);
}
}
}
if(e.getSource()==btnCerrar){
System.exit(0);
}
if(e.getSource()==btnAnterior){
try{
cont--;
txtApellidos.setText(collection.get(cont).getApellido());
txtDNI.setText(collection.get(cont).getDNI());
txtEdad.setText(String.format("%d", collection.get(cont).getEdad()));
txtNombre.setText(collection.get(cont).getNombre());
}
catch(IndexOutOfBoundsException e3){
cont++;
JOptionPane.showMessageDialog(this, "No hay elemento anterior",
"Elemento no Disponible",JOptionPane.WARNING_MESSAGE);
}
}
if(e.getSource()==btnSiguiente){
try{
cont++;
txtApellidos.setText(collection.get(cont).getApellido());
txtDNI.setText(collection.get(cont).getDNI());
txtEdad.setText(String.format("%d", collection.get(cont).getEdad()));
txtNombre.setText(collection.get(cont).getNombre());
}
catch(IndexOutOfBoundsException e3){
cont--;
JOptionPane.showMessageDialog(this, "No hay elemento siguiente",
"Elemento no Disponible",JOptionPane.WARNING_MESSAGE);
}
}
if(e.getSource()==btnCancelar){
btnAñadir.setVisible(true);
btnAceptar.setVisible(false);
btnCancelar.setVisible(false);
btnCerrar.setVisible(true);
btnSiguiente.setEnabled(true);
btnAnterior.setEnabled(true);
txtApellidos.setText("Apellidos");
txtNombre.setText("Nombre");
txtDNI.setText("Num DNI");
txtEdad.setText("Edad");
for(int i=0 ;i<getContentPane().getComponentCount();i++){
if(getContentPane().getComponent(i).getClass()==JTextField.class){
((JTextField)getContentPane().getComponent(i)).setEnabled(false);
}
}
}
if(e.getSource()==btnVisualizar){
String mostrar="";
if(collection.size()>0){
mostrar+=collection.get(0).Cabecera();
for(int i=0;i<collection.size();i++){
mostrar+=collection.get(i).devulveDatos();
}
JOptionPane.showMessageDialog(this, mostrar,"The Collection",JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(this, "No hay personas en la base de datos","The Collection",JOptionPane.WARNING_MESSAGE);
}
}
}
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == sexMasc) {
EnumSexo = EnumSexo.MASCULINO;
}
if (e.getSource() == sexFem) {
EnumSexo = EnumSexo.FEMENINO;
}
}
}
| true |
75598333c73a048b3174ca9ff390562bdec3fd7a | Java | huifer/fast-view | /fast-view-common/src/main/java/com/github/huifer/fast/view/common/handler/LoginService.java | UTF-8 | 2,242 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | /*
*
* Copyright 2020 HuiFer All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.github.huifer.fast.view.common.handler;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.github.huifer.fast.view.common.model.ResultVo;
import com.github.huifer.fast.view.common.servlet.ResourceServlet;
import com.github.huifer.fast.view.common.utils.HttpServletUtils;
import com.github.huifer.fast.view.common.DataStore;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* 登录的url处理
*
* @author huifer
*/
public class LoginService implements HandlerUrlService {
private static final Logger log = LoggerFactory.getLogger(LoginService.class);
Gson gson = new Gson();
@Override
public void handler(String url, HttpServletRequest req, HttpServletResponse resp) {
if (log.isDebugEnabled()) {
log.debug("handler login url ,url = {}", url);
}
try {
String postBody = HttpServletUtils.getPostBody(req);
if (log.isDebugEnabled()) {
log.debug("请求参数 = {}", postBody);
}
Map<String, String> map = gson.fromJson(postBody, Map.class);
String username = map.get("username");
String password = map.get("password");
if (username.equals(DataStore.getUsername()) && password.equals(DataStore.getPassword())) {
req.getSession().setAttribute(ResourceServlet.SESSION_USER_KEY, username);
HttpServletUtils.write(resp, new ResultVo("success", true, 200));
}
else {
HttpServletUtils.write(resp, new ResultVo("fail", false, 400));
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
a3220e7f944189affc5d66cddd6d15f9a0694c75 | Java | 790226223/journal | /src/main/java/chenweipan/journal/repository/RecordTypeRepository.java | UTF-8 | 280 | 1.890625 | 2 | [] | no_license | package chenweipan.journal.repository;
import chenweipan.journal.po.RecordType;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RecordTypeRepository extends JpaRepository<RecordType, Long> {
public RecordType findByRecordId(Long recordId);
}
| true |
6a70335d6cc3b0ba062b32fdb71fa60c508ac3c1 | Java | danielpusil/machineLearning | /jMetal-jmetal-5.2/unicauca-ann/src/main/java/co/edu/unicauca/problem/trainingtesting/Wine.java | UTF-8 | 559 | 2.125 | 2 | [] | no_license | package co.edu.unicauca.problem.trainingtesting;
import co.edu.unicauca.dataset.DataSet;
import co.edu.unicauca.elm.function.impl.Sigmoid;
import co.edu.unicauca.moorepenrose.impl.MultiplicationMethod;
import java.io.IOException;
public class Wine extends TrainingTestingEvaluator {
private static final long serialVersionUID = 1L;
public Wine() throws IOException {
super(50, new DataSet("src/resources-elm", "wine.train", 13), new DataSet("src/resources-elm", "wine.test", 13),
new Sigmoid(), new MultiplicationMethod(null), "Wine", 3000);
}
}
| true |
1dc07fe63318c6484b9257215652e918d5d9319d | Java | zgh2020/crm | /qz-jeemis-demo/qz-module-business/src/main/java/com/qzsoft/business/modules/demo/teststudent/dao/TestStudentDao.java | UTF-8 | 425 | 1.523438 | 2 | [] | no_license | package com.qzsoft.business.modules.demo.teststudent.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qzsoft.business.modules.demo.teststudent.entity.TestStudentEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 学生表(TestStudent)表数据库访问层
*
* @author sdmq
* @since 2019-10-09 13:39:14
*/
@Mapper
public interface TestStudentDao extends BaseMapper<TestStudentEntity> {
} | true |
cf9fe0ce95234bdd6090aa35167409c362dcb165 | Java | vladimirAndreevich-git/Lesson8Practic | /src/Box.java | UTF-8 | 474 | 2.953125 | 3 | [] | no_license | public class Box<T extends Number, S extends Number> {
T number1;
S number2;
public Box(T number1, S number2) {
this.number1 = number1;
this.number2 = number2;
}
public T getNumber1() {
return number1;
}
public void setNumber1(T number1) {
this.number1 = number1;
}
public S getNumber2() {
return number2;
}
public void setNumber2(S number2) {
this.number2 = number2;
}
}
| true |
af03580da81ea5c7f03587c1c3ee54aced8d5d8e | Java | DanielSOhara27/CapstoneProject_CMU | /Project1Task2_1/src/java/capstone/admin/AddUserServlet.java | UTF-8 | 8,065 | 2.375 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package capstone.admin;
import capstone.connection.DBConnectionManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Ellie
*/
@WebServlet(urlPatterns = {"/AddUserServlet"})
public class AddUserServlet extends HttpServlet {
Statement stmt = null;
Connection connection = null;
DBConnectionManager manager = DBConnectionManager.getInstance();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AddUserServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AddUserServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String message = null;
String nextPage = null;
String firstname = request.getParameter("firstName");
String lastname = request.getParameter("lastName");
String username = request.getParameter("username");
String password1 = request.getParameter("password1");
String password2 = request.getParameter("password2");
String position = request.getParameter("radios");
System.out.println(position);
boolean exists;
try {
exists = checkForUser(username);
System.out.println("here");
System.out.println(exists);
} catch (SQLException ex) {
Logger.getLogger(AddUserServlet.class.getName()).log(Level.SEVERE, null, ex);
}
if(exists = true)
{
message = "Username already exists in the system. Please create a new username.";
}
if(!password1.equals(password2))
{
System.out.println(password1 + " " + password2);
message = "Passwords entered do not match. Try again.";
nextPage = "5.1_Admin-CreateNewUser.jsp";
}
else
{
if(position.equals("researcher"))
{
try {
int i = insertIntoUserTable(firstname, lastname, username, password1, 0);
if(i > 0)
{
message = "User created succesfully.";
nextPage = "5.1_Admin-CreateNewUser.jsp"; // set to login page
}
else
{
message = "User creation unsuccessful. Please try again.";
nextPage = "5.1_Admin-CreateNewUser.jsp";
}
} catch (SQLException ex) {
Logger.getLogger(AddUserServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(position.equals("faculty"))
{
try {
int i = insertIntoUserTable(firstname, lastname, username, password1, 1);
int j = insertIntoPermsTable(username);
if(i > 0 && j > 0)
{
message = "User created successfully & permissions added to the database";
nextPage = "5.1_Admin-CreateNewUser.jsp"; // redirect to log in page
}
} catch (SQLException ex) {
Logger.getLogger(AddUserServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
RequestDispatcher view = request.getRequestDispatcher(nextPage);
request.setAttribute("message", message);
System.out.println(nextPage);
view.forward(request, response);
}
public boolean checkForUser(String username) throws SQLException
{
System.out.println(username + " in the check for user method.");
boolean exists;
ResultSet rs;
connection = manager.getConnection();
stmt = connection.createStatement();
String query = "select * from users where uname = '" + username + "'";
System.out.println(query);
rs = stmt.executeQuery(query);
exists = rs.next();
return exists;
}
public int insertIntoUserTable(String firstname, String lastname, String username, String password, int faculty) throws SQLException
{
System.out.println(firstname + " " + lastname + " " + username + " " + password + " " + faculty);
connection = manager.getConnection();
stmt = connection.createStatement();
String query = "insert into users(first_name, last_name, uname, password, faculty) values ('" + firstname + "','" + lastname + "','" + username + "','" + password + "','" + faculty + "')";
System.out.println(query);
int i = stmt.executeUpdate(query);
System.out.println(i);
return i;
}
public int insertIntoPermsTable(String username) throws SQLException
{
connection = manager.getConnection();
stmt = connection.createStatement();
String query = "insert into permissions(uname, faculty_name, active) values ('" + username + "','" + username + "', '1')";
System.out.println(query);
int i = stmt.executeUpdate(query);
System.out.println(i);
return i;
}
}
| true |
8a6de4ddad6cab1d054c7264517d8e6385b48f6e | Java | gonzamandarino/QMP_02 | /src/main/java/EstadoDelTiempo.java | UTF-8 | 364 | 2.34375 | 2 | [] | no_license | public class EstadoDelTiempo {
int temperatura;
Humedad humedad;
String direccion;
EstadoDelTiempo(int temperatura, Humedad humedad){
this.temperatura = temperatura;
this.humedad = humedad;
}
public void get(String direccion) {
this.direccion = direccion;
}
public void getEstadoDelTiempo() {
}
}
| true |
207619e282ba27761b6effbd0a0a57c9fb7235c5 | Java | ift-zjc/toolchain | /src/main/java/com/ift/toolchain/Service/MSApplicationService.java | UTF-8 | 714 | 2.09375 | 2 | [] | no_license | package com.ift.toolchain.Service;
import com.ift.toolchain.model.MSAApplication;
import com.ift.toolchain.repository.MSApplicationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MSApplicationService {
@Autowired
MSApplicationRepository msApplicationRepository;
public void removeAll(){
msApplicationRepository.deleteAll();
}
public List<MSAApplication> getApplications(){
return msApplicationRepository.findAll();
}
public MSAApplication add(MSAApplication msaApplication){
return msApplicationRepository.save(msaApplication);
}
}
| true |
5e25aa7c6b16dc97f9037dae746e1d7145a92698 | Java | xellolss/talFoStudy | /Solution.java | UTF-8 | 1,960 | 3.3125 | 3 | [] | no_license | package Kevin.exercise;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
static int anagramCnt;
public static void addChar(ArrayList<char[]> charArr, String substrString) {
char[] substrAnagramTochar = substrString.toCharArray();
Arrays.sort(substrAnagramTochar);
charArr.add(substrAnagramTochar);
}
public static void compareArr(ArrayList<char[]> arr) {
for(int i=0;i<arr.size()-1;i++) {
String aaa = new String(arr.get(i));
for (int j = 1+i; j < arr.size(); j++) {
String bbb = new String(arr.get(j));
if(aaa.equals(bbb)) {
anagramCnt++;
}
}
}
}
// Complete the sherlockAndAnagrams function below.
static int sherlockAndAnagrams(String s) {
anagramCnt = 0;
/* 진행중 */
for(int i=1;i<s.length();i++) {
ArrayList<char[]> substrAnagram = new ArrayList<char[]>();
for(int j=0;j<=s.length()-i;j++) {
addChar(substrAnagram, s.substring(j, j+i));
}
compareArr(substrAnagram);
}
return anagramCnt;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int qItr = 0; qItr < q; qItr++) {
String s = scanner.nextLine();
int result = sherlockAndAnagrams(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
} | true |
caf0620da3da962a9f7d1f6fc2c70fb2fa9f9dda | Java | leratoWendy/IT_Development_Project | /SystemAccountLogic/src/main/java/com/wendy/logic/impl/RewardsServiceImpl.java | UTF-8 | 1,064 | 2.125 | 2 | [] | no_license | package com.wendy.logic.impl;
import com.wendy.domain.dtos.RewardsDTO;
import com.wendy.logic.RewardsService;
import com.wendy.translators.RewardsTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.util.List;
@Transactional
@Component
public class RewardsServiceImpl implements RewardsService {
private RewardsTranslator translator;
@Autowired
public RewardsServiceImpl(RewardsTranslator translator) {
this.translator = translator;
}
@Override
public List<RewardsDTO> getAllRewards() {
return translator.getAllRewards();
}
@Override
public RewardsDTO updateReward(Long id, int price) {
return translator.updateReward(id,price);
}
@Override
public RewardsDTO deleteReward(Long id) {
return translator.deleteReward(id);
}
@Override
public RewardsDTO addReward(RewardsDTO rewardsDTO) {
return translator.addReward(rewardsDTO);
}
}
| true |
a9d646efab92782a59d0aa6c4e42a704b4e8c404 | Java | perchits/integral-document-cargoinspection | /docum/src/com/docum/view/container/CargoPackageDlgView.java | UTF-8 | 2,260 | 2.140625 | 2 | [] | no_license | package com.docum.view.container;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.docum.domain.po.common.CargoPackage;
import com.docum.domain.po.common.CargoPackageWeight;
import com.docum.domain.po.common.Measure;
import com.docum.view.AbstractDlgView;
import com.docum.view.DialogActionEnum;
import com.docum.view.wrapper.WeightPresentation;
public class CargoPackageDlgView extends AbstractDlgView implements Serializable {
private static final long serialVersionUID = -7662302467873387704L;
private CargoPackage cargoPackage;
private List<Measure> measures;
private CargoPackageWeight weight;
public CargoPackageDlgView(CargoPackage cargoPackage, List<Measure> measures) {
this.measures = measures;
this.cargoPackage = cargoPackage;
}
public CargoPackageWeight getWeight() {
return weight;
}
public void setWeight(CargoPackageWeight weight) {
this.weight = weight;
}
public void setCargoPackage(CargoPackage cargoPackage) {
this.cargoPackage = cargoPackage;
}
public CargoPackage getCargoPackage() {
return cargoPackage;
}
public List<Measure> getMeasures() {
return measures;
}
public List<WeightPresentation> getWeights(){
if (cargoPackage == null) {
return null;
}
List<WeightPresentation> result = new ArrayList<WeightPresentation>();
for (CargoPackageWeight w : cargoPackage.getWeights()) {
result.add(new WeightPresentation(w));
}
return result;
}
public void addWeight(){
CargoPackageWeight weight = new CargoPackageWeight();
weight.setCargoPackage(cargoPackage);
cargoPackage.getWeights().add(weight);
}
public void removeWeight(){
cargoPackage.getWeights().remove(weight);
}
public boolean isActual(){
return cargoPackage != null?
cargoPackage.getCargo().getCondition().isSurveyable() : false;
}
public String getTitle() {
return String.format("Редактирование упаковки для груза «%1$s»" ,
cargoPackage != null && cargoPackage.getCargo() != null ?
cargoPackage.getCargo().toString() : "" );
}
public void save() {
fireAction(this, DialogActionEnum.ACCEPT);
}
} | true |
9fb4f6adf6dbe4aa400550d9440acf1b55510df4 | Java | zouxj/mall-game | /app/src/main/java/com/shenyu/laikaword/model/rxjava/rxbus/event/Event.java | UTF-8 | 292 | 1.664063 | 2 | [] | no_license | package com.shenyu.laikaword.model.rxjava.rxbus.event;
/**
* Created by shenyu_zxjCode on 2017/10/16 0016.
*/
public class Event {
public int event;
public Object object;
public Event(int event,Object object) {
this.event = event;
this.object=object;
}
}
| true |
4c8ac93098f3f47e6da0c2b283d41986d25e29c2 | Java | itlgc/AndroidPlugin-Hook | /plugin_package/src/main/java/com/it/plugin_package/PluginHookActivity.java | UTF-8 | 870 | 2.421875 | 2 | [] | no_license | package com.it.plugin_package;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
/**
* 目标Activity
*/
public class PluginHookActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plugin_hook);
//如果是占位式 使用this 会报错
// Toast.makeText(this,"我是插件", Toast.LENGTH_SHORT).show();
//hook式 不会报错 因为插件和宿主dexElements 相互融合了 this可以使用到宿主中的了
Toast.makeText(getApplicationContext(),"我是插件", Toast.LENGTH_SHORT).show();//这行代码 在andriod9.0机型上toast 出现异常
Log.d("TAG: PluginHookActivity","恭喜你,成功启动我,我是插件包中的Activity" );
}
}
| true |
8dcc710c8e15011d5a147ac7a6041658ede5f963 | Java | tri-bao/remote-agent | /src/main/java/org/funsoft/remoteagent/host/view/HostSelectionPanel.java | UTF-8 | 3,800 | 2.359375 | 2 | [
"Apache-2.0"
] | permissive | /**
*
*/
package org.funsoft.remoteagent.host.view;
import org.apache.commons.lang.StringUtils;
import org.funsoft.remoteagent.gui.component.GUIUtils;
import org.funsoft.remoteagent.host.dto.HostDto;
import org.painlessgridbag.PainlessGridBag;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.List;
/**
* @author htb
*
*/
public class HostSelectionPanel extends JPanel {
private final HostTablePanel<HostSelectionTableModel> pnlHost = new HostTablePanel<>(
new HostSelectionTableModel());
private final HostDetailPanel pnlConnection = new HostDetailPanel();
private final String installerName;
public HostSelectionPanel() {
this(null);
}
public HostSelectionPanel(String installerName) {
this.installerName = installerName;
initState();
initAction();
initLayout();
}
private void initState() {
pnlConnection.setForMakingConnection();
pnlConnection.getBtnOK().setEnabled(false);
pnlConnection.getBtnOK().setText("Connect");
}
private void initAction() {
ActionListener[] als = pnlConnection.getBtnOK().getActionListeners();
for (ActionListener actionListener : als) {
pnlConnection.getBtnOK().removeActionListener(actionListener);
}
pnlHost.getPnlHost().getTable().getSelectionModel()
.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
HostDto sel = pnlHost.getPnlHost().getSelectedRowData();
pnlConnection.getBtnOK().setEnabled(sel != null);
displayHost(sel);
}
});
}
private void initLayout() {
JPanel pnlConn = pnlConn();
pnlConn.setMinimumSize(new Dimension(450, 1));
PainlessGridBag gbl = new PainlessGridBag(this, false);
gbl.row().cell(pnlHost).fillXY().cell(pnlConn).fillY();
gbl.constraints(pnlConn).anchor = GridBagConstraints.CENTER;
gbl.done();
}
private JPanel pnlConn() {
if (StringUtils.isBlank(installerName)) {
return pnlConnection;
}
JLabel lblName = new JLabel(installerName);
lblName.setForeground(Color.RED);
GUIUtils.makeFontBold(lblName);
JPanel pnl = new JPanel();
PainlessGridBag gbl = new PainlessGridBag(pnl, false);
gbl.row().cell(lblName);
gbl.row().cell(pnlConnection).fillXY();
gbl.done();
return pnl;
}
public boolean checkValid() {
return pnlConnection.checkValid();
}
public HostDto getSelectedHost() {
HostDto host = pnlHost.getPnlHost().getSelectedRowData();
// let changes persisted during session. host = (HostDto) SerializationUtils.clone(host);
pnlConnection.collectData(host);
return host;
}
public JButton getBtnConnect() {
return pnlConnection.getBtnOK();
}
public boolean isCancel() {
return pnlConnection.isCancel();
}
public void displayHosts(List<HostDto> knownHosts) {
pnlHost.showHostList(knownHosts);
pnlHost.clearHostSelection(); // to prevent unanted host selected due to default selection
}
public void setSelectedHost(HostDto h) {
List<HostDto> allRowData = pnlHost.getPnlHost().getSortableModel().getAllRowData();
if (allRowData.size() == 1) {
pnlHost.getPnlHost().getTable().getSelectionModel().setSelectionInterval(0, 0);
}
if (h == null) {
return;
}
for (int i = 0; i < allRowData.size(); i++) {
HostDto host = allRowData.get(i);
if (StringUtils.equalsIgnoreCase(host.getUuid(), h.getUuid())) {
int viewId = pnlHost.getPnlHost().getTable().convertRowIndexToView(i);
pnlHost.getPnlHost().getTable().getSelectionModel().setSelectionInterval(viewId, viewId);
break;
}
}
}
private void displayHost(HostDto host) {
pnlConnection.fillDataToScreen(host);
}
}
| true |
49c24e8b7aaf706d5c78974ab289d064ecfc4d99 | Java | jijilan/dangerouschemical | /dangerouschemical-alarm/src/main/java/cn/jijl/alarm/modules/mapper/AlarmInfoMapper.java | UTF-8 | 352 | 1.554688 | 2 | [] | no_license | package cn.jijl.alarm.modules.mapper;
import cn.jijl.alarm.modules.entity.AlarmInfo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* 报警信息表 Mapper 接口
* </p>
*
* @author jijl
* @since 2020-07-20
*/
public interface AlarmInfoMapper extends BaseMapper<AlarmInfo> {
}
| true |