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
f116f6c86d09abd8af0a5c7ef45d44341560e4a0
Java
huyducvo972001/Java5ShoppingCart
/src/main/java/com/poly/dao/OriginDAO.java
UTF-8
188
1.59375
2
[]
no_license
package com.poly.dao; import com.poly.entity.Origin; import org.springframework.data.jpa.repository.JpaRepository; public interface OriginDAO extends JpaRepository<Origin, Integer> { }
true
7e088468a841a1a2d3dcce2a532a97bda4eacd94
Java
GuusHamm/Kwetter-Spring
/src/main/java/nl/guushamm/Receiver.java
UTF-8
1,183
2.125
2
[]
no_license
package nl.guushamm; import nl.guushamm.domain.Account; import nl.guushamm.domain.Kweet; import nl.guushamm.service.AccountService; import nl.guushamm.service.KweetService; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.json.BasicJsonParser; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; import java.util.Map; import static nl.guushamm.utils.UtilsKt.getKwetterGoAccount; /** * Created by guushamm on 3-5-17. */ @Component public class Receiver { @Autowired private KweetService kweetService; @Autowired private AccountService accountService; @RabbitListener(queues = "kwetter") public void processKweet(byte[] data) throws InterruptedException { String dataString = new String(data, StandardCharsets.UTF_8); BasicJsonParser jsonParser = new BasicJsonParser(); Map incoming = jsonParser.parseMap(dataString); Account kwetterGoAccount = accountService.findOrSave(getKwetterGoAccount()); Kweet kweet = new Kweet(incoming.get("message").toString(), kwetterGoAccount); kweetService.save(kweet); } }
true
dbcc6cdc5212d6c33a0fc479df148bfd20bfd861
Java
dpoddubko/Cruiser
/tests/com/test/BattleFieldTest.java
UTF-8
4,098
2.75
3
[]
no_license
package com.test; import battleField.BaseBattleField; import battleField.ShipsBuilder; import battleField.Variants; import cruiser.BaseCruiser; import cruiser.Cruiser; import cruiser.MissileCruiser; import cruiser.ProtectedCruiser; import cruiserForTest.NullWeaponCruiser; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static battleField.ShipsBuilder.*; import static org.junit.Assert.*; public class BattleFieldTest { @Test public void randomNumTest() { for (int i = 0; i < 10; i++) { int ranNum = chooseCruiser(10); assertTrue(0 <= ranNum && ranNum <= 9); } for (int i = 0; i < 10; i++) { int ranNum = chooseCruiser(0); assertEquals(0, ranNum); } } @Test public void shipsBuilderNotNullTest() { ShipsBuilder shipsBuilder = new ShipsBuilder(); assertNotNull(shipsBuilder.build()); } @Test public void createCruisersTest() { BaseBattleField battleField = new BaseBattleField(createCruisers(), createCruisers()); assertNotNull(battleField.getBlackTeam()); assertNotNull(battleField.getWhiteTeam()); assertEquals(10, battleField.getWhiteTeam().size()); assertEquals(10, battleField.getBlackTeam().size()); for (Cruiser cruiser : battleField.getWhiteTeam()) { assertTrue(cruiser instanceof BaseCruiser); } ShipsBuilder.setRandomSize(0); List<Cruiser> list = ShipsBuilder.createCruisers(); for (Cruiser cruiser : list) assertTrue(cruiser.getClass().equals(MissileCruiser.class)); } @Test public void doRoundNoChargeTest() { List<Cruiser> wTeam = new ArrayList<>(); List<Cruiser> bTeam = new ArrayList<>(); wTeam.add(new NullWeaponCruiser()); wTeam.add(new NullWeaponCruiser()); bTeam.add(new NullWeaponCruiser()); BaseBattleField battleField = new BaseBattleField(wTeam, bTeam); assertEquals(Variants.WHITE_TEAM_WIN, battleField.doRound()); bTeam.add(new NullWeaponCruiser()); wTeam.remove(0); assertEquals(Variants.BLACK_TEAM_WIN, battleField.doRound()); wTeam.add(new NullWeaponCruiser()); assertEquals(Variants.TIE, battleField.doRound()); wTeam.get(0).setLife(20); assertEquals(Variants.WHITE_TEAM_WIN, battleField.doRound()); bTeam.get(0).setLife(30); assertEquals(Variants.BLACK_TEAM_WIN, battleField.doRound()); } @Test public void attackTeam() { List<Cruiser> wTeam = new ArrayList<>(); List<Cruiser> bTeam = new ArrayList<>(); wTeam.add(new ProtectedCruiser()); bTeam.add(new NullWeaponCruiser()); bTeam.add(new NullWeaponCruiser()); BaseBattleField battleField = new BaseBattleField(wTeam, bTeam); assertEquals(false, battleField.attack(wTeam, bTeam)); assertEquals(true, battleField.attack(wTeam, bTeam)); } @Test public void doRoundTest() { List<Cruiser> wTeam = new ArrayList<>(); List<Cruiser> bTeam = new ArrayList<>(); wTeam.add(new ProtectedCruiser()); bTeam.add(new NullWeaponCruiser()); BaseBattleField battleField = new BaseBattleField(wTeam, bTeam); assertEquals(Variants.WHITE_TEAM_WIN, battleField.doRound()); List<Cruiser> wTeam1 = new ArrayList<>(); List<Cruiser> bTeam1 = new ArrayList<>(); wTeam1.add(new NullWeaponCruiser()); bTeam1.add(new NullWeaponCruiser()); BaseBattleField battleField1 = new BaseBattleField(wTeam1, bTeam1); assertEquals(Variants.TIE, battleField1.doRound()); List<Cruiser> wTeam2 = new ArrayList<>(); List<Cruiser> bTeam2 = new ArrayList<>(); wTeam2.add(new NullWeaponCruiser()); bTeam2.add(new NullWeaponCruiser()); BaseBattleField battleField2 = new BaseBattleField(wTeam2, bTeam2); battleField2.getWhiteTeam().get(0).setLife(30); assertEquals(Variants.WHITE_TEAM_WIN, battleField2.doRound()); } }
true
63f1fad1549aea4f6a1da4b546d0eeb7a1a29656
Java
AndrewShaw123/NotePad
/src/com/andrew/control/codingcontrol/CodingActionListener.java
GB18030
573
2.4375
2
[]
no_license
package com.andrew.control.codingcontrol; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import com.andrew.view.App; public class CodingActionListener implements ActionListener{ /* * Appеıʽ */ @Override public void actionPerformed(ActionEvent e) { String temp=e.getActionCommand(); if(temp.equals("GBK")) { App.setEnCodingAndDeCoding("GBK"); }else if(temp.equals("UTF-8")){ App.setEnCodingAndDeCoding("UTF-8"); }else if(temp.equals("Unicode")) { App.setEnCodingAndDeCoding("Unicode"); } } }
true
6eb5010b0b3d8385f8235f91eef0648f11c7e79f
Java
cui779304118/interviewExercise
/src/com/cuiwei/thread/SimpleDateFormatThreadProblem.java
UTF-8
973
3.265625
3
[]
no_license
package com.cuiwei.thread; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDateFormatThreadProblem extends Thread { String pattern; private DateFormat dateFormat; private String dateString; public SimpleDateFormatThreadProblem(String pattern, String dateString){ this.pattern = pattern; this.dateString = dateString; } public void run(){ dateFormat = new SimpleDateFormat(pattern); System.out.println(1/0); try { Date dateParse = dateFormat.parse(dateString); String dateParseString = dateFormat.format(dateParse).toString(); if(!dateParseString.equals(dateString)){ System.out.println("ThreadName=" + this.getName() + "" + "解析错误 日期字符串: " + dateString + " 转换成的日期为: " + dateParseString); }else{ System.out.println("解析正确!"); } } catch (ParseException e) { e.printStackTrace(); } } }
true
3ed4b3bf1129958dad4c59773f896ae0449fcaf2
Java
altayeb1980/personality_test
/src/main/java/com/sparknetworks/model/Question.java
UTF-8
3,864
2.4375
2
[]
no_license
package com.sparknetworks.model; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.validation.constraints.NotEmpty; @Entity public class Question { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotEmpty private String text; @ManyToOne(cascade = {CascadeType.MERGE},optional = true) @JoinColumn(name = "category_id") private QuestionCategory category; @OneToOne(cascade = CascadeType.ALL) private QuestionType questionType; private String condValue; @ManyToOne(fetch = FetchType.LAZY, optional = true) @JoinColumn(name = "parent_id") private Question parent; @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) private List<Question> children; // private Question() { // } // // public Question(String text, QuestionCategory category, QuestionType questionType){ // this.text = text; // this.category = category; // this.questionType = questionType; // } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setText(String text) { this.text = text; } public void setCategory(QuestionCategory category) { this.category = category; } public void setQuestionType(QuestionType questionType) { this.questionType = questionType; } public void setCondValue(String condValue) { this.condValue = condValue; } public void setParent(Question parent) { this.parent = parent; } public void setChildren(List<Question> children) { this.children = children; } public String getText() { return text; } public QuestionCategory getCategory() { return category; } public QuestionType getQuestionType() { return questionType; } public String getCondValue() { return condValue; } public Question getParent() { return parent; } public List<Question> getChildren() { return children; } public static class Builder { private String text; private QuestionCategory category; private QuestionType questionType; private String condValue; private Question parent; private List<Question> children; public Builder withParent(Question parent) { this.parent = parent; return this; } public Builder withEmptyChildren() { this.children = new ArrayList<>(); return this; } public Builder withChildren(List<Question> children) { this.children = children; return this; } public Builder withText(String text) { this.text = text; return this; } public Builder withQuestionCategory(QuestionCategory category) { this.category = category; return this; } public Builder withQuestionType(QuestionType questionType) { this.questionType = questionType; return this; } public Builder withConditionExactValue(String condValue) { this.parent.condValue = condValue; return this; } public Question build() { Question question = new Question(); question.parent = this.parent; question.children = this.children; question.text = this.text; question.category = this.category; question.questionType = this.questionType; question.condValue = this.condValue; return question; } } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Question)) { return false; } Question q = (Question) o; return id == q.id && Objects.equals(text, q.text); } @Override public int hashCode() { return Objects.hash(id, category); } }
true
0ef0960a7046ae8c7c2f3c075ab3a9854cd9b683
Java
caixiaojie/CbsdBase
/app/src/main/java/com/yjhs/cbsdbase/common/PhotoHandle.java
UTF-8
1,696
2.140625
2
[]
no_license
package com.yjhs.cbsdbase.common; import java.util.List; /** * author: Administrator * date: 2018/1/25 0025 * desc: */ public class PhotoHandle { private IWebCallback iWebCallback; private String callbackname; public PhotoHandle(IWebCallback iWebCallback) { this.iWebCallback = iWebCallback; } public void setCallbackname(String callbackname) { this.callbackname = callbackname; } public void setSuccess (List<String> urls, String strImgrootpath) { /** * "filePath": [ * "2019/02/28/8f58193fbffd4991946b2a19da7519e2.png", * "2019/02/28/b5f0134278764d0db0f01b7d373f2e3f.png" * ] */ StringBuilder sb = new StringBuilder(""); sb.append(String.format("\"url\":[")); for (int i = 0; i < urls.size(); i++) { sb.append(String.format("\"%s\",",urls.get(i))); } String substring = sb.substring(0, sb.length() - 1); StringBuilder stringBuilder = new StringBuilder(substring); stringBuilder.append("]"); stringBuilder.append(String.format(",\"strImgrootpath\":\"%s\"",strImgrootpath)); // .append(",") String json= String.format("{\"code\":1,\"data\":{%s}}",stringBuilder); if (iWebCallback != null) { iWebCallback.fun(callbackname,json); } } public void setError (String code, String msg) { if ("".equals(code)) { return; } String json = String.format("{\"code\":%s,\"msg\":%s}",code,msg); if (iWebCallback != null) { iWebCallback.fun(callbackname,json); } } }
true
6a43cbce460a4c624c3d93e0dc172bd35e159875
Java
tingley/globalsight
/main6/envoy/src/java/com/globalsight/everest/webapp/pagehandler/administration/config/MTProfileImport.java
UTF-8
18,015
1.828125
2
[]
no_license
/** * Copyright 2009 Welocalize, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.globalsight.everest.webapp.pagehandler.administration.config; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import com.globalsight.everest.projecthandler.EngineEnum; import com.globalsight.everest.projecthandler.MachineTranslationExtentInfo; import com.globalsight.everest.projecthandler.MachineTranslationProfile; import com.globalsight.everest.webapp.pagehandler.administration.mtprofile.MTProfileHandlerHelper; import com.globalsight.persistence.hibernate.HibernateUtil; /** * Imports mt profile info to system. */ public class MTProfileImport implements ConfigConstants { private static final Logger logger = Logger.getLogger(MTProfileImport.class); private Map<Long, MachineTranslationProfile> mtpMap = new HashMap<Long, MachineTranslationProfile>(); private Map<Long, Long> mtpExtentInfoMap = new HashMap<Long, Long>(); private String currentCompanyId; private String sessionId; private String importToCompId; private EngineEnum[] engines = null; public MTProfileImport(String sessionId, String currentCompanyId, String importToCompId) { this.sessionId = sessionId; this.currentCompanyId = currentCompanyId; this.importToCompId = importToCompId; engines = EngineEnum.values(); } public void analysisAndImport(File uploadedFile) { Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); try { String[] keyArr = null; String key = null; String strKey = null; String strValue = null; InputStream is; is = new FileInputStream(uploadedFile); BufferedReader bf = new BufferedReader(new InputStreamReader(is)); Properties prop = new Properties(); prop.load(bf); Enumeration enum1 = prop.propertyNames(); while (enum1.hasMoreElements()) { // The key profile strKey = (String) enum1.nextElement(); key = strKey.substring(0, strKey.lastIndexOf('.')); keyArr = strKey.split("\\."); // Value in the properties file strValue = prop.getProperty(strKey); Set<String> keySet = map.keySet(); if (keySet.contains(key)) { Map<String, String> valueMap = map.get(key); Set<String> valueKey = valueMap.keySet(); if (!valueKey.contains(keyArr[2])) { valueMap.put(keyArr[2], strValue); } } else { Map<String, String> valueMap = new HashMap<String, String>(); valueMap.put(keyArr[2], strValue); map.put(key, valueMap); } } // Data analysis analysisData(map); } catch (Exception e) { logger.error("Failed to parse the file", e); } } private void analysisData(Map<String, Map<String, String>> map) throws ParseException { if (map.isEmpty()) return; Map<String, List> dataMap = new HashMap<String, List>(); List<MachineTranslationProfile> mtpList = new ArrayList<MachineTranslationProfile>(); List<MachineTranslationExtentInfo> extenInfoList = new ArrayList<MachineTranslationExtentInfo>(); Set<String> keySet = map.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String key = (String) it.next(); String[] keyArr = key.split("\\."); Map<String, String> valueMap = map.get(key); if (!valueMap.isEmpty()) { if (keyArr[0].equalsIgnoreCase("MachineTranslationProfile")) { MachineTranslationProfile mtp = putDataIntoMTP(valueMap); if (mtp.getMtEngine() == null || "".equals(mtp.getMtEngine())) { addToError("<b >Profile name is " + mtp.getMtProfileName() + " imported failed because mt engine was modified type not supported!</b>"); } if (mtp.getMtEngine() != null && !"".equals(mtp.getMtEngine())) { mtpList.add(mtp); } } if (keyArr[0].equalsIgnoreCase("MachineTranslationExtentInfo")) { MachineTranslationExtentInfo globalSightLocale = putDataIntoMTPExtenInfo(valueMap); extenInfoList.add(globalSightLocale); } } } if (mtpList.size() > 0) dataMap.put("MachineTranslationProfile", mtpList); if (extenInfoList.size() > 0) dataMap.put("MachineTranslationExtentInfo", extenInfoList); // Storing data storeDataToDatabase(dataMap); } private void storeDataToDatabase(Map<String, List> dataMap) { if (dataMap.isEmpty()) return; try { if (dataMap.containsKey("MachineTranslationProfile")) { storeMTPData(dataMap); } if (dataMap.containsKey("MachineTranslationExtentInfo")) { storeMTPExtentInfoData(dataMap); } addMessage("<b> Done importing Machine Translation Profiles.</b>"); } catch (Exception e) { logger.error("Failed to import Machine Translation Profiles.", e); addToError(e.getMessage()); } } @SuppressWarnings("unchecked") private void storeMTPData(Map<String, List> dataMap) { List<MachineTranslationProfile> mtpList = dataMap.get("MachineTranslationProfile"); MachineTranslationProfile mtp = null; try { for (int i = 0; i < mtpList.size(); i++) { mtp = mtpList.get(i); long oldId = mtp.getId(); String oldName = mtp.getMtProfileName(); String newName = getMTPNewName(oldName, mtp.getCompanyid()); mtp.setMtProfileName(newName); HibernateUtil.save(mtp); long newId = selectNewId(newName, mtp.getCompanyid()); mtp = MTProfileHandlerHelper.getMTProfileById(String .valueOf(newId)); mtpMap.put(oldId, mtp); if (oldName.equals(newName)) { addMessage("<b>" + mtp.getMtProfileName() + "</b> imported successfully."); } else { addMessage(" MT Profile name <b>" + oldName + "</b> already exists. <b>" + mtp.getMtProfileName() + "</b> imported successfully."); } } } catch (Exception e) { String msg = "Upload MachineTranslationProfile data failed !"; logger.warn(msg); addToError(msg); } } @SuppressWarnings("unchecked") private void storeMTPExtentInfoData(Map<String, List> dataMap) { MachineTranslationExtentInfo extenInfo = null; List<MachineTranslationExtentInfo> extenInfoList = dataMap .get("MachineTranslationExtentInfo"); try { for (int i = 0; i < extenInfoList.size(); i++) { extenInfo = extenInfoList.get(i); long id = extenInfo.getId(); if (mtpExtentInfoMap.containsKey(id)) { long value = mtpExtentInfoMap.get(id); if (mtpMap.containsKey(value)) { MachineTranslationProfile mtp = mtpMap.get(value); extenInfo.setMtProfile(mtp); } } HibernateUtil.save(extenInfo); } } catch (Exception e) { String msg = "Upload MachineTranslationExtentInfo data failed !"; logger.warn(msg); addToError(msg); } } private MachineTranslationProfile putDataIntoMTP(Map<String, String> valueMap) throws ParseException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); dateFormat.setLenient(false); MachineTranslationProfile mtp = new MachineTranslationProfile(); mtp.setMtEngine(""); mtp.setMsTransVersion(null); String keyField = null; String valueField = null; Set<String> valueKey = valueMap.keySet(); Iterator itor = valueKey.iterator(); while (itor.hasNext()) { keyField = (String) itor.next(); valueField = valueMap.get(keyField); if (keyField.equalsIgnoreCase("ID")) { mtp.setId(Long.parseLong(valueField)); } else if (keyField.equalsIgnoreCase("MT_PROFILE_NAME")) { mtp.setMtProfileName(valueField); } else if (keyField.equalsIgnoreCase("MT_ENGINE")) { for (int i = 0; i < engines.length; i++) { String _engine = engines[i].name(); if (_engine.equalsIgnoreCase(valueField)) { mtp.setMtEngine(valueField); } } } else if (keyField.equalsIgnoreCase("DESCRIPTION")) { mtp.setDescription(valueField); } else if (keyField.equalsIgnoreCase("MT_THRESHOLD")) { mtp.setMtThreshold(Long.parseLong(valueField)); } else if (keyField.equalsIgnoreCase("URL")) { mtp.setUrl(valueField); } else if (keyField.equalsIgnoreCase("MS_TRANS_VERSION")) { mtp.setMsTransVersion(valueField); } else if (keyField.equalsIgnoreCase("MS_TOKEN_URL")) { mtp.setMsTokenUrl(valueField); } else if (keyField.equalsIgnoreCase("PORT")) { mtp.setPort(Integer.parseInt(valueField)); } else if (keyField.equalsIgnoreCase("USERNAME")) { mtp.setUsername(valueField); } else if (keyField.equalsIgnoreCase("PASSWORD")) { mtp.setPassword(valueField); } else if (keyField.equalsIgnoreCase("CATEGORY")) { mtp.setCategory(valueField); } else if (keyField.equalsIgnoreCase("ACCOUNTINFO")) { mtp.setAccountinfo(valueField); } else if (keyField.equalsIgnoreCase("COMPANY_ID")) { if (importToCompId != null && !importToCompId.equals("-1")) { mtp.setCompanyid(Long.parseLong(importToCompId)); } else { mtp.setCompanyid(Long.parseLong(currentCompanyId)); } } else if (keyField.equalsIgnoreCase("TIMESTAMP")) { Date timeDate = dateFormat.parse(valueField); Timestamp dateTime = new Timestamp(timeDate.getTime()); mtp.setTimestamp(dateTime); } else if (keyField.equalsIgnoreCase("INCLUDE_MT_IDENTIFIERS")) { mtp.setIncludeMTIdentifiers(Boolean.parseBoolean(valueField)); } else if (keyField.equalsIgnoreCase("IGNORE_TM_MATCHES")) { mtp.setIgnoreTMMatch(Boolean.parseBoolean(valueField)); } else if (keyField.equalsIgnoreCase("LOG_DEBUG_INFO")) { mtp.setLogDebugInfo(Boolean.parseBoolean(valueField)); } else if (keyField.equalsIgnoreCase("MS_TRANS_TYPE")) { mtp.setMsTransType(valueField); } else if (keyField.equalsIgnoreCase("MS_MAX_LENGTH")) { mtp.setMsMaxLength(Long.parseLong(valueField)); } else if (keyField.equalsIgnoreCase("MT_IDENTIFIER_LEADING")) { mtp.setMtIdentifierLeading(valueField); } else if (keyField.equalsIgnoreCase("MT_IDENTIFIER_TRAILING")) { mtp.setMtIdentifierTrailing(valueField); } else if (keyField.equalsIgnoreCase("IS_ACTIVE")) { mtp.setActive(Boolean.parseBoolean(valueField)); } else if (keyField.equalsIgnoreCase("EXTENT_JSON_INFO")) { if (valueField == null || "".equals(valueField)) { mtp.setJsonInfo(null); } else { mtp.setJsonInfo(valueField); } } } if (mtp.getMsTransVersion() == null) { mtp.setMsTransVersion(mtp.getMsVersion()); } return mtp; } private MachineTranslationExtentInfo putDataIntoMTPExtenInfo(Map<String, String> valueMap) { MachineTranslationExtentInfo extenInfo = new MachineTranslationExtentInfo(); Long mtProfileId = null; String key = null; String value = null; Set<String> valueKey = valueMap.keySet(); Iterator itor = valueKey.iterator(); while (itor.hasNext()) { key = (String) itor.next(); value = valueMap.get(key); if (key.equalsIgnoreCase("ID")) { extenInfo.setId(Long.parseLong(value)); } else if (key.equalsIgnoreCase("MT_PROFILE_ID")) { mtProfileId = Long.parseLong(value); } else if (key.equalsIgnoreCase("LANGUAGE_PAIR_CODE")) { extenInfo.setLanguagePairCode(Long.parseLong(value)); } else if (key.equalsIgnoreCase("LANGUAGE_PAIR_NAME")) { extenInfo.setLanguagePairName(value); } else if (key.equalsIgnoreCase("DOMAIN_CODE")) { extenInfo.setDomainCode(value); } } mtpExtentInfoMap.put(extenInfo.getId(), mtProfileId); return extenInfo; } private String getMTPNewName(String filterName, Long companyId) { String hql = "select mtp.mtProfileName from MachineTranslationProfile " + " mtp where mtp.companyid=:companyid"; Map map = new HashMap(); map.put("companyid", companyId); List itList = HibernateUtil.search(hql, map); if (itList.contains(filterName)) { for (int num = 1;; num++) { String returnStr = null; if (filterName.contains("_import_")) { returnStr = filterName.substring(0, filterName.lastIndexOf('_')) + "_" + num; } else { returnStr = filterName + "_import_" + num; } if (!itList.contains(returnStr)) { return returnStr; } } } else { return filterName; } } private Long selectNewId(String mtProfileName, Long companyId) { Map map = new HashMap(); String hql = "select mtp.id from MachineTranslationProfile " + " mtp where mtp.companyid=:companyid and mtp.mtProfileName=:mtProfileName "; map.put("companyid", companyId); map.put("mtProfileName", mtProfileName); Long id = (Long) HibernateUtil.getFirst(hql, map); return id; } private void addToError(String msg) { String former = config_error_map.get(sessionId) == null ? "" : config_error_map .get(sessionId); config_error_map.put(sessionId, former + "<p>" + msg); } private void addMessage(String msg) { String former = config_error_map.get(sessionId) == null ? "" : config_error_map .get(sessionId); config_error_map.put(sessionId, former + "<p>" + msg); } }
true
2c2a378fb6b56ed464a00ad286a7268f3ff1dbcd
Java
DWL5/2021-tyf
/server/src/main/java/com/example/tyfserver/payment/dto/RefundVerificationReadyRequest.java
UTF-8
436
1.851563
2
[]
no_license
package com.example.tyfserver.payment.dto; import com.example.tyfserver.payment.util.UUID; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter public class RefundVerificationReadyRequest { @UUID private String merchantUid; public RefundVerificationReadyRequest(String merchantUid) { this.merchantUid = merchantUid; } }
true
c35dcb56d22bc652fab5dc9e018a4255b9ea399c
Java
mohdjahid/Java_J2SE
/File IO/Using List()/List1.java
UTF-8
271
3.140625
3
[]
no_license
import java.io.*; class List1 { public static void main(String[] args) { int count=0; File f=new File("F:\\JAVA\\Coaching\\Inheritance"); String[] s=f.list(); for(String s1:s) { count++; System.out.println(s1); } System.out.println(count); } }
true
9dc0a6e7bd1d2859f0031eb7f5a4fd8b0d71752c
Java
adumbgreen/TriviaCrap
/Android/triviacrack_src/src/com/etermax/gamescommon/login/datasource/a/d.java
UTF-8
2,926
1.648438
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.etermax.gamescommon.login.datasource.a; import com.etermax.gamescommon.login.datasource.dto.SocialAccountDTO; import com.etermax.gamescommon.login.datasource.dto.UserDTO; import com.etermax.gamescommon.login.datasource.dto.UserInfo; import java.util.List; import org.a.a.a.a; import org.b.c.b; import org.b.c.b.j; import org.b.c.f; import org.b.c.l; import org.b.e.a.k; // Referenced classes of package com.etermax.gamescommon.login.datasource.a: // c public final class d implements c { private k a; private String b; private a c; public d() { a = new k(); b = ""; a.c().add(new j()); } public l a(SocialAccountDTO socialaccountdto) { b b1 = new b(socialaccountdto); l l; try { l = a.a(b.concat("/social-login"), f.b, b1, com/etermax/gamescommon/login/datasource/dto/UserDTO, new Object[0]); } catch (org.b.e.a.j j1) { if (c != null) { c.a(j1); return null; } else { throw j1; } } return l; } public l a(UserInfo userinfo) { b b1 = new b(userinfo); l l; try { l = a.a(b.concat("/login"), f.b, b1, com/etermax/gamescommon/login/datasource/dto/UserDTO, new Object[0]); } catch (org.b.e.a.j j1) { if (c != null) { c.a(j1); return null; } else { throw j1; } } return l; } public void a(String s) { b = s; } public void a(k k1) { a = k1; } public l b(SocialAccountDTO socialaccountdto) { b b1 = new b(socialaccountdto); l l; try { l = a.a(b.concat("/social-users"), f.b, b1, com/etermax/gamescommon/login/datasource/dto/UserDTO, new Object[0]); } catch (org.b.e.a.j j1) { if (c != null) { c.a(j1); return null; } else { throw j1; } } return l; } public l b(UserInfo userinfo) { b b1 = new b(userinfo); l l; try { l = a.a(b.concat("/users"), f.b, b1, com/etermax/gamescommon/login/datasource/dto/UserDTO, new Object[0]); } catch (org.b.e.a.j j1) { if (c != null) { c.a(j1); return null; } else { throw j1; } } return l; } }
true
90725e7f7767fe1af191daf9c684b31257ec3389
Java
yuanyp/y_gon
/src/main/java/com/gon/AbstractHelper.java
UTF-8
3,798
1.695313
2
[]
no_license
/* 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.gon; import org.activiti.engine.*; import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.activiti.engine.impl.db.DbSqlSession; import org.activiti.engine.impl.db.DbSqlSessionFactory; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AbstractHelper { protected Logger logger = LoggerFactory.getLogger(getClass()); protected ProcessEngine processEngine; protected ProcessEngineConfiguration processEngineConfiguration; protected RepositoryService repositoryService = null; protected RuntimeService runtimeService = null; protected HistoryService historyService = null; protected IdentityService identityService = null; protected TaskService taskService = null; protected FormService formService = null; protected ManagementService managementService = null; /** * 开启一个mybatis的session,切记要关闭 */ protected SqlSession openSession() { ProcessEngineConfigurationImpl peci = (ProcessEngineConfigurationImpl) processEngineConfiguration; DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) peci.getSessionFactories().get(DbSqlSession.class); SqlSessionFactory sqlSessionFactory = dbSqlSessionFactory.getSqlSessionFactory(); return sqlSessionFactory.openSession(); } // -- getter and setter --// public ProcessEngine getProcessEngine() { return processEngine; } public void setProcessEngine(ProcessEngine processEngine) { this.processEngine = processEngine; } public ProcessEngineConfiguration getProcessEngineConfiguration() { return processEngineConfiguration; } public void setProcessEngineConfiguration(ProcessEngineConfiguration processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; } public RepositoryService getRepositoryService() { return repositoryService; } public void setRepositoryService(RepositoryService repositoryService) { this.repositoryService = repositoryService; } public RuntimeService getRuntimeService() { return runtimeService; } public void setRuntimeService(RuntimeService runtimeService) { this.runtimeService = runtimeService; } public HistoryService getHistoryService() { return historyService; } public void setHistoryService(HistoryService historyService) { this.historyService = historyService; } public IdentityService getIdentityService() { return identityService; } public void setIdentityService(IdentityService identityService) { this.identityService = identityService; } public TaskService getTaskService() { return taskService; } public void setTaskService(TaskService taskService) { this.taskService = taskService; } public FormService getFormService() { return formService; } public void setFormService(FormService formService) { this.formService = formService; } public ManagementService getManagementService() { return managementService; } public void setManagementService(ManagementService managementService) { this.managementService = managementService; } }
true
e0e4d85457f50ed8d19d3301297ed1e16ca50e24
Java
RaphByrne/quarto-ai-4211
/Code/src/quarto/Quarto.java
UTF-8
1,218
3.078125
3
[]
no_license
package quarto; import agent.Action; public class Quarto { QBoard board; Player p1; Player p2; /** * * @param p1 * @param p2 */ public Quarto(Player p1, Player p2) { board = new QBoard(); this.p1 = p1; this.p2 = p2; } public Quarto(Player p1, Player p2, QBoard board) { this.board = board; this.p1 = p1; this.p2 = p2; } public boolean isDraw() { return board.gameOver() && !board.isWinningBoard(); } public boolean oneHasWon() { return !board.oneToMove() && board.isWinningBoard(); } public boolean twoHasWon() { return board.oneToMove() && board.isWinningBoard(); } public boolean gameOver() { return board.gameOver(); } public String printBoard() { return board.toString(); } public Player getNextPlayer() { if(board.oneToMove()) return p1; else return p2; } public void step() { Player nextPlayer = getNextPlayer(); //System.out.println(nextPlayer.getName() + " to move"); QMove nextMove = (QMove)nextPlayer.getAction(board.getPercept()); //System.out.println(nextPlayer.getName() + " making move: " + nextMove.toString()); board.update(nextMove); } }
true
114748b813c93fad8875d5a5eb744319111b9d79
Java
shimashima35/violations-lib
/src/main/java/se/bjurr/violations/lib/parsers/ViolationParserUtils.java
UTF-8
5,740
2.328125
2
[ "Apache-2.0" ]
permissive
package se.bjurr.violations.lib.parsers; import static java.lang.Integer.parseInt; import static java.util.regex.Pattern.DOTALL; import static java.util.regex.Pattern.quote; import static se.bjurr.violations.lib.util.Optional.absent; import static se.bjurr.violations.lib.util.Optional.fromNullable; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import se.bjurr.violations.lib.util.Optional; public final class ViolationParserUtils { public static String asString(XMLStreamReader xmlr) throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter stringWriter = new StringWriter(); transformer.transform(new StAXSource(xmlr), new StreamResult(stringWriter)); return stringWriter.toString(); } public static Optional<String> findAttribute(String in, String attribute) { Pattern pattern = Pattern.compile(attribute + "='([^']+?)'"); Matcher matcher = pattern.matcher(in); if (matcher.find()) { return fromNullable(matcher.group(1)); } pattern = Pattern.compile(attribute + "=\"([^\"]+?)\""); matcher = pattern.matcher(in); if (matcher.find()) { return fromNullable(matcher.group(1)); } return absent(); } public static Optional<String> findAttribute(XMLStreamReader in, String attribute) { return fromNullable(in.getAttributeValue("", attribute)); } public static Optional<Integer> findIntegerAttribute(String in, String attribute) { if (findAttribute(in, attribute).isPresent()) { return fromNullable(parseInt(getAttribute(in, attribute))); } return absent(); } public static Optional<Integer> findIntegerAttribute(XMLStreamReader in, String attribute) { String attr = in.getAttributeValue("", attribute); if (attr == null) { return Optional.absent(); } else { return fromNullable(Integer.parseInt(attr)); } } public static String getAttribute(String in, String attribute) { Optional<String> foundOpt = findAttribute(in, attribute); if (foundOpt.isPresent()) { return foundOpt.get(); } throw new RuntimeException("\"" + attribute + "\" not found in \"" + in + "\""); } public static String getAttribute(XMLStreamReader in, String attribute) { String foundOpt = in.getAttributeValue("", attribute); if (foundOpt == null) { String foundin; try { foundin = asString(in); } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("\"" + attribute + "\" not found in:\n" + foundin); } return foundOpt; } public static List<String> getChunks(String in, String includingStart, String includingEnd) { Pattern pattern = Pattern.compile("(" + includingStart + ".+?" + includingEnd + ")", DOTALL); Matcher matcher = pattern.matcher(in); List<String> chunks = new ArrayList<>(); while (matcher.find()) { chunks.add(matcher.group()); } return chunks; } public static String getContent(String in, String tag) { Pattern pattern = Pattern.compile( "<" + tag + ">[^<]*<!\\[CDATA\\[(" + ".+?" + ")\\]\\]>[^<]*</" + tag + ">", DOTALL); Matcher matcher = pattern.matcher(in); if (matcher.find()) { return matcher.group(1); } pattern = Pattern.compile("<" + tag + ">(" + ".+?" + ")</" + tag + ">", DOTALL); matcher = pattern.matcher(in); if (matcher.find()) { return matcher.group(1); } throw new RuntimeException("\"" + tag + "\" not found in " + in); } public static Integer getIntegerAttribute(String in, String attribute) { return parseInt(getAttribute(in, attribute)); } public static Integer getIntegerAttribute(XMLStreamReader in, String attribute) { return parseInt(getAttribute(in, attribute)); } public static Integer getIntegerContent(String in, String tag) { String content = getContent(in, tag); return parseInt(content); } public static List<String> getLines(String string) { return Arrays.asList(string.split("\n")); } /** @return List per line in String, with groups from regexpPerLine. */ public static List<List<String>> getLines(String string, String regexpPerLine) { List<List<String>> results = new ArrayList<>(); Pattern pattern = Pattern.compile(regexpPerLine); for (String line : string.split("\n")) { Matcher matcher = pattern.matcher(line); if (!matcher.find()) { continue; } List<String> lineParts = new ArrayList<>(); for (int g = 0; g <= matcher.groupCount(); g++) { lineParts.add(matcher.group(g)); } results.add(lineParts); } return results; } /** * Match one regexp at a time. Remove the matched part from the string, trim, and match next * regexp on that string... */ public static List<String> getParts(String string, String... regexpList) { List<String> parts = new ArrayList<>(); for (String regexp : regexpList) { Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(string); boolean found = matcher.find(); if (!found) { return new ArrayList<>(); } String part = matcher.group(1).trim(); parts.add(part); string = string.replaceFirst(quote(matcher.group()), "").trim(); } return parts; } private ViolationParserUtils() {} }
true
e0406858d0b628a8129e486d86b306367c20129c
Java
shangtt/ELS-Server-
/Server/src/dataservice/profitdataservice/ProfitDataService.java
UTF-8
341
1.953125
2
[]
no_license
package dataservice.profitdataservice; import java.util.ArrayList; import po.profitPO.ProfitPO; public interface ProfitDataService { // public ProfitPO find(String name); public void add(ProfitPO pp); public void change(ProfitPO pp1, ProfitPO pp2); public void remove(ProfitPO pp); public ArrayList<ProfitPO> getProfitList(); }
true
1ef56331fd682d6b94494c00426ceba2b3859298
Java
LukaszBorucki/EasyKanban
/app/src/main/java/co/borucki/easykanban/statics/ImageBitmap.java
UTF-8
670
2.453125
2
[]
no_license
package co.borucki.easykanban.statics; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; public class ImageBitmap { public static byte[] decodeImageFromStringToByteArray(String image) { return Base64.decode(image, Base64.DEFAULT); } public static Bitmap decodeImageFromByteArrayToBitmap(byte[] image) { return BitmapFactory.decodeByteArray(image, 0, image.length); } public static Bitmap decodeImageFromStringToBitmap(String image) { byte[] byteArrayImage = decodeImageFromStringToByteArray(image); return decodeImageFromByteArrayToBitmap(byteArrayImage); } }
true
17327262a6ee9256ec9c926b4016b39ff4fcdf17
Java
sorydi3/HabitTrackerApp
/app/src/main/java/com/example/ibrah/habittraker/dataBase/ContractHabit.java
UTF-8
1,910
2.4375
2
[]
no_license
package com.example.ibrah.habittraker.dataBase; import android.provider.BaseColumns; /** * Created by ibrah on 21/07/2017. */ public final class ContractHabit { private ContractHabit() { } public static final class entryHabit implements BaseColumns { //-----------------TABLE NAME----------------- /** * Name of database table for habits */ public final static String TABLE_NAME = "rutine"; //----------ID----------------------- /** * Unique ID number for the pet (only for use in the database table). * <p> * Type: INTEGER */ public final static String _ID = BaseColumns._ID; //---------NAME----------------------- /** * Name of the user. * <p> * Type: TEXT */ public final static String NAME = "name"; //---------------GYM------------------------ /** * Gym. * <p> * Type: INTEGER */ public final static String COLUMN_GYM = "Gym"; /** * Time spended in Gym * <p> * Type: INTEGER */ public final static String TIME_GYM = "time"; /** * Possible answers of the user. */ public final static int GYM_YES = 1; public final static int GYM_NO = 0; // ---------------- RUNNING------------------------ /** * Running info. * <p> * Type: INTEGER */ public final static String COLUMN_RUNNING = "running"; /** * Running info. * <p> * Type: INTEGER */ public final static String DISTANCE = "distance"; /** * Possible answers of the user. */ public final static int RUNNING_YES = 1; public final static int RUNNING_NO = 0; } }
true
cc52a510477eea36e26fa9bb7eaf7f467a04aecd
Java
GeorgeBanica1990/testJPA
/src/test/java/queries/bulk/TestBulkSelectAndInsert.java
UTF-8
1,591
2.40625
2
[]
no_license
package queries.bulk; import org.junit.Before; import org.junit.Test; import org.unitils.reflectionassert.ReflectionAssert; import org.unitils.reflectionassert.ReflectionComparatorMode; import setup.TransactionalSetup; import java.util.ArrayList; import java.util.List; public class TestBulkSelectAndInsert extends TransactionalSetup { @Before public void before() { persist(buildModel()); flushAndClear(); } private List<BulkQueryEntity> buildModel() { List<BulkQueryEntity> list = new ArrayList<>(); for (int i = 1; i < 6; i++) { BulkQueryEntity entity = new BulkQueryEntity(); entity.setId(i); entity.setName("name " + i); entity.setValue(i * i); list.add(entity); } return list; } private List<BulkTarget> buildExpectedModel() { List<BulkTarget> list = new ArrayList<>(); for (int i = 1; i < 6; i++) { BulkTarget entity = new BulkTarget(); entity.setId(i); entity.setName("name " + i); list.add(entity); } return list; } @Test public void testSelectAndInsert() { // select and insert em.createQuery("insert into BulkTarget(id,name) select t.id, t.name from BulkQueryEntity t").executeUpdate(); flushAndClear(); // verify ReflectionAssert.assertReflectionEquals(buildExpectedModel(), em.createQuery("select t from BulkTarget t", BulkTarget.class).getResultList(), ReflectionComparatorMode.LENIENT_ORDER); } }
true
3e22d15f4e9de21d923c4e6946b3697418caec5d
Java
rashit-t-v/Pixabay-Latest-Photo
/app/src/main/java/com/rashit/tiugaev/image/activity/SplashActivity.java
UTF-8
1,149
2.109375
2
[]
no_license
package com.rashit.tiugaev.image.activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import com.rashit.tiugaev.image.HomeActivity; import com.rashit.tiugaev.image.R; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); new CountDownTimer(1000, 1000) { @Override public void onTick(long millisUntilFinished) { // do something after 1s } @Override public void onFinish() { // do something end times 5s final Intent intent = new Intent(getApplicationContext(), HomeActivity.class); startActivity(intent); } }.start(); } @Override protected void onPause() { super.onPause(); this.finish(); } @Override protected void onDestroy() { super.onDestroy(); finish(); } }
true
9ee4eec3c8457207d39e8283236991f7e65a4066
Java
shijianasdf/HibernateTest
/src/intercepts/myInterceptor.java
GB18030
6,008
2.15625
2
[]
no_license
package intercepts; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; import com.opensymphony.xwork2.ognl.OgnlValueStack; import com.opensymphony.xwork2.util.ValueStack; public class myInterceptor implements Interceptor { private static final long serialVersionUID = 1L; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init() { // TODO Auto-generated method stub } public String intercept(ActionInvocation invocation) throws Exception { System.out.println("============"+invocation.getInvocationContext().getName()); System.out.println("============"+invocation.getInvocationContext().getLocale()); System.out.println("============"+invocation.getInvocationContext().getParameters()); ActionContext act = invocation.getInvocationContext(); Map<String, Object> params = invocation.getInvocationContext().getParameters(); //String idName=""; ArrayList<String> parameters=new ArrayList<String>(); for(String key : params.keySet()) { //mapkeySet() keyӦmapеString Object obj = params.get(key); if(obj instanceof String[]) { String[] array = (String[])obj; System.out.print("Param: " + key + "values: "); for(String value : array) { System.out.print(value); //idName=value; parameters.add(value); } System.out.print("\n"); } } System.out.println(parameters); //System.out.println(idName); if(parameters.size()==0){ return invocation.invoke(); } if(parameters.get(2).contains("AM")&&!parameters.get(2).equals("AM")){ act.put("tableName", "array_matrix"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("AM")){ act.put("tableName", "array_matrix"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } if(parameters.get(2).contains("GM")&&!parameters.get(2).equals("GM")){ act.put("tableName", "general_matrix"); act.put("cols", "oneDesc,inputUser"); act.put("number", 2); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("GM")){ act.put("tableName", "general_matrix"); act.put("cols", "oneDesc,inputUser"); act.put("number", 2); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } if(parameters.get(2).contains("NT")&&!parameters.get(2).equals("NT")){ act.put("tableName", "network_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("NT")){ act.put("tableName", "network_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } if(parameters.get(2).contains("IT")&&!parameters.get(2).equals("IT")){ act.put("tableName", "interaction_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("IT")){ act.put("tableName", "interaction_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } if(parameters.get(2).contains("RT")&&!parameters.get(2).equals("RT")){ act.put("tableName", "region_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("RT")){ act.put("tableName", "region_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } if(parameters.get(2).contains("SM")&&!parameters.get(2).equals("SM")){ act.put("tableName", "seq_matrix"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("SM")){ act.put("tableName", "seq_matrix"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } if(parameters.get(2).contains("ST")&&!parameters.get(2).equals("ST")){ act.put("tableName", "super_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("ST")){ act.put("tableName", "super_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } if(parameters.get(2).contains("VT")&&!parameters.get(2).equals("VT")){ act.put("tableName", "vector_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "id"); act.put("v", parameters.get(2)); }else if(parameters.get(2).equals("VT")){ act.put("tableName", "vector_table"); act.put("cols", "oneDesc,inputUser,libraryType"); act.put("number", 3); act.put("searchColName", "oneDesc"); act.put("v", parameters.get(1)); } return invocation.invoke(); } }
true
3f779250b3585bcad95b3e84ffb94f542d3027c5
Java
davidozhang/MyLibraryManager
/src/mylibrarymanager/MyLibraryManager_Library.java
UTF-8
5,859
3.25
3
[]
no_license
package mylibrarymanager; /* * TIME STAMP: June 1, 2012 - * LAST EDITED/REVIEWED BY: David Zhang * REPORT: Everything good to go. */ import java.io.*; import java.util.*; import javax.swing.JFrame; import javax.swing.table.AbstractTableModel; /* * This section is a model on which the JTable in the database is built upon. It includes all the critical * methods that allow the JTable to manipulate its data and its cells. */ public class MyLibraryManager_Library extends AbstractTableModel{ public static Vector data; //very critical vector that stores all data within the table and is used among all the classes Vector columns; //stores all column information JFrame frame; private Object [][] values; //only used within this class to process editing private String[] columnNames = {"Unique Key", //set the column headers "Book Title", "Author Name", "Year Published", "Page Numbers", "Publisher", "Category", "Book Rating (/10)", }; /* MyLibraryManager_Library() * This method reads and obtains all the values for the core vector data * Pre: Reads from library.txt * Post: Stores the data as vector into vector data */ public MyLibraryManager_Library() { String line; data= new Vector(); columns= new Vector(); try { //reads the library.txt file, which contains all the data for the library FileInputStream fis = new FileInputStream("library.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); StringTokenizer st1 = new StringTokenizer(br.readLine(), "|"); //all data are stored using '|' as a separator while (st1.hasMoreTokens()) columns.addElement(st1.nextToken()); // obtains the information read in first row as the column headers while ((line = br.readLine()) != null) { StringTokenizer st2 = new StringTokenizer(line, "|"); while (st2.hasMoreTokens()) data.addElement(st2.nextToken()); //obtains all remaining information as useful information for the table } values=new Object[data.size()/8][8]; transferDataToValue(data); br.close();} catch (Exception e) { //tells the user in a user-friendly message if the 'library.txt' file is missing, and how to fix/add the file System.out.println("Notice from MyLibraryManager: Please repair or add file 'library.txt' into the workspace folder " + "of MyLibraryManager to continue program operation."); System.out.println("Add the following line into 'library.txt': Unique|Title|Author|Year|Pages|Publisher|Category|Rating|"); System.out.println("Then add two blank lines, and add a single integer which indicates the initial unique key number for the library"); System.out.println("You may close the file."); System.exit(0); } }//MyLibraryManager_Library() /* transferDataToValue() * This method transfers the vector data into an array for editing processing * Pre: // * Post: Transfers vector into an array */ private void transferDataToValue(Vector data) { //transfers the vector data into the 2-d array for use in processing editing only int k=0; for (int i=0; i<data.size()/8;i++) { for (int j=0; j<8;j++) { values[i][j]=data.elementAt(k); k++; } } }//transferDataToValue() /* setValueAt() * This method saves the edited value for cells immediately * Pre: User changes the value of a cell * Post: The value is saved on the interface and in library.txt */ public void setValueAt(Object aValue, int rowIndex, int columnIndex) { values[rowIndex][columnIndex]=aValue; //the values array is immediately changed if a change in a cell is detected fireTableDataChanged(); //the table is notified of change, and immediately changes the interface data.set(rowIndex*8+columnIndex,((String) values[rowIndex][columnIndex]).trim()); //the core data is also changed immediately MyLibraryManager_Administrator.updateFile(data); //the library.txt file is immediately updated }//setValueAt() public int getRowCount() { //get the number of rows depending on the size of data divided by number of columns return data.size() / getColumnCount(); } public int getColumnCount() { //get the number of columns return columns.size(); } /* getValueAt() * This method gets the value of every cell * Pre: // * Post: returns the most updated values for all cells */ public Object getValueAt(int rowIndex, int columnIndex) { //get the value of each cell if (MyLibraryManager_Administrator.dataChanged==false) { //if data is changed by admin, the table will be notified immediately fireTableDataChanged(); MyLibraryManager_Administrator.dataChanged=true; } return (String) values[rowIndex][columnIndex]; //returns the value as an array }//getValueAt() public String getColumnName(int col) { //gets column header names return columnNames[col]; } /* isCellEditable() * This method determines which cells are editable and which are not * Pre: // * Post: For administrator, all cells except the unique key column can be edited; otherwise, all cells cannot be edited */ public boolean isCellEditable(int row, int col) { if (MyLibraryManager_LogIn.globalAccount.equalsIgnoreCase("Admin")) { //only the first column is ineditable for admin if (col==0) return false; else return true; //everything else is editable } else { //normal user cannot edit any cell return false; } }//isCellEditable() }
true
6a7af89d0e75506a9591ac96b188fd0e0bacd754
Java
krishnanand5/DebateNav
/MyApplication/app/src/main/java/com/example/android/myapplication/MainActivity.java
UTF-8
7,171
2
2
[]
no_license
package com.example.android.myapplication; import android.app.Dialog; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private float x1,x2; static final int MIN_DISTANCE = 150; public static final String MSG="com.example.android.MSG"; List<Planet> planetsList = new ArrayList<Planet>(); PlanetAdapter aAdpt; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initList(); // We get the ListView component from the layout ListView lv = (ListView) findViewById(R.id.listView); lv.setDivider(this.getResources().getDrawable(R.drawable.transperent_color)); lv.setDividerHeight(20); // This is a simple adapter that accepts as parameter // Context // Data list // The row layout that is used during the row creation // The keys used to retrieve the data // The View id used to show the data. The key number and the view id must match //aAdpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, planetsList); aAdpt = new PlanetAdapter(planetsList, this); lv.setAdapter(aAdpt); // React to user clicks on item lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id) { // We know the View is a <extView so we can cast it TextView clickedView = (TextView) view.findViewById(R.id.name); ListView lv1=(ListView)findViewById(R.id.listView); String msg=((TextView)findViewById(R.id.name)).getText().toString(); Intent intent=new Intent(view.getContext() , com.example.android.myapplication.SecondActivity.class); intent.putExtra(MSG,msg); startActivity(intent); } }); // we register for the contextmneu registerForContextMenu(lv); // TextFilter lv.setTextFilterEnabled(true); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } // We want to create a context Menu when the user long click on an item @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo aInfo = (AdapterView.AdapterContextMenuInfo) menuInfo; // We know that each row in the adapter is a Map Planet planet = aAdpt.getItem(aInfo.position); menu.setHeaderTitle("Options for " + planet.getName()); menu.add(1, 2, 2, "Delete"); } // This method is called when user selects an Item in the Context menu @Override public boolean onContextItemSelected(MenuItem item) { int itemId = item.getItemId(); AdapterView.AdapterContextMenuInfo aInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); planetsList.remove(aInfo.position); aAdpt.notifyDataSetChanged(); return true; } private void initList() { // We populate the planets } // Handle user click public void addPlanet(View view) { final Dialog d = new Dialog(this); d.setContentView(R.layout.dialog); d.setTitle("Add Topic"); d.setCancelable(true); final EditText edit = (EditText) d.findViewById(R.id.editTextPlanet); Button b = (Button) d.findViewById(R.id.button1); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String planetName = edit.getText().toString(); MainActivity.this.planetsList.add(new Planet(planetName)); MainActivity.this.aAdpt.notifyDataSetChanged(); // We notify the data model is changed d.dismiss(); } }); d.show(); } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app URL is correct. Uri.parse("android-app://com.example.android.myapplication/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app URL is correct. Uri.parse("android-app://com.example.android.myapplication/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } }
true
472c68705b33c8f4da49bef2a4af814c1ea67f6c
Java
MartimAndersen/ShareNCare
/ShareNCare/app/src/main/java/pt/unl/fct/di/example/sharencare/common/rank/RankMethods.java
UTF-8
1,015
2.28125
2
[]
no_license
package pt.unl.fct.di.example.sharencare.common.rank; import com.google.gson.Gson; import com.google.gson.internal.LinkedTreeMap; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import retrofit2.Response; import okhttp3.ResponseBody; public class RankMethods { public static Gson gson = new Gson(); public static List<PointsData> getTopUsers(Response<ResponseBody> r){ List<PointsData> users = new ArrayList<>(); try { JSONArray array = new JSONArray(r.body().string()); Type t = new TypeToken<List<PointsData>>(){}.getType(); users = gson.fromJson(array.toString(), t); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return users; } }
true
54e1dace2868957804520750e0b6c1e718fcb882
Java
kjetilkl/motiflab
/src/main/java/motiflab/engine/data/analysis/CompareRegionDatasetsAnalysis.java
UTF-8
34,299
2.078125
2
[]
no_license
/* */ package motiflab.engine.data.analysis; import de.erichseifert.vectorgraphics2d.EPSGraphics2D; import de.erichseifert.vectorgraphics2d.PDFGraphics2D; import de.erichseifert.vectorgraphics2d.SVGGraphics2D; import de.erichseifert.vectorgraphics2d.VectorGraphics2D; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DecimalFormat; import motiflab.engine.data.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Future; import javax.imageio.ImageIO; import motiflab.engine.task.ExecutableTask; import motiflab.engine.ExecutionError; import motiflab.engine.Graph; import motiflab.engine.task.OperationTask; import motiflab.engine.ParameterSettings; import motiflab.engine.MotifLabEngine; import motiflab.engine.Parameter; import motiflab.engine.TaskRunner; import motiflab.engine.dataformat.DataFormat; import motiflab.gui.VisualizationSettings; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; /** * * @author kjetikl */ public class CompareRegionDatasetsAnalysis extends Analysis { private final static String typedescription="Analysis: compare region datasets"; private final static String analysisName="compare region datasets"; private final static String description="Compares one Region Dataset to another and returns nucleotide level statistics of their similarity"; private int nTP=0,nFP=0,nFN=0,nTN=0; private int sTP=0,sFP=0,sFN=0,sTN=0; // reserved for later use... HashMap<String,Double> storage=new HashMap<String, Double>(); private double siteOverlapFraction=0.25; // minimum overlap required to call a True Positive on the site level private String predictionTrackName=null; private String answerTrackName=null; private String sequenceCollectionName=null; private int sequenceCollectionSize=0; private final String[] variables = new String[]{"nTP","nFP","nTN","nFN","nSn","nSp","nPPV","nNPV","nASP","nPC","nF","nAcc","nCC"}; public CompareRegionDatasetsAnalysis() { this.name="CompareRegionDatasetsAnalysis_temp"; addParameter("First",RegionDataset.class, null,new Class[]{RegionDataset.class},"A 'prediction dataset'",true,false); addParameter("Second",RegionDataset.class, null,new Class[]{RegionDataset.class},"A second region dataset that the first dataset will be compared against ('answer dataset')",true,false); addParameter("Sequences",SequenceCollection.class, null,new Class[]{SequenceCollection.class},"If provided, the analysis will be limited to the sequences in the given collection",false,false); } /** Returns a list of output parameters that can be set when an Analysis is output */ @Override public Parameter[] getOutputParameters() { Parameter imageformat=new Parameter("Image format",String.class, "png",new String[]{"png","svg","pdf","eps"},"The image format to use for the graph",false,false); Parameter scalepar=new Parameter("Graph scale",Integer.class,100,new Integer[]{10,2000},"Scale of graphics plot (in percent)",false,false); return new Parameter[]{imageformat,scalepar}; } @Override public String[] getOutputParameterFilter(String parameter) { if (parameter.equals("Graph scale") || parameter.equals("Image format")) return new String[]{"HTML"}; return null; } @Override public String[] getSourceProxyParameters() {return new String[]{"First","Second"};} @Override public String getAnalysisName() { return analysisName; } @Override public String getDescription() {return description;} @Override public String[] getResultVariables() { return variables; } @Override public Data getResult(String variablename, MotifLabEngine engine) throws ExecutionError { if (variablename.equals("nTP")) return new NumericVariable("result", nTP); else if (variablename.equals("nFP")) return new NumericVariable("result", nFP); else if (variablename.equals("nTN")) return new NumericVariable("result", nTN); else if (variablename.equals("nFN")) return new NumericVariable("result", nFN); if (storage!=null && storage.containsKey(variablename)) return new NumericVariable("result", storage.get(variablename)); else throw new ExecutionError("'"+getName()+"' does not have a result for '"+variablename+"'"); } @Override public Class getResultType(String variablename) { if (!hasResult(variablename)) return null; else return NumericVariable.class; // all exported values in this analysis are numerical } private double getStatistic(String name) { if (storage!=null && storage.containsKey(name)) return storage.get(name); else return Double.NaN; } @Override @SuppressWarnings("unchecked") public CompareRegionDatasetsAnalysis clone() { CompareRegionDatasetsAnalysis newanalysis=new CompareRegionDatasetsAnalysis(); super.cloneCommonSettings(newanalysis); newanalysis.storage=(HashMap<String,Double>)this.storage.clone(); newanalysis.nTP=this.nTP; newanalysis.nFP=this.nFP; newanalysis.nTN=this.nTN; newanalysis.nFN=this.nFN; newanalysis.sTP=this.sTP; newanalysis.sFP=this.sFP; newanalysis.sTN=this.sTN; newanalysis.sFN=this.sFN; newanalysis.siteOverlapFraction=this.siteOverlapFraction; newanalysis.predictionTrackName=this.predictionTrackName; newanalysis.answerTrackName=this.answerTrackName; newanalysis.sequenceCollectionName=this.sequenceCollectionName; newanalysis.sequenceCollectionSize=this.sequenceCollectionSize; return newanalysis; } @Override @SuppressWarnings("unchecked") public void importData(Data source) throws ClassCastException { super.importData(source); this.storage=((CompareRegionDatasetsAnalysis)source).storage; this.nTP=((CompareRegionDatasetsAnalysis)source).nTP; this.nFP=((CompareRegionDatasetsAnalysis)source).nFP; this.nTN=((CompareRegionDatasetsAnalysis)source).nTN; this.nFN=((CompareRegionDatasetsAnalysis)source).nFN; this.sTP=((CompareRegionDatasetsAnalysis)source).sTP; this.sFP=((CompareRegionDatasetsAnalysis)source).sFP; this.sTN=((CompareRegionDatasetsAnalysis)source).sTN; this.sFN=((CompareRegionDatasetsAnalysis)source).sFN; this.siteOverlapFraction=((CompareRegionDatasetsAnalysis)source).siteOverlapFraction; this.predictionTrackName=((CompareRegionDatasetsAnalysis)source).predictionTrackName; this.answerTrackName=((CompareRegionDatasetsAnalysis)source).answerTrackName; this.sequenceCollectionName=((CompareRegionDatasetsAnalysis)source).sequenceCollectionName; this.sequenceCollectionSize=((CompareRegionDatasetsAnalysis)source).sequenceCollectionSize; } public static String getType() {return typedescription;} @Override public String getDynamicType() { return typedescription; } @Override public String getTypeDescription() {return typedescription;} @Override public OutputData formatHTML(OutputData outputobject, MotifLabEngine engine, ParameterSettings settings, ExecutableTask task, DataFormat format) throws ExecutionError, InterruptedException { double nSn=getStatistic("nSn"); double nSp=getStatistic("nSp"); double nPPV=getStatistic("nPPV"); double nNPV=getStatistic("nNPV"); double nPC=getStatistic("nPC"); double nASP=getStatistic("nASP"); double nF=getStatistic("nF"); double nAcc=getStatistic("nAcc"); double nCC=getStatistic("nCC"); int scalepercent=100; String imageFormat="png"; if (format!=null) format.setProgress(5); if (settings!=null) { try { Parameter[] defaults=getOutputParameters(); imageFormat=(String)settings.getResolvedParameter("Image format",defaults,engine); scalepercent=(Integer)settings.getResolvedParameter("Graph scale",defaults,engine); } catch (ExecutionError e) {throw e;} catch (Exception ex) {throw new ExecutionError("An error occurred during output formatting", ex);} } double scale=(scalepercent==100)?1.0:(((double)scalepercent)/100.0); File imagefile=outputobject.createDependentFile(engine,imageFormat); Object dimension=null; try { dimension=createGraphImage(imagefile, scale, engine.getClient().getVisualizationSettings()); } catch (IOException e) { engine.errorMessage("An error occurred when creating image file: "+e.toString(),0); } if (format!=null) format.setProgress(50); DecimalFormat formatter=new DecimalFormat("#.###"); DecimalFormat decimalFormatter=new DecimalFormat("#.#"); engine.createHTMLheader("Compare Region Datasets Analysis", null, null, true, true, true, outputobject); double total=nTP+nFP+nTN+nFN; outputobject.append("<div align=\"center\">\n<h2 class=\"headline\">Comparing '"+predictionTrackName+"' against '"+answerTrackName+"'</h2>\n",HTML); outputobject.append("Analysis based on "+sequenceCollectionSize+" sequence"+((sequenceCollectionSize!=1)?"s":""),HTML); if (sequenceCollectionName!=null) outputobject.append(" from collection <span class=\"dataitem\">"+sequenceCollectionName+"</span>",HTML); outputobject.append("<br><br>\n<h2>Base Counts</h2>\n<table class=\"sortable\">\n",HTML); outputobject.append("<tr><th width=\"60\">TP</th><th width=\"60\">FP</th><th width=\"60\">TN</th><th width=\"60\">FN</th></tr>\n",HTML); outputobject.append("<tr><td style=\"text-align:center\">"+nTP+"</td><td style=\"text-align:center\">"+nFP+"</td><td style=\"text-align:center\">"+nTN+"</td><td style=\"text-align:center\">"+nFN+"</td></tr>",HTML); outputobject.append("<tr><td style=\"text-align:center\">"+decimalFormatter.format(nTP/total*100)+"%</td><td style=\"text-align:center\">"+decimalFormatter.format(nFP/total*100)+"%</td><td style=\"text-align:center\">"+decimalFormatter.format(nTN/total*100)+"%</td><td style=\"text-align:center\">"+decimalFormatter.format(nFN/total*100)+"%</td></tr>\n",HTML); outputobject.append("</table>\n<br />\n",HTML); outputobject.append("<h2>Statistics</h2>\n<table class=\"sortable\">\n",HTML); outputobject.append("<tr><th width=\"60\">SN</th><th width=\"60\">SP</th><th width=\"60\">PPV</th><th width=\"60\">NPV</th><th width=\"60\">PC</th><th width=\"60\">ASP</th><th width=\"60\">F</th><th width=\"60\">Acc</th><th width=\"60\">CC</th></tr>\n",HTML); outputobject.append("<tr><td style=\"text-align:center\">"+((Double.isNaN(nSn))?"-":formatter.format(nSn))+"</td><td style=\"text-align:center\">"+((Double.isNaN(nSp))?"-":formatter.format(nSp))+"</td><td style=\"text-align:center\">"+((Double.isNaN(nPPV))?"-":formatter.format(nPPV))+"</td><td style=\"text-align:center\">"+((Double.isNaN(nNPV))?"-":formatter.format(nNPV))+"</td><td style=\"text-align:center\">"+((Double.isNaN(nPC))?"-":formatter.format(nPC))+"</td>" + "<td style=\"text-align:center\">"+((Double.isNaN(nASP))?"-":formatter.format(nASP))+"</td>" + "<td style=\"text-align:center\">"+((Double.isNaN(nF))?"-":formatter.format(nF))+"</td>" + "<td style=\"text-align:center\">"+((Double.isNaN(nAcc))?"-":formatter.format(nAcc))+"</td><td style=\"text-align:center\">"+((Double.isNaN(nCC))?"-":formatter.format(nCC))+"</td></tr>\n</table>\n",HTML); outputobject.append("<br><br>\n",HTML); if (imageFormat.equals("pdf")) outputobject.append("<object type=\"application/pdf\" data=\"file:///"+imagefile.getAbsolutePath()+"\"></object>",HTML); else { outputobject.append("<img src=\"file:///"+imagefile.getAbsolutePath()+"\"",HTML); if (dimension instanceof Dimension) { int width=((Dimension)dimension).width; int height=((Dimension)dimension).height; outputobject.append(" width="+(int)Math.ceil(width*scale)+" height="+(int)Math.ceil(height*scale),HTML); } outputobject.append(" />\n<br>\n",HTML); } outputobject.append("<br>\n",HTML); outputobject.append(decimalFormatter.format(nPPV*100)+"% of <span class=\"dataitem\">"+predictionTrackName+"</span> overlaps with <span class=\"dataitem\">"+answerTrackName+"</span> (PPV)<br>\n",HTML); outputobject.append(decimalFormatter.format(nSn*100)+"% of <span class=\"dataitem\">"+answerTrackName+"</span> overlaps with <span class=\"dataitem\">"+predictionTrackName+"</span> (SN)&nbsp;<br>\n",HTML); outputobject.append("The relative overlap is "+decimalFormatter.format(nPC*100)+"% with respect to both tracks (Performance Coefficient)<br>",HTML); outputobject.append("</div>\n",HTML); outputobject.append("</body>\n</html>\n",HTML); if (format!=null) format.setProgress(100); return outputobject; } private Object createGraphImage(File file, double scale, VisualizationSettings settings) throws IOException { String[] legends=new String[]{"Overlap (TP)","Unique to "+predictionTrackName+" (FP)","Unique to "+answerTrackName+" (FN)","Background (TN)"}; Font font=settings.getSystemFont("graph.legendFont"); Dimension legendsdim=Graph.getLegendDimension(legends, font); int pieChartSize=160; // int pieMargin=40; int margin=5; int width=pieChartSize+legendsdim.width+pieMargin+margin+margin; int height=Math.max(pieChartSize,legendsdim.height)+margin+margin; // image height if (file!=null) { if (file.getName().endsWith(".png")) { // bitmap PNG format BufferedImage image=new BufferedImage((int)Math.ceil(width*scale),(int)Math.ceil(height*scale), BufferedImage.TYPE_INT_RGB); Graphics2D g=image.createGraphics(); paintGraphImage(g, scale, width, height, pieChartSize, margin, pieMargin, legends, legendsdim, settings); OutputStream output=MotifLabEngine.getOutputStreamForFile(file); ImageIO.write(image, "png", output); output.close(); g.dispose(); return new Dimension(width,height); } else { // vector format VectorGraphics2D g=null; String filename=file.getName(); if (filename.endsWith(".svg")) g = new SVGGraphics2D(0, 0, Math.ceil(width*scale), Math.ceil(height*scale)); else if (filename.endsWith(".pdf")) g = new PDFGraphics2D(0, 0, Math.ceil(width*scale), Math.ceil(height*scale)); else if (filename.endsWith(".eps")) g = new EPSGraphics2D(0, 0, Math.ceil(width*scale), Math.ceil(height*scale)); g.setClip(0, 0, (int)Math.ceil(width*scale),(int)Math.ceil(height*scale)); paintGraphImage(g, scale, width, height, pieChartSize, margin, pieMargin, legends, legendsdim, settings); FileOutputStream fileStream = new FileOutputStream(file); try { fileStream.write(g.getBytes()); } finally { fileStream.close(); } return new Dimension(width,height); } } else { // No output file. Create the image as a byte[] array for inclusion in Excel BufferedImage image=new BufferedImage((int)Math.ceil(width*scale),(int)Math.ceil(height*scale), BufferedImage.TYPE_INT_RGB); Graphics2D g=image.createGraphics(); paintGraphImage(g, scale, width, height, pieChartSize, margin, pieMargin, legends, legendsdim, settings); g.dispose(); return image; } } private void paintGraphImage(Graphics2D g, double scale, int width, int height, int pieChartSize, int margin, int pieMargin, String[] legends, Dimension legendsdim, VisualizationSettings settings) throws IOException { Color firstTrackColor=settings.getForeGroundColor(predictionTrackName); Color secondTrackColor=settings.getForeGroundColor(answerTrackName); Color blendColor=blendColors(firstTrackColor, secondTrackColor); Color[] colors=new Color[]{secondTrackColor,blendColor,firstTrackColor,Color.WHITE}; g.scale(scale, scale); g.setColor(java.awt.Color.WHITE); g.fillRect(0, 0, width, height); g.drawRect(0, 0, width, height); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // draw piechart int translateY=margin; int legendY=(int)((height-legendsdim.height)/2)+margin; if (legendsdim.height>pieChartSize) { translateY=(int)((legendsdim.height-pieChartSize)/2.0)+margin; legendY=margin; } Graph piechart=new Graph(g, 0, 1, 0, 1, pieChartSize, pieChartSize, margin, translateY); piechart.drawPieChart(new double[]{nFN,nTP, nFP,nTN}, colors, true); Font legendFont=settings.getSystemFont("graph.legendFont"); g.setFont(legendFont); piechart.drawLegendBox(legends, new Color[]{blendColor,firstTrackColor,secondTrackColor,Color.WHITE}, pieChartSize+pieMargin, legendY, true); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } private Color blendColors (Color color1, Color color2) { float[] HSB1=Color.RGBtoHSB(color1.getRed(), color1.getGreen(), color1.getBlue(), null); float[] HSB2=Color.RGBtoHSB(color2.getRed(), color2.getGreen(), color2.getBlue(), null); float minH=(HSB1[0]<HSB2[0])?HSB1[0]:HSB2[0]; float maxH=(HSB1[0]>HSB2[0])?HSB1[0]:HSB2[0]; float distUP=maxH-minH; float distDOWN=(1-maxH+minH); float newH=0; if (distUP<=distDOWN) { newH=minH+distUP/2.0f; } else { newH=minH-distDOWN/2.0f; } if (newH<0) newH=1+newH; // if (newH>=1) newH=newH-1; // return Color.getHSBColor(newH, (HSB1[1]+HSB2[1])/2.0f, (HSB1[2]+HSB2[2])/2.0f); } @Override public OutputData formatRaw(OutputData outputobject, MotifLabEngine engine, ParameterSettings settings, ExecutableTask task, DataFormat format) throws ExecutionError, InterruptedException { double nSn=getStatistic("nSn"); double nSp=getStatistic("nSp"); double nPPV=getStatistic("nPPV"); double nNPV=getStatistic("nNPV"); double nPC=getStatistic("nPC"); double nASP=getStatistic("nASP"); double nF=getStatistic("nF"); double nAcc=getStatistic("nAcc"); double nCC=getStatistic("nCC"); outputobject.append("#Comparing '"+predictionTrackName+"' against '"+answerTrackName+"'\n",RAWDATA); outputobject.append("#Analysis based on "+sequenceCollectionSize+" sequence"+((sequenceCollectionSize!=1)?"s":""),RAWDATA); if (sequenceCollectionName!=null) outputobject.append(" from collection '"+sequenceCollectionName+"'",RAWDATA); outputobject.append("\n",RAWDATA); outputobject.append("nTP="+nTP+"\n",RAWDATA); outputobject.append("nFP="+nFP+"\n",RAWDATA); outputobject.append("nTN="+nTN+"\n",RAWDATA); outputobject.append("nFN="+nFN+"\n",RAWDATA); outputobject.append("nSn="+((Double.isNaN(nSn))?"-":nSn)+"\n",RAWDATA); outputobject.append("nSp="+((Double.isNaN(nSp))?"-":nSp)+"\n",RAWDATA); outputobject.append("nPPV="+((Double.isNaN(nPPV))?"-":nPPV)+"\n",RAWDATA); outputobject.append("nNPV="+((Double.isNaN(nNPV))?"-":nNPV)+"\n",RAWDATA); outputobject.append("nPC="+((Double.isNaN(nPC))?"-":nPC)+"\n",RAWDATA); outputobject.append("nASP="+((Double.isNaN(nASP))?"-":nASP)+"\n",RAWDATA); outputobject.append("nF="+((Double.isNaN(nASP))?"-":nF)+"\n",RAWDATA); outputobject.append("nAcc="+((Double.isNaN(nAcc))?"-":nAcc)+"\n",RAWDATA); outputobject.append("nCC="+((Double.isNaN(nCC))?"-":nCC)+"\n",RAWDATA); if (format!=null) format.setProgress(100); return outputobject; } @Override public OutputData formatExcel(OutputData outputobject, MotifLabEngine engine, ParameterSettings settings, ExecutableTask task, DataFormat format) throws ExecutionError, InterruptedException { Workbook workbook=null; try { InputStream stream = CompareRegionDatasetsAnalysis.class.getResourceAsStream("resources/AnalysisTemplate_CompareRegionDatasets.xlt"); workbook = WorkbookFactory.create(stream); stream.close(); Sheet sheet = workbook.getSheetAt(0); // just use the first sheet sheet.setForceFormulaRecalculation(true); sheet.getRow(17).getCell(1).setCellValue(predictionTrackName); sheet.getRow(18).getCell(1).setCellValue(answerTrackName); sheet.getRow(7).getCell(1).setCellValue(nTP); sheet.getRow(7).getCell(2).setCellValue(nFP); sheet.getRow(7).getCell(3).setCellValue(nTN); sheet.getRow(7).getCell(4).setCellValue(nFN); String numberOfSequencesString="Analysis based on "+sequenceCollectionSize+" sequence"+((sequenceCollectionSize==1)?"":"s"); if (sequenceCollectionName!=null) numberOfSequencesString+=" from collection \""+sequenceCollectionName+"\""; sheet.getRow(2).getCell(1).setCellValue(numberOfSequencesString); // HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook); } catch (Exception e) { throw new ExecutionError(e.getMessage()); } // now write to the outputobject. The binary Excel file is included as a dependency in the otherwise empty OutputData object. File excelFile=outputobject.createDependentBinaryFile(engine,"xls"); try { BufferedOutputStream stream=new BufferedOutputStream(new FileOutputStream(excelFile)); workbook.write(stream); stream.close(); } catch (Exception e) { throw new ExecutionError("An error occurred when creating the Excel file: "+e.toString(),0); } outputobject.setBinary(true); outputobject.setDirty(true); // this is not set automatically since I don't append to the document outputobject.setDataFormat(EXCEL); // this is not set automatically since I don't append to the document return outputobject; } @Override public void runAnalysis(OperationTask task) throws Exception { RegionDataset prediction=(RegionDataset)task.getParameter("First"); RegionDataset answer=(RegionDataset)task.getParameter("Second"); predictionTrackName=prediction.getName(); answerTrackName=answer.getName(); SequenceCollection sequenceCollection=(SequenceCollection)task.getParameter("Sequences"); if (sequenceCollection==null) sequenceCollection=task.getEngine().getDefaultSequenceCollection(); if (sequenceCollection.getName().equals(task.getEngine().getDefaultSequenceCollectionName())) sequenceCollectionName=null; else sequenceCollectionName=sequenceCollection.getName(); ArrayList<Sequence> sequences=sequenceCollection.getAllSequences(task.getEngine()); sequenceCollectionSize=sequences.size(); TaskRunner taskRunner=task.getEngine().getTaskRunner(); task.setProgress(0L,sequenceCollectionSize); long[] counters=new long[]{0,0,sequenceCollectionSize}; // counters[0]=motifs started, [1]=motifs completed, [2]=total number of motifs ArrayList<ProcessSequenceTask> processTasks=new ArrayList<ProcessSequenceTask>(sequenceCollectionSize); for (int i=0;i<sequenceCollectionSize;i++) { String sequenceName=sequences.get(i).getName(); processTasks.add(new ProcessSequenceTask(prediction, answer, sequenceName, task, counters)); } List<Future<String>> futures=null; int countOK=0; try { futures=taskRunner.invokeAll(processTasks); // this call apparently blocks until all tasks finish (either normally or by exceptions or being cancelled) for (Future<String> future:futures) { if (future.isDone() && !future.isCancelled()) { future.get(); // this blocks until completion but the return value is not used countOK++; } } } catch (Exception e) { taskRunner.shutdownNow(); // Note: this will abort all executing tasks (even those that did not cause the exception), but that is OK. if (e instanceof java.util.concurrent.ExecutionException) throw (Exception)e.getCause(); else throw e; } if (countOK!=sequenceCollectionSize) { throw new ExecutionError("Some mysterious error occurred while performing analysis: "+getAnalysisName()); } double nSn=(nTP+nFN==0)?Double.NaN:(double)nTP/(double)(nTP+nFN); double nSp=(nTN+nFP==0)?Double.NaN:(double)nTN/(double)(nTN+nFP); double nPPV=(nTP+nFP==0)?Double.NaN:(double)nTP/(double)(nTP+nFP); double nNPV=(nTN+nFN==0)?Double.NaN:(double)nTN/(double)(nTN+nFN); double nPC=(nTP+nFN+nFP==0)?Double.NaN:(double)nTP/(double)(nTP+nFN+nFP); double nASP=(Double.isNaN(nSn) || Double.isNaN(nPPV))?Double.NaN:(nSn+nPPV)/2f; double nAcc=(double)(nTP+nTN)/(double)(nTP+nFP+nTN+nFN); double nCC=MotifLabEngine.calculateMatthewsCorrelationCoefficient(nTP,nFP,nTN,nFN); double sSn=(sTP+sFN==0)?Double.NaN:(double)sTP/(double)(sTP+sFN); double sPPV=(sTP+sFP==0)?Double.NaN:(double)sTP/(double)(sTP+sFP); double sASP=(Double.isNaN(sSn) || Double.isNaN(sPPV))?Double.NaN:(sSn+sPPV)/2f; double sPC=(sTP+sFN+sFP==0)?Double.NaN:(double)sTP/(double)(sTP+sFN+sFP); double sF=0; if (Double.isNaN(sSn) || Double.isNaN(sPPV)) sF=Double.NaN; else if (sSn>0 && sPPV>0) sF=(2.0*sSn*sPPV)/(sSn+sPPV); double nF=0; if (Double.isNaN(nSn) || Double.isNaN(nPPV)) nF=Double.NaN; else if (nSn>0 && nPPV>0) nF=(2.0*nSn*nPPV)/(nSn+nPPV); storage.put("nSn",nSn); storage.put("nSp",nSp); storage.put("nPPV",nPPV); storage.put("nNPV",nNPV); storage.put("nPC",nPC); storage.put("nASP",nASP); storage.put("nF",nF); storage.put("nAcc",nAcc); storage.put("nCC",nCC); storage.put("sSn",sSn); storage.put("sPPV",sPPV); storage.put("sASP",sASP); storage.put("sPC",sPC); storage.put("sF",sF); } private int[] processSequence(RegionSequenceData predictionSequence, RegionSequenceData answerSequence) { int[] results=countTrueFalse(predictionSequence, answerSequence); return results; } protected class ProcessSequenceTask implements Callable<String> { final String sequenceName; final RegionDataset prediction; final RegionDataset answer; final long[] counters; // counters[0]=sequences started, [1]=sequences completed, [2]=total number of sequences. NB: this array will be shared with other tasks since all tasks are given the same pointer final OperationTask task; public ProcessSequenceTask(RegionDataset prediction, RegionDataset answer, String sequenceName, OperationTask task, long[] counters) { this.sequenceName=sequenceName; this.prediction=prediction; this.answer=answer; this.counters=counters; this.task=task; } @Override @SuppressWarnings("unchecked") public String call() throws Exception { synchronized(counters) { counters[0]++; // number of sequences started } task.checkExecutionLock(); // checks to see if this task should suspend execution if (Thread.interrupted() || task.getStatus().equals(ExecutableTask.ABORTED)) throw new InterruptedException(); RegionSequenceData predictionSequence=(RegionSequenceData)prediction.getSequenceByName(sequenceName); RegionSequenceData answerSequence=(RegionSequenceData)answer.getSequenceByName(sequenceName); int[] results=processSequence(predictionSequence,answerSequence); synchronized(counters) { // finished one of the sequences counters[1]++; // number of sequences completed nTP+=results[0]; nFP+=results[1]; nTN+=results[2]; nFN+=results[3]; if (results.length>=7) { sTP=results[4]; sFP=results[5]; sFN=results[6]; } if (results.length>=8) {sTN=results[7];} task.setStatusMessage("Executing analysis: "+getAnalysisName()+" ("+counters[1]+"/"+counters[2]+")"); task.setProgress(counters[1],counters[2]); } if (Thread.interrupted() || task.getStatus().equals(ExecutableTask.ABORTED)) throw new InterruptedException(); return sequenceName; } } /** count the number of TP, FP, TN and FN in a sequence*/ // private int[] countTrueFalse_old(RegionSequenceData prediction, RegionSequenceData answer) { // int[] results= new int[]{0,0,0,0}; // for (int i=0;i<prediction.getSize();i++) { // boolean hit1=prediction.isWithinRegion(i); // boolean hit2=answer.isWithinRegion(i); // if (hit1 && hit2) results[0]++; // a TP // else if (hit1 && !hit2) results[1]++; // a FP // else if (!hit1 && !hit2) results[2]++; // a TN // else if (!hit1 && hit2) results[3]++; // a FN // } // return results; // } /** count the number of TP, FP, TN and FN in a sequence */ /* This implementation is a new optimized version compared to the old method above. It flattens sections into int[] buffers * which are then compared position by position by a tight loop, rather than calling isWithinRegion(pos) for each position. * isWithinRegion(pos) is currently very slow since it always searches from the beginning of the region list to determine * if the position is overlapped by a region which results in a O(n^2) running time and poor scaling */ private int[] countTrueFalse(RegionSequenceData prediction, RegionSequenceData answer) { int[] results= new int[]{0,0,0,0}; int buffersize=10000; int sequenceSize=prediction.getSize(); if (sequenceSize<buffersize) buffersize=sequenceSize; int[] buffer1=new int[buffersize]; int[] buffer2=new int[buffersize]; int bufferstart=0; for (int pos=0;pos<sequenceSize;pos++) { if (pos%buffersize==0) { // flatten new segment int bufferend=bufferstart+buffersize-1; if (bufferend>sequenceSize-1) bufferend=sequenceSize-1; buffer1=prediction.flattenSegment(buffer1, bufferstart, bufferend); buffer2=answer.flattenSegment(buffer2, bufferstart, bufferend); bufferstart+=buffersize; } boolean hit1=buffer1[pos%buffersize]>0; boolean hit2=buffer2[pos%buffersize]>0; if (hit1 && hit2) results[0]++; // a TP else if (hit1 && !hit2) results[1]++; // a FP else if (!hit1 && !hit2) results[2]++; // a TN else if (!hit1 && hit2) results[3]++; // a FN } return results; } @Override protected Dimension getDefaultDisplayPanelDimensions() { return new Dimension(600,606); } // ------------ Serialization --------- private static final long serialVersionUID = 1L; private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { short currentinternalversion=2; // this is an internal version number for serialization of objects of this type out.writeShort(currentinternalversion); out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { short currentinternalversion=in.readShort(); // the internalversion number is used to determine correct format of data if (currentinternalversion==1) { in.defaultReadObject(); // this will fail... } else if (currentinternalversion==2) { in.defaultReadObject(); } else if (currentinternalversion>2) throw new ClassNotFoundException("Newer version"); } }
true
678c72bf171ef158f1e16f93945fe919a0431901
Java
jgmatu/IWCN_spring_testing
/ManagementProductsAPIRestServerTesting/src/main/java/es/urjc/javsan/master/controllers/ProductsController.java
UTF-8
1,991
2.40625
2
[]
no_license
package es.urjc.javsan.master.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import es.urjc.javsan.master.configuration.ProductsDB; import es.urjc.javsan.master.entities.Product; @RestController public class ProductsController { @Autowired private ProductsDB productDB; @RequestMapping(value = "/add", method = RequestMethod.POST) public ResponseEntity<String> addSubmit(@RequestBody Product product, BindingResult bindingResult) { productDB.add(product); return new ResponseEntity<String>("Product Added!", HttpStatus.CREATED); } @RequestMapping(value = "/edit", method = RequestMethod.POST) public ResponseEntity<String> editSubmit(@RequestBody Product product, BindingResult bindingResult) { productDB.edit(product); return new ResponseEntity<String>("Product Edited!", HttpStatus.CREATED); } @RequestMapping(value = "/list", method = RequestMethod.GET) public ResponseEntity<List<Product>> list() { return new ResponseEntity<List<Product>>(productDB.findAll(), HttpStatus.ACCEPTED); } @RequestMapping(value = "/delete", method = RequestMethod.GET) public ResponseEntity<String> delete(@RequestParam int code) { productDB.delete(code); return new ResponseEntity<String>("Product Deleted!!", HttpStatus.ACCEPTED); } @RequestMapping(value = "/product", method = RequestMethod.GET) public ResponseEntity<Product> product(@RequestParam int code) { return new ResponseEntity<Product>(productDB.get(code), HttpStatus.ACCEPTED); } }
true
56164346d34e579800ca8307f872f43d430ea679
Java
mary-kiragu/java-project
/src/com/mary/kiragu/frames/TenantsFrame.java
UTF-8
1,528
2.796875
3
[]
no_license
package com.mary.kiragu.frames; import com.mary.kiragu.dataaccess.TenantsDataManager; import com.mary.kiragu.panels.TenantsPanel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.HeadlessException; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JTable; public class TenantsFrame extends JFrame { private JTable table; private TenantsPanel tenantsPanel; private MainFrame mainFrame; private TenantsDataManager tenantsDataManager; public TenantsFrame(MainFrame mainFrameObject) throws HeadlessException { super(); this.tenantsPanel = new TenantsPanel(); this.mainFrame = mainFrameObject; this.tenantsDataManager = new TenantsDataManager(); setFrameSize(); setComponents(); } private void setFrameSize() { //set resizable this.setResizable(true); //get the screen dimension of the computer Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize(); int width = (int) screenDimension.getWidth(); int height = (int) screenDimension.getHeight() - 50; // substract 50 because of the computer tool bar this.setSize(width, height); } private void addComponents() { super.dispose(); table = new JTable(); } private void setComponents() { this.setLayout(new BorderLayout()); //set the tenants as the default panel this.add(tenantsPanel, BorderLayout.CENTER); } }
true
323b66f19e80d216bcb46abb4ae171138c3b31e4
Java
qm1083824922/scfs
/scfs-service/src/main/java/com/scfs/service/report/ReceiveReportService.java
UTF-8
13,972
1.648438
2
[]
no_license
package com.scfs.service.report; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.scfs.common.consts.BaseConsts; import com.scfs.common.consts.BizCodeConsts; import com.scfs.common.consts.CacheKeyConsts; import com.scfs.common.utils.DecimalUtil; import com.scfs.common.utils.PageUtil; import com.scfs.dao.fi.VoucherLineDao; import com.scfs.dao.interceptor.CountHelper; import com.scfs.dao.report.ReceiveLineReportDao; import com.scfs.dao.report.ReceiveReportDao; import com.scfs.domain.base.entity.BaseDepartment; import com.scfs.domain.base.entity.BaseProject; import com.scfs.domain.fi.dto.req.VoucherLineSearchReqDto; import com.scfs.domain.fi.entity.VoucherLine; import com.scfs.domain.report.entity.ReceiveLineReport; import com.scfs.domain.report.entity.ReceiveReport; import com.scfs.domain.report.req.ReceiveReportSearchReq; import com.scfs.domain.report.resp.ReceiveLineReportResDto; import com.scfs.domain.report.resp.ReceiveReportResDto; import com.scfs.domain.result.PageResult; import com.scfs.service.common.ReportProjectService; import com.scfs.service.support.CacheService; import com.scfs.service.support.ServiceSupport; /** * <pre> * * File: ReceiveReportService.java * Description: * TODO * Date, Who, * 2017年2月13日 Administrator * * </pre> */ @Service public class ReceiveReportService { @Autowired private ReceiveReportDao receiveReportDao; @Autowired private ReceiveLineReportDao receiveLineReportDao; @Autowired private CacheService cacheService; @Autowired private VoucherLineDao voucherLineDao; @Autowired private ReportProjectService reportProjectService; public PageResult<ReceiveReportResDto> queryResultByCon(ReceiveReportSearchReq receiveReportSearchReq) { receiveReportSearchReq.setExcludeProjectIdList(reportProjectService.queryReportProject(BaseConsts.TWO)); PageResult<ReceiveReportResDto> pageResult = new PageResult<ReceiveReportResDto>(); if (!StringUtils.isEmpty(receiveReportSearchReq.getDepartmentId())) { List<String> departmentList = Arrays.asList(receiveReportSearchReq.getDepartmentId().split(",")); receiveReportSearchReq.setDepartmentList(departmentList); } receiveReportSearchReq.setUserId(ServiceSupport.getUser().getId()); int offSet = PageUtil.getOffSet(receiveReportSearchReq.getPage(), receiveReportSearchReq.getPer_page()); RowBounds rowBounds = new RowBounds(offSet, receiveReportSearchReq.getPer_page()); List<ReceiveReportResDto> receiveReportResDtos = convertToResult( receiveReportDao.queryResultsByCon(receiveReportSearchReq, rowBounds), receiveReportSearchReq); int totalPage = PageUtil.getTotalPage(CountHelper.getTotalRow(), receiveReportSearchReq.getPer_page()); pageResult.setItems(receiveReportResDtos); pageResult.setLast_page(totalPage); pageResult.setTotal(CountHelper.getTotalRow()); pageResult.setCurrent_page(receiveReportSearchReq.getPage()); pageResult.setPer_page(receiveReportSearchReq.getPer_page()); if (receiveReportSearchReq.getNeedSum() != null && receiveReportSearchReq.getNeedSum().equals(BaseConsts.ONE)) { List<ReceiveReport> receiveReports = receiveReportDao.querySumByCon(receiveReportSearchReq); BigDecimal balance = BigDecimal.ZERO; BigDecimal expireRecAmount = BigDecimal.ZERO; BigDecimal expireAmount1 = BigDecimal.ZERO; BigDecimal expireAmount2 = BigDecimal.ZERO; BigDecimal expireAmount3 = BigDecimal.ZERO; BigDecimal adventAmount1 = BigDecimal.ZERO; BigDecimal adventAmount2 = BigDecimal.ZERO; BigDecimal adventAmount3 = BigDecimal.ZERO; for (ReceiveReport receiveReport : receiveReports) { balance = DecimalUtil.add(balance, ServiceSupport.amountNewToRMB(receiveReport.getBalance(), receiveReport.getCurrencyType(), new Date())); expireRecAmount = DecimalUtil.add(expireRecAmount, ServiceSupport.amountNewToRMB( receiveReport.getExpireRecAmount(), receiveReport.getCurrencyType(), new Date())); expireAmount1 = DecimalUtil.add(expireAmount1, ServiceSupport .amountNewToRMB(receiveReport.getExpireAmount1(), receiveReport.getCurrencyType(), new Date())); expireAmount2 = DecimalUtil.add(expireAmount2, ServiceSupport .amountNewToRMB(receiveReport.getExpireAmount2(), receiveReport.getCurrencyType(), new Date())); expireAmount3 = DecimalUtil.add(expireAmount3, ServiceSupport .amountNewToRMB(receiveReport.getExpireAmount3(), receiveReport.getCurrencyType(), new Date())); adventAmount1 = DecimalUtil.add(adventAmount1, ServiceSupport .amountNewToRMB(receiveReport.getAdventAmount1(), receiveReport.getCurrencyType(), new Date())); adventAmount2 = DecimalUtil.add(adventAmount2, ServiceSupport .amountNewToRMB(receiveReport.getAdventAmount2(), receiveReport.getCurrencyType(), new Date())); adventAmount3 = DecimalUtil.add(adventAmount3, ServiceSupport .amountNewToRMB(receiveReport.getAdventAmount3(), receiveReport.getCurrencyType(), new Date())); } StringBuilder sBuilder = new StringBuilder(); sBuilder.append("应收金额: "); sBuilder.append(DecimalUtil.formatScale2(balance)); sBuilder.append(" CNY 超期应收金额: "); sBuilder.append(DecimalUtil.formatScale2(expireRecAmount)); sBuilder.append(" CNY 超期1-7天金额: "); sBuilder.append(DecimalUtil.formatScale2(expireAmount1)); sBuilder.append(" CNY 超期8-15天金额: "); sBuilder.append(DecimalUtil.formatScale2(expireAmount2)); sBuilder.append(" CNY 超期15天以上金额: "); sBuilder.append(DecimalUtil.formatScale2(expireAmount3)); sBuilder.append(" CNY 临期0-7天金额: "); sBuilder.append(DecimalUtil.formatScale2(adventAmount1)); sBuilder.append(" CNY 临期8到15天金额: "); sBuilder.append(DecimalUtil.formatScale2(adventAmount2)); sBuilder.append(" CNY 临期15天以上金额: "); sBuilder.append(DecimalUtil.formatScale2(adventAmount3)); pageResult.setTotalStr(sBuilder.toString()); } return pageResult; } public PageResult<ReceiveLineReportResDto> queryResultDetailByCon(ReceiveReportSearchReq receiveReportSearchReq) { receiveReportSearchReq.setExcludeProjectIdList(reportProjectService.queryReportProject(BaseConsts.TWO)); PageResult<ReceiveLineReportResDto> pageResult = new PageResult<ReceiveLineReportResDto>(); if (!StringUtils.isEmpty(receiveReportSearchReq.getDepartmentId())) { List<String> departmentList = Arrays.asList(receiveReportSearchReq.getDepartmentId().split(",")); receiveReportSearchReq.setDepartmentList(departmentList); } receiveReportSearchReq.setUserId(ServiceSupport.getUser().getId()); int offSet = PageUtil.getOffSet(receiveReportSearchReq.getPage(), receiveReportSearchReq.getPer_page()); RowBounds rowBounds = new RowBounds(offSet, receiveReportSearchReq.getPer_page()); List<ReceiveLineReportResDto> receiveReportResDtos = convertToLineResult( receiveLineReportDao.queryResultDetialByCon(receiveReportSearchReq, rowBounds)); int totalPage = PageUtil.getTotalPage(CountHelper.getTotalRow(), receiveReportSearchReq.getPer_page()); String totalStr = ""; List<ReceiveLineReport> billTypeSums = receiveLineReportDao.querySumByCon(receiveReportSearchReq); String currencySymbol = ""; if (receiveReportSearchReq.getCurrencyType() == BaseConsts.ONE) { currencySymbol = "CNY"; } else if (receiveReportSearchReq.getCurrencyType() == BaseConsts.TWO) { currencySymbol = "USD"; } else if (receiveReportSearchReq.getCurrencyType() == BaseConsts.THREE) { currencySymbol = "HKD"; } if (!CollectionUtils.isEmpty(billTypeSums)) { for (ReceiveLineReport receiveLineReport : billTypeSums) { if (!StringUtils.isEmpty(receiveLineReport.getBillType())) { totalStr += ServiceSupport.getValueByBizCode(BizCodeConsts.BILL_TYPE, receiveLineReport.getBillType() + "") + "总金额: " + DecimalUtil.formatScale2(receiveLineReport.getBalance()) + currencySymbol + " "; } } } pageResult.setItems(receiveReportResDtos); pageResult.setLast_page(totalPage); pageResult.setTotal(CountHelper.getTotalRow()); pageResult.setCurrent_page(receiveReportSearchReq.getPage()); pageResult.setPer_page(receiveReportSearchReq.getPer_page()); pageResult.setTotalStr(totalStr); return pageResult; } public List<ReceiveReportResDto> queryListByCon(ReceiveReportSearchReq receiveReportSearchReq) { receiveReportSearchReq.setExcludeProjectIdList(reportProjectService.queryReportProject(BaseConsts.TWO)); if (!StringUtils.isEmpty(receiveReportSearchReq.getDepartmentId())) { List<String> departmentList = Arrays.asList(receiveReportSearchReq.getDepartmentId().split(",")); receiveReportSearchReq.setDepartmentList(departmentList); } receiveReportSearchReq.setUserId(ServiceSupport.getUser().getId()); return convertToResult(receiveReportDao.queryResultsByCon(receiveReportSearchReq), receiveReportSearchReq); } private List<ReceiveReportResDto> convertToResult(List<ReceiveReport> receiveReports, ReceiveReportSearchReq receiveReportSearchReq) { List<ReceiveReportResDto> receiveReportResDtos = new ArrayList<ReceiveReportResDto>(); if (CollectionUtils.isEmpty(receiveReports)) { return receiveReportResDtos; } for (ReceiveReport receiveReport : receiveReports) { ReceiveReportResDto receiveReportResDto = new ReceiveReportResDto(); BeanUtils.copyProperties(receiveReport, receiveReportResDto); if (!StringUtils.isEmpty(receiveReport.getCustId())) { receiveReportResDto.setCustName( cacheService.getSubjectNcByIdAndKey(receiveReport.getCustId(), CacheKeyConsts.CUSTOMER)); } VoucherLineSearchReqDto voucherLineSearchReq = new VoucherLineSearchReqDto(); voucherLineSearchReq.setUserId(receiveReportSearchReq.getUserId()); voucherLineSearchReq.setStatisticsDimension(receiveReportSearchReq.getStatisticsDimension()); voucherLineSearchReq.setDebitOrCredit(BaseConsts.ONE); voucherLineSearchReq.setCustId(receiveReport.getCustId()); voucherLineSearchReq.setProjectId(receiveReport.getProjectId()); voucherLineSearchReq.setCurrencyType(receiveReport.getCurrencyType()); List<VoucherLine> voucherLines = voucherLineDao.queryGroupResultsByCon(voucherLineSearchReq); if (!CollectionUtils.isEmpty(voucherLines) && voucherLines.size() == 1) { VoucherLine voucherLine = voucherLines.get(0); receiveReportResDto.setUnCheckAmount( DecimalUtil.formatScale2(voucherLine.getAmount().subtract(voucherLine.getAmountChecked()))); } else { receiveReportResDto.setUnCheckAmount(BigDecimal.ZERO); } if (DecimalUtil.eq(receiveReportResDto.getBalance(), DecimalUtil.ZERO) && DecimalUtil.eq(receiveReportResDto.getUnCheckAmount(), DecimalUtil.ZERO)) { continue; } if (!StringUtils.isEmpty(receiveReport.getProjectId())) { receiveReportResDto.setProjectName(cacheService.getProjectNameById(receiveReport.getProjectId())); BaseProject baseProject = cacheService.getProjectById(receiveReport.getProjectId()); BaseDepartment baseDepartment = cacheService.getBaseDepartmentById(baseProject.getDepartmentId()); receiveReportResDto .setBizManagerName(cacheService.getUserChineseNameByid(baseProject.getBizSpecialId())); receiveReportResDto.setDepartmentName(baseDepartment.getName()); receiveReportResDto.setProjectName(baseProject.getProjectNo() + "-" + baseProject.getProjectName()); } receiveReportResDto.setCurrencyTypeName(ServiceSupport .getValueByBizCode(BizCodeConsts.DEFAULT_CURRENCY_TYPE, receiveReport.getCurrencyType() + "")); receiveReportResDto.setBillTypeName( ServiceSupport.getValueByBizCode(BizCodeConsts.BILL_TYPE, receiveReport.getBillType() + "")); receiveReportResDtos.add(receiveReportResDto); } return receiveReportResDtos; } private List<ReceiveLineReportResDto> convertToLineResult(List<ReceiveLineReport> receiveLineReports) { List<ReceiveLineReportResDto> receiveLineReportResDtos = new ArrayList<ReceiveLineReportResDto>(); if (CollectionUtils.isEmpty(receiveLineReports)) { return receiveLineReportResDtos; } for (ReceiveLineReport receiveLineReport : receiveLineReports) { ReceiveLineReportResDto receiveLineReportResDto = new ReceiveLineReportResDto(); BeanUtils.copyProperties(receiveLineReport, receiveLineReportResDto); if (!StringUtils.isEmpty(receiveLineReport.getCustId())) { receiveLineReportResDto.setCustName( cacheService.getSubjectNcByIdAndKey(receiveLineReport.getCustId(), CacheKeyConsts.CUSTOMER)); } if (!StringUtils.isEmpty(receiveLineReport.getProjectId())) { receiveLineReportResDto .setProjectName(cacheService.getProjectNameById(receiveLineReport.getProjectId())); BaseProject baseProject = cacheService.getProjectById(receiveLineReport.getProjectId()); BaseDepartment baseDepartment = cacheService.getBaseDepartmentById(baseProject.getDepartmentId()); receiveLineReportResDto .setBizManagerName(cacheService.getUserChineseNameByid(baseProject.getBizSpecialId())); receiveLineReportResDto.setDepartmentName(baseDepartment.getName()); receiveLineReportResDto.setProjectName(baseProject.getProjectNo() + "-" + baseProject.getProjectName()); } receiveLineReportResDto.setCurrencyTypeName(ServiceSupport .getValueByBizCode(BizCodeConsts.DEFAULT_CURRENCY_TYPE, receiveLineReport.getCurrencyType() + "")); receiveLineReportResDto.setBillTypeName( ServiceSupport.getValueByBizCode(BizCodeConsts.BILL_TYPE, receiveLineReport.getBillType() + "")); receiveLineReportResDtos.add(receiveLineReportResDto); } return receiveLineReportResDtos; } }
true
6017b11d059839070ebc552597b2050168344eb3
Java
allef-brendel/MarvelApiProject
/app/src/main/java/com/e/marvelapiproject/contentprovider/Authority.java
UTF-8
475
1.84375
2
[]
no_license
package com.e.marvelapiproject.contentprovider; import android.net.Uri; public class Authority { public static final String AUTHORITY = "com.e.marvelapiproject.contentprovider"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/quadrinhos"); public static final String URL = "content://com.e.marvelapiproject.contentprovider/quadrinhos/"; public static final int QUADRINHO = 1; public static final int QUADRINHO_ID = 2; }
true
1004269ee4bb74602c4615f2bfe49a481bda8813
Java
zhongxingyu/Seer
/Diff-Raw-Data/7/7_b8e769c338c2410b7816c7b255c215e12ce08ac0/FreeMarkerActionTest/7_b8e769c338c2410b7816c7b255c215e12ce08ac0_FreeMarkerActionTest_s.java
UTF-8
5,406
1.867188
2
[]
no_license
/* * GeoBatch - Open Source geospatial batch processing system * http://code.google.com/p/geobatch/ * Copyright (C) 2007-2008-2009 GeoSolutions S.A.S. * http://www.geo-solutions.it * * GPLv3 + Classpath exception * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.geosolutions.geobatch.actions.freemarker.test; import it.geosolutions.filesystemmonitor.monitor.FileSystemEvent; import it.geosolutions.filesystemmonitor.monitor.FileSystemEventType; import it.geosolutions.geobatch.actions.freemarker.FreeMarkerAction; import it.geosolutions.geobatch.actions.freemarker.FreeMarkerConfiguration; import it.geosolutions.geobatch.actions.freemarker.TemplateModelEvent; import it.geosolutions.geobatch.flow.event.action.ActionException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.EventObject; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import org.junit.Assert; import org.junit.Test; import com.thoughtworks.xstream.XStream; /** * * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it * */ public class FreeMarkerActionTest { /* * <?xml version="1.0" encoding="UTF-8"?> <!-- OCTAVE ENV --> <octave> <sheets> <!-- OCTAVE SHEET --> <sheet name="${SHEET_NAME}"> <commands> <OctaveCommand executed="false"> <command>source "${event.SOURCE_PATH}";</command> </OctaveCommand> <OctaveCommand executed="false"> <command>cd "${event.WORKING_DIR}";</command> </OctaveCommand> <OctaveCommand executed="false"> <command>mars3d("${event.FILE_IN}","${event.FILE_OUT}");</command> </OctaveCommand> </commands> <definitions/> <returns/> </sheet> </sheets> </octave> */ @Test public void test() throws ActionException { FreeMarkerConfiguration fmc=new FreeMarkerConfiguration("ID","NAME","DESC"); // SIMULATE THE XML FILE CONFIGURATION OF THE ACTION fmc.setDirty(false); fmc.setFailIgnored(false); fmc.setServiceID("serviceID"); fmc.setWorkingDirectory("src/test/resources/data/"); fmc.setInput("test.xml"); fmc.setOutput("test_out.xml"); Map<String,Object> m=new HashMap<String, Object>(); m.put("SHEET_NAME", "MY_NEW_SHEET_NAME"); fmc.setRoot(m); // SIMULATE THE EventObject on the queue Map<String,Object> mev=new HashMap<String, Object>(); mev.put("SOURCE_PATH", "/path/to/source"); mev.put("WORKING_DIR", "/absolute/working/dir"); mev.put("FILE_IN", "in_test_file.dat"); mev.put("FILE_OUT", "out_test_file.dat"); mev.put("FILE_OUT", "out_test_file.dat"); List<String> list=new ArrayList<String>(4); list.add("1"); list.add("2"); list.add("3"); list.add("4"); mev.put("LIST", list); Queue<EventObject> q=new ArrayBlockingQueue<EventObject>(2); q.add(new TemplateModelEvent(mev)); q.add(new FileSystemEvent(new File("TEST.txt"), FileSystemEventType.FILE_ADDED)); FreeMarkerAction fma=new FreeMarkerAction(fmc); q=fma.execute(q); try{ FileSystemEvent res=(FileSystemEvent)q.remove(); File out=res.getSource(); if (!out.exists()) Assert.fail("FAIL: unable to create output file"); // FileInputStream fin=new FileInputStream(out); // StringBuilder test=new StringBuilder(); // byte[] buf=new byte[1024]; // while (fin.read(buf)!=-1){ // //test.append((char[])buf); // } // fin.close(); // System.out.print(test.toString()); } catch (ClassCastException cce){ Assert.fail("FAIL: "+cce.getLocalizedMessage()); // } catch (FileNotFoundException e) { // Assert.fail("FAIL: "+e.getLocalizedMessage()); // } catch (IOException e) { // Assert.fail("FAIL: "+e.getLocalizedMessage()); } return; } }
true
5d2f4924861d60c083a9c4729b5a6e9eabf02c80
Java
rosnasimon/Playground
/Reversing a sentence/Main.java
UTF-8
290
2.734375
3
[]
no_license
#include<stdio.h> #include<string.h> int main() { // Type your code here char str[100]; scanf("%[^\n]s",str); int len=strlen(str); for(int i=len-1;i>=0;i--) { if(str[i]==' ') { printf("%s ",&str[i+1]); str[i]='\0'; } } printf("%s",str); return 0; }
true
f28101ed42b5a88e6fed3d07cd56846ad7d2d1cc
Java
SepehrNoey/Mafia-game
/src/server_side/manager/Logic.java
UTF-8
13,072
2.6875
3
[]
no_license
package server_side.manager; import server_side.model.Player_ServerSide; import server_side.model.Server; import utils.Message; import utils.MessageTypes; import utils.Role_Group; import utils.StateEnum; import utils.logClasses.Logger; import java.io.Serializable; import java.util.*; /** * a class to monitor logical rules of game * * @author Sepehr Noey * @version 1.0 */ public class Logic implements Serializable { private Map<MessageTypes , Integer> usedLimitedCommands; private Server server; private GameState gameState; /** * constructor * @param server of game * @param gameState state of this round */ public Logic(Server server , GameState gameState){ usedLimitedCommands = new HashMap<>(); this.server = server; this.gameState = gameState; } /** * checking validity of kill order * @param msg entered by player * @return true if valid , false if not */ public boolean isKillValid(Message msg){ boolean isFound = isTargetFound(msg); if (!isFound) return false; if (msg.getMsgType() == MessageTypes.ACTIONS_GODFATHER_ORDERED_KILL){ if (!msg.getTarget().equals(msg.getSender()) && server.getPlayerByName(server.getPlayers(), msg.getTarget()).getGroup() != Role_Group.MAFIA_GROUP) // godfather ordered kill - can't kill himself or any of mafias return true; else return false; } else // sniper ordered kill { if (usedLimitedCommands.containsKey(MessageTypes.ACTIONS_SNIPER_ORDERED_KILL)){ return false; } else if (!usedLimitedCommands.containsKey(MessageTypes.ACTIONS_SNIPER_ORDERED_KILL) && !msg.getSender().equals(msg.getTarget())) { usedLimitedCommands.put(MessageTypes.ACTIONS_SNIPER_ORDERED_KILL , 1); return true; } else { return false; } } } /** * to know if is valid or not * @param msg entered by player * @return true if valid , false if not */ public boolean isSaveValid(Message msg){ boolean isFound = isTargetFound(msg); if (!isFound) return false; if (msg.getTarget().equals(msg.getSender()) && usedLimitedCommands.containsKey(msg.getMsgType())) return false; if (msg.getTarget().equals(msg.getSender())) { usedLimitedCommands.put(msg.getMsgType(), 1); // to know that this command has been used for saving himself return true; } // others are true return true; } /** * checking validity - psychologist can't silence himself * @param msg entered by player * @return false if target is himself , else true */ public boolean isSilenceValid(Message msg){ return !msg.getTarget().equals(msg.getSender()); } /** * to do inquiry * @param msg entered msg * @return a string in special format: accepted(or refused),some data.... */ public String inquiry(Message msg){ if (msg.getMsgType() == MessageTypes.ACTIONS_DETECTIVE_ORDERED_INQUIRY) { boolean isFound = isTargetFound(msg); if (!isFound) return "refused,Player not found!"; Player_ServerSide target = server.getPlayerByName(server.getPlayers(),msg.getTarget()); if (target.getRole() == Role_Group.GODFATHER || target.getGroup() == Role_Group.CITIZEN_GROUP){ return "accepted,No ... This player isn't mafia."; } else return "accepted,Yes! ... This player is mafia!"; } else { // die hard inquiry int num = 0; try { num = usedLimitedCommands.get(MessageTypes.ACTIONS_DIEHARD_ORDERED_INQUIRY); }catch (InputMismatchException e) { num = 0; } if (num == 0 || num == 1){ usedLimitedCommands.replace(MessageTypes.ACTIONS_DIEHARD_ORDERED_INQUIRY , num == 0 ? 1 : 2); if (server.getOutOfGame().size() == 0) return "refused,No players out of game yet!"; String str = "accepted,"; for (Player_ServerSide player: server.getOutOfGame()) { str += "Name : " + player.getName() + "\tRole: " + player.getRole() + "\n"; } return str; } else { return "refused,You have used this command for 2 times. No more is allowed!"; } } } /** * to vote * @param msg entered by player * @return a result string in this format : accepted(or refused), and data about */ public String vote(Message msg){ boolean isFound = isTargetFound(msg); if (!isFound) return "refused,Player not found!"; if (!(gameState.getState() == StateEnum.VOTING_TIME)) return "refused,Not allowed to vote now!"; if (msg.getSender().equals(msg.getTarget())) return "refused,You can't vote to yourself!"; return "accepted,Your vote recorded."; } /** * to check if the game is finished or not * @return true if finished , false if not */ public boolean isFinished() { int mafNum = 0; int citNum = 0; for (Player_ServerSide player: server.getPlayers()) { if (player.getGroup() == Role_Group.MAFIA_GROUP) mafNum++; else citNum++; } return mafNum >= citNum || mafNum == 0; } /** * to search between players * @param msg the entered message * @return true if found , false if not */ private boolean isTargetFound(Message msg) { for (Player_ServerSide player: server.getPlayers()) { if (player.getName().equals(msg.getTarget())){ // null exception??? return true; } } return false; } /** * getter * @return current game state */ public GameState getGameState() { return gameState; } /** * to handle events of night - voting events are ignored and after this method , the only events in events list , would just be of voting type * @param events of night * @return a string in a special format to split and use in other classes */ public String handleEvents(List<Message> events) { Player_ServerSide killedByMaf = null; Player_ServerSide savedByDoc = null; Player_ServerSide killedBySniper = null; Player_ServerSide savedByLec = null; Player_ServerSide silenced = null; Iterator<Message> it = events.listIterator(); while (it.hasNext()) { Message event = it.next(); if (event.getMsgType() != MessageTypes.ACTIONS_PLAYER_VOTED) // keeping vote events and deleting rest { if (event.getMsgType() == MessageTypes.ACTIONS_GODFATHER_ORDERED_KILL) killedByMaf = server.getPlayerByName(server.getPlayers(), event.getTarget()); else if (event.getMsgType() == MessageTypes.ACTIONS_SNIPER_ORDERED_KILL) killedBySniper = server.getPlayerByName(server.getPlayers(),event.getTarget()); else if (event.getMsgType() == MessageTypes.ACTIONS_DOCTOR_ORDERED_SAVE) savedByDoc = server.getPlayerByName(server.getPlayers(),event.getTarget()); else if (event.getMsgType() == MessageTypes.ACTIONS_LECTER_ORDERED_SAVE) savedByLec = server.getPlayerByName(server.getPlayers(),event.getTarget()); else if (event.getMsgType() == MessageTypes.ACTIONS_PSYCHOLOGIST_ORDERED_SILENCE) silenced = server.getPlayerByName(server.getPlayers(),event.getTarget()); it.remove(); } } String result = ""; if (killedByMaf != null) { if (savedByDoc != null) { if (savedByDoc.getName().equals(killedByMaf.getName())) result += "info-Mafias tried to kill someone but doctor saved him!,"; else{ result += "kill-" + killedByMaf.getName() + ","; result += "info-Mafias killed " + killedByMaf.getName() + "!,"; } } else { result += "kill-" + killedByMaf.getName() + ","; result += "info-Mafias killed " + killedByMaf.getName() + "!,"; } } if (killedBySniper != null){ if (killedBySniper.getGroup() == Role_Group.CITIZEN_GROUP) { result += "kick-" + server.getRoleToPlayer().get(Role_Group.SNIPER).getName() + ","; result += "info-Sniper tried to kill a citizen so sniper kicked out! " + server.getRoleToPlayer().get(Role_Group.SNIPER).getName() + " was sniper.,"; } else { if ((savedByDoc != null && savedByDoc.getName().equals(killedBySniper.getName())) || (savedByLec != null && savedByLec.getName().equals(killedBySniper.getName()))) // doctor has saved him result += "info-Sniper tried to kill someone but doctor saved him!,"; else { result += "kill-" + killedBySniper.getName() + ","; result += "info-Sniper killed " + killedBySniper.getName() + " which was a mafia!,"; } } } if (silenced != null) { result += "silence-" + silenced.getName() + ","; result += "Psychologist silenced " + silenced.getName() + " for this round!,"; } return result; } /** * the votes entered are valid - no need to check * @param votes list of vote messages * @return the result string */ public String countVotes(List<Message> votes){ HashMap<String , String> voterTarget = new HashMap<>(); HashMap<String , Integer> targetVotes = new HashMap<>(); for (Message msg: votes) { if (voterTarget.containsKey(msg.getSender())) voterTarget.replace(voterTarget.get(msg.getSender()) , msg.getTarget()); else voterTarget.put(msg.getSender() , msg.getTarget()); } for (String str : voterTarget.values()) { if (targetVotes.containsKey(str)) targetVotes.replace(str , targetVotes.get(str) + 1); else targetVotes.put(str , 1); } String candidate1name = null; int candidate1votes = 0; String candidate2name = null; int candidate2votes = 0; for (Map.Entry<String , Integer> entry:targetVotes.entrySet()) { if (candidate1name == null) { candidate1name = entry.getKey(); candidate1votes = entry.getValue(); } else if (entry.getValue() > candidate1votes) { candidate1name = entry.getKey(); candidate1votes = entry.getValue(); } else if (entry.getValue() == candidate1votes) { candidate2name = entry.getKey(); candidate2votes = entry.getValue(); } } if (candidate1votes > candidate2votes) { return candidate1name + "_" + candidate1votes; } else { return "nobody_same number votes."; } } /** * to get the details the winner group and others at the end of game * @return the result string */ public String getEndingResult(){ String winner = ""; int mafNum = 0; int citNum = 0; for (Player_ServerSide player: server.getPlayers()) { if (player.getGroup() == Role_Group.MAFIA_GROUP) mafNum++; else citNum++; } winner = mafNum >= citNum ? "Mafia group is the winner!" : "Citizen group is the winner!"; String result = ""; for (Player_ServerSide player: server.getOutOfGame()) { result += player.getName() + " was " + player.getRole() + "\n"; } for (Player_ServerSide player: server.getPlayers()) { result += player.getName() + " was " + player.getRole() + "\n"; } return winner + "\n\n" + result; } /** * setter * @param server created server */ public void setServer(Server server) { this.server = server; } /** * setter * @param gameState created gameState */ public void setGameState(GameState gameState) { this.gameState = gameState; } }
true
26ba8f3377b6c4e9364a9a64778f0f7cbd9a55ec
Java
JerryZhangcy/SmartHelmet
/src/com/cy/helmet/video/controller/StreamController.java
UTF-8
8,202
1.914063
2
[]
no_license
package com.cy.helmet.video.controller; import android.media.MediaCodec; import android.util.Log; import com.cy.helmet.util.LogUtil; import com.cy.helmet.video.audio.OnAudioEncodeListener; import com.cy.helmet.video.callback.VideoLiveCallback; import com.cy.helmet.video.callback.VideoRecordCallback; import com.cy.helmet.video.configuration.AudioConfiguration; import com.cy.helmet.video.controller.audio.IAudioController; import com.cy.helmet.video.controller.audio.NormalAudioController; import com.cy.helmet.video.controller.video.CameraVideoController; import com.cy.helmet.video.controller.video.IVideoController; import com.cy.helmet.video.stream.packer.Packer; import com.cy.helmet.video.stream.packer.flv.FlvPacker; import com.cy.helmet.video.stream.packer.rtmp.RtmpPacker; import com.cy.helmet.video.stream.sender.local.LocalSender; import com.cy.helmet.video.stream.sender.rtmp.RtmpSender; import com.cy.helmet.video.utils.SopCastUtils; import com.cy.helmet.video.video.MyRenderer; import com.cy.helmet.video.video.OnVideoEncodeListener; import java.nio.ByteBuffer; public class StreamController implements OnAudioEncodeListener, OnVideoEncodeListener, Packer.OnPacketListener { //flv packer and sender private FlvPacker mFlvPacker; private LocalSender mFlvSender; //rtmp packer and sender private RtmpPacker mRtmpPacker; private RtmpSender mRtmpSender; private IVideoController mVideoController; private IAudioController mAudioController; //callback private VideoRecordCallback mRecordCallback; private VideoLiveCallback mLiveCallback; public StreamController(MyRenderer render) { if (render == null) { throw new RuntimeException("Camera preview not ready."); } mVideoController = new CameraVideoController(render); mAudioController = new NormalAudioController(); } public void setAudioConfiguration(AudioConfiguration audioConfiguration) { mAudioController.setAudioConfiguration(audioConfiguration); } public boolean setVideoBps(int bps) { return mVideoController.setVideoBps(bps); } public boolean setLiveBps(int bps) { return mVideoController.setLiveBps(bps); } @Override public void onAudioEncode(ByteBuffer bb, MediaCodec.BufferInfo bi) { if (mFlvPacker != null) { mFlvPacker.onAudioData(bb, bi); } if (mRtmpPacker != null) { mRtmpPacker.onAudioData(bb, bi); } } @Override public void onVideoEncode(ByteBuffer bb, MediaCodec.BufferInfo bi) { if (mFlvPacker != null) { mFlvPacker.onVideoData(bb, bi); } } @Override public void onLiveVideoEncode(ByteBuffer bb, MediaCodec.BufferInfo bi) { if (mRtmpPacker != null) { mRtmpPacker.onVideoData(bb, bi); } } @Override public void onPacket(byte[] data, int packetType) { if (mFlvSender != null) { mFlvSender.onData(data, packetType); } } @Override public void onPacketLiveStream(byte[] data, int packetType) { if (mRtmpSender != null) { mRtmpSender.onData(data, packetType); } } @Override public boolean onTransferFile() { if (mFlvSender != null) { return mFlvSender.onTransferFile(); } return false; } public void setFlvPackerSender(FlvPacker packer, LocalSender sender) { mFlvPacker = packer; mFlvSender = sender; mFlvPacker.setPacketListener(this); } public void setRtmpPackerSender(RtmpPacker packer, RtmpSender sender) { mRtmpPacker = packer; mRtmpSender = sender; mRtmpPacker.setPacketListener(this); } public synchronized void startRecording(VideoRecordCallback callback) { if (mFlvPacker == null) { return; } if (mFlvSender == null) { return; } mRecordCallback = callback; mFlvPacker.start(); mFlvSender.start(); mVideoController.startRecord(StreamController.this, callback); mAudioController.setAudioEncodeListener(StreamController.this); mAudioController.start(); } public synchronized void stopRecording() { if (mVideoController != null) { mVideoController.stopRecord(); } if (mFlvSender != null) { mFlvSender.stop(); } if (mFlvPacker != null) { mFlvPacker.stop(); } if (mRtmpPacker == null || !mRtmpPacker.isRunning()) { mAudioController.setAudioEncodeListener(null); mAudioController.stop(); } } public synchronized void startLiving(final String url, final int frameSize, final VideoLiveCallback callback) { LogUtil.e("start living......"); if (mRtmpPacker == null) { return; } if (mRtmpSender == null) { return; } if (mVideoController.isLiving()) { return; } mLiveCallback = callback; mRtmpSender.setSenderListener(mSenderListener); mRtmpSender.setVideoStatusCallback(mLiveCallback); LogUtil.e("LiveUrl=" + url); mRtmpSender.setAddress(url); mRtmpSender.setFrameBufferSize(frameSize); mRtmpSender.connect(); } private void startLivingInternal() { SopCastUtils.getLivingHandler().post(new Runnable() { @Override public void run() { if (mRtmpPacker == null) { return; } if (mRtmpSender == null) { return; } mRtmpPacker.start(); mRtmpSender.start(); mVideoController.startLive(StreamController.this, mLiveCallback); mAudioController.setAudioEncodeListener(StreamController.this); mAudioController.start(); } }); } public synchronized void stopLiving() { SopCastUtils.getLivingHandler().postDelayed(new Runnable() { @Override public void run() { Log.e("Jerry_zhangcy", "<<<<<<<<<<停止直播>>>>>>>> mVideoController = " + (mVideoController == null) + " mFlvPacker = " + (mFlvPacker == null)); if (mVideoController != null) { mVideoController.stopLive(); } if (mRtmpSender != null) { mRtmpSender.stop(); } if (mRtmpPacker != null) { mRtmpPacker.stop(); } if (mFlvPacker == null || !mFlvPacker.isRunning()) { mAudioController.setAudioEncodeListener(null); mAudioController.stop(); } } },1000); } private RtmpSender.OnSenderListener mSenderListener = new RtmpSender.OnSenderListener() { @Override public void onConnecting() { Log.e("YJQ", ">>>>>>>>>>>>>>>on connecting<<<<<<<<<<<<<<<"); } @Override public void onConnected() { Log.e("YJQ", ">>>>>>>>>>>>>>>on connected<<<<<<<<<<<<<<<"); Log.e("Jerry_zhangcy", ">>>>>>>>>>>>>>>Rtmp 已经连接<<<<<<<<<<<<<<<"); startLivingInternal(); } @Override public void onDisConnected() { Log.e("YJQ", ">>>>>>>>>>>>>>>on disConnected<<<<<<<<<<<<<<<"); Log.e("Jerry_zhangcy", ">>>>>>>>>>>>>>>Rtmp 断开连接<<<<<<<<<<<<<<<"); stopLiving(); } @Override public void onPublishFail() { Log.e("YJQ", ">>>>>>>>>>>>>>>on publish failed<<<<<<<<<<<<<<<"); stopLiving(); } @Override public void onNetGood() { } @Override public void onNetBad() { } }; public String getRecordingFileName() { if (mFlvSender != null) { return mFlvSender.getRecordingFileName(); } return ""; } }
true
9ba599cce33cffed8179f0fe8369d68d806c5104
Java
cping/RipplePower
/eclipse/jcoinlibs/src/com/ripple/core/coretypes/Amount.java
UTF-8
21,842
2.34375
2
[ "Apache-2.0" ]
permissive
package com.ripple.core.coretypes; import com.ripple.core.coretypes.uint.UInt64; import com.ripple.core.fields.AmountField; import com.ripple.core.fields.Field; import com.ripple.core.fields.Type; import com.ripple.core.serialized.BinaryParser; import com.ripple.core.serialized.BytesSink; import com.ripple.core.serialized.SerializedType; import com.ripple.core.serialized.TypeTranslator; import org.json.JSONObject; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; /** * In ripple, amounts are either XRP, the native currency, or an IOU of * a given currency as issued by a designated account. */ public class Amount extends Number implements SerializedType, Comparable<Amount> { private static BigDecimal TAKER_PAYS_FOR_THAT_DAMN_OFFER = new BigDecimal("1000000000000.000100"); // public static final Amount NEUTRAL_ZERO = new Amount(Currency.NEUTRAL, AccountID.NEUTRAL); /** * Thrown when an Amount is constructed with an invalid value */ public static class PrecisionError extends RuntimeException { public Amount illegal; public PrecisionError(String s) { super(s); } public PrecisionError(String s, Amount amount) { super(s); illegal = amount; } } // For rounding/multiplying/dividing public static final MathContext MATH_CONTEXT = new MathContext(16, RoundingMode.HALF_UP); // The maximum amount of digits in mantissa of an IOU amount public static final int MAXIMUM_IOU_PRECISION = 16; // The smallest quantity of an XRP is a drop, 1 millionth of an XRP public static final int MAXIMUM_NATIVE_SCALE = 6; // Defines bounds for native amounts public static final BigDecimal MAX_NATIVE_VALUE = parseDecimal("100,000,000,000.0"); public static final BigDecimal MIN_NATIVE_VALUE = parseDecimal("0.000,001"); // These are flags used when serializing to binary form public static final UInt64 BINARY_FLAG_IS_IOU = new UInt64("8000000000000000", 16); public static final UInt64 BINARY_FLAG_IS_NON_NEGATIVE_NATIVE = new UInt64("4000000000000000", 16); public static final Amount ONE_XRP = fromString("1.0"); // The quantity of XRP or Issue(currency/issuer pairing) // When native, the value unit is XRP, not drops. private BigDecimal value; private Currency currency; // If the currency is XRP private boolean isNative; // Normally, in the constructor of an Amount the value is checked // that it's scale/precision and quantity are correctly bounded. // If unbounded is true, these checks are skipped. // This is there for historical ledgers that contain amounts that // would now be considered malformed (in the sense of the transaction // engine result class temMALFORMED) private boolean unbounded = false; // The ZERO account is used for specifying the issuer for native // amounts. In practice the issuer is never used when an // amount is native. private AccountID issuer; // While internally the value is stored as a BigDecimal // the mantissa and exponent, as per the binary // format can be computed. // The mantissa is computed lazily, then cached private UInt64 mantissa = null; // The exponent is always calculated. private int exponent; public Amount(BigDecimal value, Currency currency, AccountID issuer) { this(value, currency, issuer, false); } public Amount(BigDecimal value) { isNative = true; currency = Currency.XRP; this.setAndCheckValue(value); } public Amount(BigDecimal value, Currency currency, AccountID issuer, boolean isNative, boolean unbounded) { this.isNative = isNative; this.currency = currency; this.unbounded = unbounded; this.setAndCheckValue(value); // done AFTER set value which sets some default values this.issuer = issuer; } public Amount(Currency currency, AccountID account) { this(BigDecimal.ZERO, currency, account); } // Private constructors Amount(BigDecimal newValue, Currency currency, AccountID issuer, boolean isNative) { this(newValue, currency, issuer, isNative, false); } private Amount(BigDecimal value, String currency, String issuer) { this(value, currency); if (issuer != null) { this.issuer = AccountID.fromString(issuer); } } public Amount(BigDecimal value, String currency) { isNative = false; this.currency = Currency.fromString(currency); this.setAndCheckValue(value); } private void setAndCheckValue(BigDecimal value) { this.value = value.stripTrailingZeros(); initialize(); } private void initialize() { if (isNative()) { issuer = AccountID.XRP_ISSUER; if (!unbounded) { checkXRPBounds(); } // Offset is unused for native amounts exponent = -6; // compared to drops. } else { issuer = AccountID.NEUTRAL; exponent = calculateExponent(); if (value.precision() > MAXIMUM_IOU_PRECISION && !unbounded) { String err = "value precision of " + value.precision() + " is greater than maximum " + "iou precision of " + MAXIMUM_IOU_PRECISION; throw new PrecisionError(err, this); } } } private Amount newValue(BigDecimal newValue) { return newValue(newValue, false, false); } private Amount newValue(BigDecimal newValue, boolean round, boolean unbounded) { if (round) { newValue = roundValue(newValue, isNative); } return new Amount(newValue, currency, issuer, isNative, unbounded); } private Amount newValue(BigDecimal val, boolean round) { return newValue(val, round, false); } /* Getters and Setters */ public BigDecimal value() { return value; } public Currency currency() { return currency; } public AccountID issuer() { return issuer; } public Issue issue() { // TODO: store the currency and issuer as an Issue return new Issue(currency, issuer); } public UInt64 mantissa() { if (mantissa == null) { mantissa = calculateMantissa(); } return mantissa; } public int exponent() { return exponent; } public boolean isNative() { return isNative; } public String currencyString() { return currency.toString(); } public String issuerString() { if (issuer == null) { return ""; } return issuer.toString(); } /* Offset & Mantissa Helpers */ /** * @return a positive value for the mantissa */ private UInt64 calculateMantissa() { if (isNative()) { return new UInt64(bigIntegerDrops().abs()); } else { return new UInt64(bigIntegerIOUMantissa()); } } protected int calculateExponent() { return -MAXIMUM_IOU_PRECISION + value.precision() - value.scale(); } public BigInteger bigIntegerIOUMantissa() { return exactBigIntegerScaledByPowerOfTen(-exponent).abs(); } private BigInteger bigIntegerDrops() { return exactBigIntegerScaledByPowerOfTen(MAXIMUM_NATIVE_SCALE); } private BigInteger exactBigIntegerScaledByPowerOfTen(int n) { return value.scaleByPowerOfTen(n).toBigIntegerExact(); } /* Equality testing */ private boolean equalValue(Amount amt) { return compareTo(amt) == 0; } @Override public boolean equals(Object obj) { if (obj instanceof Amount) { return equals((Amount) obj); } return super.equals(obj); } public boolean equals(Amount amt) { return equalValue(amt) && currency.equals(amt.currency) && (isNative() || issuer.equals(amt.issuer)); } public boolean equalsExceptIssuer(Amount amt) { return equalValue(amt) && currencyString().equals(amt.currencyString()); } public int compareTo(Amount amount) { return value.compareTo(amount.value); } public boolean isZero() { return value.signum() == 0; } public boolean isNegative() { return value.signum() == -1; } // Maybe you want !isNegative() // Any amount that !isNegative() isn't necessarily positive // Is a zero amount strictly positive? no public boolean isPositive() { return value.signum() == 1; } /** Arithmetic Operations There's no checking if an amount is of a different currency/issuer. All operations return amounts of the same currency/issuer as the first operand. eg. amountOne.add(amountTwo) The currency/issuer of the resultant amount, is that of `amountOne` Divide and multiply are equivalent to the javascript ripple-lib ratio_human and product_human. */ public Amount add(BigDecimal augend) { return newValue(value.add(augend), true); } public Amount add(Amount augend) { return add(augend.value); } public Amount add(Number augend) { return add(BigDecimal.valueOf(augend.doubleValue())); } public Amount subtract(BigDecimal subtrahend) { return newValue(value.subtract(subtrahend), true); } public Amount subtract(Amount subtrahend) { return subtract(subtrahend.value); } public Amount subtract(Number subtrahend) { return subtract(BigDecimal.valueOf(subtrahend.doubleValue())); } public Amount multiply(BigDecimal divisor) { return newValue(value.multiply(divisor, MATH_CONTEXT), true); } public Amount multiply(Amount multiplicand) { return multiply(multiplicand.value); } public Amount multiply(Number multiplicand) { return multiply(BigDecimal.valueOf(multiplicand.doubleValue())); } public Amount divide(BigDecimal divisor) { return newValue(value.divide(divisor, MATH_CONTEXT), true); } public Amount divide(Amount divisor) { return divide(divisor.value); } public Amount divide(Number divisor) { return divide(BigDecimal.valueOf(divisor.doubleValue())); } public Amount negate() { return newValue(value.negate()); } public Amount abs() { return newValue(value.abs()); } public Amount min(Amount val) { return (compareTo(val) <= 0 ? this : val); } public Amount max(Amount val) { return (compareTo(val) >= 0 ? this : val); } /* Offer related helpers */ public BigDecimal computeQuality(Amount toExchangeThisWith) { return value.divide(toExchangeThisWith.value, MathContext.DECIMAL128); } /** * @return Amount * The real native unit is a drop, one million of which are an XRP. * We want `one` unit at XRP scale (1e6 drops), or if it's an IOU, * just `one`. */ public Amount one() { if (isNative()) { return ONE_XRP; } else { return issue().amount(1); } } /* Serialized Type implementation */ @Override public Object toJSON() { if (isNative()) { return toDropsString(); } else { return toJSONObject(); } } public JSONObject toJSONObject() { if (isNative()) { throw new RuntimeException("Native amounts must be serialized as a string"); } JSONObject out = new JSONObject(); out.put("currency", currencyString()); out.put("value", valueText()); out.put("issuer", issuerString()); return out; } @Override public byte[] toBytes() { return translate.toBytes(this); } @Override public String toHex() { return translate.toHex(this); } @Override public void toBytesSink(BytesSink to) { UInt64 man = mantissa(); if (isNative()) { if (!isNegative()) { man = man.or(BINARY_FLAG_IS_NON_NEGATIVE_NATIVE); } to.add(man.toByteArray()); } else { int exponent = exponent(); UInt64 packed; if (isZero()) { packed = BINARY_FLAG_IS_IOU; } else if (isNegative()) { packed = man.or(new UInt64(512 + 0 + 97 + exponent).shiftLeft(64 - 10)); } else { packed = man.or(new UInt64(512 + 256 + 97 + exponent).shiftLeft(64 - 10)); } to.add(packed.toByteArray()); to.add(currency.bytes()); to.add(issuer.bytes()); } } @Override public Type type() { return Type.Amount; } public static class Translator extends TypeTranslator<Amount> { @Override public Amount fromString(String s) { // We need to use the full dotted.path here, otherwise // we get confused with the AmountField Amount return com.ripple.core.coretypes.Amount.fromString(s); } @Override public Amount fromParser(BinaryParser parser, Integer hint) { BigDecimal value; byte[] mantissa = parser.read(8); byte b1 = mantissa[0], b2 = mantissa[1]; boolean isIOU = (b1 & 0x80) != 0; boolean isPositive = (b1 & 0x40) != 0; int sign = isPositive ? 1 : -1; if (isIOU) { mantissa[0] = 0; Currency curr = Currency.translate.fromParser(parser); AccountID issuer = AccountID.translate.fromParser(parser); int exponent = ((b1 & 0x3F) << 2) + ((b2 & 0xff) >> 6) - 97; mantissa[1] &= 0x3F; value = new BigDecimal(new BigInteger(sign, mantissa), -exponent); return new Amount(value, curr, issuer, false); } else { mantissa[0] &= 0x3F; value = xrpFromDropsMantissa(mantissa, sign); return new Amount(value); } } @Override public String toString(Amount obj) { return obj.stringRepr(); } @Override public JSONObject toJSONObject(Amount obj) { return obj.toJSONObject(); } @Override public Amount fromJSONObject(JSONObject jsonObject) { String valueString = jsonObject.getString("value"); String issuerString = jsonObject.getString("issuer"); String currencyString = jsonObject.getString("currency"); return new Amount(new BigDecimal(valueString), currencyString, issuerString); } } static public Translator translate = new Translator(); public static BigDecimal xrpFromDropsMantissa(byte[] mantissa, int sign) { return new BigDecimal(new BigInteger(sign, mantissa), 6); } /* Number overides */ @Override public int intValue() { return value.intValueExact(); } @Override public long longValue() { return value.longValueExact(); } @Override public float floatValue() { return value.floatValue(); } @Override public double doubleValue() { return value.doubleValue(); } public BigInteger bigIntegerValue() { return value.toBigIntegerExact(); } public Amount newIssuer(AccountID issuer) { return new Amount(value, currency, issuer); } public Amount copy() { return new Amount(value, currency, issuer, isNative, unbounded); } // Static constructors public static Amount fromString(String val) { if (val.contains("/")) { return fromIOUString(val); } else if (val.contains(".")) { return fromXrpString(val); } else { return fromDropString(val); } } public static Amount fromDropString(String val) { BigDecimal drops = new BigDecimal(val).scaleByPowerOfTen(-6); checkDropsValueWhole(val); return new Amount(drops); } public static Amount fromIOUString(String val) { String[] split = val.split("/"); if (split.length == 1) { throw new RuntimeException("IOU string must be in the form number/currencyString or number/currencyString/issuerString"); } else if (split.length == 2) { return new Amount(new BigDecimal(split[0]), split[1]); } else { return new Amount(new BigDecimal(split[0]), split[1], split[2]); } } @Deprecated private static Amount fromXrpString(String valueString) { BigDecimal val = new BigDecimal(valueString); return new Amount(val); } /** * @return A String representation as used by ripple json format */ public String stringRepr() { if (isNative()) { return toDropsString(); } else { return iouTextFull(); } } public String toDropsString() { if (!isNative()) { throw new RuntimeException("Amount is not native"); } return bigIntegerDrops().toString(); } private String iouText() { return String.format("%s/%s", valueText(), currencyString()); } public String iouTextFull() { return String.format("%s/%s/%s", valueText(), currencyString(), issuerString()); } public String toTextFull() { if (isNative()) { return nativeText(); } else { return iouTextFull(); } } public String nativeText() { return String.format("%s/XRP", valueText()); } @Override public String toString() { return toTextFull(); } public String toText() { if (isNative()) { return nativeText(); } else { return iouText(); } } /** * @return A String containing the value as a decimal number (in XRP scale) */ public String valueText() { return value.signum() == 0 ? "0" : value().toPlainString(); } public void checkLowerDropBound(BigDecimal val) { if (val.scale() > 6) { PrecisionError bigger = getOutOfBoundsError(val, "smaller than min native value", MIN_NATIVE_VALUE); bigger.illegal = this; throw bigger; } } public void checkUpperBound(BigDecimal val) { if (val.compareTo(MAX_NATIVE_VALUE) == 1) { PrecisionError bigger = getOutOfBoundsError(val, "bigger than max native value ", MAX_NATIVE_VALUE); bigger.illegal = this; throw bigger; } } private static PrecisionError getOutOfBoundsError(BigDecimal abs, String sized, BigDecimal bound) { return new PrecisionError(abs.toPlainString() + " absolute XRP is " + sized + bound); } public void checkXRPBounds() { BigDecimal v = value.abs(); if (v.compareTo(TAKER_PAYS_FOR_THAT_DAMN_OFFER) == 0) { return; } checkLowerDropBound(v); checkUpperBound(v); } private static int significantDigits(BigDecimal input) { input = input.stripTrailingZeros(); return input.scale() < 0 ? input.precision() - input.scale() : input.precision(); } public int significantDigits() { return significantDigits(value); } public static void checkDropsValueWhole(String drops) { boolean contains = drops.contains("."); if (contains) { throw new RuntimeException("Drops string contains floating point is decimal"); } } public static BigDecimal roundValue(BigDecimal value, boolean nativeSrc) { int i = value.precision() - value.scale(); return value.setScale(nativeSrc ? MAXIMUM_NATIVE_SCALE : MAXIMUM_IOU_PRECISION - i, MATH_CONTEXT.getRoundingMode()); } private static BigDecimal parseDecimal(String s) { return new BigDecimal(s.replace(",", "")); //# .scaleByPowerOfTen(6); } private static AmountField amountField(final Field f) { return new AmountField() { @Override public Field getField() { return f; } }; } static public AmountField Amount = amountField(Field.Amount); static public AmountField Balance = amountField(Field.Balance); static public AmountField LimitAmount = amountField(Field.LimitAmount); static public AmountField DeliveredAmount = amountField(Field.DeliveredAmount); static public AmountField TakerPays = amountField(Field.TakerPays); static public AmountField TakerGets = amountField(Field.TakerGets); static public AmountField LowLimit = amountField(Field.LowLimit); static public AmountField HighLimit = amountField(Field.HighLimit); static public AmountField Fee = amountField(Field.Fee); static public AmountField SendMax = amountField(Field.SendMax); static public AmountField MinimumOffer = amountField(Field.MinimumOffer); static public AmountField RippleEscrow = amountField(Field.RippleEscrow); static public AmountField taker_gets_funded = amountField(Field.taker_gets_funded); static public AmountField taker_pays_funded = amountField(Field.taker_pays_funded); }
true
16e3cb09df70c87a7055f0816057a7f8c20dbbc3
Java
Juwaria/PuzBug
/test_snippet/4Pieces/S11IC11.java
UTF-8
310
3.34375
3
[]
no_license
public class S11IC11 { public static void FloydTriangle(int k) { int n, num = 1, c, d; System.out.println("Floyd's triangle :-"); for ( c = 1 ; c <= n ; c++ ) { for ( d = 1 ; d <= c ; d++ ) { System.out.print(num+" "); num++; } System.out.println(); } } }
true
0172ee47d23d9d444cfda9cff18e4a85d7ff130c
Java
kookeeper/administrativo
/Web/Hibernate/src/br/com/msystem/bo/NfiscaisBo.java
ISO-8859-1
14,483
2.03125
2
[]
no_license
package br.com.msystem.bo; import java.math.BigDecimal; import java.util.List; import br.com.msystem.dao.NfiscaisDao; import br.com.msystem.exceptions.SystemException; import br.com.msystem.util.Calculos; import br.com.msystem.util.TipoMovimentacaoEstoque; import br.com.msystem.util.TipoNfiscal; import br.com.msystem.vo.Duplicatas; import br.com.msystem.vo.Empresas; import br.com.msystem.vo.Estado; import br.com.msystem.vo.EstadoIva; import br.com.msystem.vo.Naturezas; import br.com.msystem.vo.Nfiscais; import br.com.msystem.vo.NfiscaisItens; import br.com.msystem.vo.NfiscaisItensSerie; import br.com.msystem.vo.Pedidos; import br.com.msystem.vo.PedidosItens; import br.com.msystem.vo.PedidosItensSerie; import br.com.msystem.vo.ProdutoNumeroSerie; import br.com.msystem.vo.Produtos; public class NfiscaisBo extends GenericBo<Nfiscais> { private NfiscaisBo(Class<Nfiscais> argClass) throws SystemException { super(argClass); } private static NfiscaisBo instance; public static NfiscaisBo getInstance() throws SystemException { if (instance == null) instance = new NfiscaisBo(Nfiscais.class); return instance; } public void finalizar(Nfiscais instance) throws SystemException { if (instance.getConcluida().equals("S")) return; if (instance.getPedidos().getBaixouEstoque() == 'S') return; if (instance.getNaturezasByNaturezaSq().getEntSai().equals("")) return; boolean entrada = instance.getNaturezasByNaturezaSq().getEntSai() .equals("E"); ProdutoNumeroSerieBo produtoNumeroSerieBo = (ProdutoNumeroSerieBo) GenericBo .getInstance(ProdutoNumeroSerie.class); ProdutosBo produtoBo = (ProdutosBo) GenericBo .getInstance(Produtos.class); for (NfiscaisItens item : instance.getNfiscaisItenses()) { Integer numeroEstoque = item.getNumeroEstoque(); if (numeroEstoque == 0) { if (entrada) { numeroEstoque = instance.getNaturezasByNaturezaSq() .getNumeroEstoqueEntrada(); } else { numeroEstoque = instance.getNaturezasByNaturezaSq() .getNumeroEstoqueSaida(); } } if (item.getProdutos().getControleNumeroSerie() == 1) { for (NfiscaisItensSerie itemSerie : item .getNfiscaisItensSeries()) { TipoMovimentacaoEstoque tipoMovimentacao = TipoMovimentacaoEstoque .valueOf(instance.getNaturezasByNaturezaSq() .getEntSai()); produtoNumeroSerieBo.movimentarEstoque(itemSerie .getProdutoNumeroSerie().getNumeroSerie(), tipoMovimentacao, item.getProdutos(), numeroEstoque, instance.getNumeroNfiscal(), null, item.getVlrTotalItem()); /* * produtoNumeroSerieBo.registrarSaida(itemSerie * .getProdutoNumeroSerie().getNumeroSerie(), * instance.getDtemissaoNfiscal(), item * .getVlrTotalItem().longValue(), * instance.getNumeroNfiscal()); */ /* * produtoNumeroSerieBo.registrarEntrada(itemSerie * .getProdutoNumeroSerie().getNumeroSerie(), item * .getProdutos(), numeroEstoque, instance * .getDtemissaoNfiscal(), instance .getNumeroNfiscal(), * item.getVlrTotalItem() .longValue()); */ } } else { produtoBo.movimentarEstoque(instance.getDtemissaoNfiscal(), item.getNrSerieItem(), numeroEstoque, item .getProdutos(), item.getQtdeItem(), TipoMovimentacaoEstoque.valueOf(instance .getNaturezasByNaturezaSq().getEntSai()), null, item.getVlrTotalItem().longValue(), instance .getNumeroNfiscal()); } // transferencia de produto if ((TipoMovimentacaoEstoque.valueOf(instance .getNaturezasByNaturezaSq().getEntSai()) .equals(TipoMovimentacaoEstoque.Saida)) && (instance.getNaturezasByNaturezaSq() .getNumeroEstoqueEntrada() > 0)) { produtoBo.movimentarEstoque(instance.getDtemissaoNfiscal(), item.getNrSerieItem(), instance .getNaturezasByNaturezaSq() .getNumeroEstoqueEntrada(), item.getProdutos(), item.getQtdeItem(), TipoMovimentacaoEstoque.Entrada, null, item.getVlrTotalItem().longValue(), instance .getNumeroNfiscal()); } // transferencia de produto if ((TipoMovimentacaoEstoque.valueOf(instance .getNaturezasByNaturezaSq().getEntSai()) .equals(TipoMovimentacaoEstoque.Entrada)) && (instance.getNaturezasByNaturezaSq() .getNumeroEstoqueSaida() > 0)) { produtoBo.movimentarEstoque(instance.getDtemissaoNfiscal(), item.getNrSerieItem(), instance .getNaturezasByNaturezaSq() .getNumeroEstoqueSaida(), item.getProdutos(), item.getQtdeItem(), TipoMovimentacaoEstoque.Saida, null, item.getVlrTotalItem().longValue(), instance .getNumeroNfiscal()); } } instance.setConcluida("S"); instance.setCancelada("N"); salvar(instance); } public void atualizarItens(Nfiscais instance) throws SystemException { for (NfiscaisItens item : instance.getNfiscaisItenses()) { long valorUnitarioSemIpi = 0; long valorTotal = 0; long porcentagemDesconto = 0; long porcentagemJuros = 0; long valorFrete = 0; long valorSeguro = 0; long valorDespAcess = 0; Long aliqIcmsItem = 0l; Long aliqIpiItem = 0l; Long vlrIpiItem = 0l; Long vlrIcmsItem = 0l; Long baseIcmsSubstItem = 0l; Long vlrIcmsSubstItem = 0l; Long baseIcmsItem = 0l; Long vlrTotalItem = 0l; Calculos.atualizaItem(instance.getClientes(), item.getProdutos(), instance.getNaturezasByNaturezaSq(), instance .getCondPagto(), item.getVlrUnitItem().longValue(), 0l, instance.getCotacaoDolar().longValue(), item .getQtdeItem().longValue(), aliqIcmsItem, aliqIpiItem, vlrIpiItem, valorUnitarioSemIpi, valorTotal, vlrTotalItem, porcentagemDesconto, vlrIcmsItem, porcentagemJuros, baseIcmsSubstItem, vlrIcmsSubstItem, baseIcmsItem, 0l, valorFrete, valorSeguro, valorDespAcess); item.setBaseIcmsItem(new BigDecimal(baseIcmsItem)); item.setAliqIcmsItem(new BigDecimal(aliqIcmsItem)); item.setVlrIcmsItem(new BigDecimal(vlrIcmsItem)); item.setAliqIpiItem(new BigDecimal(aliqIpiItem)); item.setVlrIpiItem(new BigDecimal(vlrIpiItem)); item.setVlrTotalItem(new BigDecimal(vlrTotalItem)); item.setBaseIcmsSubstItem(new BigDecimal(baseIcmsSubstItem)); item.setVlrIcmsSubstItem(new BigDecimal(vlrIcmsSubstItem)); } } public void totalizarNfiscal(Nfiscais instance) throws SystemException { if (instance.getConcluida().equals("S")) return; atualizarItens(instance); Long aliquotaIcms = 0l; Long baseIcms = 0l; Long valorIcms = 0l; Long valorIpi = 0l; Long valorProdutos = 0l; Long pesoBruto = 0l; Long pesoLiquido = 0l; Long baseIcmsSubst = 0l; Long valorIcmsSubst = 0l; Long valorFrete = 0l; Long valorSeguro = 0l; Long valorDespAcess = 0l; Long valorII = 0l; long aliquotaIvaMenor = 0; AbstractBo<EstadoIva> estadoIvaBo = GenericBo .getInstance(EstadoIva.class); DuplicatasBo duplicataBo = (DuplicatasBo) GenericBo .getInstance(Duplicatas.class); for (NfiscaisItens item : instance.getNfiscaisItenses()) { Estado estado = new Estado(); estado.setCodigoEstado(instance.getClientes().getEstado()); EstadoIva exemplo = new EstadoIva(item.getProdutos().getNbm(), estado); EstadoIva estadoIva = estadoIvaBo.listar(exemplo, false, null).get( 0); if ((aliquotaIvaMenor == 0) || (aliquotaIvaMenor > estadoIva.getAliqIva().longValue())) { aliquotaIvaMenor = estadoIva.getAliqIva().longValue(); } if (item.getAliqIcmsItem().longValue() > aliquotaIcms) { aliquotaIcms = item.getAliqIcmsItem().longValue(); } baseIcms += item.getBaseIcmsItem().longValue(); valorIcms += item.getVlrIcmsItem().longValue(); valorIpi += item.getVlrIpiItem().longValue(); valorProdutos += item.getVlrTotalItem().longValue(); pesoBruto += item.getPesoBruto().longValue(); pesoLiquido += item.getPesoLiquido().longValue(); baseIcmsSubst += item.getBaseIcmsSubstItem().longValue(); valorIcmsSubst += item.getVlrIcmsSubstItem().longValue(); valorFrete += item.getVlrFreteItem().longValue(); valorSeguro += item.getVlrSeguroItem().longValue(); valorDespAcess += item.getVlrDespAcessItem().longValue(); valorII += item.getVlrIiItem().longValue(); } instance.setBaseIcms(new BigDecimal(baseIcms)); instance.setVlrIcms(new BigDecimal(valorIcms)); instance.setBaseIcmsSubst(new BigDecimal(baseIcmsSubst)); instance.setVlrIcmsSubst(new BigDecimal(valorIcmsSubst)); instance.setVlrIpi(new BigDecimal(valorIpi)); instance.setVlrProdutos(new BigDecimal(valorProdutos)); instance.setVlrTotal(new BigDecimal(valorProdutos + valorFrete + valorSeguro + valorIpi + valorDespAcess + valorIcmsSubst)); instance.setPbrutoTransp(pesoBruto.toString()); instance.setPliquidoTransp(pesoLiquido.toString()); instance.setVlrFrete(new BigDecimal(valorFrete)); instance.setVlrSeguro(new BigDecimal(valorSeguro)); instance.setVlrDespAcess(new BigDecimal(valorDespAcess)); instance.setVlrIi(new BigDecimal(valorII)); duplicataBo.atualizarCondicaoPagamento(instance .getNaturezasByNaturezaSq().getTipoNfiscal(), instance .getCondPagto(), instance.getNumeroNfiscal(), instance .getVlrTotal().longValue(), instance.getDtemissaoNfiscal(), instance.getDiasDemonstracao()); } public Nfiscais importarPedido(Pedidos pedido) throws SystemException { Empresas empresa = GenericBo.getInstance(Empresas.class).buscaPorId(1); Nfiscais instance = new Nfiscais(); instance.setPedidos(pedido); instance.setClientes(pedido.getClientes()); instance.setCondPagto(pedido.getCondPagto()); instance.setNaturezasByNaturezaSq(pedido.getNaturezas()); instance.setTransportadoras(pedido.getTransportadoras()); instance.setVendedores(pedido.getVendedores()); instance.setMensagem(pedido.getObservacaoNf()); instance.setCotacaoDolar(pedido.getCotacaoDolar()); instance.setFreteTransp(pedido.getFreteTransp()); instance.setDiasDemonstracao(pedido.getDiasDemonstracao()); instance.setPbrutoTransp(pedido.getPesoBruto().toString()); instance.setPliquidoTransp(pedido.getPesoLiquido().toString()); for (PedidosItens pedidoItem : pedido.getPedidosItenses()) { NfiscaisItens item = new NfiscaisItens(); int qtdeItem = 0; Integer qtdeFaturada = ((NfiscaisDao) dao).quantidadeFaturada( pedido.getPedidoSq(), pedidoItem.getProdutos() .getProdutoSq()); if (pedidoItem.getQtdePedidoItem() <= qtdeFaturada) { continue; } item.setProdutos(pedidoItem.getProdutos()); item.setQtdeItem(qtdeItem); item.setVlrUnitItem(pedidoItem.getPrecoUnit() .add(pedidoItem.getVlrJuros()) .subtract(pedidoItem.getVlrDesc())); item.setStribut(empresa.getStribut()); item.setAliqIcmsItem(pedidoItem.getAliqIcmsItem()); item.setAliqIpiItem(pedidoItem.getAliqIpiItem()); if (qtdeFaturada > 0) { item.setVlrIcmsItem(pedidoItem.getVlrIcmsItem()); item.setVlrIpiItem(pedidoItem.getVlrIpiItem()); item.setVlrTotalItem(pedidoItem.getVlrTotalItem()); } item.setNrSerieItem(pedidoItem.getNrSerieItem()); item.setPesoBruto(pedidoItem.getPesoBruto()); item.setPesoLiquido(pedidoItem.getPesoLiquido()); item.setOrigemMercadoria(pedidoItem.getProdutos() .getOrigemMercadoria()); if (instance.getNfiscaisItenses().size() == 0) { item.setVlrFreteItem(pedido.getVlrFrete()); item.setVlrSeguroItem(pedido.getVlrSeguro()); } item.setNumeroEstoque(pedidoItem.getNumeroEstoque()); for (PedidosItensSerie pedidoItemSerie : pedidoItem .getPedidosItensSeries()) { NfiscaisItensSerie itemSerie = new NfiscaisItensSerie( pedidoItemSerie.getProdutoNumeroSerie(), null); item.getNfiscaisItensSeries().add(itemSerie); } instance.getNfiscaisItenses().add(item); } return instance; } @Override public void validarRegistro(Nfiscais instance) throws SystemException { if (!instance.getUfPlacaTransp().equals("")) { Estado exemplo = new Estado(instance.getUfPlacaTransp(), null, null, 0, null); if (GenericBo.getInstance(Estado.class) .listar(exemplo, false, null).size() == 0) { throw new SystemException("Estado invlido."); } } if (TipoNfiscal.fromInteger( instance.getNaturezasByNaturezaSq().getTipoNfiscal()).equals( TipoNfiscal.Demonstracao)) { if ((instance.getDiasDemonstracao() == null) || (instance.getDiasDemonstracao() == 0)) { throw new SystemException( "Dias em demonstrao: Informao obrigatria para esta natureza."); } } if (instance.getClientes() == null) { throw new SystemException("Cliente no selecionado."); } if (instance.getCondPagto() == null) { throw new SystemException("Condio de pagamento no selecionada."); } if (instance.getNaturezasByNaturezaSq() == null) throw new SystemException("Natureza da Operao no selecionada."); if (instance.getTransportadoras() == null) throw new SystemException("Transportadora no selecionada."); if (instance.getVendedores() == null) throw new SystemException("Vendedor no selecionado."); NaturezasBo naturezaBo = (NaturezasBo) GenericBo .getInstance(Naturezas.class); naturezaBo.verificarEstado(instance.getNaturezasByNaturezaSq(), instance.getClientes().getEstado()); if (instance.getNfiscalSqReferencia() != null) { if (instance.getNfiscalSqReferencia().equals( instance.getNfiscalSq())) { throw new SystemException("Nota fiscal referncia invlida."); } Nfiscais exemplo = new Nfiscais(); exemplo.setNumeroNfiscal(instance.getNfiscalSqReferencia()); List<Nfiscais> lista = listar(exemplo, false, null); if (lista.size() == 0) { throw new SystemException("Nota fiscal referncia no existe."); } } for (int i = 0; i < instance.getPlacaTransp().length(); i++) { char c = instance.getPlacaTransp().charAt(i); if (((c >= 65) && (c <= 90)) || ((c >= 48) && (c <= 57))) { throw new SystemException( "Caracter invlido na placa da transportadora (" + Character.toString(c) + ")."); } } } }
true
a0d2a32701bb8579f32518b8bf8a2f8f0904878f
Java
mashnoor/doctorbaari_app_main
/app/src/main/java/com/doctorbaari/android/acvities/Reviews.java
UTF-8
2,900
2.109375
2
[]
no_license
package com.doctorbaari.android.acvities; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import com.doctorbaari.android.R; import com.doctorbaari.android.adapters.ReviewsListAdapter; import com.doctorbaari.android.models.Review; import com.doctorbaari.android.utils.Constants; import com.doctorbaari.android.utils.Geson; import com.doctorbaari.android.utils.HelperFunc; import com.doctorbaari.android.utils.ListViewEmptyMessageSetter; import com.doctorbaari.android.utils.SideNToolbarController; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import butterknife.BindView; import butterknife.ButterKnife; import cz.msebera.android.httpclient.Header; public class Reviews extends AppCompatActivity { AsyncHttpClient client; ProgressDialog dialog; @BindView(R.id.lvReviews) ListView lvReviews; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reviews); ButterKnife.bind(this); SideNToolbarController.attach(this, "Reviews"); ListViewEmptyMessageSetter.set(this, lvReviews, "No Reviews"); client = new AsyncHttpClient(); dialog = new ProgressDialog(this); dialog.setMessage("Connecting to server..."); loadReviews(); } private void loadReviews() { //Set Empty Review Intent i = getIntent(); String userid = i.getStringExtra("userid"); RequestParams params = new RequestParams(); params.put("reviewed_to", userid); client.post(Constants.GET_REVIEWS, params, new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); dialog.show(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String response = new String(responseBody); Review[] reviews = Geson.g().fromJson(response, Review[].class); ReviewsListAdapter adapter = new ReviewsListAdapter(Reviews.this, reviews); lvReviews.setAdapter(adapter); dialog.dismiss(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { HelperFunc.showToast(Reviews.this, "Something went wrong"); dialog.dismiss(); } }); } @Override protected void onPause() { super.onPause(); SideNToolbarController.closeDrawer(); overridePendingTransition(R.anim.enter, R.anim.exit); } }
true
c6a464069596f2fe728d1ea143ae189330266485
Java
DimaStoyanov/Ifmo-code
/Technologies_Programming/decorator/BracketDecorator.java
UTF-8
551
3.21875
3
[]
no_license
package decorator; import java.io.PrintStream; /** * Created by Dima Stoyanov. */ public class BracketDecorator<E> extends Decorator<E> { Character leftBracket, rightBracket; BracketDecorator(Sequence<E> sequence, char leftBracket, char rightBracket) { super(sequence); this.leftBracket = leftBracket; this.rightBracket = rightBracket; } @Override public void decorate(String delimiter, PrintStream ps) { ps.print(leftBracket); print(delimiter, ps); ps.print(rightBracket); } }
true
fb1234098815e87784d2a29f786095522f1f6f7a
Java
bessl/fdb
/src/main/java/dao/TagDAO.java
UTF-8
198
2.046875
2
[]
no_license
package dao; import java.sql.Connection; import java.util.List; import model.Tag; public interface TagDAO extends BaseDAO<Tag> { public List<Tag> findBySlug(Connection connection, String slug); }
true
7e98290059f7e6785557553ec95584dbc614fc6d
Java
Hyeongjoon/IDBDApp
/app/src/main/java/com/idbd/admin/myapplication/MainSub1Fragment.java
UTF-8
5,001
2.03125
2
[]
no_license
package com.idbd.admin.myapplication; import android.app.ProgressDialog; import android.content.DialogInterface; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.idbd.admin.myapplication.Helper.MakeDialog; import com.idbd.admin.myapplication.Helper.Post; import com.idbd.admin.myapplication.Helper.TokenInfo; import com.google.firebase.iid.FirebaseInstanceId; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.FormBody; import okhttp3.RequestBody; /** * Created by admin on 2017-01-12. */ @EFragment(R.layout.fragment_content1) public class MainSub1Fragment extends Fragment{ private String addCode = "http://52.78.18.19/gr/addByCode/"; ProgressDialog pDialog; @ViewById(R.id.main_sub1_input) EditText codeInput; @Click(R.id.addCode) public void addCodeBtn(){ String code = codeInput.getText().toString().trim(); codeInput.setText(""); if(code.length()!=5){ makeDialog(getString(R.string.main_sub1_wrong_code_dialog)); } else{ makeInputDialog(code); } } @Background public void addCode(String code , String name){ RequestBody formBody = new FormBody.Builder() .add("code" , code) .add("name" , name) .add("reg_id", FirebaseInstanceId.getInstance().getToken()) .build(); try { JSONObject result = new JSONObject(Post.post(addCode + TokenInfo.getTokenId(),formBody)); if(result.get("result").equals("true")){ pDialog.cancel(); toRight(); ((MainSub2Fragment)((MainActivity)getActivity()).getFragmentItem(1)).InsertGr(result); //2번에 붙어있는 어뎁터 불러와서 데이터 0번에 삽입 //추가 정상적으로 되고 넘어왔을때 } else if(result.get("content").equals("code")){ pDialog.cancel(); makeDialog(getString(R.string.main_sub1_wrong_code_dialog)); //코드가 틀린코드를 입력했을때 } else if(result.get("content").equals("duplication")){ pDialog.cancel(); makeDialog(getString(R.string.main_sub1_dupli_code)); //코드가 이미 있을때 } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } @UiThread public void makeDialog(String content){ MakeDialog.oneBtnDialog(getActivity() , content); } @UiThread public void toRight(){ ((MainActivity)getActivity()).mViewPager.arrowScroll(View.FOCUS_RIGHT); } @UiThread public void makeInputDialog(final String code){ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getActivity()); final View mView = layoutInflaterAndroid.inflate(R.layout.user_input_dialog_box, null); builder.setView(mView) .setCancelable(true) .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String gr_title = ((EditText)mView.findViewById(R.id.userInputDialog)).getText().toString().trim(); if(gr_title.length()==0){ MakeDialog.oneBtnDialog(getActivity() , getString(R.string.wrong_gr_name_input)); } else{ pDialog = ProgressDialog.show(getActivity(), "그룹 추가중입니다.", "Please wait", true, false); addCode(code , gr_title ); } } }) .setNegativeButton(R.string.dialog_cancle, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }); TextView titleText = (TextView)mView.findViewById(R.id.dialogTitle); titleText.setText(R.string.main_sub2_gr_create_dialog_title); builder.show(); //Edit Text에서 불러오는법 몰라서 일단 여기다가 넣어놓음................후........ } }
true
65d5f921419006e0badf2fdc5b5eb0657e449830
Java
srujanch/Weka-ML
/src/main/java/com/optum/healthcare/Users.java
UTF-8
779
2.515625
3
[]
no_license
package com.optum.healthcare; public class Users { String name; int age; String gender; String prediction; String isDiabetic; public String getIsDiabetic() { return isDiabetic; } public void setIsDiabetic(String isDiabetic) { this.isDiabetic = isDiabetic; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPrediction() { return prediction; } public void setPrediction(String prediction) { this.prediction = prediction; } }
true
9338aa258af47a66500bd946762bca6c9ba4fb25
Java
michaeldenzler/ProjectGroupNokia3210
/longtermstudy/app/src/main/java/usi/Nokia3210/local/database/db/LocalSQLiteDBHelper.java
UTF-8
4,853
1.773438
2
[]
no_license
package usi.Nokia3210.local.database.db; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.List; import usi.Nokia3210.local.database.tables.AccelerometerTable; import usi.Nokia3210.local.database.tables.ActivityRecognitionTable; import usi.Nokia3210.local.database.tables.ApplicationLogsTable; import usi.Nokia3210.local.database.tables.BlueToothTable; import usi.Nokia3210.local.database.tables.EdiaryTable; import usi.Nokia3210.local.database.tables.FatigueSurveyTable; import usi.Nokia3210.local.database.tables.LectureSurveyTable; import usi.Nokia3210.local.database.tables.NotificationsTable; import usi.Nokia3210.local.database.tables.OverallSurveyTable; import usi.Nokia3210.local.database.tables.PAMSurveyTable; import usi.Nokia3210.local.database.tables.PAMTable; import usi.Nokia3210.local.database.tables.PSQISurveyTable; import usi.Nokia3210.local.database.tables.PSSSurveyTable; import usi.Nokia3210.local.database.tables.PersonalitySurveyTable; import usi.Nokia3210.local.database.tables.PhoneCallLogTable; import usi.Nokia3210.local.database.tables.LocationTable; import usi.Nokia3210.local.database.tables.PhoneLockTable; import usi.Nokia3210.local.database.tables.ProductivitySurveyTable; import usi.Nokia3210.local.database.tables.SMSTable; import usi.Nokia3210.local.database.tables.SWLSSurveyTable; import usi.Nokia3210.local.database.tables.SimpleMoodTable; import usi.Nokia3210.local.database.tables.SleepQualityTable; import usi.Nokia3210.local.database.tables.StressSurveyTable; import usi.Nokia3210.local.database.tables.UploaderUtilityTable; import usi.Nokia3210.local.database.tables.UserTable; import usi.Nokia3210.local.database.tables.WeeklySurveyTable; import usi.Nokia3210.local.database.tables.WiFiTable; /** * Created by shkurtagashi on 29/12/16. */ public class LocalSQLiteDBHelper extends SQLiteOpenHelper { //db information private static final int DATABASE_VERSION = 3; private static final String DATABASE_NAME = "Memotion"; private SQLiteDatabase db; public LocalSQLiteDBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); db = getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { //create actual data table db.execSQL(LocationTable.getCreateQuery()); db.execSQL(AccelerometerTable.getCreateQuery()); db.execSQL(PhoneCallLogTable.getCreateQuery()); db.execSQL(SMSTable.getCreateQuery()); db.execSQL(BlueToothTable.getCreateQuery()); db.execSQL(PhoneLockTable.getCreateQuery()); db.execSQL(WiFiTable.getCreateQuery()); db.execSQL(UploaderUtilityTable.getCreateQuery()); db.execSQL(UserTable.getCreateQuery()); db.execSQL(SimpleMoodTable.getCreateQuery()); db.execSQL(PAMTable.getCreateQuery()); db.execSQL(LectureSurveyTable.getCreateQuery()); db.execSQL(NotificationsTable.getCreateQuery()); db.execSQL(ApplicationLogsTable.getCreateQuery()); db.execSQL(ActivityRecognitionTable.getCreateQuery()); db.execSQL(PersonalitySurveyTable.getCreateQuery()); db.execSQL(SWLSSurveyTable.getCreateQuery()); db.execSQL(PSSSurveyTable.getCreateQuery()); db.execSQL(PSQISurveyTable.getCreateQuery()); db.execSQL(SleepQualityTable.getCreateQuery()); db.execSQL(FatigueSurveyTable.getCreateQuery()); db.execSQL(OverallSurveyTable.getCreateQuery()); db.execSQL(ProductivitySurveyTable.getCreateQuery()); db.execSQL(StressSurveyTable.getCreateQuery()); db.execSQL(WeeklySurveyTable.getCreateQuery()); db.execSQL(PAMSurveyTable.getCreateQuery()); db.execSQL(EdiaryTable.getCreateQuery()); //insert init data to uploader_utility table insertRecords(db, UploaderUtilityTable.TABLE_UPLOADER_UTILITY, UploaderUtilityTable.getRecords()); Log.d("DATABASE HELPER", "Db created"); } /** * Utility function to insert the given records in the given table. * * @param db * @param tableName * @param records */ private void insertRecords(SQLiteDatabase db, String tableName, List<ContentValues> records) { for(ContentValues record: records) { Log.d("DBHelper", "Inserting into table " + tableName + " record " + record.toString()); db.insert(tableName, null, record); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d("DBHelper", "Upgrading db. Truncating accelerometer"); db.execSQL("delete from "+ AccelerometerTable.TABLE_ACCELEROMETER); return; } }
true
2bbfa1858465307379ecded59b1b287d3d760daa
Java
smilelie2/e-commerce
/src/main/java/com/th/ac/ku/kps/cpe/ecommerce/model/buyer/ratingshop/read/RatingShopBodyReadResponse.java
UTF-8
407
1.8125
2
[]
no_license
package com.th.ac.ku.kps.cpe.ecommerce.model.buyer.ratingshop.read; public class RatingShopBodyReadResponse { private RatingShopRatingShopBodyReadResponse rating_shop; public RatingShopRatingShopBodyReadResponse getRating_shop() { return rating_shop; } public void setRating_shop(RatingShopRatingShopBodyReadResponse rating_shop) { this.rating_shop = rating_shop; } }
true
54998efc14d1b9997bd48d0dc194a5d235f3dbad
Java
maslakonetop/sargap01
/app/src/main/java/id/co/gesangmultimedia/sergap/Sosmed.java
UTF-8
3,134
1.835938
2
[ "Apache-2.0" ]
permissive
package id.co.gesangmultimedia.sergap; import android.media.Image; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.Button; import android.widget.ImageButton; public class Sosmed extends Fragment { Button btnLogo, btnFacebook, btnInstagram, btnTwitter; WebView browser; public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_sosmed, container, false); final WebView browser = (WebView) view.findViewById(R.id.wvTribrata); browser.loadUrl("https://tribratanews.jateng.polri.go.id/"); browser.getSettings().setUseWideViewPort(true); browser.getSettings().setLoadWithOverviewMode(true); Button btnLogo = (Button) view.findViewById(R.id.btnLogo); btnLogo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final WebView browser = (WebView) view.findViewById(R.id.wvTribrata); browser.loadUrl("https://tribratanews.jateng.polri.go.id/"); browser.getSettings().setUseWideViewPort(true); browser.getSettings().setLoadWithOverviewMode(true); } }); Button btnFacebook = (Button) view.findViewById(R.id.btnFacebook); btnFacebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final WebView browser = (WebView) view.findViewById(R.id.wvTribrata); browser.loadUrl("https://www.facebook.com/polrescilacap"); browser.getSettings().setUseWideViewPort(true); browser.getSettings().setLoadWithOverviewMode(true); } }); Button btnInstagram = (Button) view.findViewById(R.id.btnInstagram); btnInstagram.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final WebView browser = (WebView) view.findViewById(R.id.wvTribrata); browser.loadUrl("https://www.instagram.com/team_terkam_polrescilacap/"); browser.getSettings().setUseWideViewPort(true); browser.getSettings().setLoadWithOverviewMode(true); } }); Button btnTwitter = (Button) view.findViewById(R.id.btnTwitter); btnTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final WebView browser = (WebView) view.findViewById(R.id.wvTribrata); browser.loadUrl("https://twitter.com/BinmasCilacap"); browser.getSettings().setUseWideViewPort(true); browser.getSettings().setLoadWithOverviewMode(true); } }); return view; } }
true
7ec69177b2a13466684b207d6d56f83b9ede9392
Java
LuizCasagrande/marmita_serve
/src/main/java/com/marmitex/model/Pedido.java
UTF-8
2,284
2.171875
2
[]
no_license
package com.marmitex.model; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.marmitex.Enum.DiaSemana; import com.marmitex.config.LocalDateDeserializer; import com.marmitex.config.LocalDateSerializer; import lombok.Data; import lombok.ToString; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import javax.persistence.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @Data @Entity @Table(name = "PEDIDO") @ToString(of = "id") public class Pedido { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private Long id ; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) @Column(name = "DATA") private LocalDate data; @JsonManagedReference @OneToMany(mappedBy = "pedido", cascade = CascadeType.ALL, orphanRemoval = true) private List<TamanhoPedido> tamanhoPedidoList = new ArrayList<>(); @OneToOne @JoinColumn(name = "ID_CLIENTE", nullable = false) private Cliente cliente; @OneToOne @JoinColumn(name = "ID", nullable = false) private Cardapio cardapio; ; @Column(name = "STATUS") private boolean status = false; @Column(name = "PAGO") private boolean pago = false; @Enumerated(EnumType.STRING) @Column(name = "DIA_SEMANA") private DiaSemana diaSemana; @Column(name = "VALOR_TOTAL") private Double valorTotal; @PrePersist public void preSave() { var dataAtual = LocalDate.now(); if (diaSemana.getDia() < dataAtual.getDayOfWeek().getValue()) { throw new RuntimeException("Não é possivel fazer um pedido para data anterior da atual"); } var diferencaDias = diaSemana.getDia() - dataAtual.getDayOfWeek().getValue(); data = dataAtual.plusDays(diferencaDias); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Cliente cliente = (Cliente) authentication.getPrincipal(); this.setCliente(cliente); } }
true
0d695f5f65932a3d338d6d2fb35dcaffd3be8220
Java
Java-Events/20171102_Vaadin-DevDay-2017-memory-leaks
/modules/trainer/ui/src/test/java/demo/org/rapidpm/vaadin/demo/memoryleak/references/SoftReferenceDemo.java
UTF-8
508
2.46875
2
[]
no_license
package demo.org.rapidpm.vaadin.demo.memoryleak.references; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.List; /** * run this with -Xmx5m -Xms5m */ public class SoftReferenceDemo extends AbstractReferenceDemo { public static void main(String[] args) { new SoftReferenceDemo().doWork(); } @Override public void createReference(int i , List<Reference<MyObject>> references) { references.add(new SoftReference<>(new MyObject("soft " + i))); } }
true
1a6a3e634ac1494c79e3ba44e2de4dbae82a1549
Java
YunTang1997/JavaLearning
/DataStructuresAndAlgorithms/src/main/java/map/HashTableDemo.java
UTF-8
7,045
3.90625
4
[]
no_license
package main.java.map; import java.io.DataOutputStream; import java.util.Scanner; /** * 有一个公司,当有新的员工来报道时,要求将该员工的信息加入(id,性别,年龄,住址..),当输入该员工的id时,要求查找到该员工的所有信息。 * 要求:不使用数据库,尽量节省内存,速度越快越好=>哈希表(散列) * @author YunTang * @create 2020-08-08 16:52 */ public class HashTableDemo { public static void main(String[] args) { //创建哈希表 HashTab hashTab = new HashTab(7); //写一个简单的菜单 String key = ""; boolean loop = true; Scanner scanner = new Scanner(System.in); while (loop) { System.out.println("add: 添加雇员"); System.out.println("show: 显示雇员"); System.out.println("find: 查找雇员"); System.out.println("del: 删除雇员"); System.out.println("exit: 退出系统"); key = scanner.next(); switch (key) { case "add": System.out.println("输入id"); int id = scanner.nextInt(); System.out.println("输入名字"); String name = scanner.next(); //创建 雇员 Employee emp = new Employee(id, name); hashTab.add(emp); break; case "show": hashTab.showHashTab(); break; case "find": System.out.println("请输入要查找的id:"); id = scanner.nextInt(); hashTab.findEmployeeById(id); break; case "del": System.out.println("请输入要删除的id:"); id = scanner.nextInt(); hashTab.delEmployeeById(id); break; case "exit": scanner.close(); loop = false; default: break; } } } } // 创建HashTab class HashTab { private EmployeeLinkedList[] employeeLinkedLists; private int size; public HashTab(int size) { this.size = size; // 初始化empLinkedListArray employeeLinkedLists = new EmployeeLinkedList[size]; // 这时不要忘记分别初始化每个链表 for (int i = 0; i < size; i++) { employeeLinkedLists[i] = new EmployeeLinkedList(); } } public void add(Employee employee) { // 根据员工的id,得到该员工应当添加到哪条链表 int index = HashFun(employee.id); // 将employee添加到对应的链表中 employeeLinkedLists[index].add(employee); } // 遍历所有的链表,遍历HashTab public void showHashTab() { for (int i = 0; i < size; i++) { employeeLinkedLists[i].showEmployee(i); } } // 根据id查找雇员 public void findEmployeeById(int id) { int index = HashFun(id); Employee byId = employeeLinkedLists[index].findById(id); if (byId == null) { System.out.println("查找的雇员不存在"); } else{ System.out.printf("在第%d条链表中找到雇员id = %d\n", index + 1, id); } } // 根据id删除雇员 public void delEmployeeById(int id) { int index = HashFun(id); boolean res = employeeLinkedLists[index].del(id); if (res) { System.out.println("删除成功"); } else { System.out.println("删除失败"); } } // 编写散列函数,使用一个简单取模法 public int HashFun(int n) { return n % size; } } // 表示一个雇员 class Employee { public int id; public String name; public Employee next; public Employee(int id, String name) { this.id = id; this.name = name; } } // 创建EmployeeLinkedList class EmployeeLinkedList { // 头指针,执行第一个Employee,因此这个链表的head是直接指向第一个Employee private Employee head; // 添加雇员到链表 // 说明:假定,当添加雇员时,id是自增长,即id的分配总是从小到大,因此我们将该雇员直接加入到本链表的最后即可 public void add(Employee employee) { // 如果是添加第一个雇员 if (head == null) { head = employee; return; } // 插在头节点前面 if (head.id > employee.id) { employee.next = head; head = employee; // 别忘了将head拿到链表头部 return; } // 如果不是第一个雇员,则使用一个辅助的指针,帮助定位到最后 Employee cur = head; while(true) { if (cur.next == null) { // 找到最后一个节点 break; } if (cur.next.id > employee.id) { // 找到合适的插入位置 break; } cur = cur.next; } // 退出时直接将employee加入链表 employee.next = cur.next; cur.next = employee; } // 通过id删除Employee public boolean del(int id) { Employee byId = findById(id); if (byId == null) { System.out.println("所要删除的对象不存在"); return false; } Employee cur = head; while (true) { if (cur.next == byId) { break; } cur = cur.next; } cur.next = byId.next; // 删除节点 return true; } // 遍历雇员信息 public void showEmployee(int no) { if (head == null) { System.out.println("第" + (no + 1) + "链表信息为空"); return; } Employee cur = head; // 辅助指针 System.out.print("第" + (no + 1) + "个雇员的信息为:"); while (true) { System.out.printf(" ==> id = %d, name = %S",cur.id, cur.name); if (cur.next == null) { break; } cur = cur.next; } System.out.println(); } // 根据id查找雇员 // 如果查找到,就返回Employee, 如果没有找到,就返回null public Employee findById(int id) { if (head == null) { System.out.println("链表为空"); return null; } Employee cur = head; while (true) { if (cur.id == id) { // 找到 break; // 这时cur就指向要查找的雇员 } if (cur.next == null) { // 说明遍历当前链表没有找到该雇员 cur = null; break; } cur = cur.next; } return cur; } }
true
544521ea869aa080cbd5f750eb512472cae5e5cf
Java
psette/WorldOfText
/CSCI201_Assignment5_psette/src/other_gui/QuestionGUIElementNetworked.java
UTF-8
8,581
2.453125
2
[]
no_license
package other_gui; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.Timer; import frames.MainGUI; import frames.MainGUINetworked; import game_logic.GameData; import messages.BuzzInMessage; import messages.QuestionAnsweredMessage; import messages.QuestionClickedMessage; import server.Client; //inherits from QuestionGUIElement public class QuestionGUIElementNetworked extends QuestionGUIElement { private static final long serialVersionUID = -6276366816659938513L; private Client client; // very similar variables as in the AnsweringLogic class public Boolean hadSecondChance; private TeamGUIComponents currentTeam; private TeamGUIComponents originalTeam; int teamIndex; int numTeams; public Timer clockTimer; public Timer fishTimer; private MainGUINetworked gui; // stores team index as the key to a Boolean indicating whether they have // gotten a chance to answer the question private HashMap<Integer, Boolean> teamHasAnswered; public QuestionGUIElementNetworked(String question, String answer, String category, int pointValue, int indexX, int indexY) { super(question, answer, category, pointValue, indexX, indexY); setWaitBuzz(false); } // set the client and also set the map with the booleans to all have false public void setClient(Client client, int numTeams) { this.client = client; this.numTeams = numTeams; teamIndex = client.getTeamIndex(); teamHasAnswered = new HashMap<>(); for (int i = 0; i < numTeams; i++) teamHasAnswered.put(i, false); } // returns whether every team has had a chance at answering this question public Boolean questionDone() { Boolean questionDone = true; for (Boolean currentTeam : teamHasAnswered.values()) questionDone = questionDone && currentTeam; return questionDone; } public Timer getTimer() { return timer; } public Timer getClockTimer() { return clockTimer; } private void setClock() { clockTimer = new Timer(83, new ActionListener() { int i = 0; @Override public void actionPerformed(ActionEvent e) { if (images == null) { images = gui.images; } teamLabel.setIcon(images.get(i)); i++; if (i == images.size() - 1) { i = 0; } if (!questionPanel.isVisible()) { ((Timer) e.getSource()).removeActionListener(this); ((Timer) e.getSource()).stop(); } } }); clockTimer.start(); } private void setFish() { fishTimer = new Timer(200, new ActionListener() { int i = 0; @Override public void actionPerformed(ActionEvent e) { if (fishImages == null) { fishImages = gui.fishImages; } if (announcementsLabel.getText().contains("Buzz")) { announcementsLabel.setText("Fish should be removed but this assignment is reallllly hard"); ((Timer) e.getSource()).removeActionListener(this); ((Timer) e.getSource()).stop(); } announcementsLabel.setIcon(fishImages.get(i)); i++; if (i == fishImages.size() - 1) { i = 0; } if (!questionPanel.isVisible()) { ((Timer) e.getSource()).removeActionListener(this); ((Timer) e.getSource()).stop(); } } }); fishTimer.start(); } // overrides the addActionListeners method in super class @Override public void addActionListeners(MainGUI mainGUI, GameData gameData) { gui = ((MainGUINetworked) mainGUI); images = gui.images; passButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { timer.stop(); startTimer(19); client.sendMessage(new BuzzInMessage(teamIndex)); } }); gameBoardButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // send a question clicked message client.sendMessage(new QuestionClickedMessage(getX(), getY())); } }); submitAnswerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { timer.stop(); // send question answered message client.sendMessage(new QuestionAnsweredMessage(answerField.getText())); if (answerField.getText().equals("Too Late!")) { for (int i = 0; i < gameData.getNumberOfTeams(); i++) { mainGUI.teams[i].setIcon(null); mainGUI.teams[i].revalidate(); } answerField.setText("Please enter an answer."); setWaitBuzz(true); } else if (answerField.getText().equals("No one clicked!")) { submitAnswerButton.setEnabled(false); gameData.nextTurn(); gui.addUpdate("The correct answer was: " + getAnswer()); if (gameData.readyForFinalJeoaprdy()) { gui.startFinalJeopardy(); } // if not ready, move on to another question else { // add update to Game Progress, determine whether the // game board // buttons should be enabled or disabled, and change the // main panel gui.addUpdate( "It is " + gameData.getCurrentTeam().getTeamName() + "'s turn to choose a question."); if (gameData.getCurrentTeam().getTeamIndex() != client.getTeamIndex()) gui.disableAllButtons(); for (int i = 0; i < gameData.getNumberOfTeams(); i++) { mainGUI.teams[i].setIcon(null); mainGUI.teams[i].revalidate(); } mainGUI.showMainPanel(); gui.titleTimer(); } } } }); } // override the resetQuestion method @Override public void resetQuestion() { super.resetQuestion(); hadSecondChance = false; currentTeam = null; originalTeam = null; teamHasAnswered.clear(); // reset teamHasAnswered map so all teams get a chance to anaswer again for (int i = 0; i < numTeams; i++) teamHasAnswered.put(i, false); } @Override public void populate() { super.populate(); passButton.setText("Buzz In!"); } public int getOriginalTeam() { return originalTeam.getTeamIndex(); } public void updateAnnouncements(String announcement) { announcementsLabel.setText(announcement); } public void setOriginalTeam(int team, GameData gameData) { originalTeam = gameData.getTeamDataList().get(team); updateTeam(team, gameData); } // update the current team of this question public void updateTeam(int team, GameData gameData) { currentTeam = gameData.getTeamDataList().get(team); passButton.setVisible(false); answerField.setText(""); // if the current team is this client for (int i = 0; i < gameData.getNumberOfTeams(); ++i) { gui.teams[i].setIcon(null); gui.revalidate(); } gui.clockOnTeam(gui.teams[team]); if (team == teamIndex) { teamLabel.setForeground(AppearanceConstants.darkBlue); setClock(); AppearanceSettings.setEnabled(true, submitAnswerButton, answerField); announcementsLabel.setText("It's your turn to try to answer the question!"); startTimer(19); } // if the current team is an opponent else { teamLabel.setForeground(Color.lightGray); teamLabel.setIcon(null); teamLabel.revalidate(); setFish(); AppearanceSettings.setEnabled(false, submitAnswerButton, answerField); announcementsLabel.setText("It's " + currentTeam.getTeamName() + "'s turn to try to answer the question."); } // mark down that this team has had a chance to answer teamHasAnswered.replace(team, true); hadSecondChance = false; teamLabel.setText(currentTeam.getTeamName()); } // called from QuestionAnswerAction when there is an illformated answer public void illFormattedAnswer() { if (currentTeam.getTeamIndex() == teamIndex) { announcementsLabel.setText("You had an illformatted answer. Please try again"); } else { announcementsLabel .setText(currentTeam.getTeamName() + " had an illformatted answer. They get to answer again."); } } // set the gui to be a buzz in period, also called from QuestionAnswerAction public void setBuzzInPeriod() { passButton.setVisible(true); teamLabel.setText(""); teamLabel.setIcon(null); teamLabel.revalidate(); announcementsLabel.setIcon(null); if (teamHasAnswered.get(teamIndex)) { timer.stop(); startTimer(19); AppearanceSettings.setEnabled(false, submitAnswerButton, answerField, passButton); announcementsLabel.setText("It's time to buzz in! But you've already had your chance.."); } else { timer.stop(); startTimer(19); setWaitBuzz(true); announcementsLabel.setText("Buzz in to answer the question!"); passButton.setEnabled(true); AppearanceSettings.setEnabled(false, submitAnswerButton, answerField); } } public TeamGUIComponents getCurrentTeam() { return currentTeam; } }
true
1b5be994ce8c24d7440d8713220e3c11e3166092
Java
hwbsyx/learnGit
/myJAVA/src/annotation/Student.java
UTF-8
453
3.5
4
[]
no_license
package annotation; //使用注解限定学生的名字不能超过6个字符,年龄范围在18-60 public class Student { @NameConstraint(maxLength = 6) public String name; @AgeConstraint(minAge = 18,maxAge = 60) public int age; private Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "名字:"+name+"年龄:"+age; } }
true
289cf913dad2993b1c9b086002a04b3b0a91ff8e
Java
suevip/zplatform-trade
/zplatform-trade-common/src/main/java/com/zlebank/zplatform/trade/dao/ITxnsInsteadPayDAO.java
UTF-8
793
1.992188
2
[]
no_license
package com.zlebank.zplatform.trade.dao; import java.util.List; import com.zlebank.zplatform.commons.dao.BaseDAO; import com.zlebank.zplatform.trade.model.PojoBankTransferBatch; import com.zlebank.zplatform.trade.model.PojoTxnsInsteadPay; public interface ITxnsInsteadPayDAO extends BaseDAO<PojoTxnsInsteadPay>{ /** * 通过回盘文件名称获取代付交易流水 * @param fileName * @return */ public PojoTxnsInsteadPay getByResponseFileName(String fileName); /** * @param batchNo 代付批次号/代付流水号 * 判断文件是否上传 * @return */ public boolean isUpload(String batchNo); /** * 查询博士金点批量代付没有结果的记录 * @return */ public List<PojoTxnsInsteadPay> queryBossPayNoResult(); }
true
7fea2e3ff4b75660e6627d10fedbd70052fa8bd8
Java
DaniyarIndiana/FirstProject
/src/Babies/RandomNumber.java
UTF-8
743
3.71875
4
[]
no_license
package Babies; import java.util.Random; import java.util.Scanner; public class RandomNumber { public static void main(String[] args) { Random random = new Random(); int numberRandom = random.nextInt(10); numberRandom++; System.out.println("Enter guess number from 1 to 10 "); Scanner input = new Scanner(System.in); int guessNumber = input.nextInt(); if (numberRandom==guessNumber){ System.out.println("Congrats you guess number!"); } else if (numberRandom<guessNumber){ System.out.println("Your guess is too high"); } else if (numberRandom>guessNumber){ System.out.println("Your guess is too low"); } } }
true
5868849b46627ebbcc1e2cafaab514138dbe2218
Java
EphecLLN/Fractions2TM1
/src/test/java/tp/FractionTest.java
UTF-8
11,721
2.9375
3
[]
no_license
/** * */ package tp; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * @author Virginie Van den Schrieck * */ class FractionTest { /** * @throws java.lang.Exception */ @BeforeEach void setUp() throws Exception { } /** * Test method for {@link tp.Fraction#Fraction()}. */ @Test void testFraction() { Fraction f = new Fraction(); assertEquals(f.getNumerator(),0); assertNotEquals(f.getDenominator(),0); } /** * Test method for {@link tp.Fraction#Fraction(int, int)}. */ @Test void testFractionIntInt() { Fraction f = new Fraction(2,4); assertEquals(f.getNumerator(),1); assertEquals(f.getDenominator(),2); f = new Fraction(2,-4); assertEquals(f.getNumerator(),-1); assertEquals(f.getDenominator(),2); f = new Fraction(-8,-4); assertEquals(f.getNumerator(),2); assertEquals(f.getDenominator(),1); } /** * Test method for {@link tp.Fraction#Fraction(int, tp.Fraction)}. */ @Test void testFractionIntFraction() { //Test 1+1/2 Fraction f = new Fraction(1,2); Fraction m = new Fraction(1,f); assertEquals(m.getNumerator(),3); assertEquals(m.getDenominator(),2); //Test 2 + 4/2 f = new Fraction(4,2); m = new Fraction(2,f); assertEquals(m.getNumerator(),4); assertEquals(m.getDenominator(),1); } /** * Test method for {@link tp.Fraction#getNumerator()}. */ @Test void testGetNumerator() { Fraction f = new Fraction(2,4); assertEquals(f.getNumerator(),1); } /** * Test method for {@link tp.Fraction#setNumerator(int)}. */ @Test void testSetNumerator() { Fraction f = new Fraction(1,2); f.setNumerator(4); assertEquals(f.getNumerator(),2); } /** * Test method for {@link tp.Fraction#getDenominator()}. */ @Test void testGetDenominator() { Fraction f = new Fraction(1,2); assertEquals(f.getDenominator(),2); f = new Fraction(2,4); assertEquals(f.getDenominator(),2); } /** * Test method for {@link tp.Fraction#setDenominator(int)}. */ @Test void testSetDenominator() { Fraction f = new Fraction(1,2); f.setDenominator(4); assertEquals(f.getDenominator(),4); f = new Fraction(2,3); f.setDenominator(4); assertEquals(f.getDenominator(),2); //Test the case of the null denominator //Method fails silently, i.e. no change to the fraction f.setDenominator(0); assertEquals(f.getDenominator(),2); } /** * Test method for {@link tp.Fraction#toString()}. */ @Test void testToString() { Fraction f = new Fraction(2,4); assertEquals(f.toString(), "1/2"); f = new Fraction(0,4); assertEquals(f.toString(), "0"); f = new Fraction(4,4); assertEquals(f.toString(), "1"); f = new Fraction(-1,4); assertEquals(f.toString(), "-1/4"); f = new Fraction(1,-4); assertEquals(f.toString(), "-1/4"); f = new Fraction(4,3); assertEquals(f.toString(), "4/3"); } /** * Test method for {@link tp.Fraction#asMixedNumber()}. */ @Test void testAsMixedNumber() { Fraction f = new Fraction(2,4); assertEquals("1/2", f.asMixedNumber()); f = new Fraction(0,4); assertEquals("0", f.asMixedNumber()); f = new Fraction(4,4); assertEquals("1", f.asMixedNumber()); f = new Fraction(-1,4); assertEquals("-1/4", f.asMixedNumber()); f = new Fraction(1,-4); assertEquals("-1/4", f.asMixedNumber()); f = new Fraction(4,3); assertEquals("1 + 1/3", f.asMixedNumber()); f = new Fraction(41,9); assertEquals("4 + 5/9", f.asMixedNumber()); f = new Fraction(41,-9); assertEquals("-4 - 5/9", f.asMixedNumber()); f = new Fraction(41,9); assertEquals("4 + 5/9", f.asMixedNumber()); f = new Fraction(-41,9); assertEquals("-4 - 5/9", f.asMixedNumber()); f = new Fraction(25,35); assertEquals("5/7", f.asMixedNumber()); f = new Fraction(6,15); assertEquals("2/5", f.asMixedNumber()); } /** * Test method for {@link tp.Fraction#add(tp.Fraction)}. */ @Test void testAdd() { // 1/2 + 2/4 = 1 Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(2,4); Fraction f3 = new Fraction(1,1); assertEquals(f1.add(f2), f3); // 1/5 + 1/5 = 2/5 -> use twice the same param f1 = new Fraction(1,5); f3 = new Fraction(1,5); assertEquals(f1.add(f1), f3); // 1/2 + 2/3 = 7/6 f1 = new Fraction(1,2); f2 = new Fraction(2,3); f3 = new Fraction(7,6); assertEquals(f1.add(f2), f3); // 1/2 + -2/3 = -1/6 f1 = new Fraction(1,2); f2 = new Fraction(-2,3); f3 = new Fraction(-1,6); assertEquals(f1.add(f2), f3); // 1/2 + 0/3 = 1/2 f1 = new Fraction(1,2); f2 = new Fraction(0,3); assertEquals(f1.add(f2), f1); } /** * Test method for {@link tp.Fraction#soustract(tp.Fraction)}. */ @Test void testSoustract() { // 1/2 - -2/4 = 1 Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(2,-4); Fraction f3 = new Fraction(1,1); assertEquals(f1.soustract(f2), f3); // 1/5 - 1/5 = 0 -> use twice the same param f1 = new Fraction(1,5); f3 = new Fraction(0,5); assertEquals(f1.soustract(f1), f3); // 1/2 - 2/3 = -1/6 f1 = new Fraction(1,2); f2 = new Fraction(2,-3); f3 = new Fraction(-1,6); assertEquals(f1.soustract(f2), f3); // 1/2 - -2/3 = 7/6 f1 = new Fraction(1,2); f2 = new Fraction(-2,3); f3 = new Fraction(7,6); assertEquals(f1.soustract(f2), f3); // 1/2 - 0/3 = 0 f1 = new Fraction(1,2); f2 = new Fraction(0,3); assertEquals(f1.soustract(f2), f1); } /** * Test method for {@link tp.Fraction#multiply(tp.Fraction)}. */ @Test void testMultiply() { // 1/2 * 1/3 = 1/6 Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(1,3); Fraction f3 = new Fraction(1,6); assertEquals(f1.multiply(f2), f3); // 1/5 * 1/5 = 1/25 -> use twice the same param f1 = new Fraction(1,5); f3 = new Fraction(1,25); assertEquals(f1.multiply(f1), f3); // 1/5 * 1/5 = 1/25 -> use twice the same param f1 = new Fraction(1,5); f2 = new Fraction(1,-2); f3 = new Fraction(-1,10); assertEquals(f1.multiply(f2), f3); // 1/5 * 0 = 0 f1 = new Fraction(1,5); f2 = new Fraction(0,-2); f3 = new Fraction(0,10); assertEquals(f1.multiply(f2), f3); // 4 * -1/4 = -1 f1 = new Fraction(4,1); f2 = new Fraction(1,-4); f3 = new Fraction(-1,1); assertEquals(f1.multiply(f2), f3); // 4 * 1/2 = 2 f1 = new Fraction(4,1); f2 = new Fraction(1,2); f3 = new Fraction(2,1); assertEquals(f1.multiply(f2), f3); } /** * Test method for {@link tp.Fraction#divide(tp.Fraction)}. */ @Test void testDivide() { // 1/2 : 1/3 = 3/2 Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(1,3); Fraction f3 = new Fraction(6,1); assertEquals(f1.divide(f2), f3); // 1/5 : 1/5 = 1 -> use twice the same param f1 = new Fraction(1,5); f3 = new Fraction(1,1); assertEquals(f1.divide(f1), f3); // 2/3 : 2 = 1/3 f1 = new Fraction(2,3); f2 = new Fraction(2,1); f3 = new Fraction(1,3); assertEquals(f1.divide(f2), f3); // 2/3 : 4/3 = 1/2 f1 = new Fraction(2,3); f2 = new Fraction(4,3); f3 = new Fraction(1,2); assertEquals(f1.divide(f2), f3); } /** * Test method for {@link tp.Fraction#raiseToPower(int)}. */ @Test void testRaiseToPower() { // 1/2 pw 2 Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(2,1); Fraction f3 = new Fraction(1,4); assertEquals(f1.raiseToPower(f2), f3); // 1/4 pw 1/2 = sqrt(1/4) = 1/2 f1 = new Fraction(1,4); f2 = new Fraction(1,2); assertEquals(f1.raiseToPower(f2), f2); // 3/4 pw 0 = 1 f1 = new Fraction(1,4); f2 = new Fraction(0,2); f3 = new Fraction(1,1); assertEquals(f1.raiseToPower(f2), f3); // 3/4 pw -1 = 4/3 f1 = new Fraction(3,4); f2 = new Fraction(-1,1); f3 = new Fraction(4,3); assertEquals(f1.raiseToPower(f2), f3); // 3/4 pw 1 = 3/4 f1 = new Fraction(3,4); f2 = new Fraction(1,1); assertEquals(f1.raiseToPower(f2), f1); } /** * Test method for {@link tp.Fraction#isZero()}. */ @Test void testIsZero() { Fraction zero = new Fraction(0,2); assertTrue(zero.isZero()); Fraction nonZero = new Fraction(3,4); assertFalse(nonZero.isZero()); } /** * Test method for {@link tp.Fraction#isInteger()}. */ @Test void testIsInteger() { Fraction integer = new Fraction(2,2); Fraction zero = new Fraction(0,2); Fraction notInteger = new Fraction(1,2); Fraction negativeInt = new Fraction(-1,2); assertTrue(integer.isInteger()); assertTrue(zero.isInteger()); assertFalse(notInteger.isInteger()); assertTrue(negativeInt.isInteger()); } /** * Test method for {@link tp.Fraction#isNegative()}. */ @Test void testIsNegative() { Fraction pos = new Fraction(1,2); Fraction zero = new Fraction(0,2); Fraction neg = new Fraction(-1,2); assertTrue(neg.isNegative()); assertFalse(pos.isNegative()); assertFalse(zero.isNegative()); } /** * Test method for {@link tp.Fraction#equals(tp.Fraction)}. */ @Test void testEquals() { Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(2,4); Fraction f3 = new Fraction(1,2); Fraction f4 = new Fraction(1,3); assertTrue(f1.equals(f2)); assertTrue(f2.equals(f1)); assertTrue(f1.equals(f3)); assertTrue(f1.equals(f1)); assertFalse(f1.equals(f4)); } /** * Test method for {@link tp.Fraction#isGreaterThan(tp.Fraction)}. */ @Test void testIsGreaterThan() { Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(2,4); Fraction f3 = new Fraction(1,2); Fraction f4 = new Fraction(1,3); Fraction f5 = new Fraction(-1,2); Fraction f6 = new Fraction(1,-3); assertEquals(f1.compareTo(f2), 0); assertEquals(f1.compareTo(f1),0); assertTrue(f1.compareTo(f4)>0); assertTrue(f4.compareTo(f1)<0); assertTrue(f1.compareTo(f5)>0); assertTrue(f5.compareTo(f1)<0); assertTrue(f6.compareTo(f5)>0); assertTrue(f5.compareTo(f6)<0); } /** * Test method for {@link tp.Fraction#isUnitFraction()}. */ @Test void testIsUnitFraction() { Fraction f1 = new Fraction(1,2); assertTrue(f1.isUnitFraction()); Fraction f2 = new Fraction(3,2); assertFalse(f2.isUnitFraction()); Fraction f3 = new Fraction(2,3); assertFalse(f3.isUnitFraction()); Fraction zero = new Fraction(0,3); assertFalse(zero.isUnitFraction()); Fraction one = new Fraction(1,1); assertTrue(one.isUnitFraction()); } /** * Test method for {@link tp.Fraction#isProperFraction()}. */ @Test void testIsProperFraction() { Fraction f1 = new Fraction(1,2); assertTrue(f1.isProperFraction()); Fraction f2 = new Fraction(3,2); assertFalse(f2.isProperFraction()); Fraction f3 = new Fraction(1,1); assertFalse(f3.isProperFraction()); Fraction f4 = new Fraction(0,1); assertFalse(f4.isProperFraction()); } /** * Test method for {@link tp.Fraction#isAdjacentTo(tp.Fraction)}. */ @Test void testIsAdjacentTo() { //1/2 - 1/3 = 1/6 Fraction f1 = new Fraction(1,2); Fraction f2 = new Fraction(1,3); assertTrue(f1.isAdjacentTo(f2)); // 1/2 - 1/5 = 3/10 f1 = new Fraction(1,2); f2 = new Fraction(1,5); assertFalse(f1.isAdjacentTo(f2)); // 1/2 - 0 = 1/2 f1 = new Fraction(1,2); f2 = new Fraction(0,5); assertTrue(f1.isAdjacentTo(f2)); // 2/3 - 1 = -1/3 f1 = new Fraction(2,3); f2 = new Fraction(1,1); assertTrue(f1.isAdjacentTo(f2)); } /** * Test method for {@link tp.Fraction#toDouble()}. */ @Test void testToDouble() { assertEquals((new Fraction(1,2)).toDouble(),0.5,0); assertEquals((new Fraction(1,1)).toDouble(),1,0); assertEquals((new Fraction(-1,3)).toDouble(),-0.333,0.001); assertEquals((new Fraction(0,3)).toDouble(),0,0); } /** * Test method for {@link tp.Fraction#clone()}. */ @Test void testClone() { Fraction f = new Fraction(1,2); assertEquals(f.clone(), f); } }
true
e4b0e38f24b22b4e67e81c9612280555f715f107
Java
mvaenskae/asl2018
/middleware/src/ch/ethz/asltest/Utilities/Statistics/MiddlewareStatistics.java
UTF-8
2,771
2.765625
3
[ "BSD-3-Clause" ]
permissive
package ch.ethz.asltest.Utilities.Statistics; import ch.ethz.asltest.Utilities.Misc.Tuple; import java.util.concurrent.TimeUnit; abstract public class MiddlewareStatistics { private static volatile boolean enabled = false; final protected static int INITIAL_CAPACITY = 90; final protected static TimeUnit TIME_UNIT = TimeUnit.SECONDS; final protected long WINDOW_SIZE = multiplyGetLong(TIME_INTERVAL, NANOS_TO_SECOND); // Defines the size of each window normalized to a second. final protected static double TIME_INTERVAL = 1.0; final protected static long NANOS_TO_SECOND = 1_000_000_000; private static long enabledTimestamp; private static long disabledTimestamp; // Continuous "counter" for the currently active window normalized to a second. private double windowNormalized = 0; private long latestElementTimestamp = 0; public static void enableStatistics() { enabledTimestamp = System.nanoTime(); enabled = true; } public static void disableStatistics() { disabledTimestamp = System.nanoTime(); if (enabledTimestamp == 0) { enabledTimestamp = disabledTimestamp; } enabled = false; } protected static long getDisabledTimestamp() { return disabledTimestamp; } private static long multiplyGetLong(double a, double b) { double res = a * b; return Math.round(res); } protected double getWindow() { return windowNormalized; } protected void updateWindow() { windowNormalized += TIME_INTERVAL; } protected long getCurrentWindowStart() { return multiplyGetLong(NANOS_TO_SECOND, windowNormalized) + enabledTimestamp; } private long diffToCurrentWindow(long timestamp) { return timestamp - getCurrentWindowStart(); } protected long diffToLatestTimestamp(long timestamp) { if (latestElementTimestamp == 0) { latestElementTimestamp = enabledTimestamp; } return timestamp - latestElementTimestamp; } protected void updateLatestElementTimestamp(long timestamp) { this.latestElementTimestamp = timestamp; } protected Tuple<Long, Long> splitOverWindowBoundary(long timestamp) { updateWindow(); long previousSecondQueue = diffToLatestTimestamp(getCurrentWindowStart()); updateLatestElementTimestamp(timestamp); long nextSecondQueue = diffToCurrentWindow(timestamp); return new Tuple<>(previousSecondQueue, nextSecondQueue); } protected boolean timestampWithinCurrentWindow(long timestamp) { return diffToCurrentWindow(timestamp) < TIME_INTERVAL * WINDOW_SIZE; } }
true
9c39b3128b1698780c70585a41f26aeffd97c850
Java
MingquanLiuWHU/DMSByServlet
/src/cn/lmq/dmsbyservlet/servlet/ModifyDocServlet.java
UTF-8
1,954
2.1875
2
[]
no_license
package cn.lmq.dmsbyservlet.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.lmq.dmsbyservlet.bean.Document; import cn.lmq.dmsbyservlet.bean.User; import cn.lmq.dmsbyservlet.dao.DocumentDAO; /** * Servlet implementation class ModifyDocServlet */ @WebServlet("/ModifyDocServlet") public class ModifyDocServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // System.out.println(session.getId()); User user = (User) session.getAttribute("user"); Document doc = new Document(); String id = request.getParameter("id"); doc.setId(Integer.valueOf(id)); doc.setTitle(request.getParameter("title")); doc.setType(request.getParameter("type")); doc.setContent(request.getParameter("content")); DocumentDAO dao = new DocumentDAO(); try { dao.update(doc); List<Document> docs = dao.getAllByAuthor(user.getId(), false); request.setAttribute("docList", docs); String url = "/common/docList.jsp"; request.getRequestDispatcher(url).forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
421c99471b57a1c7f4a69674fd06eecbcd773e44
Java
CliuGeek9229/HotelChainManagement
/src/com/zlgl/ssh/action/BusinessAction.java
UTF-8
5,137
2.296875
2
[]
no_license
package com.zlgl.ssh.action; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.zlgl.ssh.beans.Business; import com.zlgl.ssh.service.BusinessManager; import com.zlgl.ssh.web.BusinessCommand; /** * * @ClassName BusinessAction.java * @author Leno E-mail:cliugeek@us-forever.com * @date 2017年12月5日 上午11:31:47 * @Description 统计营业控制层 */ public class BusinessAction extends ActionSupport{ private static final long serialVersionUID=1L; private BusinessCommand businessCommand; private BusinessManager businessManager; public String SearchBusiness() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); System.out.println(businessCommand.getBeginT()); System.out.println(businessCommand.getEndT()); System.out.println(businessCommand.getIsShow()); System.out.println(businessCommand.getSelectType()); System.out.println(businessCommand.getSumType()); Date beginDate = null; Date endDate = null; //trycatch 中的代码没有用到 不过对simpledateformat的使用很有帮助 留着吧 try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); beginDate = sdf.parse(businessCommand.getBeginT()); endDate = sdf.parse(businessCommand.getEndT()); //Date b = sdf.format(beginDate.getTime()); businessCommand.setrBeginT(beginDate); businessCommand.setrEndT(endDate); System.out.println(businessCommand.getrBeginT()); System.out.println(businessCommand.getrEndT()); } catch (ParseException e) { e.printStackTrace(); } int sumall = 0; int sumnormal = 0; int sumunnormal = 0; int numnormal = 0; int numunnormal = 0; List<Business> bList = businessManager.getBusinesses(businessCommand); List<Business> bListN = businessManager.getBusinessesN(businessCommand); List<Business> bListUn = businessManager.getBusinessesUn(businessCommand); for (int i = 0; i < bList.size(); i++) { System.out.println(bList.get(i)); sumall+=bList.get(i).getPrice(); //计算得出总的营业额 } for (int i = 0; i < bListN.size(); i++) { sumnormal+=bListN.get(i).getPrice(); //计算得出正常营业的营业额 } for (int i = 0; i < bListUn.size(); i++) { sumunnormal+=bListUn.get(i).getPrice(); //计算得出折扣营业的营业额 } numnormal = bListN.size(); //在规定的日期范围内正常营业的笔数 numunnormal = bListUn.size(); //在规定的日期范围内折扣营业的笔数 if(businessCommand.getIsShow().equals("1")) { if(businessCommand.getSelectType().equals("1")) { request.getSession().setAttribute("blist", bList); }else if(businessCommand.getSelectType().equals("2")) { request.getSession().setAttribute("blist", bListN); }else { request.getSession().setAttribute("blist", bListUn); } }else { businessCommand.setBeginT("2010-10-10"); businessCommand.setEndT("2010-10-11"); List<Business> bList1 = businessManager.getBusinesses(businessCommand); request.getSession().setAttribute("blist", bList1); } if(businessCommand.getSumType().equals("1")) { businessCommand.setSumAll(sumall); businessCommand.setSumNormal(0); businessCommand.setSumUnnormal(0); businessCommand.setNumNormal(0); businessCommand.setNumUnnormal(0); request.getSession().setAttribute("bcommand", businessCommand); }else if(businessCommand.getSumType().equals("2")) { businessCommand.setSumAll(0); businessCommand.setSumNormal(sumnormal); businessCommand.setSumUnnormal(0); businessCommand.setNumNormal(0); businessCommand.setNumUnnormal(0); request.getSession().setAttribute("bcommand", businessCommand); }else if(businessCommand.getSumType().equals("3")) { businessCommand.setSumAll(0); businessCommand.setSumNormal(0); businessCommand.setSumUnnormal(sumunnormal); businessCommand.setNumNormal(0); businessCommand.setNumUnnormal(0); request.getSession().setAttribute("bcommand", businessCommand); }else if(businessCommand.getSumType().equals("4")) { businessCommand.setSumAll(0); businessCommand.setSumNormal(0); businessCommand.setSumUnnormal(0); businessCommand.setNumNormal(numnormal); businessCommand.setNumUnnormal(0); request.getSession().setAttribute("bcommand", businessCommand); }else { businessCommand.setSumAll(0); businessCommand.setSumNormal(0); businessCommand.setSumUnnormal(0); businessCommand.setNumNormal(0); businessCommand.setNumUnnormal(numunnormal); request.getSession().setAttribute("bcommand", businessCommand); } return "success"; } public BusinessCommand getBusinessCommand() { return businessCommand; } public void setBusinessCommand(BusinessCommand businessCommand) { this.businessCommand = businessCommand; } public void setBusinessManager(BusinessManager businessManager) { this.businessManager = businessManager; } }
true
151e70de021a876faef9b4384b33f26228a522b6
Java
MarcGeorgeCatalin/Exercism
/largest-series-product/src/main/java/LargestSeriesProductCalculator.java
UTF-8
1,208
3.453125
3
[]
no_license
import java.util.stream.IntStream; class LargestSeriesProductCalculator { String inputNumber; LargestSeriesProductCalculator(String inputNumber) { if (!inputNumber.isEmpty() && !inputNumber.matches("(([-+])?[0-9]+(\\.[0-9]+)?)+")){ throw new IllegalArgumentException("String to search may only contain digits."); } this.inputNumber = inputNumber; } long calculateLargestProductForSeriesLength(int numberOfDigits) { if( numberOfDigits > inputNumber.length() ){ throw new IllegalArgumentException("Series length must be less than or equal to the length of the string to search."); } if( numberOfDigits < 0 ){ throw new IllegalArgumentException("Series length must be non-negative."); } return numberOfDigits == 0 ? 1 : IntStream.range(numberOfDigits, inputNumber.length()+1) .map( i -> inputNumber.substring(i-numberOfDigits, i) .chars() .map(Character::getNumericValue) .reduce((a, b) -> a*b ).getAsInt()) .max() .getAsInt(); } }
true
fc003a216b939272f60d7d27ad206d4abbb4da0c
Java
nikhilsurfingaus/DECO2800-Java-Gradle-Game
/src/main/java/deco/combatevolved/entities/dynamicentities/VehicleEntity.java
UTF-8
2,090
2.65625
3
[]
no_license
package deco.combatevolved.entities.dynamicentities; import com.google.gson.annotations.Expose; import deco.combatevolved.managers.GameManager; import deco.combatevolved.entities.AbstractEntity; import deco.combatevolved.entities.RenderConstants; import deco.combatevolved.entities.items.Inventory; import deco.combatevolved.util.HexVector; public class VehicleEntity extends DynamicEntity{ @Expose int driverID =-1; AgentEntity driver; private transient Inventory stash; public VehicleEntity() { stash = new Inventory(64); } public VehicleEntity(float row, float col, int ferretRender, float speed) { super(row, col, RenderConstants.FERRET_RENDER, speed); stash = new Inventory(64); } public boolean enterVehicle(AgentEntity agentPeon) { if (this.driver == null) { this.driver = agentPeon; driver.vehicle = this; driver.currentSpeed = this.speed; driverID = driver.getEntityID(); return true; } return false; } private void setDriver(int driverID) { if (driverID != -1) { AbstractEntity newDriver = GameManager.get().getWorld().getEntityById(driverID); if (newDriver instanceof AgentEntity) { this.driver = (AgentEntity) newDriver; this.driver.setVehicle(this); } } } public void setDriverID(int driverID) { this.driverID = driverID; } public void move(HexVector velocity) { if (driver != null) { this.position = this.position.add(velocity); driver.setPosition(this.position); } else if (this.driverID != -1) { setDriver(this.driverID); } } @Override public void onTick(long i) { if (driver == null && this.driverID != -1) { setDriver(this.driverID); } } /** * Get the inventory of the vehicle * * @return vehicle stash */ public Inventory getInventory() { return stash; } }
true
4f4a966ef72c096b32f8b270d6b43ad97507f38b
Java
4liraza/Real_estate1
/src/bean/Deal.java
UTF-8
2,339
2.4375
2
[]
no_license
/* * Deal.java * * Created on March 4, 2009, 9:06 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package bean; /** * * @author student */ public class Deal { /** Creates a new instance of Deal */ private String ownername,owneradd,tenantname,tenantadd,propadd,broker,information; private String checkno,ptype,purpose,paidvia,dealdate; private int brokerage,price_paid,prop_price; public void setOwnername(String ownername){this.ownername=ownername;} public void setOwneradd(String owneradd){this.owneradd=owneradd;} public void setTenantname(String tenantname){this.tenantname=tenantname;} public void setTenantadd(String tenantadd){this.tenantadd=tenantadd;} public void setBroker(String broker){this.broker=broker;} public void setPropadd(String propadd){this.propadd=propadd;} public void setInformation(String information){this.information=information;} public void setCheckno(String checkno){this.checkno=checkno;} public void setPtype(String ptype){this.ptype=ptype;} public void setPurpose(String purpose){this.purpose=purpose;} public void setPaidvia(String paidvia){this.paidvia=paidvia;} public void setDealdate(String dealdate){this.dealdate=dealdate;} public String getOwnername(){return ownername;} public String getOwneradd(){return owneradd;} public String getTenantname(){return tenantname;} public String getTenantadd(){return tenantadd;} public String getBroker(){return broker;} public String getPropadd(){return propadd;} public String getInformation(){return information;} public String getCheckno(){return checkno;} public String getPtype(){return ptype;} public String getPurpose(){return purpose;} public String getPaidvia(){return paidvia;} public String getDealdate(){return dealdate;} public void setBrokerage(int brokerage){this.brokerage= brokerage;} public void setPrice_paid(int price_paid){this.price_paid=price_paid;} public void setProp_price(int prop_price){this.prop_price=prop_price;} public int getBrokerage(){return brokerage;} public int getPrice_paid(){return price_paid;} public int getProp_price(){return prop_price;} }
true
95367d27ec5cc82142577b25a920d5d28c70a977
Java
avi268/Programming
/workspace/MyCourse/src/practice/Rectangle.java
UTF-8
631
3.875
4
[]
no_license
package practice; public class Rectangle { public Rectangle(int height) { int househeight = height; System.out.println("Height of House:" + househeight); } public Rectangle(Double height) { double buildingheight = height; System.out.println("Height of building: " + buildingheight); } public void aofr(int l, int b) { System.out.println("area is :" +(l*b)); } public void aofr(double l, double b) { System.out.println("area :" +(l*b)); } public static void main(String[] args) { Rectangle r = new Rectangle(25); Rectangle r1 = new Rectangle(30.5); r.aofr(10.5, 20.5); r1.aofr(10, 20); } }
true
51825ef0d991093dddf81c1a15dfd98decb8b426
Java
Aquerr/EagleFactions
/src/main/java/io/github/aquerr/eaglefactions/storage/serializers/SlotItemTypeSerializer.java
UTF-8
4,719
2.125
2
[ "MIT" ]
permissive
package io.github.aquerr.eaglefactions.storage.serializers; import com.google.common.collect.Lists; import io.github.aquerr.eaglefactions.api.entities.FactionChest; import io.github.aquerr.eaglefactions.entities.FactionChestImpl; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataFormats; import org.spongepowered.api.data.persistence.DataQuery; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.registry.RegistryEntry; import org.spongepowered.api.registry.RegistryTypes; import org.spongepowered.api.util.Tuple; import org.spongepowered.configurate.ConfigurationNode; import org.spongepowered.configurate.hocon.HoconConfigurationLoader; import org.spongepowered.configurate.serialize.SerializationException; import org.spongepowered.configurate.serialize.TypeSerializer; import java.io.IOException; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import java.util.Optional; public class SlotItemTypeSerializer implements TypeSerializer<FactionChest.SlotItem> { @Override public FactionChest.SlotItem deserialize(Type type, ConfigurationNode node) throws SerializationException { final int column = node.node("column").getInt(); final int row = node.node("row").getInt(); final ConfigurationNode itemNode = node.node("item"); DataContainer dataContainer = null; try { String itemNodeAsString = HoconConfigurationLoader.builder().buildAndSaveString(itemNode); dataContainer = DataFormats.HOCON.get().read(itemNodeAsString); } catch (IOException e) { e.printStackTrace(); } final Optional<ItemType> itemType = Sponge.game().registry(RegistryTypes.ITEM_TYPE) .findEntry(ResourceKey.resolve(String.valueOf(dataContainer.get(DataQuery.of("ItemType")).get()))) .map(RegistryEntry::value); if (!itemType.isPresent()) { throw new SerializationException("ItemType could not be recognized. Probably comes from a mod that has been removed from the server."); } ItemStack itemStack; try { itemStack = ItemStack.builder().fromContainer(dataContainer).build(); } catch (Exception e) { throw new SerializationException("Could not create Item Stack from data container."); } // Validate the item. if (itemStack.isEmpty() || itemStack.type() == null) { // don't bother throw new SerializationException("Could not deserialize item. Item is empty."); } return new FactionChestImpl.SlotItemImpl(column, row, itemStack); } @Override public void serialize(Type type, FactionChest.@Nullable SlotItem obj, ConfigurationNode node) throws SerializationException { if (obj == null) return; final ItemStack itemStack = obj.getItem().copy(); DataView view; try { view = itemStack.toContainer(); } catch (NullPointerException e) { throw new SerializationException(e); } final Map<DataQuery, Object> dataQueryObjectMap = view.values(true); for (final Map.Entry<DataQuery, Object> entry : dataQueryObjectMap.entrySet()) { if (entry.getValue().getClass().isArray()) { if (entry.getValue().getClass().getComponentType().isPrimitive()) { DataQuery old = entry.getKey(); Tuple<DataQuery, List<?>> dqo = TypeHelper.getList(old, entry.getValue()); view.remove(old); view.set(dqo.first(), dqo.second()); } else { view.set(entry.getKey(), Lists.newArrayList((Object[]) entry.getValue())); } } } node.node("column").set(obj.getColumn()); node.node("row").set(obj.getRow()); try { String itemStackAsString = DataFormats.HOCON.get().write(view); ConfigurationNode itemNode = HoconConfigurationLoader.builder().buildAndLoadString(itemStackAsString); node.node("item").set(itemNode); } catch (IOException e) { e.printStackTrace(); } } }
true
d2c54b61fe53c241ecf38224f922b44c43d592d4
Java
moutainhigh/loanshop
/dkgj-api/src/main/java/io/dkgj/controller/ApiIndexController.java
UTF-8
7,133
1.890625
2
[ "Apache-2.0" ]
permissive
package io.dkgj.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import io.dkgj.annotation.Login; import io.dkgj.common.utils.PageUtils; import io.dkgj.common.utils.R; import io.dkgj.controller.vo.SortVO; import io.dkgj.controller.vo.TypeVO; import io.dkgj.entity.BannerEntity; import io.dkgj.entity.ChannelManageEntity; import io.dkgj.entity.LoanEntity; import io.dkgj.entity.MarketEntity; import io.dkgj.service.BannerService; import io.dkgj.service.ChannelManageService; import io.dkgj.service.LoanService; import io.dkgj.service.MarketService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/api") @Api(tags = "首页接口") public class ApiIndexController { @Autowired BannerService bannerService; @Autowired LoanService loanService; @Autowired MarketService marketService; @Autowired ChannelManageService channelManageService; public static Map<String, String> typeBasners = new HashMap<>(); static { typeBasners.put("1", "https://ycqb.oss-cn-hangzhou.aliyuncs.com/index-pic/card.png"); typeBasners.put("2", "https://ycqb.oss-cn-hangzhou.aliyuncs.com/index-pic/high.png"); typeBasners.put("3", "https://ycqb.oss-cn-hangzhou.aliyuncs.com/index-pic/low.png"); typeBasners.put("4", "https://ycqb.oss-cn-hangzhou.aliyuncs.com/index-pic/fast.png"); } @GetMapping("getChannelEnable") @ApiOperation("渠道是否可用") public R getChannelEnable(@RequestParam String channel) { ChannelManageEntity channelManageEntity = channelManageService.getOne(new QueryWrapper<ChannelManageEntity>() .eq("channelcode", channel).eq("state", 0)); return R.ok().put("data", channelManageEntity == null); } @GetMapping("index") @ApiOperation("首页接口") @Login public R index(@ApiIgnore @RequestAttribute("userId") Integer userId, @RequestParam(required = false, defaultValue = "") String channel, @RequestParam(required = false, defaultValue = "") String version) { MarketEntity market = marketService.getOne(new QueryWrapper<MarketEntity>() .eq("state", 1) .eq("channel_code", channel) .eq("version", version)); Map<String, Object> params = new HashMap<>(); params.put("page", "1"); params.put("limit", "4"); PageUtils page = bannerService.queryPage(params); List<BannerEntity> banners = (List<BannerEntity>) page.getList(); List<TypeVO> types = new ArrayList<TypeVO>(); types.add(new TypeVO(1, "身份证贷", 1)); types.add(new TypeVO(2, "高通过率", 2)); types.add(new TypeVO(3, "超低门槛", 3)); types.add(new TypeVO(4, "极速下款", 4)); params.put("page", "1"); params.put("limit", "1000"); params.put("sidx", "weights"); params.put("order", "asc"); if (market != null) { params.put("market", market.getChannelCode()); } page = loanService.queryPage(params); List<LoanEntity> loans = (List<LoanEntity>) page.getList(); Map<String, Object> result = new HashMap<>(); if (market != null) { result.put("banners", null); } else { result.put("banners", banners); } result.put("types", types); result.put("loans", loans); return R.ok().put("data", result); } @GetMapping("getLoanList") @ApiOperation("贷款大全接口") @Login public R getLoanList(@ApiIgnore @RequestAttribute("userId") Integer userId, @RequestParam Map<String, Object> params, @RequestParam(required = false, defaultValue = "") String channel, @RequestParam(required = false, defaultValue = "") String version) { MarketEntity market = marketService.getOne(new QueryWrapper<MarketEntity>() .eq("state", 1) .eq("channel_code", channel) .eq("version", version)); if (market != null) { params.put("market", market.getChannelCode()); } PageUtils page = loanService.queryPage(params); return R.ok().put("data", page); } @GetMapping("getTypeLoanList") @ApiOperation("贷款类型接口") @Login public R getTypeLoanList(@ApiIgnore @RequestAttribute("userId") Integer userId, @RequestParam Map<String, Object> params, @RequestParam(required = false, defaultValue = "") String channel, @RequestParam(required = false, defaultValue = "") String version) { MarketEntity market = marketService.getOne(new QueryWrapper<MarketEntity>() .eq("state", 1) .eq("channel_code", channel) .eq("version", version)); if (market != null) { params.put("market", market.getChannelCode()); } PageUtils page = loanService.queryPage(params); page.setTypeBanner(typeBasners.get((String) params.get("type"))); return R.ok().put("data", page); } @GetMapping("getRandomLoan") @ApiOperation("贷款类型接口") @Login public R getRandomLoan(@RequestParam Integer limit) { List<LoanEntity> list = loanService.getRandomLoan(limit); return R.ok().put("data", list); } @GetMapping("getFiltrate") @ApiOperation("获取筛选条件") @Login public R getFiltrate(@ApiIgnore @RequestAttribute("userId") Integer userId) { List<SortVO> moneyFiltrate = new ArrayList<>(); List<SortVO> typesortFiltrate = new ArrayList<>(); List<SortVO> tagsFiltrate = new ArrayList<>(); moneyFiltrate.add(new SortVO("0", "金额不限", 1)); moneyFiltrate.add(new SortVO("1", "2000以下", 2)); moneyFiltrate.add(new SortVO("2", "2000-5000", 3)); moneyFiltrate.add(new SortVO("3", "5000以上", 4)); typesortFiltrate.add(new SortVO("", "默认排序", 1)); typesortFiltrate.add(new SortVO("HIGH", "贷款额度高", 2)); typesortFiltrate.add(new SortVO("LOW", "贷款利率低", 3)); typesortFiltrate.add(new SortVO("FAST", "放款速度快", 4)); tagsFiltrate.add(new SortVO("", "全部", 1)); tagsFiltrate.add(new SortVO("RECOMMENDED", "推荐", 2)); tagsFiltrate.add(new SortVO("HOT", "爆款", 3)); tagsFiltrate.add(new SortVO("OPTIMIZATION", "优选", 4)); Map<String, Object> result = new HashMap<>(); result.put("moneyFiltrate", moneyFiltrate); result.put("typesortFiltrate", typesortFiltrate); result.put("tagsFiltrate", tagsFiltrate); return R.ok().put("data", result); } }
true
fe0dea3976ffac3278cd03b8755b5665bf009a1c
Java
CFabian04/Generics-SIIT
/src/genericmethod/Main1.java
UTF-8
733
2.8125
3
[]
no_license
package genericmethod; import multiplegenerics.OrderedPair; import multiplegenerics.Pair; public class Main1 { public static void main(String[] args) { Pair<Integer,String> p1=new OrderedPair<Integer,String>(1,"unu"); Pair<Integer,String> p2=new OrderedPair<Integer,String>(10,"zece"); Pair<Integer,Integer> p3=new OrderedPair<>(10,30); System.out.println("p1 == p2 "+Util.compare(p1,p2)); System.out.println("p1 == p2 "+Util.compare(p1,p1)); // System.out.println("p1 == p2 "+Util.compare(p1,p3)); gresit din cauza ca noi am declarat in metoda compare p1 si p2 ca fiind Pair<K,V> in ambele cazuri System.out.println("p1 == p2 "+Util.comparePeSteroizi(p1,p3)); } }
true
ecf7f94bc5ed8a2a0b36340c6424a1176c40dede
Java
angelzgh/TT
/src/com/ipn/mx/tt/modelo/Cuestionario.java
UTF-8
7,319
2.28125
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 com.ipn.mx.tt.modelo; import java.util.Date; import java.util.LinkedList; /** * * @author Axel Reyes */ public class Cuestionario { private int numCuestionario = 0; private Instrumento s50, hsdr; private Date inicioCuestionario, duracion, finCuestionario; private LinkedList RespuestasContestadas; private int contadorRespuestasContestadas; private String[] sintomasDetectados; public String[] getSintomasDetectados() { return sintomasDetectados; } public void setSintomasDetectados(String[] sintomasDetectados) { this.sintomasDetectados = sintomasDetectados; } public Cuestionario() { s50 = new Instrumento(); hsdr = new Instrumento(); inicioCuestionario = new Date(); RespuestasContestadas = new LinkedList(); contadorRespuestasContestadas = 0; sintomasDetectados = new String[10]; for (int i = 1; i < 10; i++) { sintomasDetectados[i] = ""; } } public int getContadorRespuestasContestadas() { return contadorRespuestasContestadas; } public void setContadorRespuestasContestadas(int contadorRespuestasContestadas) { this.contadorRespuestasContestadas = contadorRespuestasContestadas; } public Instrumento getS50() { return s50; } public void setS50(Instrumento s50) { this.s50 = s50; } public Instrumento getHsdr() { return hsdr; } public void setHsdr(Instrumento hsdr) { this.hsdr = hsdr; } public Cuestionario(Cuestionario c) { this.numCuestionario = c.numCuestionario; this.s50=new Instrumento(c.s50); this.hsdr=new Instrumento(c.hsdr); this.inicioCuestionario = c.inicioCuestionario; this.duracion = c.duracion; this.finCuestionario = c.finCuestionario; this.RespuestasContestadas = new LinkedList(c.RespuestasContestadas); this.contadorRespuestasContestadas = c.contadorRespuestasContestadas; sintomasDetectados = new String[10]; System.arraycopy(c.sintomasDetectados, 1, sintomasDetectados, 1, 9); } public LinkedList getRespuestasContestadas() { return RespuestasContestadas; } public void setRespuestasContestadas(LinkedList RespuestasContestadas) { this.RespuestasContestadas = RespuestasContestadas; } public void setCuestionario(Cuestionario c) { this.numCuestionario = c.numCuestionario; this.s50 = c.s50; this.hsdr = c.hsdr; this.inicioCuestionario = c.inicioCuestionario; this.duracion = c.duracion; this.finCuestionario = c.finCuestionario; this.RespuestasContestadas = new LinkedList(c.RespuestasContestadas); } public boolean respuestaContestada(int numeroPregunta) { boolean existe = false; Respuesta r = new Respuesta(numeroPregunta, 0); for (int i = 0; i < RespuestasContestadas.size(); i++) { Respuesta archivo = (Respuesta) RespuestasContestadas.get(i); if (archivo.getNumeroPregunta() == r.getNumeroPregunta()) { //System.out.println(archivo.getNumeroPregunta() +"//"+ r.getNumeroPregunta()); existe = true; } } return existe; } public void agregarRespuesta(int numeroPregunta, int valorRespuesta) { Respuesta r = new Respuesta(numeroPregunta, valorRespuesta); RespuestasContestadas.add(r); } public void quitarRespuesta(int numeroPregunta) { int x = 0; for (Object RespuestasContestada : RespuestasContestadas) { Respuesta r = (Respuesta) RespuestasContestada; if (r.getNumeroPregunta() == numeroPregunta) { RespuestasContestadas.remove(x); break; } x++; } } public void mostrarRespuestas() { System.out.println("RESPUESTAS"); for (Object RespuestasContestada : RespuestasContestadas) { Respuesta r = (Respuesta) RespuestasContestada; System.out.println(r.toString()); } System.out.println("FIN RESPUESTAS"); } public void quitarDesde(int desde) { while (desde < RespuestasContestadas.size()) { RespuestasContestadas.remove(desde); } } public Respuesta obtenerRespuesta(int numeroPregunta) { Respuesta r = null; for (int i = 1; i < RespuestasContestadas.size(); i++) { Respuesta res = (Respuesta) RespuestasContestadas.get(i); if (res.getNumeroPregunta() == numeroPregunta) { r = res; break; } } return r; } public LinkedList obtenerPreguntasContestadas() { return RespuestasContestadas; } public void calificarPregunta(int instrumento, int trastorno, Double puntaje) { if (instrumento == 1) { s50.sumarPuntaje(trastorno, puntaje); } else { hsdr.sumarPuntaje(trastorno, puntaje); } } public void quitarPregunta(int instrumento, int trastorno, int puntaje) { if (instrumento == 1) { s50.restarPuntaje(trastorno, puntaje); } else { hsdr.restarPuntaje(trastorno, puntaje); } } public Double getTrastorno(int instrumento, int trastorno) { if (instrumento == 1) { return s50.getTrastorno(trastorno); } else { return hsdr.getTrastorno(trastorno); } } public int getNumCuestionario() { return numCuestionario; } public void setNumCuestionario(int numCuestionario) { this.numCuestionario = numCuestionario; } @Override public String toString() { return "Cuestionario{" + "numCuestionario=" + numCuestionario + ", s50=" + s50 + ", hsdr=" + hsdr + ", inicioCuestionario=" + inicioCuestionario + ", duracion=" + duracion + ", finCuestionario=" + finCuestionario + ", RespuestasContestadas=" + RespuestasContestadas + '}'; } public Date getInicioCuestionario() { return inicioCuestionario; } public void setInicioCuestionario(Date inicioCuestionario) { this.inicioCuestionario = inicioCuestionario; } public Date getDuracion() { System.out.println(finCuestionario.getTime() - inicioCuestionario.getTime()); duracion = new Date(finCuestionario.getTime() - inicioCuestionario.getTime()); return duracion; } public void setDuracion(Date duracion) { this.duracion = duracion; } public Date getFinCuestionario() { finCuestionario = new Date(); return finCuestionario; } public void setFinCuestionario(Date finCuestionario) { this.finCuestionario = finCuestionario; } }
true
34f7ea91006ed6e9e2a03c2233d4ea2c2a940eed
Java
sajithsr150915/jenkinsDashboard
/src/main/java/com/jenkins/controller/JenkinsController.java
UTF-8
1,746
1.609375
2
[]
no_license
package com.jenkins.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.jenkins.service.JenkinsService; @RestController public class JenkinsController { @Autowired(required=true) JenkinsService jenkinsService; /** * @return String * The method invokes the jenkins API */ @GetMapping("/jenkinsDetails") public String jenkinsDetails() { return jenkinsService.getJenkinsDetails(); /*http://localhost:8080/api/json?tree=jobs[name,url,builds[number,result,duration,url]] http://localhost:8080/job/build%20project/31/api/json http://localhost:8080/api/json?tree=jobs[name,url,builds[number,result,duration,url,actions[buildsByBranchName]]] http://localhost:8080/api/json?tree=jobs[name,url,builds[number,result,duration,url,actions[buildsByBranchName.refs/remotes/origin/master]]] http://localhost:8080/api/json?tree=jobs[name,url,builds[number,result,duration,url,actions[buildsByBranchName[*[*[*]]]]]] */ } /** * @return String * The method invokes the jenkins API and produce results with test report */ @GetMapping("/jenkinswithTestReport") public String jenkinswithTestReport() { return jenkinsService.jenkinswithTestReport(); } /**sample selenuim projects * https://github.com/reportportal/example-cucumber-junit-selenium-logback-maven.git * https://github.com/kolorobot/spring-boot-thymeleaf.git * https://github.com/paulvi/selenium-for-spring-boot * * In post build action give test report Xmls- target/surefire-reports/*.xml * use Test Result Analyzer plugin * */ }
true
64406265da9f09ddc9f771955901cfb750a1e46e
Java
dzmitryh/jdk9-playground
/main/src/main/java/com/lgi/main/PrivateMethodInInterface.java
UTF-8
945
3.953125
4
[]
no_license
package com.lgi.main; import java.util.stream.IntStream; import static com.lgi.commons.util.PrintUtil.println; public class PrivateMethodInInterface { public static void main(String[] args) { new SumTest(new int[]{1,2,3,4}).calculate(); } } interface Sum { default boolean evenSum(int[] numbers) { return sum(numbers) % 2 == 0; } default boolean oddSum(int[] numbers) { return sum(numbers) % 2 == 1; } // we don't want this to be public; private int sum(int[] numbers) { return IntStream.of(numbers).sum(); } } class SumTest implements Sum { private final int[] numbers; SumTest(int[] numbers) { this.numbers = numbers; } void calculate() { println("Is sum even ? -> " + this.evenSum(numbers)); println("Is sum odd ? -> " + this.oddSum(numbers)); // has a private access // println(this.sum(1, 2, 3, 4)); } }
true
799f24947658671ad03c99e896fcb72f5da32928
Java
TKler/Maze
/GenMaze/src/Main.java
UTF-8
2,011
3.390625
3
[]
no_license
import java.io.IOException; import java.nio.file.Paths; import java.util.Scanner; /* * Run as per usual. File pathes are relativ to the project path so in this case Samples/SOMETITLE.txt, * though I guess you can add your own folders to alter said structure. * * All but one Testcase run through. * The miss lies withing the nature of sparse lists and recursion. * Still it is an error non the less. */ public class Main { // feel free to run pseudoTest instead of the other lines public static void main(String[] args) { // runPseudoTest(); Level level = null; try { String path = askForPathToLevel(); level = new Level(Paths.get(path)); } catch (IOException | java.util.NoSuchElementException e) { System.out.println("This path was invalid. Please start again"); System.exit(0); // would be nicer with a re ask and such, but I guess //this is not the focus here and I find quite okay for a //one function program } Mazerunner runner = new Mazerunner(level); runner.findAPathAndPrint(); } private static String askForPathToLevel() throws IOException { String path; Scanner input = new Scanner(System.in); System.out.println("Please enter a path too a level: "); path = input.nextLine(); input.close(); return path; } /* * feel free to enter your own files in here */ private static void runPseudoTest() { String[] input = {"Samples/input.txt", "Samples/large_input.txt", "Samples/medium_input.txt", "Samples/small_input.txt", "Samples/small_wrap_input.txt", "Samples/sparse_medium.txt"}; // Yes , "Samples/sparse_large.txt" fails since it has too many possible paths that can be pursued at the same time for(String s : input) { Mazerunner runner; try { System.out.println(s); runner = new Mazerunner(new Level(Paths.get(s))); runner.findAPathAndPrint(); System.out.println(); } catch (IOException e) { e.printStackTrace(); } } } }
true
a6796aaa9772429c905db92d8f509640aa38cc5b
Java
tgrall/mapr-kafka-sample
/producer-xml-basic/src/main/java/com/mapr/db/sample/producer/TR069Stream.java
UTF-8
2,488
2.078125
2
[]
no_license
package com.mapr.db.sample.producer; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import twitter4j.FilterQuery; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusListener; import twitter4j.TwitterStreamFactory; import twitter4j.json.DataObjectFactory; import java.io.InputStream; import java.util.Date; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; public class TR069Stream { private static String[] track = null; public TR069Stream() { } public static void main(String args[]) throws Exception { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("request.required.acks", "1"); injectMessages(props); } private static void injectMessages(Properties props) throws InterruptedException { final KafkaProducer producer = new KafkaProducer(props); final String topic = "TR069"; for (; ; ) { int deviceId = ThreadLocalRandom.current().nextInt(100000); int ip = ThreadLocalRandom.current().nextInt(255); int ip2 = ThreadLocalRandom.current().nextInt(20); // generate log String log = "<log>\n" + " <device_id>"+ deviceId +"</device_id>\n" + " <ip>123.124.200."+ ip2 +"</ip>\n" + " <ts>"+ new Date() +"</ts>\n" + " <uuid>"+ UUID.randomUUID().toString() +"</uuid>\n" + "</log>"; Thread.sleep(800); try { ProducerRecord data = new ProducerRecord(topic, UUID.randomUUID().toString() , log); Future rs = producer.send(data, new Callback() { public void onCompletion(RecordMetadata recordMetadata, Exception e) { } }); try { RecordMetadata rm = (RecordMetadata) rs.get(); System.out.print("|"); } catch (Exception e) { System.out.println(e); } } catch (Exception e) { e.printStackTrace(); } } } }
true
0e56fc020e53b15b570ed14979ade722352d793a
Java
YarikST/Chat-WS-
/src/WS/MyClass/Connect.java
UTF-8
4,686
2.953125
3
[]
no_license
package WS.MyClass; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Connect { private Selector selector; protected HashMap<SelectionKey, LinkedList<ByteBuffer>> map; protected HashMap<SelectionKey, WriteControl> mapControl; public Connect() { } public Connect(Selector selector) { this.selector = selector; map = new HashMap<>(selector.keys().size() / 2); mapControl = new HashMap<>(map.size()); for (Iterator<SelectionKey> keys = selector.keys().iterator(); keys.hasNext(); ) { add(keys.next()); } } public void read(final SelectionKey key) { System.out.println("Read"); WriteControl writeControl = mapControl.get(key); ByteBuffer buffer; if (writeControl == null) { buffer = addBuffer(key); } else { buffer = writeControl.getBuffer(); } SocketChannel channel = (SocketChannel) key.channel(); try { channel.read(buffer); boolean boo = WriteControl.is(buffer); if (!boo) { if(writeControl==null) { writeControl = new WriteControl(key, buffer); WriteControlListener listener = new WriteControlListener() { @Override public void writeControl(WriteControlEvent event) { WriteControl control = event.getWriteControl(); ByteBuffer byteBuffer = control.getBuffer(); int l = byteBuffer.limit(); for (Iterator<SelectionKey> iterator = map.keySet().iterator(); iterator.hasNext(); ) { SelectionKey selectionKey = iterator.next(); LinkedList<ByteBuffer> list = map.get(selectionKey); if (list != map.get(key)) { ByteBuffer wrap = ByteBuffer.wrap(byteBuffer.array()); wrap.limit(l); list.offer(wrap); selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } } } }; writeControl.addWriteControlListener(listener); mapControl.put(key, writeControl); } key.interestOps(SelectionKey.OP_READ); } else { buffer.flip(); if (writeControl != null) { writeControl.control(); mapControl.remove(key); } else { map.get(key).offer(buffer); } key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ); } } catch (IOException e) { e.printStackTrace(); } } public void write(SelectionKey key) { System.out.println("Write"); LinkedList<ByteBuffer> bufferLinkedList = map.get(key); ByteBuffer buffer = bufferLinkedList.peek(); try { SocketChannel channel = (SocketChannel) key.channel(); channel.write(buffer); if (buffer.position() != buffer.limit()) { key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ); } else { int size = bufferLinkedList.size(); if (size <= 1) { key.interestOps(SelectionKey.OP_READ); } else { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } bufferLinkedList.remove(buffer); } } catch (IOException e) { e.printStackTrace(); } } public ByteBuffer addBuffer(SelectionKey key) { ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 8); LinkedList<ByteBuffer> list = map.get(key); list.offer(byteBuffer); return byteBuffer; } public void add(SelectionKey key) { LinkedList<ByteBuffer> list = new LinkedList<>(); map.put(key, list); } }
true
b6b554c8c595ecdb50a0c9b895017b968d69eaf6
Java
farhanjk/vmachine
/app/src/test/java/com/vending/machine/app/data/ItemIntializerTest.java
UTF-8
1,462
2.3125
2
[]
no_license
package com.vending.machine.app.data; import com.vending.machine.app.common.concurrency.BackgroundThreadPool; import com.vending.machine.app.common.concurrency.MockBackgroundThreadPool; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Farhan * 2018-04-30 */ @RunWith(JUnit4.class) public class ItemIntializerTest { @Test public void given_populate_is_called_it_saves_items_in_item_repository() { ItemRepository itemRepository = mock(ItemRepository.class); BackgroundThreadPool backgroundThreadPool = MockBackgroundThreadPool.newInstance(); ItemInitializer itemInitializer = new ItemInitializer(itemRepository, backgroundThreadPool); itemInitializer.populate(() -> { }); verify(itemRepository).saveAll(anyCollection()); } @Test public void given_populate_is_called_it_executes_the_passed_runnable() { ItemRepository itemRepository = mock(ItemRepository.class); BackgroundThreadPool backgroundThreadPool = MockBackgroundThreadPool.newInstance(); ItemInitializer itemInitializer = new ItemInitializer(itemRepository, backgroundThreadPool); Runnable runnable = mock(Runnable.class); itemInitializer.populate(runnable); verify(runnable).run(); } }
true
4d8947114d9a8203dc014c7f6cab16cc65d8f456
Java
TaklaGerguis/QuickQuizApp
/build/classes/Model/GenerateFromFile.java
UTF-8
2,042
2.96875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Model; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Takla Gerguis */ public class GenerateFromFile implements GenerateDataInterface{ private final String fileName; public GenerateFromFile(String fileName) { this.fileName = fileName; } /** * * @return */ @Override public Question[] generateQuestions() { Scanner in = null; try { in = new Scanner(new File(fileName)); } catch (FileNotFoundException ex) { Logger.getLogger(GenerateFromFile.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<Question> allQuestions = new ArrayList<Question>(); while(in.hasNext()){ String type = in.nextLine(); String questionText = in.nextLine(); String answer = in.nextLine(); if(type.equals("tf")){ TrueFalseQuestion question = new TrueFalseQuestion (questionText, answer.equals("true")? true : false); allQuestions.add(question); }else if (type.equals("fill")){ FillInBlankQuestion question = new FillInBlankQuestion(questionText, answer); allQuestions.add(question); }else if(type.equals("short")){ ShortAnswerQuestion question = new ShortAnswerQuestion(questionText, answer); allQuestions.add(question); } } Question[] questions = new Question[allQuestions.size()]; return allQuestions.toArray(questions); } }
true
cae23b6eb63a8de6a6655480895024a6a1184756
Java
aowens6/WGUMobile
/app/src/main/java/model/Mentor.java
UTF-8
726
2.4375
2
[]
no_license
package model; import android.content.ContentValues; import com.example.aowenswgumobile.database.MentorTable; public class Mentor { private String name; private String phone; private String email; private int mentorCode; public Mentor(String name, String phone, String email, int mentorCode) { this.name = name; this.phone = phone; this.email = email; this.mentorCode = mentorCode; } public ContentValues toValues(){ ContentValues values = new ContentValues(); values.put(MentorTable.MENTOR_NAME, name); values.put(MentorTable.MENTOR_PHONE, phone); values.put(MentorTable.MENTOR_EMAIL, email); values.put(MentorTable.MENTOR_CODE, mentorCode); return values; } }
true
e37fbca018b86054ef31197d9050aafcb09617a4
Java
mykelson/flowcontrol
/flow.java
UTF-8
3,317
3.796875
4
[]
no_license
import java.util.Scanner; import java.lang.*; public class flow{ public static void main(String args[]) { // Initiate a new scanner Scanner userInputScanner = new Scanner(System.in); int option; // asks users for an input to determine what they want to do System.out.println("Please how may we be of service to you today?\n"); System.out.println("kindly press 1 to check your grade\n"); System.out.println("Or press 2 to check if you were promoted\n"); System.out.println("Else press 3 to quit:\n"); option = userInputScanner.nextInt(); if (option == 3) { System.out.println("Goodbye!!!"); return; } directUser(option); userInputScanner.close(); } public static void directUser(int userOption) { // Initiate a new scanner Scanner userInputScanner = new Scanner(System.in); int newOption; int newOption2; int testscore; char grade; //flow control to direct user to their destination switch (userOption) { case 1: System.out.println("Please what is your testscore: "); testscore = userInputScanner.nextInt(); getGrade(testscore); break; case 2: System.out.println("Please what is your grade: "); break; case 3: System.out.println("Goodbye!!!"); return; default : do { System.out.println("Invalid Entry, Retry: "); newOption = userInputScanner.nextInt(); directUser(newOption); } while((newOption < 1) && (newOption > 3)); break; } do{ System.out.println("kindly press 1 to check your grade\n"); System.out.println("Or press 2 to check if you were promoted:\n"); System.out.println("Else press 3 to quit:\n"); newOption2 = userInputScanner.nextInt(); directUser(newOption2); } while((newOption2 < 1) && (newOption2 > 3)); userInputScanner.close(); } public static void getGrade(int score) { char grade; if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("YOUR GRADE IS " + grade); } public static void getPromotionStatus(char userGrade) { if (userGrade >= 'A' && userGrade <= 'Z') { userGrade = Character.toUpperCase(userGrade); } switch (userGrade) { case 'A': case 'B': case 'C': System.out.println("CONGRATULATION YOU HAVE BEEN PROMOTED!!!"); break; case 'D': case 'F': System.out.println("SORRY, YOU WERE NOT PROMOTED"); break; default: System.out.println("Invalid entry"); break; } } }
true
8c188f0f923476161119f84407dd5f4f4e7fe599
Java
raver119/dl4j-deployment
/serving-text/src/main/java/org/deeplearning4j/TextServingApp.java
UTF-8
1,139
2.203125
2
[]
no_license
package org.deeplearning4j; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.deeplearning4j.serving.ModelHolder; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; @Slf4j public class TextServingApp { public static void main( String[] args ) throws Exception { log.info("Starting TextServing app"); // initialize before starting jersey val holder = ModelHolder.getInstance(); // first of all we start HTTP server to handle REST API requests var context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); var server = new Server(8080); server.setHandler(context); var jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*"); jerseyServlet.setInitOrder(0); jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", "org.deeplearning4j.endpoints.Serving"); // actually start the server server.start(); // run till the end of eternity server.join(); } }
true
52af29c6f0b18eba96dc02eeb35be60689097773
Java
zhangbogh/eyes
/eyes/src/com/union/check/checker/SnapCheckCondition.java
UTF-8
358
1.976563
2
[]
no_license
package com.union.check.checker; import java.util.List; import com.union.check.obj.BeanProxy; public interface SnapCheckCondition { //返回的结果,供界面展示的时候打印用,snaps的数据会被继续序列化到硬盘,dbs的数据会每次从数据库查询 public List<BeanProxy> compare(List<BeanProxy> snaps, List<BeanProxy> dbs); }
true
0c50a6460ea5401e58b2f33df9b4b8c65c232080
Java
Encoder96/BookmyShow
/src/main/java/com/bookmyshow/bookmyshowapi/repositories/BookingRepository.java
UTF-8
312
1.921875
2
[]
no_license
package com.bookmyshow.bookmyshowapi.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.bookmyshow.bookmyshowapi.models.Booking; public interface BookingRepository extends JpaRepository<Booking, Long>{ List<Booking> findAllByUserId(Long userId); }
true
8769d5ba78c30d872e4843ea15efd2c4eddd9081
Java
marre/sipstack
/sipstack-core/src/main/java/io/sipstack/transaction/event/impl/TransactionEventImpl.java
UTF-8
473
1.984375
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package io.sipstack.transaction.event.impl; import io.sipstack.transaction.Transaction; import io.sipstack.transaction.event.TransactionEvent; /** * @author jonas@jonasborjesson.com */ public class TransactionEventImpl implements TransactionEvent { final Transaction transaction; public TransactionEventImpl(final Transaction transaction) { this.transaction = transaction; } @Override public Transaction transaction() { return transaction; } }
true
8fa107e41cebe53e2e35f5f64d07037f4ed9e92d
Java
latifatozoya/TwitterApp
/app/src/main/java/com/codepath/apps/restclienttemplate/TimelineActivity.java
UTF-8
7,867
2.21875
2
[ "Apache-2.0", "MIT" ]
permissive
package com.codepath.apps.restclienttemplate; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.codepath.apps.restclienttemplate.models.Tweet; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcels; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; public class TimelineActivity extends AppCompatActivity { private SwipeRefreshLayout swipeContainer; TwitterClient client; TweetAdapter tweetAdapter; ArrayList<Tweet> tweets; RecyclerView rvTweets; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.miCompose: launchComposeView(); return true; case R.id.miProfile: //showProfileView(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // REQUEST_CODE is defined above Log.d("Tweet", "entered OnActivity"); if (resultCode == RESULT_OK && (requestCode == REQUEST_CODE || requestCode == 10)) { // Extract name value from result extras String name = data.getExtras().getString("name"); Log.d("Tweet", "entered if statement"); int code = data.getExtras().getInt("code", 0); // Toast the name to display temporarily on screen Tweet tweet = (Tweet) Parcels.unwrap(data.getParcelableExtra("tweet")); Toast.makeText(this, name, Toast.LENGTH_SHORT).show(); tweets.add(0, tweet); tweetAdapter.notifyItemInserted(0); rvTweets.scrollToPosition(0); } } public void launchComposeView() { // first parameter is the context, second is the class of the activity to launch Intent i = new Intent(this, ComposeActivity.class); i.putExtra("username", "foobar"); i.putExtra("in_reply_to", "george"); i.putExtra("code", 400); startActivityForResult(i, REQUEST_CODE); // brings up the second activity } public void onSubmit(View v) { // closes the activity and returns to first screen EditText etName = (EditText) findViewById(R.id.et_simple); // Prepare data intent Intent data = new Intent(); // Pass relevant data back as a result data.putExtra("name", etName.getText().toString()); data.putExtra("code", 200); // ints work too // Activity finished ok, return the data setResult(RESULT_OK, data); this.finish(); } private final int REQUEST_CODE = 20; public void onClick(View view) { Intent i = new Intent(this, ComposeActivity.class); i.putExtra("mode", 2); // pass arbitrary data to launched activity startActivityForResult(i, REQUEST_CODE); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); client = TwitterApp.getRestClient(getApplicationContext()); //find the recyclerView rvTweets = (RecyclerView) findViewById(R.id.rvTweet); //init the array list (data source) tweets = new ArrayList<>(); //construct the adapter from this datasource tweetAdapter = new TweetAdapter(this, tweets); //RecyclerView setup rvTweets.setLayoutManager(new LinearLayoutManager(this)); //set the adapter rvTweets.setAdapter(tweetAdapter); populateTimeline(); String username = getIntent().getStringExtra("username"); String inReplyTo = getIntent().getStringExtra("in_reply_to"); int code = getIntent().getIntExtra("code", 0); swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeContainer.setRefreshing(false); // once the network request has completed successfully. fetchTimelineAsync(0); } }); //loading colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); } public void fetchTimelineAsync(int page) { client.getHomeTimeline(new JsonHttpResponseHandler() { public TweetAdapter adapter; public void onSuccess(JSONArray json) { // Remember to CLEAR OUT old items before appending in the new ones adapter.clear(); // ...the data has come back, add new items to your adapter... adapter.addAll(); // Now we call setRefreshing(false) to signal refresh has finished swipeContainer.setRefreshing(false); } public void onFailure(Throwable e) { Log.d("DEBUG", "Fetch timeline error: " + e.toString()); } }); } private void populateTimeline() { client.getHomeTimeline(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { Log.d("TwitterClient", response.toString()); } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray response) { Log.d("TwitterClient", response.toString()); for (int i = 0; i < response.length(); i++) { try { Tweet tweet = Tweet.fromJSON(response.getJSONObject(i)); tweets.add(tweet); tweetAdapter.notifyItemInserted(tweets.size() - 1); } catch (JSONException e) { e.printStackTrace(); } } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { Log.d("TwitterClient", responseString); throwable.printStackTrace(); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { Log.d("TwitterClient", errorResponse.toString()); throwable.printStackTrace(); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("TwitterClient", errorResponse.toString()); throwable.printStackTrace(); } }); } }
true
e9865d17b7c207fdcb77558762f23c03fc1072e9
Java
amitabhverma/jif-experimental
/jif0/src/main/java/edu/mbl/jif/device/mm/Stage.java
UTF-8
612
2.078125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.mbl.jif.device.mm; /** * * @author GBH */ public interface Stage extends Device { // Device API public DeviceType getType(); static DeviceType Type = DeviceType.StageDevice; // Stage API public int setPositionUm(double pos); public int getPositionUm(double pos); public int setPositionSteps(long steps); public int getPositionSteps(long steps); public int setOrigin(); public int getLimits(double lower, double upper); };
true
dc0e0dae0a2ab1ec30ff44a8807e6338f2b946d5
Java
skidson/cpsc304-project
/allegro/src/ca/ubc/cs304/allegro/model/Refund.java
UTF-8
1,311
2.484375
2
[]
no_license
package ca.ubc.cs304.allegro.model; import java.sql.Date; import java.util.ArrayList; import java.util.List; import ca.ubc.cs304.allegro.jdbc.JDBCManager.Table; public class Refund implements AllegroItem { private Integer retid, receiptId; private Date retDate; private String name; public Refund(Integer retid, Integer receiptId, Date retDate, String name) { super(); this.retid = retid; this.receiptId = receiptId; this.retDate = retDate; this.name = name; } public List<Object> getParameters() { List<Object> parameters = new ArrayList<Object>(); parameters.add(new Integer(retid)); parameters.add(retDate); parameters.add(receiptId); parameters.add(name); return parameters; } public Table getTable() { return Table.Refund; } public int getRetid() { return retid; } public void setRetid(int retid) { this.retid = retid; } public int getReceiptId() { return receiptId; } public void setReceiptId(int receiptId) { this.receiptId = receiptId; } public Date getRetDate() { return retDate; } public void setRetDate(Date retDate) { this.retDate = retDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
2e343501497bddf435e66b1563a1da870f0358f3
Java
FelixFanPenn/leetcode
/Brick_Wall.java
UTF-8
684
3.125
3
[]
no_license
public class Solution { public int leastBricks(List<List<Integer>> wall) { Map<Integer, Integer> map = new HashMap<>(); int max = 0; for (int i = 0; i < wall.size(); i++) { List<Integer> list = wall.get(i); int sum = 0; for (int j = 0; j < list.size() - 1; j++) { sum += list.get(j); if (!map.containsKey(sum)) { map.put(sum, 1); } else { map.put(sum, map.get(sum) + 1); } if (max < map.get(sum)) max = map.get(sum); } } return wall.size() - max; } }
true
7fa7a3a3158ed56aa37fe9acb2777947bf38584f
Java
WKH-shadow/Java
/Demo8.java
UTF-8
1,077
4.25
4
[]
no_license
package LeetCode; import java.util.HashSet; import java.util.Set; /** * 题目描述: * 给定一个整数数组,判断是否存在重复元素。 * * 如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。 * */ public class Demo8 { /** * 解题思路: * 遍历数组,数字放到 set 中。如果数字已经存在于 set 中, * 直接返回 true。如果成功遍历完数组,则表示没有重复元素,返回 false。 * @param nums * @return */ public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<>(); for (int num: nums) { if (set.contains(num)) { return true; } set.add(num); } return false; } public static void main(String[] args) { int[] arr = {1,1,1,3,3,4,3,2,4,2}; Demo8 demo8 = new Demo8(); System.out.println(demo8.containsDuplicate(arr)); } }
true
697644f1d4c32705e06cb894f0790dd827161f12
Java
deiknymi0/WordFinder
/src/main/java/BoggleBoard.java
UTF-8
6,360
2.75
3
[]
no_license
import javax.swing.*; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.function.Function; public class BoggleBoard { private static JTextArea[][] arr = new JTextArea[4][4]; static String[][] strArr = new String[4][4]; private String[] dictionary; private BoggleBoard board; public java.util.List<String> results; public int rows() { return 4; } public int cols() { return 4; } public char getLetter(int i, int j) { return strArr[i][j].charAt(0); } public void initialize() { JFrame f = new JFrame(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int height = screenSize.height; int width = screenSize.width; f.setSize(width / 2, height / 2); f.setTitle("Word Find Solver"); JPanel panel = new JPanel(new GridLayout(4, 4, 5,5)); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { arr[i][j] = new JTextArea(4,4); int finalI = i; int finalJ = j; arr[i][j].addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_TAB) { if (e.getModifiers() > 0) { arr[finalI][finalJ].transferFocusBackward(); } else { arr[finalI][finalJ].transferFocus(); } e.consume(); } } }); AbstractDocument pDoc=(AbstractDocument)arr[i][j].getDocument(); pDoc.setDocumentFilter(new DocumentSizeFilter(1, BoggleBoard::tabNext)); panel.add(arr[i][j]); } } JButton button = new JButton("Find Solutions"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { strArr[i][j] = arr[i][j].getText(); } } BoggleSolver solver = new BoggleSolver(dictionary); results = new ArrayList<>(); for (String word : solver.getAllValidWords(board)) { results.add(word); } Collections.sort(results, (o1, o2) -> -Integer.valueOf(o1.length()).compareTo(o2.length())); StringBuilder sb = new StringBuilder(); for (int i=0; i < 20; i++) { int fromIndex = i*10; if (results.size() <= fromIndex) break; sb.append(results.subList(fromIndex, fromIndex + Math.min(10, results.size() - fromIndex))); sb.append("\n"); } JOptionPane.showMessageDialog(null, sb, "InfoBox: ", JOptionPane.INFORMATION_MESSAGE); } }); JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); panel2.add(panel); panel2.add(button); f.add(panel2); f.setVisible(true); f.setLocationRelativeTo(null); Container c = f.getContentPane(); c.setBackground(Color.DARK_GRAY); f.setResizable(false); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new FlowLayout()); } public BoggleBoard(String[] dictionary) { this.board = this; this.dictionary = dictionary; initialize(); } private static String tabNext(String string) { return string; } private class DocumentSizeFilter extends DocumentFilter { int maxCharacters; boolean DEBUG = false; Function<String,String> function; public DocumentSizeFilter(int maxChars, Function<String,String> function) { maxCharacters = maxChars; this.function = function; } public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { if (DEBUG) { System.out.println("in DocumentSizeFilter's insertString method"); } //This rejects the entire insertion if it would make //the contents too long. Another option would be //to truncate the inserted string so the contents //would be exactly maxCharacters in length. if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) super.insertString(fb, offs, str, a); else { function.apply("bogus"); } } public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException { if (DEBUG) { System.out.println("in DocumentSizeFilter's replace method"); } //This rejects the entire replacement if it would make //the contents too long. Another option would be //to truncate the replacement string so the contents //would be exactly maxCharacters in length. if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters) super.replace(fb, offs, length, str, a); else { Robot robot = null; try { robot = new Robot(); } catch (AWTException e) { // } robot.keyPress(KeyEvent.VK_TAB); robot.keyPress(Integer.valueOf(KeyEvent.getExtendedKeyCodeForChar(str.charAt(0)))); } } } }
true
3e0ddffd2f0cd9805829f55ddd1e164debb7ade8
Java
Msyang123/weixin
/src.main.java/com/sgsl/activity/RegisterActivityWatcher.java
UTF-8
338
2.421875
2
[]
no_license
package com.sgsl.activity; //具体的主题角色注册活动 public class RegisterActivityWatcher implements Watcher { @Override public void update(TransmitDataInte data) { RegisterTransmitData registerData=(RegisterTransmitData)data; System.out.println("注册活动"+registerData.getUserId()); } }
true
1f31bde30f8e4162152d91aa5fe56370b504156f
Java
lanhuidong/LPT
/src/main/java/com/nexusy/log/log4j2/ThreadContextTest.java
UTF-8
1,878
2.640625
3
[]
no_license
package com.nexusy.log.log4j2; import org.apache.logging.log4j.CloseableThreadContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.ThreadContext; import java.util.UUID; /** * @author lanhuidong * @since 2017-01-05 */ public class ThreadContextTest { private static final Logger LOGGER = LogManager.getLogger(); public static void main(String[] args) throws Exception { new Thread(new SubThread()).start(); testMDC(); testNDC(); testCloseableThreadContext(); } /** * PatternLayout中使用%X或%X{key} */ public static void testMDC() throws Exception { ThreadContext.put("id", UUID.randomUUID().toString()); LOGGER.info("MDC test."); Thread.sleep(2000); LOGGER.info("before clear map"); ThreadContext.clearMap(); } /** * PatternLayout中使用%x */ public static void testNDC() { ThreadContext.push(UUID.randomUUID().toString()); LOGGER.info("NDC test"); ThreadContext.clearStack(); } public static void testCloseableThreadContext() { try (CloseableThreadContext.Instance ctc = CloseableThreadContext.put("id", UUID.randomUUID().toString())) { LOGGER.info("Message 1"); LOGGER.info("Message 2"); } } /** * 需要设置系统属性-DisThreadContextMapInheritable=true * * 注:测试时无法加载log4j2.component.properties,为找到具体原因 */ public static class SubThread implements Runnable { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } LOGGER.info("sub thread test"); } } }
true
9fc49a93901afb23dda3d04cdf0b4d1ff50b81ca
Java
kegesch/tdt4250-2019
/no.tdtd4250.model.html/src/no/tdt4250/model/html/service/CourseGroupService.java
UTF-8
485
2.453125
2
[]
no_license
package no.tdt4250.model.html.service; import java.util.Optional; import programmes.Course; import programmes.CourseGroup; import programmes.Programme; public class CourseGroupService { public CourseGroup getCourseGroupOfCourse(Course course, Programme programme) { Optional<CourseGroup> group = programme.getCourseGroups().stream().filter(g -> g.getCourses().contains(course)).findAny(); if(group.isPresent()) { return group.get(); } else { return null; } } }
true
4bb831577a704fc441719f534768d6e22207388b
Java
mudongzi/SpringBoot-Excel
/src/main/java/com/xudong/mapper/BookService.java
UTF-8
486
2.046875
2
[]
no_license
package com.xudong.mapper; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import com.xudong.pojo.Book; @Mapper public interface BookService { @Select(value = { "select * from book" }) public List<Book> selectBookList(); @Insert(value = { "insert into book values(#{bookId},#{bookName},#{price},#{bookTime}) " }) public void insertBook(Book book); }
true
652bfdecc7d76587799d652b91081333ce0997dd
Java
rami11/electronic-telephone-system
/src/Award.java
UTF-8
2,161
2.96875
3
[]
no_license
public class Award implements Comparable<Award> { private static long count = 0; private String id; private String description; private double value; private double minDonation; private int originalQty; private int availableQty; private String sponsorId; public Award(String description, double value, double minDonation, int originalQty, int availableQty, String sponsorId) { id = "A" + ++count; this.description = description; this.value = value; this.minDonation = minDonation; this.originalQty = originalQty; this.availableQty = availableQty; this.sponsorId = sponsorId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public double getMinDonation() { return minDonation; } public void setMinDonation(double minDonation) { this.minDonation = minDonation; } public int getOriginalQty() { return originalQty; } public void setOriginalQty(int originalQty) { this.originalQty = originalQty; } public int getAvailableQty() { return availableQty; } public void setAvailableQty(int availableQty) { this.availableQty = availableQty; } public String getSponsorId() { return sponsorId; } public void setSponsorId(String sponsorId) { this.sponsorId = sponsorId; } public void deduct(int value) { } @Override public String toString() { return String.format( "%s\t%-10s\t$ %-10.2f\t$ %-10.2f\t%d\t%d\t%s", id, description, value, minDonation, originalQty, availableQty, sponsorId ); } @Override public int compareTo(Award o) { return (int) (o.getValue() - this.getValue()); } }
true
9a2fb7478d897636f5e2a1fce0e8623c0fc67b13
Java
loungani/checkers
/src/Pawn.java
UTF-8
381
2.859375
3
[]
no_license
import java.awt.Color; public class Pawn extends Piece { private Color pieceColor; private boolean option; public Pawn(Color c) { pieceColor = c; setOption(true); } public Color getPieceColor() { return pieceColor; } public boolean isOption() { return option; } public void setOption(boolean option) { this.option = option; } }
true
807e7c3612a2050a61629101756af1984ff9eb2a
Java
WolvesWithSword/PathfinderGenerator
/PathfinderGenerator/src/item/gemAndJewel/GemAndJewelBuilder.java
UTF-8
11,013
3.453125
3
[]
no_license
package item.gemAndJewel; import java.util.Random; import constant.GemAndJewelConstant; import utility.Data; import utility.Debug; import utility.Tools; import utility.Tuple; /** * GemAndJewelBuilder permet de créer des bijoux et des gemmes. * @author Mentra20 * */ public class GemAndJewelBuilder { Random r; //Le random pour les tirages. /* CONSTRUCTOR */ public GemAndJewelBuilder(){ this.r = new Random(); } /* METHODS */ /** * createGemOrJewel créer une gemme ou un bijoux selon le drop. * @param grade : grade du bijoux ou de la gemme * @return un tuple contenant un bijoux et une gemme (un des deux est null). */ public Tuple<Gem, Jewel> createGemOrJewel(int grade){ Debug.debug("Choosing gem or jewel..."); Data<Integer> data = new Data<Integer>(); //Chargement des données. switch (grade) { case 1: data.addAll(GemAndJewelConstant.grade1()); break; case 2: data.addAll(GemAndJewelConstant.grade2()); break; case 3: data.addAll(GemAndJewelConstant.grade3()); break; case 4: data.addAll(GemAndJewelConstant.grade4()); break; case 5: data.addAll(GemAndJewelConstant.grade5()); break; case 6: data.addAll(GemAndJewelConstant.grade6()); break; default: Debug.error("Error switch createGemOrJewel"); break; } //Tirage int randomValue = r.nextInt(100)+1; Debug.debug("n_choice = "+randomValue); int choice = data.selectObject(randomValue); //On retourne un tuple à moitié vide. if(choice == 1) {//Gemme brute Gem res = createGem(grade, false); return new Tuple<Gem, Jewel>(res, null); } if(choice == 2) {//Gemme taillée Gem res = createGem(grade, true); return new Tuple<Gem, Jewel>(res, null); } if(choice == 3) {//Bijoux Jewel res = createJewel(grade); return new Tuple<Gem, Jewel>(null,res); } else { Debug.error("Error on choice drop"); return null; } } /** * CreateGem créer une gemme. * @param grade : grade de la gemme. * @param cut : true si elle est taillée, brut sinon. * @return La gemme créée. */ public Gem createGem(int grade, boolean cut) { if(cut) { Debug.debug("Create cut gem with grade "+grade+"..."); }else { Debug.debug("Create raw gem with grade "+grade+"..."); } Data<Gem> data = new Data<Gem>(); //Chargement des données switch(grade) { case 1: data.addAll(GemAndJewelConstant.gemGrade1()); break; case 2: data.addAll(GemAndJewelConstant.gemGrade2()); break; case 3: data.addAll(GemAndJewelConstant.gemGrade3()); break; case 4: data.addAll(GemAndJewelConstant.gemGrade4()); break; case 5: data.addAll(GemAndJewelConstant.gemGrade5()); break; case 6: data.addAll(GemAndJewelConstant.gemGrade6()); break; default: Debug.error("Error on makeGem switch : data"); break; } //Tirage int randomValue = r.nextInt(100)+1; Debug.debug("n_gem = "+randomValue); Gem gem = data.selectObject(randomValue); //Ajout du prix constant en fonction du grade. switch (grade) { case 1: gem.setPrice(5); break; case 2: gem.setPrice(25); break; case 3: gem.setPrice(50); break; case 4: gem.setPrice(250); break; case 5: gem.setPrice(500); break; case 6: gem.setPrice(2500); break; default: Debug.error("Error on makeGem switch : price"); break; } if(cut) { //La gemme est taillée. gem.setCut(TypeCut.CUT); // 2d4 x prix du grade int cutVal = r.nextInt(4)+1; cutVal += r.nextInt(4)+1; Debug.debug("n_cut = "+cutVal); //ajout au prix (valeur multipliée constante). switch (grade) { case 1: gem.setPrice(gem.getPrice() + cutVal * 1); break; case 2: gem.setPrice(gem.getPrice() + cutVal * 5); break; case 3: gem.setPrice(gem.getPrice() + cutVal * 10); break; case 4: gem.setPrice(gem.getPrice() + cutVal * 50); break; case 5: gem.setPrice(gem.getPrice() + cutVal * 100); break; case 6: gem.setPrice(gem.getPrice() + cutVal * 500); break; default: Debug.error("Error on makeGem switch : cut"); break; } } else { //La gemme est brute. gem.setCut(TypeCut.RAW); } Debug.debug(""); return gem; } /** * createJewel créer un bijoux * @param grade : le grade du bijoux. * @return Le bijoux créé. */ public Jewel createJewel(int grade) { Debug.debug("Create jewel of grade "+grade+"..."); Jewel jewel = new Jewel(); //Ajout du prix constant en fonction du grade switch (grade) { case 1: jewel.setPrice(0.5); break; case 2: jewel.setPrice(2.5); break; case 3: jewel.setPrice(5); break; case 4: jewel.setPrice(25); break; case 5: jewel.setPrice(50); break; case 6: jewel.setPrice(250); break; default: Debug.error("Error on createJewel : price"); break; } //Creation du bijoux jewel.setSize(jeweSize()); jewel.setType(jewelType(grade)); jewel.setMaterial(jewelMaterial(grade)); jewel = jewelWork(jewel, grade); //Calcul du prix du bijoux double price = jewel.getPrice() * jewel.getMaterial().getMultiplier(); if(jewel.getGemN() != null) price += jewel.getGemN().getPrice()/2; if(jewel.getGemN_1() != null) price += (jewel.getGemN_1().getX().getPrice() * jewel.getGemN_1().getY())/5; if(jewel.getGemN_2() != null) price += (jewel.getGemN_2().getX().getPrice() * jewel.getGemN_2().getY())/10; //Calcul du modificateur du prix double modificator = 1; modificator += jewel.getWork().getModificator(); modificator += jewel.getType().getModificator(); modificator += jewel.getSize().getModificator(); //FORMULE : (PRIX BIJ * PRIX MAT + PRIX GEM N,N-1,N-2) * (1 + MODIF TAILLE + MODIF WORK + MODIF TYPE) jewel.setPrice(modificator * price); jewel.setPrice(Tools.truncateTo(jewel.getPrice(),2));//On tronque le prix à deux décimale. //Affichage de fin de creation car affichage de blanc lors de l'appel de jewelWork. Debug.debug(""); return jewel; } /** * Créer un type de bijoux * @param grade : le grade du bijoux * @return Le type du bijoux. */ public TypeJewel jewelType(int grade) { Debug.debug("Create jewel type..."); Data<TypeJewel> data = new Data<TypeJewel>(); //Chargement des données switch(grade) { case 1: data.addAll(GemAndJewelConstant.jewelType1()); break; case 2: data.addAll(GemAndJewelConstant.jewelType2()); break; case 3: data.addAll(GemAndJewelConstant.jewelType3()); break; case 4: data.addAll(GemAndJewelConstant.jewelType4()); break; case 5: data.addAll(GemAndJewelConstant.jewelType5()); break; case 6: data.addAll(GemAndJewelConstant.jewelType6()); break; default: Debug.error("Error on jewelType switch : data"); break; } //Tirage int randomValue = r.nextInt(100)+1; Debug.debug("n_type = "+randomValue); return data.selectObject(randomValue); } /** * Créer la taille du bijoux. * @return la taille du bijoux. */ public TypeSize jeweSize() { Debug.debug("Create jewel size..."); Data<TypeSize> data = new Data<TypeSize>(); //Chargement des données data.addAll(GemAndJewelConstant.jewelSize()); //Tirage int randomValue = r.nextInt(100)+1; Debug.debug("n_size = "+randomValue); return data.selectObject(randomValue); } /** * Créer le matériel du bijoux. * @param grade : le grade du bijoux. * @return le matériel du bijoux. */ public Material jewelMaterial(int grade) { Debug.debug("Create jewel material..."); Data<Material> data = new Data<Material>(); //Chargement des données switch(grade) { case 1: data.addAll(GemAndJewelConstant.jewelMaterial1()); break; case 2: data.addAll(GemAndJewelConstant.jewelMaterial2()); break; case 3: data.addAll(GemAndJewelConstant.jewelMaterial3()); break; case 4: data.addAll(GemAndJewelConstant.jewelMaterial4()); break; case 5: data.addAll(GemAndJewelConstant.jewelMaterial5()); break; case 6: data.addAll(GemAndJewelConstant.jewelMaterial6()); break; default: Debug.error("Error on jewelMaterial switch : data"); break; } //Tirage int randomValue = r.nextInt(100)+1; Debug.debug("n_mat = "+randomValue); return data.selectObject(randomValue); } /** * Créer un travail ou des gemmes sur le bijoux. * @param jewel : le bijoux à modifier. * @param grade : le grade du bijoux. * @return le bijoux modifié. */ public Jewel jewelWork(Jewel jewel,int grade) { Debug.debug("Create work on jewel..."); //Nombre de tirage. int rethrow = 1; //Tant qu'il reste des tirages. while(rethrow > 0) { rethrow--; //Tirage int randomValue = r.nextInt(100)+1; Debug.debug("n_work = "+randomValue); //Selection du choix if(randomValue <= 10) { //Le bijoux a un travail normal. jewel.setWork(TypeJewelWork.SIMPLE); } else if(randomValue <= 25) { //Le bijoux a des gravures. jewel.setWork(TypeJewelWork.ENGRAVING); } else if(randomValue <= 40) { //Tirage du dé 8. int d8 = r.nextInt(8)+1; Debug.debug("d8 = "+d8); //Gemme de grade N-2 int newGrade = grade-2; if(newGrade <= 0) newGrade = 1; //Impossible d'aller plus bas. Gem gemN_2 = this.createGem(newGrade, r.nextBoolean()); jewel.setGemN_2(new Tuple<Gem, Integer>(gemN_2, d8)); } else if(randomValue <= 60) { //Tirage du dé 4. int d4 = r.nextInt(4)+1; Debug.debug("d4 = "+d4); //Gemme de grade N-1 int newGrade = grade-1; if(newGrade <= 0) newGrade = 1;//Impossible d'aller plus bas. Gem gemN_1 = this.createGem(newGrade, r.nextBoolean()); jewel.setGemN_1(new Tuple<Gem, Integer>(gemN_1, d4)); } else if(randomValue <= 90) { //Gemme de rang N. Gem gemN = this.createGem(grade, r.nextBoolean()); jewel.setGemN(gemN); } else if(randomValue <= 100) { //On gagne 2 tirages supplémentaires. Debug.debug("re-throw"); rethrow += 2; } } return jewel; } }
true
f5c56159dee1ce9c184dacfbe80f3890d642e583
Java
jydlk/ware-swift
/grpc-swift/src/main/java/com/ware/swift/grpc/AbstractGrpcRequestStreamObserver.java
UTF-8
1,515
2.046875
2
[]
no_license
package com.ware.swift.grpc; import com.ware.swift.core.remoting.IRemotingCallStreamObserver; import com.ware.swift.core.remoting.IRequestStreamCallbackRegistrator; import com.ware.swift.proto.InteractivePayload; import io.grpc.stub.CallStreamObserver; /** * */ public abstract class AbstractGrpcRequestStreamObserver extends CallStreamObserver<InteractivePayload> implements IRequestStreamCallbackRegistrator { protected IRemotingCallStreamObserver callStreamObserver; @Override public void registryCallback(IRemotingCallStreamObserver value) { this.callStreamObserver = value; } @Override public boolean isReady() { return callStreamObserver.isReady(); } @Override public void setOnReadyHandler(Runnable onReadyHandler) { callStreamObserver.setOnReadyHandler(onReadyHandler); } @Override public void disableAutoInboundFlowControl() { callStreamObserver.disableAutoInboundFlowControl(); } @Override public void request(int count) { callStreamObserver.request(count); } @Override public void setMessageCompression(boolean enable) { callStreamObserver.setMessageCompression(enable); } @Override public abstract void onNext(InteractivePayload value); @Override public void onError(Throwable t) { this.callStreamObserver.onError(t); } @Override public void onCompleted() { this.callStreamObserver.onCompleted(); } }
true
58170742cc6d4531887d36a20e7633e55fbf85a5
Java
PabloMacLinares/EndoMingo
/app/src/main/java/com/blc/endomingo/managers/ManagerRoutePoint.java
UTF-8
2,191
2.484375
2
[]
no_license
package com.blc.endomingo.managers; import android.content.Context; import com.blc.endomingo.contracts.ContractDB; import com.blc.endomingo.pojo.RoutePoint; import com.j256.ormlite.dao.GenericRawResults; import com.j256.ormlite.stmt.QueryBuilder; import java.io.IOException; import java.sql.SQLException; import java.util.List; /** * Created by Pablo on 31/12/2016. */ public class ManagerRoutePoint extends ManagerDB<RoutePoint> { public ManagerRoutePoint(Context context) { super(context); } @Override public long insert(RoutePoint object) { getHelper().getRoutePointDao().create(object); return object.getId(); } @Override public int update(RoutePoint object) { return getHelper().getRoutePointDao().update(object); } @Override public int delete(RoutePoint object) { return getHelper().getRoutePointDao().delete(object); } @Override public RoutePoint selectByID(long id) { QueryBuilder<RoutePoint, Integer> qb = getHelper().getRoutePointDao().queryBuilder(); try { qb.setWhere(qb.where().eq(ContractDB.RoutePoint.ID, id)); for (RoutePoint rp : getHelper().getRoutePointDao().query(qb.prepare())) { return rp; } } catch (SQLException e) {} return null; } @Override public List<RoutePoint> select(String[] fields, String[] values) { StringBuilder query = new StringBuilder(); query.append("select * from ").append(ContractDB.RoutePoint.TABLE).append(" where "); for (int i = 0; i < fields.length; i++) { query.append(fields[i]).append(" = ").append(values[i]); if(i < fields.length - 1){ query.append(" and "); } } GenericRawResults<RoutePoint> results = getHelper().getRoutePointDao().queryRaw( query.toString(), getHelper().getRoutePointDao().getRawRowMapper()); try { List<RoutePoint> rps = results.getResults(); results.close(); return rps; } catch (SQLException | IOException e) { return null; } } }
true
1a88bab0a79a770df6eb82f772cc51d535c82b57
Java
rentroomer/rentroomer
/src/main/java/rentroomer/roomreview/security/support/KakaoAuthenticationTemplate.java
UTF-8
1,167
2.28125
2
[]
no_license
package rentroomer.roomreview.security.support; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.web.client.RestTemplate; import rentroomer.roomreview.dto.SocialProperty; import rentroomer.roomreview.security.tokens.PreSocialLoginToken; public class KakaoAuthenticationTemplate implements SocialAuthenticationTemplate { private static final String AUTH_HEADER_KEY = "Authorization"; private static final String AUTH_HEADER_PREFIX = "Bearer "; private static final HttpMethod AUTH_METHOD = HttpMethod.GET; public SocialProperty auth(PreSocialLoginToken token) { RestTemplate template = new RestTemplate(); HttpEntity<String> entity = new HttpEntity<>(createHeader(token)); return template.exchange(token.getEndPoint(), AUTH_METHOD, entity, token.getResponseType()).getBody(); } private static HttpHeaders createHeader(PreSocialLoginToken token) { HttpHeaders headers = new HttpHeaders(); headers.add(AUTH_HEADER_KEY, AUTH_HEADER_PREFIX + token.getToken()); return headers; } }
true
5f63ba3c186c9011f0ff64610e445265369b40a9
Java
MartinGuehmann/PIA2
/pia/phyutility/src/org/virion/jam/toolbar/Toolbar.java
UTF-8
5,576
2.5625
3
[ "GPL-3.0-only", "MIT" ]
permissive
package org.virion.jam.toolbar; import javax.swing.*; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import java.awt.event.*; import java.awt.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; /** * @author Andrew Rambaut * @author Alexei Drummond * * @version $Id: Toolbar.java 488 2006-10-25 23:09:21Z rambaut $ */ public class Toolbar extends JToolBar { public Toolbar() { this(new ToolbarOptions(ToolbarOptions.ICON_AND_TEXT, false)); } public Toolbar(ToolbarOptions options) { this.options = options; // This property is only used if the Quaqua library is loaded on // Mac OS X - it makes toolbars look more Mac-like putClientProperty("Quaqua.ToolBar.isDividerDrawn", Boolean.TRUE); putClientProperty("JToolBar.isRollover", Boolean.TRUE); setLayout(new GridBagLayout()); // setBorder(BorderFactory.createCompoundBorder( // BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray), // BorderFactory.createEmptyBorder(0, 12, 0, 12))); if (options != null) { final JPopupMenu menu = new JPopupMenu(); menu.setLightWeightPopupEnabled(false); ChangeListener listener = new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { toolbarOptionsChanged(); } }; ButtonGroup group = new ButtonGroup(); iconTextMenuItem = new JRadioButtonMenuItem("Icon & Text"); iconTextMenuItem.addChangeListener(listener); group.add(iconTextMenuItem); menu.add(iconTextMenuItem); iconOnlyMenuItem = new JRadioButtonMenuItem("Icon Only"); iconOnlyMenuItem.addChangeListener(listener); group.add(iconOnlyMenuItem); menu.add(iconOnlyMenuItem); textOnlyMenuItem = new JRadioButtonMenuItem("Text Only"); textOnlyMenuItem.addChangeListener(listener); group.add(textOnlyMenuItem); menu.add(textOnlyMenuItem); menu.add(new JSeparator()); smallSizeMenuItem = new JCheckBoxMenuItem("Small Size"); smallSizeMenuItem.addChangeListener(listener); menu.add(smallSizeMenuItem); menu.add(new JSeparator()); JMenuItem item = new JMenuItem("Customize Toolbar..."); item.setEnabled(false); menu.add(item); // Set the component to show the popup menu addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { if (evt.isPopupTrigger()) { menu.show(evt.getComponent(), evt.getX(), evt.getY()); } } public void mouseReleased(MouseEvent evt) { if (evt.isPopupTrigger()) { menu.show(evt.getComponent(), evt.getX(), evt.getY()); } } }); iconTextMenuItem.setSelected(options.getDisplay() == ToolbarOptions.ICON_AND_TEXT); iconOnlyMenuItem.setSelected(options.getDisplay() == ToolbarOptions.ICON_ONLY); textOnlyMenuItem.setSelected(options.getDisplay() == ToolbarOptions.TEXT_ONLY); smallSizeMenuItem.setSelected(options.getSmallSize()); } else { iconTextMenuItem = null; iconOnlyMenuItem = null; textOnlyMenuItem = null; smallSizeMenuItem = null; } } public void addComponent(JComponent component) { if (component instanceof ToolbarItem) { ToolbarItem item = (ToolbarItem)component; toolbarItems.add(item); item.setToolbarOptions(options); } addItem(component); } public void addSeperator() { addItem(new Separator()); } public void addSpace() { addItem(new Separator()); } private void addItem(JComponent item) { GridBagConstraints c = new GridBagConstraints(); c.gridx = GridBagConstraints.RELATIVE; c.gridy = 0; c.weightx = 0; add(item, c); } public void addFlexibleSpace() { GridBagConstraints c = new GridBagConstraints(); c.gridx = GridBagConstraints.RELATIVE; c.gridy = 0; c.weightx = 1; add(new Separator(), c); } private void toolbarOptionsChanged() { int display = (iconTextMenuItem.isSelected() ? ToolbarOptions.ICON_AND_TEXT : (iconOnlyMenuItem.isSelected() ? ToolbarOptions.ICON_ONLY : ToolbarOptions.TEXT_ONLY)); boolean smallSize = smallSizeMenuItem.isSelected(); setToolbarOptions(new ToolbarOptions(display, smallSize)); } private void setToolbarOptions(ToolbarOptions toolbarOptions) { this.options = toolbarOptions; Iterator<ToolbarItem> iter = toolbarItems.iterator(); while (iter.hasNext()) { ToolbarItem item = iter.next(); item.setToolbarOptions(options); } validate(); repaint(); } private ToolbarOptions options; private final JRadioButtonMenuItem iconTextMenuItem; private final JRadioButtonMenuItem iconOnlyMenuItem; private final JRadioButtonMenuItem textOnlyMenuItem; private final JCheckBoxMenuItem smallSizeMenuItem; private List<ToolbarItem> toolbarItems = new ArrayList<ToolbarItem>(); }
true
c4f726850a65d31523846a01b1b14ba939181d7c
Java
Ahmedmmy97/Diary-Android
/app/src/main/java/com/a33y/jo/diary/MemoriesService.java
UTF-8
6,259
1.898438
2
[]
no_license
package com.a33y.jo.diary; import android.app.IntentService; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.media.AudioAttributes; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.IBinder; import android.provider.Settings; import android.service.notification.StatusBarNotification; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.applandeo.materialcalendarview.CalendarView; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by ahmed on 31/8/2018. */ public class MemoriesService extends Service { private static int NOTIFICATION_ID = 100; SharedPreferences prefs; public MemoriesService() { } @Override public void onCreate() { super.onCreate(); prefs = this.getSharedPreferences( "com.a33y.jo.diary", Context.MODE_PRIVATE); } @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { new Thread(new Runnable() { @Override public void run() { Calendar calendar = Calendar.getInstance(); List<Note> notes = NotesDatabase.getItemDatabase(getApplicationContext()).itemDao().getAll(); for(Note n : notes){ Calendar noteCal = Calendar.getInstance(); noteCal.setTime(n.getDate()); if(noteCal.get(Calendar.DAY_OF_MONTH)==calendar.get(Calendar.DAY_OF_MONTH) && noteCal.get(Calendar.MONTH)==calendar.get(Calendar.MONTH)&&noteCal.get(Calendar.YEAR)<calendar.get(Calendar.YEAR)){ long time = prefs.getLong(String.valueOf(n.getId()),0); Calendar calendar1 = Calendar.getInstance(); calendar.setTime(new Date(time)); prefs = getApplicationContext().getSharedPreferences( "com.a33y.jo.diary", Context.MODE_MULTI_PROCESS); Log.i("service","CheckService - "+String.valueOf(prefs.getBoolean("notify",true))); if(time==0 || !(calendar1.get(Calendar.DAY_OF_MONTH)==calendar.get(Calendar.DAY_OF_MONTH) && calendar1.get(Calendar.MONTH)==calendar.get(Calendar.MONTH)&&calendar1.get(Calendar.YEAR)==calendar.get(Calendar.YEAR))) if(prefs.getBoolean("notify",true)) { send_notification(n); } } } } }).start(); return START_NOT_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } public void send_notification(Note note) { Intent intent = new Intent(this, MainActivity.class); intent.putExtra("fromNotification", true); intent.putExtra("note",note); Calendar current = Calendar.getInstance(); Calendar noteCal = Calendar.getInstance(); noteCal.setTime(note.getDate()); int diff = current.get(Calendar.YEAR)-noteCal.get(Calendar.YEAR); Notification.Builder nBuilder = new Notification.Builder(this) .setSmallIcon(R.drawable.sample_icon_1) .setContentTitle(note.getTitle()) .setContentText(note.isSecured()?"You have a Secured Memory From "+diff+ (diff>1?" Years":" Year") :diff+(diff>1?" Years":"Year")+" Memory.") .setStyle(new Notification.BigTextStyle().bigText(note.isSecured()?"You have a Secured Memory From "+diff+ (diff>1?" Years":" Year") :diff+(diff>1?" Years":"Year")+" Memory.")); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); //stackBuilder.AddParentStack(); stackBuilder.addNextIntent(intent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(note.getId(), PendingIntent.FLAG_UPDATE_CURRENT); nBuilder.setContentIntent(resultPendingIntent); NotificationManager notifmanager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); nBuilder.setDefaults(Notification.DEFAULT_SOUND); Uri customSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.twirl); nBuilder.setDefaults(Notification.DEFAULT_VIBRATE); //nBuilder.setSound(customSoundUri); nBuilder.setAutoCancel(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = String.valueOf(note.getId()); NotificationChannel channel = new NotificationChannel(channelId, "Reminder Notification Channel", NotificationManager.IMPORTANCE_HIGH); AudioAttributes audioAttributes = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) .build(); channel.enableLights(true); //channel.setLightColor(Color.RED); //channel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); channel.enableVibration(true); channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),audioAttributes); notifmanager.createNotificationChannel(channel); nBuilder.setChannelId(channelId); } notifmanager.notify(note.getId(), nBuilder.build()); Calendar calendar = Calendar.getInstance(); prefs.edit().putLong(String.valueOf(note.getId()), calendar.getTimeInMillis()).apply(); } @Override public void onDestroy() { super.onDestroy(); } }
true
ef6f3a2b867a509264a4c51a71887df85dbc7f7b
Java
ChAqeelZafar/AgreggateCalculator
/app/src/main/java/com/example/johnwick/agreggatecalculator/MainActivity.java
UTF-8
7,672
1.890625
2
[]
no_license
package com.example.johnwick.agreggatecalculator; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button nust ; Button fast, pieas, giki, ist, uetLahore, uetPeshawar, uetTaxila, qau, muet ; Button custom, comsat ; ActionBar actionBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle(Html.fromHtml("<font color='#000000'>Aggregate Calculator</font>")); assign(); allListeners() ; } void assign(){ nust = findViewById(R.id.main_btn_next); fast = findViewById(R.id.main_btn_fast); pieas = findViewById(R.id.main_btn_pieas); giki = findViewById(R.id.main_btn_giki); ist = findViewById(R.id.main_btn_ist); uetLahore = findViewById(R.id.main_btn_uetLahore); uetPeshawar = findViewById(R.id.main_btn_uetPeshawar); uetTaxila = findViewById(R.id.main_btn_uetTaxila); qau = findViewById(R.id.main_btn_qau); //comsats.findViewById(R.id.main_btn_comsats); comsat = findViewById(R.id.main_btn_comsat); muet = findViewById(R.id.main_btn_muet); custom = findViewById(R.id.main_btn_custom); } void allListeners(){ nust.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", nust.getText().toString()); intent.putExtra("entryTest%", 75); intent.putExtra("fsc%", 15); intent.putExtra("matric%", 10); startActivity(intent); } }); fast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", fast.getText().toString()); intent.putExtra("entryTest%", 50); intent.putExtra("fsc%", 50); startActivity(intent); } }); pieas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", pieas.getText().toString()); intent.putExtra("entryTest%", 60); intent.putExtra("fsc%", 25); intent.putExtra("matric%", 15); startActivity(intent); } }); giki.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", giki.getText().toString()); intent.putExtra("entryTest%", 85); intent.putExtra("fsc%", 10); intent.putExtra("matric%", 5); startActivity(intent); } }); ist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", ist.getText().toString()); intent.putExtra("entryTest%", 40); intent.putExtra("fsc%", 40); intent.putExtra("matric%", 20); startActivity(intent); } }); uetLahore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", uetLahore.getText().toString()); intent.putExtra("entryTest%", 30); intent.putExtra("fsc%", 70); startActivity(intent); } }); uetPeshawar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", uetPeshawar.getText().toString()); intent.putExtra("entryTest%", 50); intent.putExtra("fsc%", 40); intent.putExtra("matric%", 10); startActivity(intent); } }); uetTaxila.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", fast.getText().toString()); intent.putExtra("entryTest%", 30); intent.putExtra("fsc%", 70); startActivity(intent); } }); qau.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", qau.getText().toString()); intent.putExtra("entryTest%", 70); intent.putExtra("matric%", 30); startActivity(intent); } }); comsat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", comsat.getText().toString()); intent.putExtra("entryTest%", 50); intent.putExtra("fsc%", 40); intent.putExtra("matric%", 10); startActivity(intent); } }); muet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", muet.getText().toString()); intent.putExtra("entryTest%", 60); intent.putExtra("fsc%", 30); intent.putExtra("matric%", 10); startActivity(intent); } }); fast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Uni_Info_Activity.class); intent.putExtra("uniName", fast.getText().toString()); intent.putExtra("entryTest%", 50); intent.putExtra("fsc%", 50); startActivity(intent); } }); custom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, custom.class); intent.putExtra("uniName", custom.getText().toString()); startActivity(intent); } }); } }
true
9a6d35d177765089578f8da246f6b67e0575b88b
Java
Stofi09/Painter
/src/com/company/painter/error/Error.java
UTF-8
211
2.390625
2
[]
no_license
package com.company.painter.error; public class Error { private Error(){} public static void error(Exception e){ System.err.println("Exception thrown:\n" + e); System.exit(0); } }
true
784576879e7a3740daec1eebde4f13e6810a56ec
Java
moonjuhyeon/2life10
/src/com/cl/controller/admin/InquiryController.java
UTF-8
398
1.609375
2
[]
no_license
package com.cl.controller.admin; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import com.cl.service.IInquiryService; @Controller public class InquiryController { private Logger log = Logger.getLogger(this.getClass()); @Resource(name="InquiryService") private IInquiryService inquiryService; }
true
28dc9711911ddf2546813159436c5f555cb6b6f8
Java
736229999/im
/im_web/imindex/src/main/java/com/cn/feiniu/imindex/config/DumpConfig.java
UTF-8
655
1.875
2
[]
no_license
package com.cn.feiniu.imindex.config; /** * Author: morningking * Date: 2016/2/5 * Contact: 243717042@qq.com */ public class DumpConfig { private String imServerDumpPath; private String pcMerchantDumpPath; public String getImServerDumpPath() { return imServerDumpPath; } public void setImServerDumpPath(String imServerDumpPath) { this.imServerDumpPath = imServerDumpPath; } public String getPcMerchantDumpPath() { return pcMerchantDumpPath; } public void setPcMerchantDumpPath(String pcMerchantDumpPath) { this.pcMerchantDumpPath = pcMerchantDumpPath; } }
true
1591fda8cab180234ea0afb0ce755ad029827f28
Java
nvn75/FinalZ
/src/game/modules/TestModule.java
UTF-8
522
2.28125
2
[]
no_license
package game.modules; import finalZ.annotation.Execute; import finalZ.annotation.InstantiationPolicy; import finalZ.annotation.Module; import finalZ.annotation.Instantiate; @Module({ TestModule.DONE, TestModule.FAILED }) @Instantiate(InstantiationPolicy.SINGLE) public class TestModule { public static final String DONE = "DONE"; public static final String FAILED = "FAILED"; @Execute public String execute() { System.out.println("Doing task"); return DONE; } }
true
7c4774b43a295a1ba2dc8b48538616ea5374af7e
Java
1YourAss1/RGB
/app/src/main/java/com/example/rgb/ModeFragment.java
UTF-8
4,475
2.265625
2
[]
no_license
package com.example.rgb; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import androidx.viewpager.widget.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.material.tabs.TabLayout; import java.util.Objects; public class ModeFragment extends Fragment { private static final String ARG_MODE = "param_mode", ARG_RGB = "param_rgb", ARG_HSV = "param_hsv", ARG_INTERVAL = "param_interval", ARG_STEP = "param_step"; private int[] RGB, HSV; private int mode, interval, step; ModeFragment(){} static ModeFragment newInstance(int param_mode, int[] param_rgb, int[] param_hsv, int param_interval, int param_step){ ModeFragment modeFragment = new ModeFragment(); Bundle args = new Bundle(); args.putInt(ARG_MODE, param_mode); args.putIntArray(ARG_RGB, param_rgb); args.putIntArray(ARG_HSV, param_hsv); args.putInt(ARG_INTERVAL, param_interval); args.putInt(ARG_STEP, param_step); modeFragment.setArguments(args); return modeFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { Bundle args = getArguments(); mode = args.getInt(ARG_MODE); RGB = args.getIntArray(ARG_RGB); HSV = args.getIntArray(ARG_HSV); interval = args.getInt(ARG_INTERVAL); step = args.getInt(ARG_STEP); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mode, container, false); ViewPager viewPager = view.findViewById(R.id.viewpager); viewPager.setAdapter(new TabsAdapter(getChildFragmentManager())); // Настройка вкладок - режимов TabLayout tabs = view.findViewById(R.id.tab_layout); tabs.setupWithViewPager(viewPager); Objects.requireNonNull(tabs.getTabAt(mode - 1)).select(); // При переключении владок, переключать режим работы - отправлять соотвествующие значения на Arduino tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { SendPackage activity = (SendPackage) getActivity(); assert activity != null; switch (tab.getPosition()){ case 0: activity.sendPackage(1, RGB); break; case 1: activity.sendPackage(2, HSV); break; case 2: activity.sendPackage(3, new int[]{interval, step, 0}); break; default: break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); return view; } public class TabsAdapter extends FragmentPagerAdapter { final int PAGE_COUNT = 4; private String[] tabTitles = new String[] {"RGB", "HSV", "GRADIENT", "FAVORITE"}; TabsAdapter(FragmentManager fm) { super(fm); } @NonNull @Override public Fragment getItem(int position) { switch (position) { case 0: return RGBFragment.newInstance(RGB); case 1: return HSVFragment.newInstance(HSV); case 2: return GradientFragment.newInstance(interval, step); case 3: return new FavoriteFragment(); } return null; } @Override public CharSequence getPageTitle(int position) { return tabTitles[position]; } @Override public int getCount() { return PAGE_COUNT; } } }
true
aaeaeed853d0725d7861fc2e480007ab5d5e27e4
Java
duzenz/pipeline
/src/main/java/com/example/demo/Calculator.java
UTF-8
178
2.265625
2
[]
no_license
package com.example.demo; import org.springframework.stereotype.Service; @Service public class Calculator { public int sum(int x, int y) { return x + y; } }
true