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
630c218cdae69de043b698ea5da6325355332bf2
Java
sudhas2611/seleniumsudha
/src/main/java/script1/Testcase1.java
UTF-8
3,150
2.109375
2
[]
no_license
package script1; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Test; import wrapper.TestngAnnotation; import wrapper.WdMethods; public class Testcase1 extends TestngAnnotation{ @Test public void createLead() { invokeAppBrowser("firefox", "http://leaftaps.com/opentaps"); type(locateElement("id", "username"), "DemoSalesManager"); type(locateElement("id", "password"), "crmsfa"); clickElement(locateElement("className", "decorativeSubmit")); clickElement(locateElement("linkText", "CRM/SFA")); clickElement(locateElement("linkText", "Create Lead")); type(locateElement("id", "createLeadForm_companyName"), "company"); type(locateElement("id", "createLeadForm_firstName"), "fname"); type(locateElement("id", "createLeadForm_lastName"), "lname"); clickElement(locateElement("id", "createLeadForm_dataSourceId")); selectByVisibleText(locateElement("id", "createLeadForm_dataSourceId"),"Cold Call"); clickElement(locateElement("id", "createLeadForm_marketingCampaignId")); selectByVisibleText(locateElement("id", "createLeadForm_marketingCampaignId"),"Automobile"); type(locateElement("id", "createLeadForm_primaryPhoneNumber"), "990080"); type(locateElement("id", "createLeadForm_primaryEmail"), "a@aa.com"); clickElement(locateElement("name", "submitButton")); getText(locateElement("id", "viewLead_companyName_sp"), "12409"); quitAppBrowser(); /*System.setProperty("webdriver.gecko.driver","./drivers/geckodriver.exe"); FirefoxDriver driver = new FirefoxDriver(); //driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get("http://leaftaps.com/opentaps"); driver.findElementById("username").sendKeys("DemoSalesManager"); driver.findElementById("password").sendKeys("crmsfa"); driver.findElementByClassName("decorativeSubmit").click(); driver.findElementByLinkText("CRM/SFA").click(); driver.findElementByLinkText("Create Lead").click(); driver.findElementById("createLeadForm_companyName").sendKeys("company"); driver.findElementById("createLeadForm_firstName").sendKeys("fname"); driver.findElementById("createLeadForm_lastName").sendKeys("lname"); WebElement ddown = driver.findElementById("createLeadForm_dataSourceId"); ddown.click(); Select dropdown = new Select(ddown); dropdown.selectByVisibleText("Cold Call"); WebElement ddown2 = driver.findElementById("createLeadForm_marketingCampaignId"); ddown2.click(); Select dropdown2 = new Select(ddown2); dropdown2.selectByVisibleText("Automobile"); driver.findElementById("createLeadForm_primaryPhoneNumber").sendKeys("990080"); driver.findElementById("createLeadForm_primaryEmail").sendKeys("a@aa.om"); driver.findElementByName("submitButton").click(); System.out.println(driver.findElementById("viewLead_companyName_sp").getText()); driver.close(); */ } }
true
a965bb146ce1950bec9764a75a02855b6de5486c
Java
Polyroot/XO
/src/game/jinterface/printer/ConsolePrinter.java
UTF-8
184
2.578125
3
[]
no_license
package game.jinterface.printer; public class ConsolePrinter implements IPrinter{ @Override public void print(final String text){ System.out.println(text); } }
true
1a5124871651149df128babca87cf28c197f60c2
Java
xka119/SWTEST
/SWExpert/D3/D3_CardCounting.java
UTF-8
2,704
3.515625
4
[]
no_license
package SWExpert.D3; /* 4047. 영준이의 카드 카운팅 */ import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class D3_CardCounting { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int t = Integer.parseInt(br.readLine().trim()); final int SIZE = 14; int[] s; int[] d; int[] h; int[] c; int sa,da,ha,ca; String card; Boolean error; for (int tc = 1; tc <= t; tc++) { //덱 초기화 s = new int[SIZE]; d = new int[SIZE]; h = new int[SIZE]; c = new int[SIZE]; for(int i=1; i<SIZE; i++){ s[i] = 1; d[i] = 1; h[i] = 1; c[i] = 1; } sa=0;da=0;ha=0;ca=0;error=false; //카드 입력 card = br.readLine(); for(int i=0; i<card.length(); i+=3){ int tm = Integer.parseInt(card.substring(i+1,i+3)); if(card.substring(i,i+3).charAt(0)=='S'){ if(s[tm]==0){ error = true; break; } s[tm] = 0; } if(card.substring(i,i+3).charAt(0)=='D'){ if(d[tm]==0){ error = true; break; } d[tm] = 0; } if(card.substring(i,i+3).charAt(0)=='H'){ if(h[tm]==0){ error = true; break; } h[tm] = 0; } if(card.substring(i,i+3).charAt(0)=='C'){ if(c[tm]==0){ error = true; break; } c[tm] = 0; } } for(int i=1; i<SIZE; i++){ if(s[i]==1){ sa++; } if(d[i]==1){ da++; } if(h[i]==1){ ha++; } if(c[i]==1){ ca++; } } if(error){ sb.append("#"+tc+" ERROR\n"); }else{ sb.append("#"+tc+" "+sa+" "+da+" "+ha+" "+ca+"\n"); } } System.out.print(sb.toString()); } }
true
fc3eabf3626624a42e520a92033ea31c669e5be6
Java
bellmit/java-7
/comp-232/BookStore/src/Book.java
UTF-8
1,279
3.21875
3
[]
no_license
public class Book { private String title, author, isbn, urlToImage; private double price; public Book(String title, String author, String isbn, String urlToImage, double price) { this.title = title; this.author = author; this.isbn = isbn; this.urlToImage = urlToImage; this.price = price; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getUrlToImage() { return urlToImage; } public void setUrlToImage(String urlToImage) { this.urlToImage = urlToImage; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Title: " + title + "\nAuthor: " + author + "\nISBN: " + isbn + "\nImage: " + urlToImage + "\nPrice: $" + price; } }
true
825e02949b96db544b1e32b284141109b22db8cd
Java
HuAngchping/project
/otas/nWave-DM-Web/src/com/npower/dm/action/profile/MappingImportAction.java
UTF-8
8,106
1.507813
2
[]
no_license
package com.npower.dm.action.profile; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.hibernate.Criteria; import org.hibernate.criterion.Expression; import com.npower.dm.action.BaseAction; import com.npower.dm.action.ddf.ValidationAction; import com.npower.dm.core.DMException; import com.npower.dm.core.Manufacturer; import com.npower.dm.core.Model; import com.npower.dm.core.ProfileMapping; import com.npower.dm.core.ProfileTemplate; import com.npower.dm.management.ManagementBeanFactory; import com.npower.dm.management.ModelBean; import com.npower.dm.management.ProfileMappingBean; import com.npower.dm.management.ProfileTemplateBean; import com.npower.dm.management.SearchBean; public class MappingImportAction extends BaseAction { private static Log log = LogFactory.getLog(ValidationAction.class); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (isCancelled(request)) { return (mapping.findForward("returnMappingedit")); } String xmlfile = (String) request.getSession().getAttribute("filedir"); String manufacturerExternalID = ""; String modelExternalID = ""; List<String> template2model = new ArrayList<String>(); boolean templateBoo = true; String temlateErrMess = ""; boolean manuerr1 = true; String manExter = ""; boolean modelerr1 = true; String modelname = ""; boolean templerr1 = true; String templatename = ""; ManagementBeanFactory factory = this.getManagementBeanFactory(request); ProfileMappingBean pmBean = factory.createProfileMappingBean(); ModelBean modelbean = factory.createModelBean(); SearchBean searchBean = factory.createSearchBean(); ProfileTemplateBean templateBean = factory.createProfileTemplateBean(); try { InputStream inputparse = null; InputStream inputimport = null; inputparse = new FileInputStream(xmlfile); inputimport = new FileInputStream(xmlfile); List parselist = pmBean.parsingProfileMapping(inputparse); for (Iterator it = parselist.iterator(); it.hasNext();) { ProfileMapping map = (ProfileMapping) it.next(); manExter = map.getManufacturerExternalID(); modelname = map.getModelExternalID(); String templateerrmoname = map.getModelExternalID(); Manufacturer manufacturer = modelbean.getManufacturerByExternalID(manExter); boolean manuerr2 = false; if (manufacturer == null) { manuerr2 = false; manExter = manExter + manufacturer.getName() + "::"; } else { manuerr2 = true; } manuerr1 = (manuerr1 && manuerr2); Criteria criteria = searchBean.newCriteriaInstance(Model.class); criteria.add(Expression.eq("name", modelname)); List result = modelbean.findModel(criteria); boolean modelerr2 = false; if (result == null) { modelerr2 = false; modelname = modelname + modelname + "::"; } else { modelerr2 = true; } modelerr1 = (modelerr1 && modelerr2); if (map.getProfileTemplate() == null) { templateBoo = false; temlateErrMess = temlateErrMess + templateerrmoname + "::"; } else { templateBoo = true; } templatename = map.getProfileTemplate().getName(); ProfileTemplate template = templateBean.getTemplateByName(templatename); boolean templerr2 = false; if (template == null) { templerr2 = false; templatename = templatename + template.getName() + "::"; } else { templerr2 = true; } templerr1 = (templerr1 && templerr2); } inputparse.close(); if (!manuerr1 || !modelerr1 || !templerr1) { ActionMessages errors = new ActionMessages(); if (!manuerr1) { String manumess[] = manExter.split("::"); for (int i = 0; i < manumess.length; i++) { errors.add("noManufacturerErr", new ActionMessage("xml.err.mapping.file.no.manufacturer", manumess[i])); } } if (!modelerr1) { String modelnamemess[] = modelname.split("::"); for (int i = 0; i < modelnamemess.length; i++) { errors.add("noModelErr", new ActionMessage("xml.err.mapping.file.no.model", modelnamemess[i])); } } if (!templerr1) { String messtemp[] = templatename.split("::"); for (int i = 0; i < messtemp.length; i++) { errors.add("noTemplateErr", new ActionMessage("xml.err.mapping.file.no.template", messtemp[i])); } } saveErrors(request, errors); return mapping.findForward("err"); } // import mapping List mappings = pmBean.importProfileMapping(inputimport); ModelBean modelBean = factory.createModelBean(); factory.beginTransaction(); for (int i = 0; i < mappings.size(); i++) { ProfileMapping map = (ProfileMapping) mappings.get(i); modelExternalID = map.getModelExternalID(); manufacturerExternalID = map.getManufacturerExternalID(); Manufacturer manufacturer = modelBean.getManufacturerByExternalID(manufacturerExternalID); Model model = modelBean.getModelByManufacturerModelID(manufacturer, modelExternalID); modelBean.attachProfileMapping(model, map.getID()); String mName = map.getModelExternalID(); String tName = map.getProfileTemplate().getName(); template2model.add(mName + " ---------- mapping ---------- " + tName); } factory.commit(); inputimport.close(); } catch (DMException e) { if (factory != null) { factory.rollback(); } log.error(e.getMessage(), e); ActionMessages errors = new ActionMessages(); String othererr = e.getMessage(); if (!templateBoo) { String messtemp[] = temlateErrMess.split("::"); for (int i = 0; i < messtemp.length; i++) { String errmessage = messtemp[i] + " do not have the match template"; errors.add("otherErr", new ActionMessage("xml.err.mapping.file.no.other", errmessage)); } } else { errors.add("otherErr", new ActionMessage("xml.err.mapping.file.no.other", othererr)); } saveErrors(request, errors); return mapping.findForward("err"); } catch (Exception e) { if (factory != null) { factory.rollback(); } log.error(e.getMessage(), e); ActionMessages errors = new ActionMessages(); String othererr = e.getMessage(); if (!templateBoo) { String messtemp[] = temlateErrMess.split("::"); for (int i = 0; i < messtemp.length; i++) { String errmessage = messtemp[i] + " do not have the match template"; errors.add("otherErr", new ActionMessage("xml.err.mapping.file.no.other", errmessage)); } } else { errors.add("otherErr", new ActionMessage("xml.err.mapping.file.no.other", othererr)); } saveErrors(request, errors); return mapping.findForward("err"); } finally { } request.setAttribute("template2model", template2model); return mapping.findForward("display"); } }
true
2055ff04c590ebbe28938ba8622f67328bed964f
Java
vaibhavsh82/FileScanner
/app/src/main/java/android/macys/com/filescanner/FileStats.java
UTF-8
476
1.945313
2
[]
no_license
package android.macys.com.filescanner; import android.util.Pair; import java.util.ArrayList; import java.util.List; public class FileStats { public FileStats() { fileInfoList = new ArrayList<>(); } /** * List of top 10 bug files */ public List<FileInfo> fileInfoList; /** * Frequency of extensions */ public List<Pair<String, Integer>> extFrequencies; public long averageFileSize; public long medianFileSize; }
true
162ca15e1636fdbc968d7896344750b48aa825cb
Java
AysenAkbal/JavaProjects
/src/project1/StarbucksCustomer.java
ISO-8859-9
371
2.484375
2
[]
no_license
package project1; public class StarbucksCustomer extends BaseCustomer{ @Override public void verifyCustomer(Customer customer) { System.out.println("Starbucks mterisi e-devlet sistemi zerinden doruland."); } @Override public void takeCoffee(Customer customer) { System.out.println("Starbucks mterisi kahve ald."); } }
true
85fbc12ec8be9fb5695f479872f7dc4b974d5f27
Java
melroy999/2IMP00-SLCO
/SLCO1.0-files/SLCO1.0/metamodels-and-grammars/slco.emf/src/slco/BinaryOperatorExpression.java
UTF-8
3,446
2.5
2
[]
no_license
/** */ package slco; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Binary Operator Expression</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link slco.BinaryOperatorExpression#getOperator <em>Operator</em>}</li> * <li>{@link slco.BinaryOperatorExpression#getOperand1 <em>Operand1</em>}</li> * <li>{@link slco.BinaryOperatorExpression#getOperand2 <em>Operand2</em>}</li> * </ul> * </p> * * @see slco.SlcoPackage#getBinaryOperatorExpression() * @model * @generated */ public interface BinaryOperatorExpression extends Expression { /** * Returns the value of the '<em><b>Operator</b></em>' attribute. * The literals are from the enumeration {@link slco.OperatorEnum}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Operator</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Operator</em>' attribute. * @see slco.OperatorEnum * @see #setOperator(OperatorEnum) * @see slco.SlcoPackage#getBinaryOperatorExpression_Operator() * @model required="true" * @generated */ OperatorEnum getOperator(); /** * Sets the value of the '{@link slco.BinaryOperatorExpression#getOperator <em>Operator</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Operator</em>' attribute. * @see slco.OperatorEnum * @see #getOperator() * @generated */ void setOperator(OperatorEnum value); /** * Returns the value of the '<em><b>Operand1</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Operand1</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Operand1</em>' containment reference. * @see #setOperand1(Expression) * @see slco.SlcoPackage#getBinaryOperatorExpression_Operand1() * @model containment="true" required="true" ordered="false" * @generated */ Expression getOperand1(); /** * Sets the value of the '{@link slco.BinaryOperatorExpression#getOperand1 <em>Operand1</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Operand1</em>' containment reference. * @see #getOperand1() * @generated */ void setOperand1(Expression value); /** * Returns the value of the '<em><b>Operand2</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Operand2</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Operand2</em>' containment reference. * @see #setOperand2(Expression) * @see slco.SlcoPackage#getBinaryOperatorExpression_Operand2() * @model containment="true" required="true" ordered="false" * @generated */ Expression getOperand2(); /** * Sets the value of the '{@link slco.BinaryOperatorExpression#getOperand2 <em>Operand2</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Operand2</em>' containment reference. * @see #getOperand2() * @generated */ void setOperand2(Expression value); } // BinaryOperatorExpression
true
decf7712e47cdfd85b75335eb9d7d2106fcceaf5
Java
burningcl/LeetcodeSolutions
/src/com/skyline/leetcode/solution/Q26.java
UTF-8
690
3.359375
3
[]
no_license
package com.skyline.leetcode.solution; /** * Remove Duplicates from Sorted Array * * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ * * @author jairus * */ public class Q26 { public int removeDuplicates(int[] nums) { if (nums == null || nums.length <= 1) { return nums.length; } int val = nums[0]; int cnt = 1; int pos = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] != val) { val = nums[i]; cnt++; nums[pos] = nums[i]; pos++; } } return cnt; } public static void main(String... strings) { Q26 q = new Q26(); int[] nums = { 1, 1, 2, 2, 3, 3, 4 }; System.out.println(q.removeDuplicates(nums)); } }
true
82a0dd142bbbc0f1873aa7ee6ea6ba6e81a5ce26
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/koelleChristian_trickytripper/app/src/main/java/de/koelle/christian/common/ui/filter/DecimalNumberInputPatternMatcher.java
UTF-8
1,183
1.835938
2
[]
no_license
// isComment package de.koelle.christian.common.ui.filter; import java.util.regex.Pattern; import de.koelle.christian.common.constants.Rglob; /** * isComment */ public class isClassOrIsInterface { private final Pattern isVariable; private final int isVariable; public isConstructor(int isParameter, int isParameter) { this(isNameExpr, isNameExpr, -isIntegerConstant); } public isConstructor(int isParameter, int isParameter, int isParameter) { String isVariable = "isStringConstant" + isNameExpr + "isStringConstant" + isNameExpr.isFieldAccessExpr + isNameExpr.isFieldAccessExpr + "isStringConstant" + isNameExpr + "isStringConstant"; isNameExpr = isNameExpr.isMethod(isNameExpr); this.isFieldAccessExpr = isNameExpr; } public isConstructor() { this(isIntegerConstant, isIntegerConstant); } public boolean isMethod(String isParameter) { return (isNameExpr <= isIntegerConstant) ? isMethod(isNameExpr) : isMethod(isNameExpr) && isNameExpr.isMethod() <= isNameExpr; } private boolean isMethod(String isParameter) { return isNameExpr.isMethod(isNameExpr).isMethod(); } }
true
d705e9ee94c0ff648d1185bbffdde6d15026cf05
Java
serk123/L2jOpenSource
/Interlude/L2J_aCis/aCis_389_LATEST_EXPERIMENTAL/aCis_gameserver/java/net/sf/l2j/gameserver/handler/targethandlers/TargetOwnerPet.java
UTF-8
888
2.359375
2
[]
no_license
package net.sf.l2j.gameserver.handler.targethandlers; import net.sf.l2j.gameserver.enums.skills.SkillTargetType; import net.sf.l2j.gameserver.handler.ITargetHandler; import net.sf.l2j.gameserver.model.WorldObject; import net.sf.l2j.gameserver.model.actor.Creature; import net.sf.l2j.gameserver.model.actor.Summon; import net.sf.l2j.gameserver.skills.L2Skill; public class TargetOwnerPet implements ITargetHandler { @Override public WorldObject[] getTargetList(L2Skill skill, Creature caster, Creature target, boolean onlyFirst) { if (!(caster instanceof Summon)) return EMPTY_TARGET_ARRAY; target = caster.getActingPlayer(); if (target == null || target.isDead()) return EMPTY_TARGET_ARRAY; return new Creature[] { target }; } @Override public SkillTargetType getTargetType() { return SkillTargetType.OWNER_PET; } }
true
486bc05985716973e1944a91402edb5d6be44696
Java
EterJen/shop-parent
/shop-www/shop-web/src/main/java/pers/eter/controller/IndexController.java
UTF-8
489
1.765625
2
[]
no_license
package pers.eter.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import pers.eter.core.base.BaseController; /** * Created by Eter on 17-6-6. */ @Controller public class IndexController extends BaseController{ @RequestMapping("index") public String index(Model model) { return "index"; } }
true
d6decea670c9294acd9c3813f7ca49f63a8225e3
Java
inpachi18/ZUCC_CC_Car_Renting
/src/ui/FrmCouponManager_AddCoupon.java
UTF-8
3,349
2.578125
3
[]
no_license
package ui; import control.CouponManager; import control.StfManager; import model.BeanCoupon; import util.BaseException; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.text.SimpleDateFormat; public class FrmCouponManager_AddCoupon extends JDialog implements ActionListener{ private BeanCoupon coupon=null; private JPanel toolBar = new JPanel(); private JPanel workPane = new JPanel(); private JPanel workPane2 = new JPanel(); private Button btnOk = new Button("确定"); private Button btnCancel = new Button("取消"); private JLabel labelContent = new JLabel("内容:"); private JLabel labelDiscount = new JLabel("减免金额:"); private JLabel labelStart_date = new JLabel("起始日期:"); private JLabel labelEnd_date = new JLabel("结束日期:"); private JTextField edtContent = new JTextField(20); private JTextField edtDiscount = new JTextField(20); private JTextField edtStart_date = new JTextField(20); private JTextField edtEnd_date = new JTextField(20); public FrmCouponManager_AddCoupon(JDialog f, String s, boolean b) { super(f, s, b); toolBar.setLayout(new FlowLayout(FlowLayout.RIGHT)); toolBar.add(btnOk); toolBar.add(btnCancel); this.getContentPane().add(toolBar, BorderLayout.SOUTH); workPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); workPane.add(labelContent); workPane.add(edtContent); workPane.add(labelDiscount); workPane.add(edtDiscount); edtDiscount.setText("0.0"); workPane.add(labelStart_date); workPane.add(edtStart_date); workPane.add(labelEnd_date); workPane.add(edtEnd_date); this.getContentPane().add(workPane, BorderLayout.CENTER); this.setSize(300, 240); // 屏幕居中显示 double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth(); double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight(); this.setLocation((int) (width - this.getWidth()) / 2, (int) (height - this.getHeight()) / 2); this.validate(); this.btnOk.addActionListener(this); this.btnCancel.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==this.btnCancel) { this.setVisible(false); return; } else if(e.getSource()==this.btnOk){ String content=this.edtContent.getText(); String location_id = StfManager.currentStf.getBranch()+""; String discount=this.edtDiscount.getText(); String start_date=this.edtStart_date.getText(); String end_date=this.edtEnd_date.getText(); BeanCoupon coupon=new BeanCoupon(); coupon.setContent(content); coupon.setLocation_id(Integer.valueOf(location_id)); coupon.setDiscount_amount(Float.parseFloat(discount)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { coupon.setStart_date(simpleDateFormat.parse(start_date)); coupon.setEnd_date(simpleDateFormat.parse(end_date)); } catch (ParseException e2) { e2.printStackTrace(); } try { (new CouponManager()).createCoupon(coupon); this.coupon=coupon; this.setVisible(false); } catch (BaseException e1) { JOptionPane.showMessageDialog(null, e1.getMessage(),"错误",JOptionPane.ERROR_MESSAGE); } } } public BeanCoupon getCoupon() { return coupon; } }
true
52f54eca951a8585fffd94cb3df67e9065953500
Java
YadneshKhode/Inventory-Management-System
/MaterialServices/MaterialServices/src/main/java/com/accenture/lkm/entity/MaterialTypeEntity.java
UTF-8
1,722
2.34375
2
[]
no_license
package com.accenture.lkm.entity; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="material_type") public class MaterialTypeEntity { @Id @Column(name="type_id") private String typeId; @Column(name="type_name") private String typeName; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="category_id") private MaterialCategoryEntity materialCategoryEntity ; public MaterialTypeEntity() { super(); } public MaterialTypeEntity(String typeId, String typeName, MaterialCategoryEntity materialCategoryEntity) { this.typeId = typeId; this.typeName = typeName; this.materialCategoryEntity = materialCategoryEntity; } public String getTypeId() { return typeId; } public void setTypeId(String typeId) { this.typeId = typeId; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } /*public String getCategoryId() { return materialCategoryEntity.getCategoryId(); }*/ /*public void setCategoryId(String categoryId) { this.categoryId = categoryId; }*/ public MaterialCategoryEntity getMaterialCategoryEntity() { return materialCategoryEntity; } public void setMaterialCategoryEntity(MaterialCategoryEntity materialCategoryEntity) { this.materialCategoryEntity = materialCategoryEntity; } @Override public String toString() { return "MaterialTypeEntity [typeId=" + typeId + ", typeName=" + typeName + "materialCategoryEntity" + materialCategoryEntity + "]"; } }
true
63d92dfbf37f81db6d9b00ab9c3fd0ca7c74ca94
Java
MrManiacc/FNData
/src/main/java/me/jraynor/data/fortnite/Category.java
UTF-8
766
3.21875
3
[]
no_license
package me.jraynor.data.fortnite; public enum Category { GENERAL("general"), TOPS("tops"), LIFE_TIME("lifeTime"), UNKNOWN("unknown"); String value; Category(String value) { this.value = value; } @Override public String toString() { return value; } /** * Converts a string category into the enum version of the category * * @param category * @return */ public static Category getCategory(String category) { switch (category) { case "General": return Category.GENERAL; case "Tops": return Category.TOPS; case "life": return Category.LIFE_TIME; } return Category.UNKNOWN; } }
true
b0918dc82cc36d96d737de21c27b531dc1d577ea
Java
janforp/iam-repo
/src/main/java/com/zbmatsu/iam/annotations/parser/JsonObjectValidator.java
UTF-8
1,137
2.46875
2
[]
no_license
package com.zbmatsu.iam.annotations.parser; import com.alibaba.fastjson.JSON; import com.zbmatsu.iam.annotations.JsonObject; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * Created by Administrator on 2017/3/4. */ public class JsonObjectValidator implements ConstraintValidator<JsonObject, Object> { @Override public void initialize(JsonObject constraintAnnotation) { } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { String messageTemplate = context.getDefaultConstraintMessageTemplate(); context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(messageTemplate) .addConstraintViolation(); if(value == null){ return true; } String str = value.toString(); //如果能转换成JsonObject对象 则校验通过, 否则 return false 校验不通过 try { JSON.parseObject(str); } catch (Exception e) { return false; } return true; } }
true
e45729f86e51ac79477ad6216995d4e62902a947
Java
rchwlsk2/DataCollectionFramework-Android
/app/src/main/java/paulrachwalski/uiuc/datacollectionframework/Activities/NewProjectActivity.java
UTF-8
2,319
2.359375
2
[]
no_license
package paulrachwalski.uiuc.datacollectionframework.Activities; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import paulrachwalski.uiuc.datacollectionframework.Managers.ProjectManager; import paulrachwalski.uiuc.datacollectionframework.R; public class NewProjectActivity extends Activity { private EditText projectNameEditText; private EditText userIdEditText; private Button createProjectButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_project); projectNameEditText = (EditText) findViewById(R.id.project_name_editText); userIdEditText = (EditText) findViewById(R.id.user_id_editText); createProjectButton = (Button) findViewById(R.id.create_project_button); createProjectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean goodFields = true; // Check and set project name String projectName = projectNameEditText.getText().toString(); if (projectName != null && !projectName.equals("")) { ProjectManager.getInstance().setName(projectName); goodFields = true; } else { projectNameEditText.setError("Invalid Project Name"); goodFields = false; } // Check and set user id String userId = userIdEditText.getText().toString(); if (userId != null && !userId.equals("")) { ProjectManager.getInstance().setUserId(userId); goodFields = true; } else { userIdEditText.setError("Invalid User ID"); goodFields = false; } // If checks pass, continue if (goodFields) { Intent i = new Intent(NewProjectActivity.this, ChooseDataActivity.class); startActivity(i); } } }); } }
true
e3f962c16d4633e00e163175044cd211810fe78d
Java
wjj2329/Settlers-of-Catan
/src/testpckg/TestCanBankGiveDevelopmentCard.java
UTF-8
3,622
2.484375
2
[]
no_license
package testpckg; import static org.junit.Assert.*; import client.model.ModelFacade; import org.junit.*; import org.junit.rules.ExpectedException; import server.ourserver.commands.MaritimeTradeCommand; import shared.definitions.DevCardType; import shared.definitions.ResourceType; import shared.game.Bank; import shared.game.DevCardList; import shared.game.ResourceList; public class TestCanBankGiveDevelopmentCard { /** This tests if the bank can give and devleopment cards and throws exceptions if the bank contains negative amounts. Tests a variety of situations. */ @Rule public final ExpectedException exception = ExpectedException.none(); @Before public void setUp()throws Exception { ModelFacade.facadeCurrentGame.currentgame.mybank.clear(); ResourceList mylist=new ResourceList(); mylist.setBrick(4); mylist.setOre(3); mylist.setSheep(2); mylist.setWheat(10); mylist.setWood(0); ModelFacade.facadeCurrentGame.currentgame.mybank.setResourceCardslist(mylist); } @After public void tearDown() throws Exception { ModelFacade.facadeCurrentGame.currentgame.mybank.clear(); } @Test public void testBank4()throws Exception { ModelFacade.facadeCurrentGame.currentgame.mybank.clear(); ModelFacade.facadeCurrentGame.currentgame.mybank.setDevCardList(-10, -10, -3, -4, -5); //exception.expect(Exception.class); // ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.MONOPOLY); } @Test public void testBank5() throws Exception { ModelFacade.facadeCurrentGame.currentgame.mybank.clear(); ModelFacade.facadeCurrentGame.currentgame.mybank.setDevCardList(10, 15, 0, 0, 2); assertTrue(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.MONOPOLY)); assertTrue(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.MONUMENT)); assertFalse(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.ROAD_BUILD)); assertFalse(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.SOLDIER)); assertTrue(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.YEAR_OF_PLENTY)); } @Test public void testBank6() throws Exception { ModelFacade.facadeCurrentGame.currentgame.mybank.clear(); DevCardList mylist=new DevCardList(); mylist.setYearOfPlenty(1); mylist.setMonopoly(0); mylist.setSoldier(1); mylist.setMonument(5); mylist.setRoadBuilding(0); ModelFacade.facadeCurrentGame.currentgame.mybank.setDevCardList(mylist); assertTrue( ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.YEAR_OF_PLENTY)); assertFalse(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.MONOPOLY)); assertTrue(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.SOLDIER)); assertTrue(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.MONUMENT)); assertFalse(ModelFacade.facadeCurrentGame.currentgame.mybank.CanBankGiveDevelopmentCard(DevCardType.ROAD_BUILD)); } @Test public void testBank7() throws Exception { MaritimeTradeCommand maritimeTradeCommand=new MaritimeTradeCommand("BRICK", "WHEAT",1,3,1); } }
true
4ebe946dcdc73bb05eaca494d5871e0a52ca368e
Java
ggiorkhelidze/xs2a
/consent-management/consent-management-lib/src/main/java/de/adorsys/psd2/consent/service/CorePaymentsConvertService.java
UTF-8
3,207
1.742188
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018-2019 adorsys GmbH & Co KG * * 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 de.adorsys.psd2.consent.service; import com.fasterxml.jackson.core.JsonProcessingException; import de.adorsys.psd2.consent.api.pis.CmsBasePaymentResponse; import de.adorsys.psd2.consent.api.pis.CmsCommonPayment; import de.adorsys.psd2.consent.api.pis.CmsCommonPaymentMapper; import de.adorsys.psd2.consent.api.pis.PisPayment; import de.adorsys.psd2.consent.service.mapper.CmsCorePaymentMapper; import de.adorsys.psd2.mapper.Xs2aObjectMapper; import de.adorsys.psd2.xs2a.core.profile.PaymentType; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.List; @Slf4j @Service @RequiredArgsConstructor public class CorePaymentsConvertService { private final CmsCorePaymentMapper cmsCorePaymentMapper; private final Xs2aObjectMapper xs2aObjectMapper; private final PaymentMapperResolver paymentMapperResolver; public byte[] buildPaymentData(List<PisPayment> pisPayments, PaymentType paymentType) { switch (paymentType) { case SINGLE: return writeValueAsBytes(cmsCorePaymentMapper.mapToPaymentInitiationJson(pisPayments)); case BULK: return writeValueAsBytes(cmsCorePaymentMapper.mapToBulkPaymentInitiationJson(pisPayments)); case PERIODIC: return writeValueAsBytes(cmsCorePaymentMapper.mapToPeriodicPaymentInitiationJson(pisPayments)); default: return new byte[0]; } } public CmsBasePaymentResponse expandCommonPaymentWithCorePayment(CmsCommonPayment cmsCommonPayment) { CmsCommonPaymentMapper cmsCommonPaymentMapper = paymentMapperResolver.getCmsCommonPaymentMapper(cmsCommonPayment.getPaymentProduct()); switch (cmsCommonPayment.getPaymentType()) { case SINGLE: return cmsCommonPaymentMapper.mapToCmsSinglePayment(cmsCommonPayment); case BULK: return cmsCommonPaymentMapper.mapToCmsBulkPayment(cmsCommonPayment); case PERIODIC: return cmsCommonPaymentMapper.mapToCmsPeriodicPayment(cmsCommonPayment); default: return cmsCommonPayment; } } private byte[] writeValueAsBytes(Object object) { if (object == null) { return new byte[0]; } try { return xs2aObjectMapper.writeValueAsBytes(object); } catch (JsonProcessingException e) { log.warn("Can't convert object to byte[] : {}", e.getMessage()); return new byte[0]; } } }
true
5751b50dbf92c159ffa5fcfb06bf3fe24d5df12b
Java
tom-graugnard/PLA
/game.shellda/src/interpreter/ITransition.java
UTF-8
489
2.484375
2
[]
no_license
package interpreter; import game.shellda.Element; /* Michael PÉRIN, Verimag / Univ. Grenoble Alpes, may 2019 */ public class ITransition { ICondition m_condition ; IAction m_action ; IState m_target ; public ITransition(ICondition condition, IAction action, IState target){ m_condition = condition ; m_action = action ; m_target = target ; } boolean feasible(Element e) { return m_condition.eval(e); } IState exec(Element e) { m_action.exec(e); return m_target; } }
true
8d9e8029628149e26b46c021a9f339df25eee19e
Java
Mukesh72ojha/DynamicProgramming
/src/TargetSumSubset.java
UTF-8
1,727
3.296875
3
[]
no_license
import java.util.Scanner; public class TargetSumSubset { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0;i < arr.length;i++){ arr[i] = sc.nextInt(); } int tar = sc.nextInt(); boolean[][] arr1 = new boolean[n+1][tar+1]; for (int i = 0;i < arr1.length;i++){ for (int j = 0;j < arr1[0].length;j++){ // for arr1[0][0]; if (i == 0 && j == 0){ arr1[i][j] = true; } // for first row. else if (i == 0){ arr1[i][j] = false; } // for first column else if (j == 0){ arr1[i][j] = true; } // for rest solutions else { // just look up from your positions if (arr1[i - 1][j]){ arr1[i][j] = true; } // then look left side and up also else { // because actual index is i -1 in arr int val = arr[i-1]; // value of j should greater or equal then val for YES otherwise NO if (j >= val){ if (arr1[i - 1][j - val]){ arr1[i][j] = true; } } } } } } // print last block of arr1 System.out.println(arr1[arr.length][tar]); } }
true
def9fbebb414adafe72233960e48eb5241cc07d1
Java
apache/geode
/geode-core/src/main/java/org/apache/geode/management/internal/JmxManagerAdvisor.java
UTF-8
11,516
1.53125
2
[ "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Predicate; import org.apache.logging.log4j.Logger; import org.apache.geode.CancelException; import org.apache.geode.DataSerializer; import org.apache.geode.SystemFailure; import org.apache.geode.distributed.internal.ClusterDistributionManager; import org.apache.geode.distributed.internal.DistributionAdvisee; import org.apache.geode.distributed.internal.DistributionAdvisor; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.HighPriorityDistributionMessage; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.serialization.DeserializationContext; import org.apache.geode.internal.serialization.SerializationContext; import org.apache.geode.logging.internal.log4j.api.LogService; /** * @since GemFire 7.0 */ public class JmxManagerAdvisor extends DistributionAdvisor { private static final Logger logger = LogService.getLogger(); private JmxManagerAdvisor(DistributionAdvisee advisee) { super(advisee); JmxManagerProfile p = new JmxManagerProfile(getDistributionManager().getId(), incrementAndGetVersion()); advisee.fillInProfile(p); ((JmxManagerAdvisee) advisee).initProfile(p); } public static JmxManagerAdvisor createJmxManagerAdvisor(DistributionAdvisee advisee) { JmxManagerAdvisor advisor = new JmxManagerAdvisor(advisee); advisor.initialize(); return advisor; } @Override public String toString() { return "JmxManagerAdvisor for " + getAdvisee(); } public void broadcastChange() { try { Set<InternalDistributedMember> recips = adviseGeneric(); // for now just tell everyone JmxManagerProfile p = new JmxManagerProfile(getDistributionManager().getId(), incrementAndGetVersion()); getAdvisee().fillInProfile(p); JmxManagerProfileMessage.send(getAdvisee().getSystem().getDistributionManager(), recips, p); } catch (CancelException ignore) { } } @SuppressWarnings("unchecked") public List<JmxManagerProfile> adviseAlreadyManaging() { return fetchProfiles(profile -> { assert profile instanceof JmxManagerProfile; JmxManagerProfile jmxProfile = (JmxManagerProfile) profile; return jmxProfile.isJmxManagerRunning(); }); } @SuppressWarnings("unchecked") public List<JmxManagerProfile> adviseWillingToManage() { return fetchProfiles(profile -> { assert profile instanceof JmxManagerProfile; JmxManagerProfile jmxProfile = (JmxManagerProfile) profile; return jmxProfile.isJmxManager(); }); } @Override protected Profile instantiateProfile(InternalDistributedMember memberId, int version) { return new JmxManagerProfile(memberId, version); } /** * Overridden to also include our profile. If our profile is included it will always be first. */ @Override protected List/* <Profile> */ fetchProfiles(Predicate<Profile> f) { initializationGate(); List result = null; { JmxManagerAdvisee advisee = (JmxManagerAdvisee) getAdvisee(); Profile myp = advisee.getMyMostRecentProfile(); if (f == null || f.test(myp)) { if (result == null) { result = new ArrayList(); } result.add(myp); } } Profile[] locProfiles = profiles; // grab current profiles for (Profile profile : locProfiles) { if (f == null || f.test(profile)) { if (result == null) { result = new ArrayList(locProfiles.length); } result.add(profile); } } if (result == null) { result = Collections.EMPTY_LIST; } else { result = Collections.unmodifiableList(result); } return result; } /** * Message used to push event updates to remote VMs */ public static class JmxManagerProfileMessage extends HighPriorityDistributionMessage { private volatile JmxManagerProfile profile; private volatile int processorId; /** * Default constructor used for de-serialization (used during receipt) */ public JmxManagerProfileMessage() {} @Override public boolean sendViaUDP() { return true; } /** * Constructor used to send * */ private JmxManagerProfileMessage(final Set<InternalDistributedMember> recips, final JmxManagerProfile p) { setRecipients(recips); processorId = 0; profile = p; } @Override protected void process(ClusterDistributionManager dm) { Throwable thr = null; JmxManagerProfile p = null; try { final InternalCache cache = dm.getCache(); if (cache != null && !cache.isClosed()) { final JmxManagerAdvisor adv = cache.getJmxManagerAdvisor(); p = profile; if (p != null) { adv.putProfile(p); } } else { if (logger.isDebugEnabled()) { logger.debug("No cache {}", this); } } } catch (CancelException e) { if (logger.isDebugEnabled()) { logger.debug("Cache closed, {}", this); } } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable t) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); thr = t; } finally { if (thr != null) { dm.getCancelCriterion().checkCancelInProgress(null); logger.info(String.format("This member caught exception processing profile %s %s", p, this), thr); } } } @Override public int getDSFID() { return JMX_MANAGER_PROFILE_MESSAGE; } @Override public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { super.fromData(in, context); processorId = in.readInt(); profile = DataSerializer.readObject(in); } @Override public void toData(DataOutput out, SerializationContext context) throws IOException { super.toData(out, context); out.writeInt(processorId); DataSerializer.writeObject(profile, out); } /** * Send profile to the provided members * * @param recips The recipients of the message */ public static void send(final DistributionManager dm, Set<InternalDistributedMember> recips, JmxManagerProfile profile) { JmxManagerProfileMessage r = new JmxManagerProfileMessage(recips, profile); dm.putOutgoing(r); } @Override public String getShortClassName() { return "JmxManagerProfileMessage"; } @Override public String toString() { return getShortClassName() + " (processorId=" + processorId + "; profile=" + profile + ")"; } } public static class JmxManagerProfile extends Profile { private boolean jmxManager; private String host; private int port; private boolean ssl; private boolean started; // Constructor for de-serialization public JmxManagerProfile() {} public boolean isJmxManager() { return jmxManager; } public boolean isJmxManagerRunning() { return started; } public void setInfo(boolean jmxManager2, String host2, int port2, boolean ssl2, boolean started2) { jmxManager = jmxManager2; host = host2; port = port2; ssl = ssl2; started = started2; } public String getHost() { return host; } public int getPort() { return port; } public boolean getSsl() { return ssl; } // Constructor for sending purposes public JmxManagerProfile(InternalDistributedMember memberId, int version) { super(memberId, version); } @Override public StringBuilder getToStringHeader() { return new StringBuilder("JmxManagerAdvisor.JmxManagerProfile"); } @Override public void fillInToString(StringBuilder sb) { super.fillInToString(sb); synchronized (this) { if (jmxManager) { sb.append("; jmxManager"); } sb.append("; host=").append(host).append("; port=").append(port); if (ssl) { sb.append("; ssl"); } if (started) { sb.append("; started"); } } } @Override public void processIncoming(ClusterDistributionManager dm, String adviseePath, boolean removeProfile, boolean exchangeProfiles, final List<Profile> replyProfiles) { final InternalCache cache = dm.getCache(); if (cache != null && !cache.isClosed()) { handleDistributionAdvisee(cache.getJmxManagerAdvisor().getAdvisee(), removeProfile, exchangeProfiles, replyProfiles); } } @Override public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { super.fromData(in, context); jmxManager = DataSerializer.readPrimitiveBoolean(in); host = DataSerializer.readString(in); port = DataSerializer.readPrimitiveInt(in); ssl = DataSerializer.readPrimitiveBoolean(in); started = DataSerializer.readPrimitiveBoolean(in); } @Override public void toData(DataOutput out, SerializationContext context) throws IOException { boolean tmpJmxManager; String tmpHost; int tmpPort; boolean tmpSsl; boolean tmpStarted; synchronized (this) { tmpJmxManager = jmxManager; tmpHost = host; tmpPort = port; tmpSsl = ssl; tmpStarted = started; } super.toData(out, context); DataSerializer.writePrimitiveBoolean(tmpJmxManager, out); DataSerializer.writeString(tmpHost, out); DataSerializer.writePrimitiveInt(tmpPort, out); DataSerializer.writePrimitiveBoolean(tmpSsl, out); DataSerializer.writePrimitiveBoolean(tmpStarted, out); } @Override public int getDSFID() { return JMX_MANAGER_PROFILE; } } }
true
84216cdfc75f0bfd56ec162685ea8f0a71b7fe77
Java
wuttke/tinyscrum
/TinyScrum/src/main/java/eu/wuttke/tinyscrum/ui/admin/AdminBeanDetails.java
UTF-8
4,046
2.203125
2
[]
no_license
package eu.wuttke.tinyscrum.ui.admin; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.data.util.BeanItem; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Component; import com.vaadin.ui.Field; import com.vaadin.ui.Form; import com.vaadin.ui.FormFieldFactory; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.VerticalLayout; import eu.wuttke.tinyscrum.ui.misc.BeanUtil; import eu.wuttke.tinyscrum.ui.misc.RefreshableComponent; public class AdminBeanDetails extends VerticalLayout implements RefreshableComponent, FormFieldFactory { interface DetailsListener { public void doCommitObject(Item item, Object bean); public void doCancelForm(Object bean); public void doDeleteObject(Object bean); } protected Object bean; protected BeanItem<Object> item; protected AdminBeanField[] fields; protected String title; protected Form form; protected Button btnDelete; protected DetailsListener listener; public AdminBeanDetails(String title, DetailsListener listener, AdminBeanField[] fields) { this.title = title; this.fields = fields; this.listener = listener; initializeLayout(); } protected void initializeLayout() { setSizeFull(); setWidth("100%"); setMargin(true); setSpacing(true); Button btnOk = new Button("OK", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { handleCommit(); } }); Button btnCancel = new Button("Cancel", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { handleCancel(); } }); btnDelete = new Button("Delete", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { handleDelete(); } }); HorizontalLayout footerLayout = new HorizontalLayout(); footerLayout.setWidth("100%"); footerLayout.setSpacing(true); footerLayout.addComponent(btnDelete); footerLayout.addComponent(btnOk); footerLayout.addComponent(btnCancel); footerLayout.setExpandRatio(btnDelete, 1f); footerLayout.setComponentAlignment(btnDelete, Alignment.MIDDLE_LEFT); footerLayout.setComponentAlignment(btnOk, Alignment.MIDDLE_RIGHT); footerLayout.setComponentAlignment(btnCancel, Alignment.MIDDLE_RIGHT); form = new Form(); form.setSizeFull(); form.setWidth("100%"); form.setCaption(title); form.setFormFieldFactory(this); form.setFooter(footerLayout); addComponent(form); } protected void handleCancel() { listener.doCancelForm(item.getBean()); } protected void handleDelete() { form.commit(); listener.doDeleteObject(item.getBean()); } protected void handleCommit() { form.commit(); listener.doCommitObject(item, item.getBean()); } public void setBean(Object bean, Class<?> clazz) { String[] propertyIds = new String[fields.length]; for (int i = 0; i < propertyIds.length; i++) propertyIds[i] = fields[i].getPropertyId(); this.bean = bean; this.item = new BeanItem<Object>(bean, propertyIds); refreshContent(); } @Override public Field createField(Item item, Object propertyId, Component uiContext) { Property property = item.getItemProperty(propertyId); AdminBeanField field = findField((String)propertyId); return field != null ? field.createField((BeanItem<?>)item, property) : null; } private AdminBeanField findField(String propertyId) { for (int i = 0; i < fields.length; i++) if (fields[i].getPropertyId().equals(propertyId)) return fields[i]; return null; } @Override public void refreshContent() { form.setItemDataSource(item); btnDelete.setEnabled(BeanUtil.getPropertyValue(bean, "id") != null); form.focus(); } private static final long serialVersionUID = 1L; }
true
d2eee02862d818e2599440bb75582c18a671dbe1
Java
moutainhigh/goddess-java
/modules/bonusmoneyperparepay/bonusmoneyperparepay-api/src/main/java/com/bjike/goddess/bonusmoneyperparepay/dto/WaitingPayDTO.java
UTF-8
1,132
1.960938
2
[]
no_license
package com.bjike.goddess.bonusmoneyperparepay.dto; import com.bjike.goddess.common.api.dto.BaseDTO; /** * 等待付款数据传输对象 * * @Author: [ lijuntao ] * @Date: [ 2017-06-30 05:32 ] * @Description: [ 等待付款数据传输对象 ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ public class WaitingPayDTO extends BaseDTO { /** * 付款开始时间 */ private String startDifference; /** * 付款结束时间 */ private String endDifference; /** * 项目组 */ private String projectGroup; public String getStartDifference() { return startDifference; } public void setStartDifference(String startDifference) { this.startDifference = startDifference; } public String getEndDifference() { return endDifference; } public void setEndDifference(String endDifference) { this.endDifference = endDifference; } public String getProjectGroup() { return projectGroup; } public void setProjectGroup(String projectGroup) { this.projectGroup = projectGroup; } }
true
68adda3389bb03c61735512b26df78bfeaba69ed
Java
meta-kritika-pandey4/GET2019
/GETassignment/src/com/metacube/get2019/Item.java
UTF-8
1,216
3.640625
4
[]
no_license
/* * package com.metacube. */ package com.metacube.get2019; /* * The class item is here with attributes id(Product id), * itemName(Product name)m and price of the product. * This fetches these attributes for the items. */ public class Item { private int id; private String itemName; private double price; /* * This method is used to set values of 3 properties and to print them. * @param id This is first parameter to set id of item * @param itemName this is second parameter to set itemname * @param price this is third parameter to set price of item */ public Item(int id, String itemName, double price) { this.id=id; this.itemName=itemName; this.price=price; System.out.println(id+"\t\t"+itemName+"\t\t"+price); } /* * This method is used to return value of itemname * @return string type itemname */ public String getItemName() { return itemName; } /* * This method is used to return value of id. * @return id of item */ public int getid() { return id; } /* * This method is used to return the price of the item. * @return price of item */ public double getprice() { return price; } }
true
bc4b14e95f01d374cb071d119ef19c074c682f0a
Java
vot-developer/sedgewick-algorithms-coursera
/src/main/java/org/sedgewick/algorithms/part_one/week_two/question_six/DutchNationalFlag.java
UTF-8
876
3.71875
4
[ "MIT" ]
permissive
package org.sedgewick.algorithms.part_one.week_two.question_six; public class DutchNationalFlag { /** * @param array contains only 3 colors : 0, 1 or 2 values * @return sorted array */ public void sortColors(int[] array) { int leftBorder = 0; int rightBorder = array.length - 1; int i = 0; while (i <= rightBorder) { if (array[i] == 0) { swap(array, i, leftBorder); leftBorder++; i++; } else if (array[i] == 2) { swap(array, i, rightBorder); rightBorder--; } else { i++; } } } private void swap(int[] array, int indexOne, int indexTwo) { int temp = array[indexOne]; array[indexOne] = array[indexTwo]; array[indexTwo] = temp; } }
true
7e5bfe95abb24b45fdfb85d15eeed1d624318a6d
Java
djsolar/vie
/TeleVectorComplier/src/com/mansion/tele/business/network/SmoothStyle.java
UTF-8
601
2.390625
2
[]
no_license
package com.mansion.tele.business.network; public class SmoothStyle { /** * 平滑只处理本线和辅路,其他类型道路都不处理 */ /** * 角度的余玄小于此值,且点两边的距离有一个小于此值,删除当前点; */ public static final float angle = 175.0f;//单位: public static final float length_1 = 2f;//单位:CM /** * 点两边的距离有都小于此值,删除此点 * 如果只有一个小于,需要判断防止出现尖角,暂时不处理; */ public static final float length_2 = 0.2f;//单位:CM }
true
36d9366ff201886caf52d2939e729a9329418456
Java
amayorgag/javatest
/src/main/java/solvosoftjavatest/CalculateRequest.java
UTF-8
893
1.890625
2
[]
no_license
// // Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.7 // Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen. // Generado el: 2016.04.16 a las 10:13:23 AM CST // package solvosoftjavatest; import javax.xml.bind.annotation.*; import java.util.Collections; import java.util.List; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "inputs" }) @XmlRootElement(name = "calculateRequest") public class CalculateRequest { @XmlElement(name="input") protected List<String> inputs; public List<String> getInputs() { if (inputs == null) { inputs = Collections.emptyList(); } return this.inputs; } }
true
c1f75ad4979f5d2762007d558b7873b680f0f3d3
Java
gitsayed/IDB-UNIVERSITY-2
/src/main/java/org/idb/service/StudentService.java
UTF-8
3,768
1.945313
2
[]
no_license
<<<<<<< HEAD package org.idb.service; import java.util.ArrayList; import java.util.List; import org.idb.model.Application; import org.idb.model.Payment; import org.idb.model.Students; import org.idb.model.Users; ======= package org.idb.service; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.idb.dto.PaymentDetails; import org.idb.model.Admin; import org.idb.model.Application; import org.idb.model.Payment; import org.idb.model.Schedule; import org.idb.model.Students; import org.idb.model.Users; import org.idb.repository.StudentDao; import org.springframework.beans.factory.annotation.Autowired; >>>>>>> 7619d62... first commit import org.springframework.stereotype.Service; @Service <<<<<<< HEAD public interface StudentService { public List<Students> getMyprofile(); public boolean getPayment(Payment payment) ; public boolean submitApplication(Application application); public List<Application> getApplictionList(); public void removeAppliction(int id); public List<Payment> getDuePaymentList(int id); public List<Payment> getStudentPaymentHistory(int id); public List<Payment> getStudentPaymentDueRecord(int id); public boolean updateStudentDuePayment(Payment payment); public List<Students> getStudentDataById(Integer i); public boolean addStudentToUserTable(Users reg_data); ======= public class StudentService { @Autowired HomeService homeService; @Autowired StudentDao stuDao; public List<Students> getMyprofile() { return stuDao.getMyprofile(); } public boolean getPayment(Payment payment) { String a = new SimpleDateFormat("dd-MM-yyyy ").format(new Date()); payment.setP_date(a); payment.setDue_amount( payment.getPayable_amount() - payment.getPaying_amount()); return stuDao.getPayment(payment); } ; public boolean submitApplication(Application application) { return stuDao.submitApplication(application); } ; public List<Application> getApplictionList() { return stuDao.getApplictionList(); } ; public void removeAppliction(int id) { stuDao.removeAppliction(id); } ; public List<Payment> getDuePaymentListByStudentID(int id) { return stuDao.getDuePaymentListByStudentID(id); } ; public List<Payment> getPaymentHistoryByStudentID(int id) { return stuDao.getPaymentHistoryByStudentID(id); } ; public List<Payment> getStudentPaymentDueRecord(int id) { return stuDao.getStudentPaymentDueRecord(id); } ; public boolean updateStudentDuePayment(Payment payment) { return stuDao.updateStudentDuePayment(payment); } ; public Students getStudentDataById(Integer i) { return stuDao.getStudentDataById(i); } ; public boolean addStudentToUserTable(Users reg_data) { return stuDao.addStudentToUserTable(reg_data); } ; public Students getStudentById(Integer role_id) { return stuDao.getStudentById(role_id); } ; public boolean updateStudent(Students student) { return stuDao.updateStudent(student); } ; public boolean updateUser(Users user1) { return stuDao.updateUser(user1); } ; public List<Application> getApplictionListByStudentID(Integer role_id) { return stuDao.getApplictionListByStudentID(role_id); } ; public List<Schedule> getScheduleofClassByDeptId(String dept_id) { return stuDao.getScheduleofClassByDeptId(dept_id); } ; >>>>>>> 7619d62... first commit <<<<<<< HEAD } ======= } >>>>>>> 7619d62... first commit
true
90877066160b69fc1e7b0e9da70658d12dfa6d56
Java
HuskyGameDev/2017-TeamEngine
/oasis-core/src/oasis/graphics/ogl/OglGraphicsDevice.java
UTF-8
5,959
2.25
2
[ "MIT" ]
permissive
package oasis.graphics.ogl; import oasis.core.Oasis; import oasis.core.OasisException; import oasis.graphics.FrontFace; import oasis.graphics.GraphicsDevice; import oasis.graphics.GraphicsState; import oasis.graphics.Mesh; import oasis.graphics.RenderTarget; import oasis.graphics.RenderTexture; import oasis.graphics.Shader; import oasis.graphics.Texture2D; import oasis.graphics.TextureFormat; import oasis.math.Vector4; public class OglGraphicsDevice implements GraphicsDevice { private Ogl ogl; private int[] vao = new int[1]; private GraphicsState curState = null; private OglShader curShader = null; private OglRenderTarget curRt = null; public OglGraphicsDevice(Ogl ogl) { this.ogl = ogl; } protected static <T> T safeCast(Object res, Class<T> realType) { if (res == null) { throw new OasisException("Resource is null"); } try { @SuppressWarnings("unchecked") T t = (T) res; return t; } catch (Exception e) { throw new OasisException("Invalid resource used: " + res); } } @Override public void preRender() { ogl.glViewport(0, 0, Oasis.getDisplay().getWidth(), Oasis.getDisplay().getHeight()); ogl.glClearColor(0.7f, 0.8f, 1.0f, 0.0f); ogl.glClear(Ogl.GL_COLOR_BUFFER_BIT | Ogl.GL_DEPTH_BUFFER_BIT); if (vao[0] == 0) { ogl.glGenVertexArrays(1, vao, 0); ogl.glBindVertexArray(vao[0]); } ogl.glEnable(Ogl.GL_BLEND); ogl.glBlendEquation(Ogl.GL_FUNC_ADD); ogl.glDepthFunc(Ogl.GL_LEQUAL); ogl.glCullFace(Ogl.GL_BACK); setRenderTarget(null); } @Override public void postRender() { // don't need to do anything so far } @Override public void applyState(GraphicsState state) { if (curState == null || curState.getDestBlendMode() != state.getDestBlendMode() || curState.getSourceBlendMode() != state.getSourceBlendMode()) { int src = OglConvert.getBlendMode(state.getSourceBlendMode()); int dst = OglConvert.getBlendMode(state.getDestBlendMode()); ogl.glBlendFunc(src, dst); } if (curState == null || curState.getFillMode() != state.getFillMode()) { ogl.glPolygonMode(Ogl.GL_FRONT_AND_BACK, OglConvert.getFillMode(state.getFillMode())); } if (curState == null || curState.getFrontFace() != state.getFrontFace()) { if (state.getFrontFace() == FrontFace.BOTH || state.getFrontFace() == null) { ogl.glDisable(Ogl.GL_CULL_FACE); } else { ogl.glEnable(Ogl.GL_CULL_FACE); ogl.glFrontFace(OglConvert.getFrontFace(state.getFrontFace())); } } if (curState == null || curState.isDepthTestEnabled() != state.isDepthTestEnabled()) { if (state.isDepthTestEnabled()) { ogl.glEnable(Ogl.GL_DEPTH_TEST); } else { ogl.glDisable(Ogl.GL_DEPTH_TEST); } } if (curState == null || curState.isDepthWriteEnabled() != state.isDepthWriteEnabled()) { ogl.glDepthMask(state.isDepthTestEnabled()); } curState = new GraphicsState(state); } @Override public void setRenderTarget(RenderTarget rt) { if (rt == null) { OglRenderTarget.bind(ogl, 0); ogl.glViewport(0, 0, Oasis.getDisplay().getWidth(), Oasis.getDisplay().getHeight()); } else if (!rt.isValid()) { throw new OasisException("Invalid render target set: " + rt); } else { OglRenderTarget ort = safeCast(rt, OglRenderTarget.class); int fbo = ort.getFboId(); OglRenderTarget.bind(ogl, fbo); ogl.glViewport(0, 0, rt.getWidth(), rt.getHeight()); } } @Override public void useShader(Shader shader) { if (shader == null) { curShader = null; } else if (!shader.isValid()) { throw new OasisException("Invalid shader cannot be used: " + shader); } else { curShader = safeCast(shader, OglShader.class); curShader.bindAndApplyUniforms(); } } @Override public void drawMesh(Mesh mesh, int submesh) { if (mesh == null) { throw new OasisException("Cannot draw a null mesh"); } if (curShader == null) { throw new OasisException("Cannot draw mesh without a shader: " + mesh); } OglMesh omesh = safeCast(mesh, OglMesh.class); curShader.bindAndApplyUniforms(); omesh.draw(submesh); } @Override public void clearBuffers(Vector4 color, boolean depth) { ogl.glClearColor(color.x, color.y, color.z, color.w); int flags = Ogl.GL_COLOR_BUFFER_BIT; if (depth) flags |= Ogl.GL_DEPTH_BUFFER_BIT; ogl.glClear(flags); } @Override public Mesh createMesh() { return new OglMesh(ogl); } @Override public Texture2D createTexture2D(TextureFormat format, int width, int height) { return new OglTexture2D(ogl, format, width, height); } @Override public RenderTexture createRenderTexture(TextureFormat format, int width, int height) { return new OglRenderTexture(ogl, format, width, height); } @Override public Shader createShader(String vs, String fs) { return new OglShader(ogl, vs, fs); } @Override public RenderTarget createRenderTarget() { return new OglRenderTarget(ogl); } }
true
dc80694d1f3bc808c0afe73971a54e3227835538
Java
Lasthuman911/lightJava
/lighttestdemo/src/main/java/normal/obj/tostring/SchoolReTwo.java
UTF-8
1,071
2.703125
3
[]
no_license
package normal.obj.tostring; /** * Created by lszhen on 2018/1/25. */ public class SchoolReTwo { public String schoolName; public String address; public int stuNum; public SchoolReTwo(String schoolName, String address, int stuNum) { this.schoolName = schoolName; this.address = address; this.stuNum = stuNum; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getStuNum() { return stuNum; } public void setStuNum(int stuNum) { this.stuNum = stuNum; } @Override public String toString() { return getClass().getSimpleName() + "{schoolName='" + schoolName + '\'' + ", address='" + address + '\'' + ", stuNum=" + stuNum + '}'; } }
true
a6cf86fdad7206ccedc5ed86fa15bb0ea793a4ec
Java
tinggu/CdqjPatrolModel
/cdqj_app/src/main/java/com/cdqj/cdqjpatrolandroid/base/BaseRecyclerView.java
UTF-8
2,445
2.46875
2
[]
no_license
package com.cdqj.cdqjpatrolandroid.base; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cdqj.cdqjpatrolandroid.R; /** * Created by lyf on 2018/5/2 10:00 * * @author lyf * desc:设置空数据 */ public class BaseRecyclerView extends RecyclerView { private View emptyView; private AdapterDataObserver observer = new AdapterDataObserver() { @Override public void onChanged() { //设置空view原理都一样,没有数据显示空view,有数据隐藏空view Adapter adapter = getAdapter(); if (adapter.getItemCount() == 0) { emptyView.setVisibility(View.VISIBLE); BaseRecyclerView.this.setVisibility(View.GONE); } else { emptyView.setVisibility(View.GONE); BaseRecyclerView.this.setVisibility(View.VISIBLE); } } @Override public void onItemRangeChanged(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeChanged(int positionStart, int itemCount, Object payload) { onChanged(); } @Override public void onItemRangeInserted(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeRemoved(int positionStart, int itemCount) { onChanged(); } @Override public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { onChanged(); } }; public BaseRecyclerView(Context context) { super(context); emptyView = LayoutInflater.from(context).inflate(R.layout.cdqj_patrol_list_empty_view,null); } public BaseRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); emptyView = LayoutInflater.from(context).inflate(R.layout.cdqj_patrol_list_empty_view,null); } public void setEmptyView(View view) { this.emptyView = view; ((ViewGroup) this.getRootView()).addView(view); } @Override public void setAdapter(Adapter adapter) { super.setAdapter(adapter); adapter.registerAdapterDataObserver(observer); //observer.onChanged(); } }
true
9cc51bd5a4cc6d5c09f7ad01e9676ad6acdfd099
Java
jcesarauj/productapi
/src/main/java/com/productapi/repository/ProductRepository.java
UTF-8
329
2.078125
2
[]
no_license
package com.productapi.repository; import com.productapi.domain.models.Product; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.List; public interface ProductRepository extends PagingAndSortingRepository<Product, Long> { List<Product> findByNameIgnoreCaseContaining(String name); }
true
61d49c839ab682981d3dcd9bfc89c7e1ffcec357
Java
juniorsolo/EstudoJava
/src/br/com/estudo/desafio/Contas.java
UTF-8
552
2.453125
2
[]
no_license
package br.com.estudo.desafio; import java.io.Serializable; public class Contas implements Serializable{ private String nome; private Float saldo; public String cliente; public int numeroConta; public Contas(){} public Contas(String nome, Float saldo){ this.nome= nome; this.saldo=saldo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Float getSaldo() { return saldo; } public void setSaldo(Float saldo) { this.saldo = saldo; } }
true
45a30c7f84afe5b3875718297ebb2610ff227d53
Java
duyve/AndroidApp
/app/src/main/java/com/example/duyve/myapplication/MainActivities/ForgotPasswordActivity.java
UTF-8
2,063
2.265625
2
[]
no_license
package com.example.duyve.myapplication.MainActivities; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.duyve.myapplication.R; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; public class ForgotPasswordActivity extends AppCompatActivity { private EditText emailView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_forgot); Typeface main = Typeface.createFromAsset(getAssets(), "fonts/Champagne & Limousines Bold.ttf"); emailView = (EditText) findViewById(R.id.EnterEmail); EditText email = (EditText)findViewById(R.id.EnterEmail); Button password = (Button)findViewById(R.id.GetPassword); email.setTypeface(main); password.setTypeface(main); } public void getNewPassword(View view){ final String email = emailView.getText().toString(); if(!isValidEmail(email)) { emailView.setError("The email you entered is not associated with a getJobs(); account"); } else{ Firebase ref = new Firebase("https://sizzling-torch-8367.firebaseio.com/"); ref.resetPassword(email, new Firebase.ResultHandler() { @Override public void onSuccess() { Toast.makeText(ForgotPasswordActivity.this, "Password Reset Email Sent", Toast.LENGTH_SHORT).show(); finish(); } @Override public void onError(FirebaseError firebaseError) { emailView.setError("An error happened"); } }); } } public Boolean isValidEmail(String email) { return Patterns.EMAIL_ADDRESS.matcher(email).matches(); } }
true
11df6ab4af3b5192f3031aeb1c657f209861372b
Java
czarkom/Insertion_Selection_Quick_Sort_Algorithms
/src/main/java/QuickSort.java
UTF-8
1,772
3.71875
4
[]
no_license
public class QuickSort implements SortingInterface { @Override public double[] sort(double[] unsortedVector) { if (unsortedVector == null || unsortedVector.length < 1) throw new IllegalArgumentException("Please give me normal array, you can't pass null or empty arrays to this method"); double[] output = unsortedVector.clone(); if (unsortedVector.length < 20) { SortingInterface sorter = new InsertionSort(); output = sorter.sort(output); return output; } else { Stack<Integer> stack = new Stack<>(); stack.push(0); stack.push(output.length); while (!stack.isStackEmpty()) { int end = stack.pop(); int start = stack.pop(); if (end - start < 2) continue; int p = start + ((end - start) / 2); p = partition(output, p, start, end); stack.push(p + 1); stack.push(end); stack.push(start); stack.push(p); } } return output; } private int partition(double[] vector, int position, int start, int end) { int l = start; int h = end - 2; double pivot = vector[position]; HelpfulMethods.swap(vector, position, end - 1); while (l < h) { if (vector[l] < pivot) { l++; } else if (vector[h] >= pivot) { h--; } else { HelpfulMethods.swap(vector, l, h); } } int index = h; if (vector[h] < pivot) { index++; } HelpfulMethods.swap(vector, end - 1, index); return index; } }
true
ceb41665e45cd619d37c387734abfd16d69415ba
Java
taiwan902/bp-src
/source/Class_11721.java
UTF-8
872
1.890625
2
[]
no_license
/* * Decompiled with CFR 0.145. */ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.util.concurrent.Callable; public class Class_11721 implements Callable { final int Field_11722; final int Field_11723; final int Field_11724; final Class_17665 Field_11725; Class_11721(Class_17665 class_17665, int n, int n2, int n3) { this.Field_11725 = class_17665; this.Field_11723 = n; this.Field_11722 = n2; this.Field_11724 = n3; } private void Method_11726() { MethodHandle methodHandle = MethodHandles.constant(String.class, "MC|BlazingPack"); } public String Method_11727() { return Class_13220.Method_13236(this.Field_11723, this.Field_11722, this.Field_11724); } public Object Method_11728() { return this.Method_11727(); } }
true
0e5d2d1a8c27a0a3f779d56b2c773b562fab2957
Java
droidphone/twjitm-core
/src/main/java/com/twjitm/core/common/enums/MessageAttributeEnum.java
UTF-8
324
1.757813
2
[]
no_license
package com.twjitm.core.common.enums; /** * @author EGLS0807 - [Created on 2018-08-06 21:20] * @company http://www.g2us.com/ * @jdk java version "1.8.0_77" */ public enum MessageAttributeEnum { /** * tcp跟udp使用 */ DISPATCH_SESSION, /** * http使用 */ DISPATCH_HTTP_REQUEST, }
true
cd2b7957c69d157992c2427dddb6d62b4c8547aa
Java
abelmza/MobileDevFundamentals2017
/app/src/main/java/com/belatrixsf/mobiledevfundamentals17/CurrentTimeActivity.java
UTF-8
1,864
2.625
3
[]
no_license
package com.belatrixsf.mobiledevfundamentals17; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class CurrentTimeActivity extends AppCompatActivity { public final static String TAG_LOG = CurrentTimeActivity.class.getSimpleName(); //this is just "CurrentTimeActivity" private EditText timeEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_current_time); // initializing UI views that will be used later timeEditText = (EditText) findViewById(R.id.timeEditText); // log needed by exercise #2 Log.d(TAG_LOG, "OnCreate"); } public void buttonClicked(View v) { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("hh:mma", Locale.US); String dateToShow = sdf.format(d); timeEditText.setText(dateToShow); } @Override protected void onStart() { super.onStart(); // log needed by exercise #2 Log.d(TAG_LOG, "onStart"); } @Override protected void onResume() { super.onResume(); // log needed by exercise #2 Log.d(TAG_LOG, "onResume"); } @Override protected void onPause() { super.onPause(); // log needed by exercise #2 Log.d(TAG_LOG, "onPause"); } @Override protected void onStop() { super.onStop(); // log needed by exercise #2 Log.d(TAG_LOG, "onStop"); } @Override protected void onDestroy() { super.onDestroy(); // log needed by exercise #2 Log.d(TAG_LOG, "onDestroy"); } }
true
731442dd195f3e5acd3ed058da2cfc6c47cf3ccc
Java
Oaks907/bookspace
/JavaTest/src/main/java/fanshe/FieldTest.java
UTF-8
894
3.140625
3
[]
no_license
package fanshe; import java.lang.reflect.Field; /** * Create by haifei on 25/12/2018 2:27 PM. */ public class FieldTest { public static void main(String[] args) throws Exception { Class studentClass = Class.forName("fanshe.Student"); System.out.println("--获取公有字段并调用"); final Field name = studentClass.getField("name"); System.out.println(name); final Object instance = studentClass.newInstance(); name.set(instance, "刘德华"); Student student = (Student) instance; System.out.println(student.name); System.out.println("--获取私有字段并调用"); final Field field = studentClass.getDeclaredField("phoneNum"); System.out.println(field); field.setAccessible(true);//暴力反射,解除私有限定 System.out.println(field); field.set(instance, "1111111"); System.out.println(instance); } }
true
b8e02dec66db0768f56f7b592d603b468274f318
Java
alemak/webapp-tests
/src/test/java/com/netaporter/pws/automation/nap/components/LiveChatComponent.java
UTF-8
5,085
2.140625
2
[]
no_license
package com.netaporter.pws.automation.nap.components; import com.google.common.base.Predicate; import com.netaporter.test.utils.pages.component.AbstractPageComponent; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import static org.junit.Assert.fail; /** * Created by s.joshi on 18/09/2014. */ @Component @Scope("cucumber-glue") public class LiveChatComponent extends AbstractPageComponent { private String FORCE_CHAT_PARAMETER_1 = "&ForcePHL=yes&forceInvite=yes"; private String FORCE_CHAT_PARAMETER_2 = "?ForcePHL=yes&forceInvite=yes"; private By START_CHAT_ELEMENT = By.cssSelector(".action-button.start-chat-button"); private By CLOSE_CHAT_ELEMENT = By.xpath(".//*[@id='chat-window']/div[2]/div/div[3]"); private By CONFIRM_CLOSE_BUTTON_YES = By.xpath(".//*[@id='chat-window']/div[3]/div[1]/div/div[2]/input[1]"); private By CONFIRM_CLOSE_BUTTON_NO= By.xpath(".//*[@id='chat-window']/div[3]/div[1]/div/div[2]/input[2]"); private By CHAT_SESSION_WINDOW_LOCATOR = By.className("chat-section"); private By CHAT_TEXT_BOX_LOCATOR = By.className("chat-input"); private By CHAT_MINIMISE_ICON = By.className("dynamic-button"); private By CHAT_MINIMISE_LINK = By.cssSelector(".minimise-button.header-button"); private By CHAT_MINIMISE_BAR_LOCATOR =By.id("chat-invite"); public void forceLiveChatToAppear() throws Throwable { String liveChatUrl; if (webBot.getCurrentUrl().contains("?")){ liveChatUrl = webBot.getCurrentUrl() + FORCE_CHAT_PARAMETER_1; }else { liveChatUrl = webBot.getCurrentUrl() + FORCE_CHAT_PARAMETER_2; } webBot.getDriver().get(liveChatUrl); waitForElementToNotBeVisible("#chat-invite"); } public void loadChatSession ()throws Throwable { webBot.click(START_CHAT_ELEMENT); Thread.sleep(1000); } public void forceAndLoadNewChatSession() throws Throwable{ forceLiveChatToAppear(); loadChatSession(); } public void closeChatWindowButton() throws Throwable{ webBot.click(CLOSE_CHAT_ELEMENT); Thread.sleep(500); } public void minimiseChatWindow() throws Throwable{ webBot.click(CHAT_MINIMISE_LINK); } public void closeChatOptionsToCloseChat(String closeChatOptions) throws Throwable { if (closeChatOptions.equals("yes")) { webBot.click(CONFIRM_CLOSE_BUTTON_YES); } else if (closeChatOptions.equals("no")) { webBot.click(CONFIRM_CLOSE_BUTTON_NO); } } public boolean isComponentActivated(String component) { if (component.equals("chat session")) { waitSecondsForElementToBeVisible(CHAT_SESSION_WINDOW_LOCATOR,4); return webBot.findElement(CHAT_SESSION_WINDOW_LOCATOR).isDisplayed(); } else if (component.equals("chat invite")) { return webBot.findElement(START_CHAT_ELEMENT).getAttribute("value").contains("Chat now"); }else if (component.equals("confirm close")){ return (webBot.findElement(CONFIRM_CLOSE_BUTTON_YES).isDisplayed() && webBot.findElement(CONFIRM_CLOSE_BUTTON_NO).isDisplayed()); }return false; } public boolean isChatTextBoxVisible() throws InterruptedException { // Thread.sleep(1000); webBot.waitForJQueryCompletion(); return webBot.findElement(CHAT_TEXT_BOX_LOCATOR).isDisplayed(); } public boolean isChatMinimised(){ return (webBot.findElement(CHAT_MINIMISE_BAR_LOCATOR).getAttribute("class").contains("is-collapsed")); } public void waitSecondsForElementToBeVisible(By locator, int maxSeconds) { webBot.waitUntil(elementDisplayed(locator), maxSeconds); } private Predicate<WebDriver> elementDisplayed(final By locator) { return new Predicate<WebDriver>() { @Override public boolean apply(WebDriver driver) { return webBot.findElement(locator).isDisplayed(); } }; } public boolean isChatIconVisible() { return webBot.findElement(CHAT_MINIMISE_ICON,2).isDisplayed(); } public void waitForElementToNotBeVisible(String cssSelector) throws Throwable{ // Return fast if the element doesn't exist if (!webBot.exists(null, By.cssSelector(cssSelector))) { return; } System.out.println("Waiting for element to disappear "+cssSelector); for(int i = 0; i <= 100 ; i++) { // find it each time to prevent selenium reference going stale WebElement e = webBot.findElement(By.cssSelector(cssSelector)); if (!e.isDisplayed()) { System.out.println("By is not visible"); return; } else { Thread.sleep(100); } System.out.print("."); } fail("By did not become invisible: "+cssSelector); } }
true
bb2bb4c318e51de75dd44852e2376b796c39e89a
Java
davidka95/museum_android
/app/src/main/java/hu/bme/aut/exhibitionexplorer/fragment/SignUpFragment.java
UTF-8
5,378
2.140625
2
[]
no_license
package hu.bme.aut.exhibitionexplorer.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import hu.bme.aut.exhibitionexplorer.R; import hu.bme.aut.exhibitionexplorer.interfaces.OnSuccesfullLoginListener; /** * Created by Adam on 2016. 10. 22.. */ public class SignUpFragment extends Fragment { public static final String TAG = "SignUpFragment"; private FirebaseAuth firebaseAuth; private EditText edEmail; private EditText edPassword; private EditText edPasswordConfirm; private Button btnSignUp; private TextView tvBack; private OnSuccesfullLoginListener onSuccesfullLoginListener; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentActivity activity = getActivity(); if (activity instanceof OnSuccesfullLoginListener) { onSuccesfullLoginListener = (OnSuccesfullLoginListener) activity; } else { throw new RuntimeException("Activity must implement OnSuccesFullLoginListener"); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sign_up, container, false); firebaseAuth = FirebaseAuth.getInstance(); initView(rootView); return rootView; } private void initView(final View rootView) { edEmail = (EditText) rootView.findViewById(R.id.edEmail); edPassword = (EditText) rootView.findViewById(R.id.edPassword); edPasswordConfirm = (EditText) rootView.findViewById(R.id.edPasswordConfirm); tvBack = (TextView) rootView.findViewById(R.id.tvBack); tvBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().onBackPressed(); } }); btnSignUp = (Button) rootView.findViewById(R.id.btnSIgnUp); setSignUpClickListener(); } private void setSignUpClickListener() { btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String password = edPassword.getText().toString(); String confirmPassword = edPasswordConfirm.getText().toString(); String email = edEmail.getText().toString(); password = password.trim(); confirmPassword = confirmPassword.trim(); email = email.trim(); if (password.isEmpty() || email.isEmpty() || confirmPassword.isEmpty()) { showMissDataAlertDialog(); } else if (!password.equals(confirmPassword)) { showConfirmPasswordErrorDialog(); } else { firebaseAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { onSuccesfullLoginListener.onSuccesfullLogin(); } else { showSignInErrorAlertDialog(task); } } }); } } }); } private void showSignInErrorAlertDialog(Task task) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(task.getException().getMessage()) .setTitle(R.string.login_error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } private void showConfirmPasswordErrorDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(R.string.confirm_email_error) .setTitle(R.string.signup_error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } private void showMissDataAlertDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(R.string.signup_error_message) .setTitle(R.string.signup_error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } }
true
a74854c83c919722a5c1d027e875f18071abf418
Java
ShawnShoper/schedule
/common/common-config/src/main/java/org/shoper/schedule/pojo/TaskMessage.java
UTF-8
988
2.453125
2
[]
no_license
package org.shoper.schedule.pojo; import com.alibaba.fastjson.JSONObject; /** * TaskMessage server to provider... * * @author ShawnShoper * */ public class TaskMessage { private Task task; private TaskTemplate taskTemplate; public static TaskMessage parseObject(String json) { return JSONObject.parseObject(json, TaskMessage.class); } public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } public TaskTemplate getTaskTemplate() { return taskTemplate; } public void setTaskTemplate(TaskTemplate taskTemplate) { this.taskTemplate = taskTemplate; } public TaskMessage(Task task, TaskTemplate taskTemplate) { this.task = task; this.taskTemplate = taskTemplate; } public TaskMessage() { } public String toJson() { String json = JSONObject.toJSONString(this); return json; } @Override public String toString() { return "TaskMessage [task=" + task + ", taskTemplate=" + taskTemplate + "]"; } }
true
d5d5bd61512a1ee3fcb7364f351500a76ae6cce0
Java
binbin5257/A001
/app/src/main/java/cn/lds/ui/MapSearchActivity.java
UTF-8
14,905
1.914063
2
[]
no_license
package cn.lds.ui; import android.app.Dialog; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.widget.ScrollView; import android.widget.TextView; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.core.PoiItem; import com.amap.api.services.poisearch.PoiResult; import com.amap.api.services.poisearch.PoiSearch; import java.util.ArrayList; import java.util.List; import cn.lds.R; import cn.lds.common.base.BaseActivity; import cn.lds.common.enums.MapSearchGridType; import cn.lds.common.table.SearchPoiTitleTable; import cn.lds.common.table.base.DBManager; import cn.lds.common.utils.CacheHelper; import cn.lds.common.utils.OnItemClickListener; import cn.lds.common.utils.OnItemLongClickListener; import cn.lds.common.utils.ToolsHelper; import cn.lds.databinding.ActivityMapSearchBinding; import cn.lds.ui.adapter.MapSearchGridAdapter; import cn.lds.ui.adapter.MapSearchListAdapter; import cn.lds.widget.dialog.CenterListDialog; import cn.lds.widget.dialog.callback.OnDialogOnItemClickListener; import cn.lds.widget.pullToRefresh.PullToRefreshBase; import io.realm.Realm; import io.realm.RealmResults; import io.realm.Sort; /** * 地图搜索poi 界面 * 列表默认显示收藏夹数据。 */ public class MapSearchActivity extends BaseActivity implements View.OnClickListener, OnItemClickListener, PoiSearch.OnPoiSearchListener { private ActivityMapSearchBinding mBinding; private String keyWord = "";// 要输入的poi搜索关键字 private String cityStr = CacheHelper.getCity();// 要输入的城市名字或者城市区号 private PoiResult poiResult; // poi返回的结果 private int currentPage = 0;// 当前页面,从0开始计数 private PoiSearch.Query query;// Poi查询条件类 private PoiSearch poiSearch;// POI搜索 private MapSearchListAdapter listAdapter; private final int REQUESTMORE = 999; private Realm realm;//数据库 实例 private boolean needJummp = false;//是否需要跳转,到poi定位页面; private CenterListDialog centerListDialog; private List<PoiItem> mList = new ArrayList<PoiItem>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_map_search); initView(); initListener(); } /** * 初始化界面 */ @Override public void initView() { //创建一个GridLayout管理器,设置为4列 GridLayoutManager layoutManager = new GridLayoutManager(mContext, 4); //设置GridView方向为:垂直方向 layoutManager.setOrientation(LinearLayoutManager.VERTICAL); //添加到RecyclerView容器里面 mBinding.mapSearchGrid.setLayoutManager(layoutManager); //设置自动适应配置的大小 mBinding.mapSearchGrid.setHasFixedSize(true); //创建适配器对象 MapSearchGridAdapter adapter = new MapSearchGridAdapter(MapSearchGridType.getList(), mContext, this); mBinding.mapSearchGrid.setAdapter(adapter); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext) { @Override public boolean canScrollVertically() { return false; } }; mBinding.mapSearchList.setLayoutManager(linearLayoutManager); listAdapter = new MapSearchListAdapter(mList, mContext, new OnItemClickListener() { @Override public void onItemClick(Object data, int position) { final PoiItem poiItem = (PoiItem) data; if (null == poiItem.getLatLonPoint()) {//为空表示为 历史记录 searchData(poiItem.getTitle()); return; } Intent intent = new Intent(mContext, PoiLocatedActivity.class); intent.setAction(PoiLocatedActivity.ACTIONSINGLEPOI); intent.putExtra("poiItem", poiItem); intent.putExtra("keyWord", keyWord); startActivity(intent); } }, new OnItemLongClickListener() { @Override public boolean onItemLongClick(Object data, final int listPosition) { if (ToolsHelper.isNull(keyWord)) {//表示历史列表被点击,弹出删除选项 final PoiItem poiItem = (PoiItem) data; ArrayList<String> strings = new ArrayList<>(); strings.add("删除"); centerListDialog = new CenterListDialog(MapSearchActivity.this, mContext, strings).setOnDialogOnItemClickListener(new OnDialogOnItemClickListener() { @Override public void onDialogItemClick(Dialog dialog, int position) { switch (position) { case 0: realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { SearchPoiTitleTable titleTable = realm.where(SearchPoiTitleTable.class). contains("title", poiItem.getTitle()).findFirst(); if (null != titleTable) { titleTable.deleteFromRealm(); listAdapter.remove(listPosition); } } }); break; } centerListDialog.dismiss(); } }); centerListDialog.show(); return true; } else return false; } }); mBinding.mapSearchList.setAdapter(listAdapter); readPoiHistory(); } /** * 读取搜索记录 */ private void readPoiHistory() { if (null == realm) { realm = DBManager.getInstance().getRealm(); } realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<SearchPoiTitleTable> poiTitleTables = realm.where(SearchPoiTitleTable.class).equalTo("loginId",CacheHelper.getLoginId()).findAllSorted("time", Sort.DESCENDING); List<PoiItem> list = new ArrayList<>(); for (int i = 0; i < poiTitleTables.size(); i++) { if (i >= 10) { break; } SearchPoiTitleTable titleTable = poiTitleTables.get(i); PoiItem poiItem = new PoiItem(titleTable.getTitle(), null, titleTable.getTitle(), titleTable.getSnippet()); list.add(poiItem); } listAdapter.updateAdapter(list); } }); } /** * 初始化监听 */ @Override public void initListener() { mBinding.topBackIv.setOnClickListener(this); mBinding.topMenuLyt.setOnClickListener(this); mBinding.pullScrollView.setMode(PullToRefreshBase.Mode.DISABLED);//上拉加载更多 mBinding.pullScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() { @Override public void onRefresh(PullToRefreshBase<ScrollView> refreshView) { refreshView.onRefreshComplete(); if (ToolsHelper.isNull(keyWord)) return; currentPage++; doSearchQuery();//分页加载 } }); mBinding.mapSearchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (0 == mBinding.mapSearchEdit.getText().length()) { ToolsHelper.showInfo(mContext, "请输入关键词"); } return true; } }); mBinding.mapSearchEdit.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { currentPage = 0;//分页重置 if (0 == charSequence.length()) {//显示历史记录 mBinding.pullScrollView.setMode(PullToRefreshBase.Mode.DISABLED); readPoiHistory(); } else { mBinding.pullScrollView.setMode(PullToRefreshBase.Mode.PULL_UP_TO_REFRESH); keyWord = charSequence.toString(); doSearchQuery();//输入检索 } } @Override public void afterTextChanged(Editable editable) { } }); } /** * 点击事件 * * @param view * 点击的view */ @Override public void onClick(View view) { switch (view.getId()) { case R.id.top_back_iv: finish(); break; case R.id.top_menu_lyt: if (0 == mBinding.mapSearchEdit.getText().length()) { ToolsHelper.showInfo(mContext, "请输入关键词"); return; } break; } } /** * 搜索poi * * @param data * 点击的数据 * @param position * 点击位置 */ @Override public void onItemClick(Object data, int position) { MapSearchGridType gridType = (MapSearchGridType) data; switch (gridType) { case SHOUCANGJIA: startActivity(new Intent(mContext, CollectionsActivity.class)); break; case JINGXIAOSHANG: startActivity(new Intent(mContext, DealerListActivity.class)); break; case GENGDUO: Intent intent = new Intent(mContext, PoiLocatedActivity.class); intent.setAction(PoiLocatedActivity.ACTIONMORE); startActivityForResult(intent, REQUESTMORE); break; default: searchData(gridType.getValue()); needJummp = true; break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case REQUESTMORE: String key = data.getStringExtra("keyWord"); searchData(key); break; default: searchData(""); break; } } } /** * 搜索poi * * @param s * 关键词 */ private void searchData(String s) { mBinding.mapSearchEdit.setText(s); mBinding.mapSearchEdit.setSelection(s.length()); } /** * 开始进行poi搜索 */ protected void doSearchQuery() { query = new PoiSearch.Query(keyWord, "", "");// 第一个参数表示搜索字符串,第二个参数表示poi搜索类型,第三个参数表示poi搜索区域(空字符串代表全国) query.setPageSize(30);// 设置每页最多返回多少条poiitem query.setCityLimit(true); query.setPageNum(currentPage);// 设置查第一页 poiSearch = new PoiSearch(this, query); poiSearch.setOnPoiSearchListener(this); //已人为中心 double lng = Double.parseDouble(CacheHelper.getLongitude()); double lat = Double.parseDouble(CacheHelper.getLatitude()); LatLonPoint lp = new LatLonPoint(lat, lng); // poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true)); //设置周边搜索的中心点以及区域 5000米-5公里 poiSearch.searchPOIAsyn(); } /** * POI信息查询回调方法 */ @Override public void onPoiSearched(PoiResult result, int rCode) { if (rCode == 1000) { if (result != null && result.getQuery() != null) {// 搜索poi的结果 if (result.getQuery().equals(query)) {// 是否是同一条 if (!ToolsHelper.isNull(keyWord)) {//如果关键字为空,不更新poi数据。否则影响 历史记录显示问题 poiResult = result; // 取得搜索到的poiitems有多少页 ArrayList<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据,页数从数字0开始 // List<SuggestionCity> suggestionCities = poiResult // .getSearchSuggestionCitys();// 当搜索不到poiitem数据时,会返回含有搜索关键字的城市信息 if (0 == currentPage) { listAdapter.updateAdapter(poiItems); } else { listAdapter.add(poiItems); } if (needJummp) {//是否需要跳转到定位页 Intent defaultIntent = new Intent(mContext, PoiLocatedActivity.class); defaultIntent.setAction(PoiLocatedActivity.ACTIONPOILIST); defaultIntent.putExtra("keyWord", keyWord); defaultIntent.putParcelableArrayListExtra("list", poiItems); startActivity(defaultIntent); needJummp = false;//跳转后开关,关闭 } } } else { // ToolsHelper.showInfo(mContext, "搜索结果为空"); listAdapter.clear(); } } } } @Override public void onPoiItemSearched(PoiItem poiItem, int i) { } @Override protected void onDestroy() { super.onDestroy(); if (null != realm) { realm.close(); realm = null; } centerListDialog = null; } }
true
9b8f2d5b03e0ea1bc800274f598997fa3e8dd261
Java
heishandian/cwskk
/cws/src/main/java/com/yaoli/vo/huangkai/CarManageSearchConditionVO.java
UTF-8
1,621
2.1875
2
[]
no_license
package com.yaoli.vo.huangkai; /** * Created by kk on 2017/7/5. */ public class CarManageSearchConditionVO { String carnumber; String starttime; String endtime; Integer page; Integer rows; public String getCarnumber() { return carnumber; } public void setCarnumber(String carnumber) { this.carnumber = carnumber; } public String getStarttime() { return starttime; } public void setStarttime(String starttime) { this.starttime = starttime; } public String getEndtime() { return endtime; } public void setEndtime(String endtime) { this.endtime = endtime; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } public CarManageSearchConditionVO() { } public CarManageSearchConditionVO(String carnumber, String starttime, String endtime, Integer page, Integer rows) { this.carnumber = carnumber; this.starttime = starttime; this.endtime = endtime; this.page = page; this.rows = rows; } @Override public String toString() { return "CarManageSearchConditionVO{" + "carnumber='" + carnumber + '\'' + ", starttime='" + starttime + '\'' + ", endtime='" + endtime + '\'' + ", page=" + page + ", rows=" + rows + '}'; } }
true
ae5f02ea329a8c35d961b52e9c1a88aa3e2f6de6
Java
Bl4ckSkull666/ExternVerify
/src/de/bl4ckskull666/externverify/EV.java
UTF-8
3,211
2.359375
2
[]
no_license
package de.bl4ckskull666.externverify; import de.bl4ckskull666.externverify.classes.Errors; import de.bl4ckskull666.externverify.classes.Language; import de.bl4ckskull666.externverify.classes.SpigotLanguage; import de.bl4ckskull666.externverify.commands.Verify; import de.bl4ckskull666.externverify.listeners.PlayerJoin; import java.util.logging.Level; import org.bukkit.plugin.java.JavaPlugin; /** * * @author Bl4ckSkull666 */ public class EV extends JavaPlugin { @Override public void onEnable() { _plugin = this; if(!getDataFolder().exists()) { getDataFolder().mkdir(); getConfig().options().copyDefaults(true); } saveConfig(); getCommand("verify").setExecutor(new Verify()); if(getBoolean("use-auto-verify-on-join", false)) getServer().getPluginManager().registerEvents(new PlayerJoin(), this); loadLanguage(); _error = new Errors(); } private void loadLanguage() { if(getServer().getVersion().toLowerCase().contains("spigot")) { SpigotLanguage lang = new SpigotLanguage(); _lang = (Language)lang; debug("Using Spigot Language support.", "", Level.INFO); } else _lang = new Language(); } public String getString(String path, String def) { if(!getConfig().isString(path)) { getConfig().set(path, def); saveConfig(); } return getConfig().getString(path); } public int getInt(String path, int def) { if(!getConfig().isInt(path)) { getConfig().set(path, def); saveConfig(); } return getConfig().getInt(path); } public double getDouble(String path, double def) { if(!getConfig().isDouble(path)) { getConfig().set(path, def); saveConfig(); } return getConfig().getDouble(path); } public boolean getBoolean(String path, boolean def) { if(!getConfig().isBoolean(path)) { getConfig().set(path, def); saveConfig(); } return getConfig().getBoolean(path); } private static EV _plugin = null; public static EV getPlugin() { return _plugin; } private static Language _lang = null; public static Language getLang() { return _lang; } private static Errors _error = null; public static Errors getErrors() { return _error; } public static void reload() { _plugin.reloadConfig(); _plugin.loadLanguage(); _error = new Errors(); } public static void debug(String msg, String localization, Level lv) { if(_plugin.getBoolean("debug", false)) { _plugin.getLogger().log(lv, "[DEBUG1] {0}", msg); if(!localization.isEmpty()) _plugin.getLogger().log(lv, "[DEBUG2] {0}", localization); } if(lv.equals(Level.WARNING)) _error.addError(msg, localization, lv); } }
true
bd69b6c6a8c7317bfbaaf470682a744785cb4e96
Java
melon-ruet/nfc
/TagInfo3.0_8_source_from_JADX/com/nxp/taginfolite/fragments/C0398e.java
UTF-8
979
1.585938
2
[]
no_license
package com.nxp.taginfolite.fragments; import com.nxp.taginfolite.p000a.C0154w; import com.nxp.taginfolite.p000a.C0155x; /* renamed from: com.nxp.taginfolite.fragments.e */ /* synthetic */ class C0398e { static final /* synthetic */ int[] f1296a; static final /* synthetic */ int[] f1297b; static { f1297b = new int[C0155x.values().length]; try { f1297b[C0155x.ASC.ordinal()] = 1; } catch (NoSuchFieldError e) { } try { f1297b[C0155x.DESC.ordinal()] = 2; } catch (NoSuchFieldError e2) { } f1296a = new int[C0154w.values().length]; try { f1296a[C0154w.TITLE.ordinal()] = 1; } catch (NoSuchFieldError e3) { } try { f1296a[C0154w.ENABLED.ordinal()] = 2; } catch (NoSuchFieldError e4) { } try { f1296a[C0154w.TYPE.ordinal()] = 3; } catch (NoSuchFieldError e5) { } } }
true
3f30f4ad75e5f567080fb9672ad4a24c6767edb3
Java
moccadroid/wiggins
/src/main/java/org/lalelu/brivel/brivelplus/database/provider/DatabaseAccessProvider.java
UTF-8
216
1.71875
2
[]
no_license
package org.lalelu.brivel.brivelplus.database.provider; import java.util.List; public interface DatabaseAccessProvider { public void execute(String sql); public List<Object[]> getResultList(String sql); }
true
cffe8b736b05c202efd1ee2d1b18ed9680646d9c
Java
dimboychuk1995/tu
/src/main/java/com/myapp/struts/DictionariActionForm.java
UTF-8
1,534
2.046875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.myapp.struts; import java.util.ArrayList; import java.util.List; /** * * @author AsuSV */ public class DictionariActionForm extends org.apache.struts.action.ActionForm { private String id; private String name; private String type; private List list_name; private String namelist; private String parid; public String getType() { return type; } public void setType(String type) { this.type = type; } public List getList_name() { return list_name; } public void setList_name(List list_name) { this.list_name = list_name; } public String getNamelist() { return namelist; } public void setNamelist(String namelist) { this.namelist = namelist; } /** * @return */ public String getName() { return name; } /** * @param string */ public void setName(String string) { name = string; } /** * @return */ public String getId() { return id; } /** * @param i */ public void setId(String i) { id = i; } public String getParid() { return parid; } public void setParid(String parid) { this.parid = parid; } /** * */ public DictionariActionForm() { super(); // TODO Auto-generated constructor stub } }
true
84a32627f486e1d6ba32b22ef0183144937044ca
Java
lzx2011/java-scaffold
/src/main/java/com/lzhenxing/javascaffold/javabase/collections/Collection.java
UTF-8
4,030
2.6875
3
[]
no_license
package com.lzhenxing.javascaffold.javabase.collections; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Created by gary on 16/6/26. */ public class Collection { public static void testMap(Map<String ,String> map){ for(Map.Entry<String,String> entry : map.entrySet()){ System.out.println(entry.getKey()+"-----"+entry.getValue()); } } public static void iteratorMap(Map<String,String> map){ Iterator iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry entry = (Map.Entry)iterator.next(); String key = (String)entry.getKey(); String value = (String)entry.getValue(); System.out.println(key+"----"+value); } } @Test public void traverse(){ //List<Integer> list = Arrays.asList(1,2); //list.add(3); //java.lang.UnsupportedOperationException //System.out.println(list.toString()); ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); //list.add(3); for (Integer i : list){ if(2 == i){ //list.set(i, 4); list.remove(i); } //System.out.println(i); } System.out.println(list.toString()); } @Test public void iteratorList(){ List<Long> list = Lists.newArrayList(); list.add(1L); list.add(2L); list.add(365756733L); list.add(4L); list.add(5L); //Long i = 365756733L; System.out.println(list); Iterator iterator = list.iterator(); while (iterator.hasNext()){ Long aLong = (Long)iterator.next(); //if("3657567".equals(aLong)){ // iterator.remove(); //} if(365756733L == aLong){ iterator.remove(); } } System.out.println(list); } public static boolean filterSellerIdAndVendor(Long sellerId, String vendor){ boolean flag = false; if(sellerId == null || StringUtils.isBlank(vendor)){ return flag; } Long i = 2972472251L; if(i.longValue() == sellerId && "intl_expedia".equals(vendor)){ return true; } if(2272687825L == sellerId && "intl_agoda".equals(vendor)){ return true; } if(2978942880L == sellerId && "intl_tourico".equals(vendor)){ return true; } if(2944730784L == sellerId && "intl_hotelbeds".equals(vendor)){ return true; } if(3070359393L == sellerId && "intl_gta".equals(vendor)){ return true; } if(2697996683L == sellerId && "intl_jtb".equals(vendor)){ return true; } return flag; } @Test public void listTest(){ List<Long> list = Lists.newArrayList(); System.out.println(list.size()); } @Test public void streamFilterTest(){ Long bizOrderId = 1100169310025215469L; Set<Long> testSet = new HashSet<>(); testSet.add(1100169310025215469L); testSet.add(1100169310026215469L); System.out.println(testSet); Set<Long> relateOrderIds = testSet.stream().filter(x -> !x.equals(bizOrderId)) .collect(Collectors.toSet()); System.out.println(relateOrderIds); System.out.println(testSet); } public static void main(String[] args){ Map<String,String> map = new HashMap<>(); // map.put("1","test1"); // map.put("2","test2"); // testMap(map); // iteratorMap(map); System.out.println(filterSellerIdAndVendor(2972472251L, "intl_expedia")); } }
true
f1cc37ac0fb349ce076dba6807395881ec56dd9e
Java
wugenshui/demo-spring-boot
/big-data/demo-flink/src/main/java/com/github/wugenshui/demo/trans/KeyByTest.java
UTF-8
1,543
2.953125
3
[ "MIT" ]
permissive
package com.github.wugenshui.demo.trans; import com.github.wugenshui.demo.model.Event; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.datastream.KeyedStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * 按键分区 * * @author : chenbo * @date : 2023-04-04 */ public class KeyByTest { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); DataStreamSource<Event> stream = env.fromElements( new Event("Mary", "./home", 1000L), new Event("Bob", "./cart2", 2000L), new Event("Bob", "./cart", 1000L) ); // 第一种方式:使用 Lambda 表达式 KeyedStream<Event, String> keyedStream = stream.keyBy(e -> e.user); // 第二种方式:使用匿名类实现 KeySelector KeyedStream<Event, String> keyedStream1 = stream.keyBy( new KeySelector<Event, String>() { @Override public String getKey(Event e) throws Exception { return e.user; } }); // 第三种方式:简单聚合,推荐使用,支持 sum,max,min,minBy,maxBy stream.keyBy(e -> e.user).sum("timestamp").print(); env.execute(); } }
true
fa2a6184c8d48d4ca6418068476bec0c079d2f0e
Java
15257703071/evan-framework
/mq/src/main/java/org/evanframework/mq/MqProducerClient.java
UTF-8
1,327
2.109375
2
[]
no_license
package org.evanframework.rabbitmq; import com.aliyun.openservices.ons.api.ONSFactory; import com.aliyun.openservices.ons.api.Producer; import com.aliyun.openservices.ons.api.PropertyKeyConst; import java.util.Properties; /** * 生产者 * <p/> * create at 2017年03月8日 下午5:15:54 * @author <a href="mailto:caozhenfei@yourong.com">Dim.Cao</a> * @version %I%, %G% * @since 1.0 */ @Deprecated public class MqProducerClient extends MqClient { private Producer producer; public MqProducerClient() { } public MqProducerClient(String accessKey, String secretKey, String onsAddr) { super(accessKey,secretKey,onsAddr); } public Producer createProducer(String ProducerId){ Properties producerProperties = new Properties(); producerProperties.setProperty(PropertyKeyConst.AccessKey, super.getAccessKey()); producerProperties.setProperty(PropertyKeyConst.SecretKey, super.getSecretKey()); producerProperties.setProperty(PropertyKeyConst.ONSAddr, super.getOnsAddr()); this.producer = ONSFactory.createProducer(producerProperties); start(); return this.producer; } public void start(){ producer.start(); } public void shutdown(){ producer.shutdown(); } }
true
243d15aa9c1720e25d0cdf4f269ad90489174144
Java
leonchen83/redis-replicator
/src/test/java/com/moilioncircle/redis/replicator/cmd/parser/SortParserTest.java
UTF-8
3,986
2.171875
2
[ "Apache-2.0", "LicenseRef-scancode-996-icu-1.0" ]
permissive
/* * Copyright 2016-2018 Leon Chen * * 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.moilioncircle.redis.replicator.cmd.parser; import static com.moilioncircle.redis.replicator.cmd.impl.OrderType.DESC; import static com.moilioncircle.redis.replicator.cmd.impl.OrderType.NONE; import org.junit.Test; import com.moilioncircle.redis.replicator.cmd.impl.SortCommand; import junit.framework.TestCase; /** * @author Leon Chen * @since 2.3.1 */ public class SortParserTest extends AbstractParserTest { @Test public void parse() { { SortParser parser = new SortParser(); SortCommand cmd = parser.parse(toObjectArray("SORT mylist".split(" "))); assertEquals("mylist", cmd.getKey()); TestCase.assertEquals(NONE, cmd.getOrder()); assertEquals(0, cmd.getGetPatterns().length); assertEquals(false, cmd.isAlpha()); } { SortParser parser = new SortParser(); SortCommand cmd = parser.parse(toObjectArray("SORT mylist DESC".split(" "))); assertEquals("mylist", cmd.getKey()); TestCase.assertEquals(DESC, cmd.getOrder()); assertEquals(0, cmd.getGetPatterns().length); assertEquals(false, cmd.isAlpha()); } { SortParser parser = new SortParser(); SortCommand cmd = parser.parse(toObjectArray("SORT mylist ALPHA DESC".split(" "))); assertEquals("mylist", cmd.getKey()); TestCase.assertEquals(DESC, cmd.getOrder()); assertEquals(0, cmd.getGetPatterns().length); assertEquals(true, cmd.isAlpha()); } { SortParser parser = new SortParser(); SortCommand cmd = parser.parse(toObjectArray("SORT mylist ALPHA DESC limit 0 10".split(" "))); assertEquals("mylist", cmd.getKey()); TestCase.assertEquals(DESC, cmd.getOrder()); assertEquals(0, cmd.getGetPatterns().length); assertEquals(true, cmd.isAlpha()); assertEquals(0L, cmd.getLimit().getOffset()); assertEquals(10L, cmd.getLimit().getCount()); } { SortParser parser = new SortParser(); SortCommand cmd = parser.parse(toObjectArray("sort mylist alpha desc limit 0 10 by weight_*".split(" "))); assertEquals("mylist", cmd.getKey()); TestCase.assertEquals(DESC, cmd.getOrder()); assertEquals(0, cmd.getGetPatterns().length); assertEquals(true, cmd.isAlpha()); assertEquals(0L, cmd.getLimit().getOffset()); assertEquals(10L, cmd.getLimit().getCount()); assertEquals("weight_*", cmd.getByPattern()); } { SortParser parser = new SortParser(); SortCommand cmd = parser.parse(toObjectArray("sort mylist alpha desc limit 0 10 by weight_* get object_* get #".split(" "))); assertEquals("mylist", cmd.getKey()); TestCase.assertEquals(DESC, cmd.getOrder()); assertEquals(true, cmd.isAlpha()); assertEquals(0L, cmd.getLimit().getOffset()); assertEquals(10L, cmd.getLimit().getCount()); assertEquals("weight_*", cmd.getByPattern()); assertEquals(2, cmd.getGetPatterns().length); assertEquals("object_*", cmd.getGetPatterns()[0]); assertEquals("#", cmd.getGetPatterns()[1]); } } }
true
4062c80f54bd9be8232df2a7cc58b6584951d4bd
Java
sufadi/decompile-hw
/decompile/app/SystemUI/src/main/java/com/fyusion/sdk/core/a/b.java
UTF-8
662
2.125
2
[]
no_license
package com.fyusion.sdk.core.a; import java.nio.ByteBuffer; /* compiled from: Unknown */ public class b { private ByteBuffer a; private int b; private int c; private int d; private int e; public b(ByteBuffer byteBuffer, int i, int i2, int i3, int i4) { this.a = byteBuffer; this.b = i; this.c = i2; this.d = i3; this.e = i4; } public ByteBuffer a() { return this.a; } public int b() { return this.b; } public int c() { return this.c; } public int d() { return this.d; } public int e() { return this.e; } }
true
11d86bf6022378303687dd04c487be6f87de3adb
Java
LUAgam/CoreDemo
/src/main/java/org/lua/web/index/formbean/MessageAttachmentFB.java
UTF-8
697
1.765625
2
[]
no_license
/** * */ package org.lua.web.index.formbean; import java.util.List; /** * @author onkyo * */ public class MessageAttachmentFB { private int filecount; private long filelength; private List<AttachmentFB> attachmentList; public int getFilecount() { return filecount; } public void setFilecount(int filecount) { this.filecount = filecount; } public long getFilelength() { return filelength; } public void setFilelength(long filelength) { this.filelength = filelength; } public List<AttachmentFB> getAttachmentList() { return attachmentList; } public void setAttachmentList(List<AttachmentFB> attachmentList) { this.attachmentList = attachmentList; } }
true
3dfe55d0e655dbe87285c586129977015880325f
Java
jozn/Bisphone
/app/setting/SettingMediaAutoDownload$$ViewInjector.java
UTF-8
2,395
1.664063
2
[]
no_license
package app.setting; import android.view.View; import android.widget.TextView; import app.setting.SettingMediaAutoDownload$$ViewInjector$SettingMediaAutoDownload$.ViewInjector; import butterknife.ButterKnife.Finder; import butterknife.ButterKnife.Injector; import butterknife.internal.DebouncingOnClickListener; public class SettingMediaAutoDownload$$ViewInjector<T extends SettingMediaAutoDownload> implements Injector<T> { /* renamed from: app.setting.SettingMediaAutoDownload$.ViewInjector.1 */ class ViewInjector extends DebouncingOnClickListener { final /* synthetic */ SettingMediaAutoDownload f4410a; final /* synthetic */ SettingMediaAutoDownload$$ViewInjector f4411b; ViewInjector(SettingMediaAutoDownload$$ViewInjector settingMediaAutoDownload$$ViewInjector, SettingMediaAutoDownload settingMediaAutoDownload) { this.f4411b = settingMediaAutoDownload$$ViewInjector; this.f4410a = settingMediaAutoDownload; } public void m6820a(View view) { this.f4410a.m6825j(); } } /* renamed from: app.setting.SettingMediaAutoDownload$.ViewInjector.2 */ class ViewInjector extends DebouncingOnClickListener { final /* synthetic */ SettingMediaAutoDownload f4412a; final /* synthetic */ SettingMediaAutoDownload$$ViewInjector f4413b; ViewInjector(SettingMediaAutoDownload$$ViewInjector settingMediaAutoDownload$$ViewInjector, SettingMediaAutoDownload settingMediaAutoDownload) { this.f4413b = settingMediaAutoDownload$$ViewInjector; this.f4412a = settingMediaAutoDownload; } public void m6821a(View view) { this.f4412a.m6826k(); } } public void inject(Finder finder, T t, Object obj) { t.f4414o = (TextView) finder.m7731a((View) finder.m7732a(obj, 2131755272, "field 'videoDesc'"), 2131755272, "field 'videoDesc'"); t.f4415p = (TextView) finder.m7731a((View) finder.m7732a(obj, 2131755270, "field 'imageDesc'"), 2131755270, "field 'imageDesc'"); ((View) finder.m7732a(obj, 2131755269, "method 'onImageclick'")).setOnClickListener(new ViewInjector(this, t)); ((View) finder.m7732a(obj, 2131755271, "method 'onVideoclick'")).setOnClickListener(new ViewInjector(this, t)); } public void reset(T t) { t.f4414o = null; t.f4415p = null; } }
true
8c77e8f403e2dcf47c92717b8984d0fc3e96ce72
Java
zAndroidDeveloper/HDD_Commerce
/overtechlibrary/src/main/java/com/overtech/djtechlibrary/http/webservice/UIHandler.java
UTF-8
303
1.890625
2
[]
no_license
package com.overtech.djtechlibrary.http.webservice; import android.content.Context; import android.os.Handler; /** * Created by Overtech on 16/4/11. */ public class UIHandler extends Handler { private Context context; public UIHandler(Context context){ this.context=context; } }
true
73e7fc2ed1a5de19616539b7360e6a8cba46450a
Java
MichalSzukala/HackerEarth-challenges
/Stacks.java
UTF-8
4,326
3.390625
3
[]
no_license
import java.util.Scanner; import java.util.Stack; /** * Created by Z on 20/06/2017. */ //The Football Fest: https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/the-football-fest-6/ public class Stacks { public void ballPasses(){ Scanner scanner = new Scanner(System.in); System.out.println("how many cases"); int cases = scanner.nextInt(); int whoHasBall = 0; char typeOfPass = 'P'; //P - pass, B - ball back int howManyBackPasses = 1; while(cases > 0){ Stack<Integer> stack = new Stack<Integer>(); System.out.println("how many pases"); int passes = scanner.nextInt(); whoHasBall = scanner.nextInt(); stack.push(whoHasBall); typeOfPass = 'P'; howManyBackPasses = 1; for(int i = 0; i < passes; i++) { System.out.println("what kind of pass?"); typeOfPass = scanner.next().charAt(0); if(typeOfPass == 'P') { System.out.println("who have the ball?"); whoHasBall = scanner.nextInt(); stack.push(whoHasBall); howManyBackPasses = 1; } if(howManyBackPasses == 2){ stack.push(whoHasBall); howManyBackPasses = 1; } else if(typeOfPass =='B') { stack.pop(); howManyBackPasses++; } } System.out.println(stack.peek()); stack.clear(); cases--; System.out.println("---------------------------"); } } //Monk and Philosopher's Stone: https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/monk-and-philosophers-stone/ public void harryGoldCoin(){ Scanner scanner = new Scanner(System.in); int coins = scanner.nextInt(); int[] harryArray = new int[coins]; Stack<Integer> monkStack = new Stack<Integer>(); for(int i = 0; i < coins; i++) harryArray[i] = scanner.nextInt(); int numberOftasks = scanner.nextInt(); int value = scanner.nextInt(); String task = null; int k = 0; int monkStackValue = 0; for(int i = 0; i < numberOftasks; i++){ task = scanner.next(); if(task.equals("Harry")){ monkStack.push(harryArray[k]); monkStackValue += harryArray[k]; k++; if(monkStackValue == value){ int numberOfCoins = 0; while(!monkStack.empty()) { numberOfCoins++; monkStack.pop(); } System.out.println(numberOfCoins); return; } } else if(task.equals("Remove")){ monkStackValue -= monkStack.pop(); } } System.out.println("-1"); } //Little Monk and Balanced Parentheses: https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/little-monk-and-balanced-parentheses/ public void balance(){ Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); int[] array = new int[size]; for(int i = 0; i < size; i++) array[i] = scanner.nextInt(); Stack<Integer> stack = new Stack<Integer>(); int lastValue = 0; int counter = 0; int maxCounter = 0; for(int i = 0; i < size; i++){ if(!stack.empty()) { lastValue = stack.peek(); } stack.push(array[i]); if(stack.peek() + lastValue == 0 && lastValue > 0){ counter++; stack.pop(); stack.pop(); if(counter > maxCounter) maxCounter = counter; } else if(stack.size() > 1) counter = 0; if(lastValue == 0 && stack.peek() < 0) stack.pop(); } System.out.println(maxCounter * 2); } }
true
5de64e2cffb36bfdd5b2b6955c4e0d65f7c89313
Java
Double-3/onlineExamSystem
/src/main/java/com/xhu/entity/Node.java
UTF-8
1,852
2.484375
2
[]
no_license
package com.xhu.entity; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; @Component public class Node { @Override public String toString() { return "Node [id=" + id + ", text=" + text + ", state=" + state + ", p_method=" + p_method + ", checked=" + checked + ", children=" + children + ", parentId=" + parentId + "]"; } //�ڵ�� id private Integer id; //��ʾ�Ľڵ����֡� private String text; //�ڵ�״̬�� 'open' �� 'closed'��Ĭ���� 'open' private String state; private String p_method; //ָʾ�ڵ��Ƿ�ѡ�� private boolean checked; //������һЩ�ӽڵ�Ľڵ����� private List<Node> children; //���ڵ� private Integer parentId; /** * ע�⣺��Ҫ�ڹ��캯�������ӽڵ���� */ public Node(){ this.children = new ArrayList<Node>(); } public String getP_method() { return p_method; } public void setP_method(String p_method) { this.p_method = p_method; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getState() { return state; } public void setState(String state) { this.state = state; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public List<Node> getChildren() { return children; } public void setChildren(List<Node> children) { this.children = children; } }
true
78b8a6a578bdeeb97cc92766ac2c13576f4f8649
Java
Sususuperman/LuanDemo
/app/src/main/java/com/hywy/luanhzt/activity/MessageBookActivity.java
UTF-8
2,020
1.984375
2
[]
no_license
package com.hywy.luanhzt.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import com.cs.android.task.Task; import com.cs.common.base.BaseToolbarActivity; import com.cs.common.view.SwipeRefreshview; import com.hywy.luanhzt.R; import com.hywy.luanhzt.adapter.item.MessageItem; import com.hywy.luanhzt.task.GetMessageListTask; import com.hywy.luanhzt.task.GetNotifyListTask; import java.util.HashMap; import java.util.Map; import butterknife.Bind; import eu.davidea.flexibleadapter.FlexibleAdapter; public class MessageBookActivity extends BaseToolbarActivity implements FlexibleAdapter.OnItemClickListener { @Bind(R.id.recyclerview) RecyclerView recyclerview; @Bind(R.id.swipeRefresh) SwipeRefreshview swipeRefresh; public static void startAction(Context context) { Intent intent = new Intent(context, MessageBookActivity.class); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message_book); init(); initData(); } private void init() { setTitleBulider(new Bulider().backicon(R.drawable.ic_arrow_back_white_24dp).title("留言簿")); swipeRefresh.setAdapter(recyclerview); swipeRefresh.getAdapter().initializeListeners(this); } private void initData() { Map<String, Object> params = new HashMap<>(); Task task = new GetMessageListTask(this); swipeRefresh.builder(new SwipeRefreshview.Builder() .task(task).params(params)); swipeRefresh.isToast(false); swipeRefresh.refresh(); } @Override public boolean onItemClick(int position) { MessageItem item = (MessageItem) swipeRefresh.getAdapter().getItem(position); MessageInfoActivity.startAction(this, item.getData()); return false; } }
true
01f9bbc5603029a3244842887789323d2dc0c67d
Java
tigerphz/ssh-client-pool
/src/main/java/com/github/woostju/ssh/autoconfigure/SshClientPoolAutoConfiguration.java
UTF-8
1,475
2.03125
2
[ "Apache-2.0" ]
permissive
package com.github.woostju.ssh.autoconfigure; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.github.woostju.ssh.pool.SshClientPoolConfig; import com.github.woostju.ssh.pool.SshClientsPool; @Configuration @EnableConfigurationProperties(SshClientPoolProperties.class) public class SshClientPoolAutoConfiguration { private final SshClientPoolProperties properties; public SshClientPoolAutoConfiguration(SshClientPoolProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean(SshClientsPool.class) SshClientsPool sshClientsPool() { return new SshClientsPool(sshClientPoolConfig()); } SshClientPoolConfig sshClientPoolConfig() { SshClientPoolConfig poolConfig = new SshClientPoolConfig(properties.getMaxActive() ,properties.getMaxIdle() ,properties.getIdleTime() ,properties.getMaxWait()); if(properties.getSshj()!=null) { poolConfig.setServerCommandPromotRegex(properties.getSshj().getServerCommandPromotRegex()); } if (properties.getSshClientImplClass()!=null) { try { poolConfig.setSshClientImplClass(Class.forName(properties.getSshClientImplClass())); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return poolConfig; } }
true
c344ae94dfb0c517786bff5948c58a36927626f6
Java
MuXin-Liang/EMG_Bluetooth
/app/src/main/java/com/lambort/emg_bluetooth_openbci/FFT.java
UTF-8
6,553
2.890625
3
[]
no_license
package com.lambort.emg_bluetooth_openbci; import java.util.ArrayList; public class FFT { private static double PI = 3.141592653; private static int FFT_N; public FFT(int fft_N){ FFT_N = fft_N; SIN_TAB = new float[FFT_N/2]; create_sin_tab(SIN_TAB); } public static class Compx { public float real; public float imag; public double abs() { return Math.sqrt(real*real+imag*imag); } }; //private Compx[] S = new Compx[FFT_N]; private float SIN_TAB[]; /******************************************************************* 函数原型:struct compx EE(struct compx b1,struct compx b2) 函数功能:对两个复数进行乘法运算 输入参数:两个以联合体定义的复数a,b 输出参数:a和b的乘积,以联合体的形式输出 *******************************************************************/ private Compx EE(Compx a,Compx b) { Compx c = new Compx(); c.real=a.real*b.real-a.imag*b.imag; c.imag=a.real*b.imag+a.imag*b.real; return(c); } /****************************************************************** 函数原型:void create_sin_tab(float *sin_t) 函数功能:创建一个正弦采样表,采样点数与福利叶变换点数相同 输入参数:*sin_t存放正弦表的数组指针 输出参数:无 ******************************************************************/ private void create_sin_tab(float[] sin_t) { int i; for(i=0;i<FFT_N/2;i++) sin_t[i]=(float) Math.sin(2*PI*i/FFT_N); } /****************************************************************** 函数原型:void sin_tab(float pi) 函数功能:采用查表的方法计算一个数的正弦值 输入参数:pi 所要计算正弦值弧度值,范围0--2*PI,不满足时需要转换 输出参数:输入值pi的正弦值 ******************************************************************/ private float sin_tab(float pi) { int n; float a = 0; n=(int)(pi*FFT_N/2/PI); if(n>=0&&n<FFT_N/2) a=SIN_TAB[n]; else if(n>=FFT_N/2&&n<FFT_N) a=-SIN_TAB[n-FFT_N/2]; return a; } /****************************************************************** 函数原型:void cos_tab(float pi) 函数功能:采用查表的方法计算一个数的余弦值 输入参数:pi 所要计算余弦值弧度值,范围0--2*PI,不满足时需要转换 输出参数:输入值pi的余弦值 ******************************************************************/ private float cos_tab(float d) { float a,pi2; pi2=(float) (d+PI/2); if(pi2>2*PI) pi2-=2*PI; a=sin_tab(pi2); return a; } /***************************************************************** 函数原型:void FFT(struct compx *xin,int N) 函数功能:对输入的复数组进行快速傅里叶变换(FFT) 输入参数:*xin复数结构体组的首地址指针,struct型 输出参数:无 *****************************************************************/ public void FFT(Compx[] xin) { int f,m,nv2,nm1,i,k,l,j=0; Compx u,w,t; nv2=FFT_N/2; //变址运算,即把自然顺序变成倒位序,采用雷德算法 nm1=FFT_N-1; for(i=0;i<nm1;i++) { if(i<j) //如果i<j,即进行变址 { t=xin[j]; xin[j]=xin[i]; xin[i]=t; } k=nv2; //求j的下一个倒位序 while(k<=j) //如果k<=j,表示j的最高位为1 { j=j-k; //把最高位变成0 k=k/2; //k/2,比较次高位,依次类推,逐个比较,直到某个位为0 } j=j+k; //把0改为1 } { int le,lei,ip; //FFT运算核,使用蝶形运算完成FFT运算 f=FFT_N; for(l=1;(f=f/2)!=1;l++) //计算l的值,即计算蝶形级数 ; for(m=1;m<=l;m++) // 控制蝶形结级数 { //m表示第m级蝶形,l为蝶形级总数l=log(2)N le=2<<(m-1); //le蝶形结距离,即第m级蝶形的蝶形结相距le点 lei=le/2; //同一蝶形结中参加运算的两点的距离 u = new Compx(); u.real=(float) 1; //u为蝶形结运算系数,初始值为1 u.imag=(float) 0; //w.real=cos(PI/lei); //不适用查表法计算sin值和cos值 // w.imag=-sin(PI/lei); w = new Compx(); w.real=cos_tab((float) (PI/lei)); //w为系数商,即当前系数与前一个系数的商 w.imag=-sin_tab((float) (PI/lei)); for(j=0;j<=lei-1;j++) //控制计算不同种蝶形结,即计算系数不同的蝶形结 { for(i=j;i<=FFT_N-1;i=i+le) //控制同一蝶形结运算,即计算系数相同蝶形结 { ip=i+lei; //i,ip分别表示参加蝶形运算的两个节点 t=EE(xin[ip],u); //蝶形运算,详见公式 xin[ip].real=xin[i].real-t.real; xin[ip].imag=xin[i].imag-t.imag; xin[i].real=xin[i].real+t.real; xin[i].imag=xin[i].imag+t.imag; } u=EE(u,w); //改变系数,进行下一个蝶形运算 } } } } public double[] FFT(ArrayList<Double> x){ Compx xin[] = new Compx[FFT_N]; for(int i =0;i<FFT_N;i++) { xin[i] = new Compx(); xin[i].real = x.get(i).floatValue(); xin[i].imag = 0; } FFT(xin); double xout[] = new double[FFT_N]; for(int i =0;i<FFT_N;i++) xout[i] = xin[i].abs(); return xout; } }
true
8e85d4408d73d98496d51e0958c080f24388ca1b
Java
goodday451999/Java-Basic-Codes
/DemoCodes/src/sampleCode/StaticDemo.java
UTF-8
797
3.4375
3
[]
no_license
package sampleCode; class Student{ int id; String name; static int count = 0; public Student(int id, String name) { this.id = id; this.name = name; count++; } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } public static int getCount() { return count; } // public static void setCount(int count) { // Student.count = count; // } } public class StaticDemo { public static void main(String args[]) { Student anil = new Student(1, "Anil"); System.out.println(anil.getCount()); Student sunil = new Student(2, "Sunil"); System.out.println(sunil.getCount()); System.out.println(Student.getCount()); } }
true
8c5c2254efe316b2760a1922ae642080174ddd4b
Java
surajdubey/auction-system
/app/src/test/java/com/crossover/auctionsystem/presenter/SubmittedItemsForAuctionPresenterTest.java
UTF-8
1,546
2.21875
2
[]
no_license
package com.crossover.auctionsystem.presenter; import com.crossover.auctionsystem.interactor.SubmittedItemsForAuctionInteractor; import com.crossover.auctionsystem.model.Item; import com.crossover.auctionsystem.view.SubmittedItemsForAuctionView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by suraj on 28/9/16. */ @RunWith(MockitoJUnitRunner.class) public class SubmittedItemsForAuctionPresenterTest { @Mock private SubmittedItemsForAuctionView mView; private SubmittedItemsForAuctionPresenter mPresenter; @Mock private SubmittedItemsForAuctionInteractor mInteractor; @Before public void setup() { mPresenter = new SubmittedItemsForAuctionPresenter(mView, mInteractor); } @Test public void shouldShowNoItemSubmitted_WhenItemNotAvailable() { when(mInteractor.listAllSubmittedItems()).thenReturn(new ArrayList<Item>()); mPresenter.listAllSubmittedItems(); verify(mView).showNoItemSubmitted(); } @Test public void shouldShowNoItemSubmitted_WhenItemAreAvailable() { ArrayList<Item> items = new ArrayList<>(); items.add(new Item()); when(mInteractor.listAllSubmittedItems()).thenReturn(items); mPresenter.listAllSubmittedItems(); verify(mView).setSubmittedItems(items); } }
true
63f5dfda0076ccd858c6f2ed4673d04f809f3910
Java
rosoareslv/SED99
/java/neo4j/2019/4/ConcatListTest.java
UTF-8
3,022
2.40625
2
[]
no_license
/* * Copyright (c) 2002-2019 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j 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 org.neo4j.values.virtual; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.neo4j.values.storable.Values.booleanValue; import static org.neo4j.values.storable.Values.intValue; import static org.neo4j.values.storable.Values.longValue; import static org.neo4j.values.storable.Values.stringValue; import static org.neo4j.values.virtual.VirtualValueTestUtil.map; import static org.neo4j.values.virtual.VirtualValues.EMPTY_LIST; import static org.neo4j.values.virtual.VirtualValues.concat; import static org.neo4j.values.virtual.VirtualValues.list; class ConcatListTest { @Test void shouldHandleZeroListConcatenation() { // Given ListValue inner = EMPTY_LIST; // When ListValue concat = concat( inner ); // Then assertTrue( concat.isEmpty() ); } @Test void shouldHandleSingleListConcatenation() { // Given ListValue inner = list( stringValue( "foo" ), longValue( 42 ), booleanValue( true ) ); // When ListValue concat = concat( inner ); // Then assertEquals(inner, concat); assertEquals(inner.hashCode(), concat.hashCode()); assertArrayEquals(inner.asArray(), concat.asArray()); } @Test void shouldHandleMultipleListConcatenation() { // Given ListValue inner1 = list( stringValue( "foo" ), longValue( 42 ), booleanValue( true ) ); ListValue inner2 = list( list(stringValue("bar"), intValue(42)) ); ListValue inner3 = list( map("foo", 1337L, "bar", 42 ), stringValue("baz") ); // When ListValue concat = concat( inner1, inner2, inner3 ); // Then ListValue expected = list( stringValue( "foo" ), longValue( 42 ), booleanValue( true ), list( stringValue( "bar" ), intValue( 42 ) ), map( "foo", 1337L, "bar", 42 ), stringValue( "baz" ) ); assertEquals(expected, concat); assertEquals(expected.hashCode(), concat.hashCode()); assertArrayEquals(expected.asArray(), concat.asArray()); } }
true
0351fa95a18bab1f297bc05ea0a267ef5b19e125
Java
yuanchaocs/ReadGroup
/apphx/src/main/java/com/feicuiedu/apphx/HxBaseApplication.java
UTF-8
2,393
2.046875
2
[]
no_license
package com.feicuiedu.apphx; import android.app.Application; import android.widget.Toast; import com.feicuiedu.apphx.model.event.HxDisconnectEvent; import com.feicuiedu.apphx.model.repository.DefaultLocalUsersRepo; import com.feicuiedu.apphx.model.repository.ILocalUsersRepo; import com.feicuiedu.apphx.model.repository.IRemoteUserRepo; import com.feicuiedu.apphx.model.repository.MockRemoteUsersRepo; import com.hyphenate.EMError; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMOptions; import com.hyphenate.easeui.controller.EaseUI; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import timber.log.Timber; /** * 环信相关基础配置 * * 作者:yuanchao on 2016/10/11 0011 11:22 * 邮箱:yuanchao@feicuiedu.com */ public abstract class HxBaseApplication extends Application { @Override public void onCreate() { super.onCreate(); // 初始化Timber日志 Timber.plant(new Timber.DebugTree()); // 初始化环信sdk和easeui库 initEaseUI(); // 初始化apphx模块 initHxModule(); EventBus.getDefault().register(this); } protected void initHxModule(){ IRemoteUserRepo remoteUsersRepo = new MockRemoteUsersRepo(); ILocalUsersRepo localUsersRepo = DefaultLocalUsersRepo.getInstance(this); HxModuleInitializer.getInstance().init(remoteUsersRepo,localUsersRepo); } private void initEaseUI() { EMOptions options = new EMOptions(); // 关闭自动登录 options.setAutoLogin(false); // 默认添加好友时是不需要验证的,改为需要 options.setAcceptInvitationAlways(false); EaseUI.getInstance().init(this, options); // 关闭环信日志 EMClient.getInstance().setDebugMode(false); } // 异常登出情况处理 @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(HxDisconnectEvent event){ if (event.errorCode == EMError.USER_LOGIN_ANOTHER_DEVICE) { Toast.makeText(this, R.string.hx_error_account_conflict, Toast.LENGTH_SHORT).show(); } else if (event.errorCode == EMError.USER_REMOVED) { Toast.makeText(this, R.string.hx_error_account_removed, Toast.LENGTH_SHORT).show(); } exit(); } protected abstract void exit(); }
true
e63961fdb3b2bf0e8eb2496b9bb559f705f2351f
Java
lemonJun/TakinMQ
/takinmq-jkafka/src/main/java/kafka/log/Cleaner.java
UTF-8
14,997
2.3125
2
[ "Apache-2.0" ]
permissive
package kafka.log; import com.google.common.collect.Lists; import kafka.common.OptimisticLockFailureException; import kafka.message.*; import kafka.utils.Function1; import kafka.utils.Throttler; import kafka.utils.Time; import kafka.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Date; import java.util.List; import static com.google.common.base.Preconditions.checkState; public class Cleaner { public int id; public OffsetMap offsetMap; public int ioBufferSize; public int maxIoBufferSize; public double dupBufferLoadFactor; public Throttler throttler; public Time time; /** * This class holds the actual logic for cleaning a log * * @param id An identifier used for logging * @param offsetMap The map used for deduplication * @param ioBufferSize The size of the buffers to use. Memory usage will be 2x this number as there is a read and write buffer. * @param throttler The throttler instance to use for limiting I/O rate. * @param time The time instance */ public Cleaner(int id, OffsetMap offsetMap, int ioBufferSize, int maxIoBufferSize, double dupBufferLoadFactor, Throttler throttler, Time time) { this.id = id; this.offsetMap = offsetMap; this.ioBufferSize = ioBufferSize; this.maxIoBufferSize = maxIoBufferSize; this.dupBufferLoadFactor = dupBufferLoadFactor; this.throttler = throttler; this.time = time; logger = LoggerFactory.getLogger(Cleaner.class + "-" + id); stats = new CleanerStats(time); readBuffer = ByteBuffer.allocate(ioBufferSize); writeBuffer = ByteBuffer.allocate(ioBufferSize); } Logger logger; /* stats on this cleaning */ public CleanerStats stats; /* buffer used for read i/o */ private ByteBuffer readBuffer; /* buffer used for write i/o */ private ByteBuffer writeBuffer; /** * Clean the given log * * @param cleanable The log to be cleaned * @return The first offset not cleaned */ public long clean(LogToClean cleanable) throws InterruptedException { stats.clear(); logger.info("Beginning cleaning of log {}.", cleanable.log.name()); Log log = cleanable.log; int truncateCount = log.numberOfTruncates(); // build the offset map logger.info("Building offset map for {}...", cleanable.log.name()); long upperBoundOffset = log.activeSegment().baseOffset; long endOffset = buildOffsetMap(log, cleanable.firstDirtyOffset, upperBoundOffset, offsetMap) + 1; stats.indexDone(); // figure out the timestamp below which it is safe to remove delete tombstones // this position is defined to be a configurable time beneath the last modified time of the last clean segment LogSegment seg = Utils.lastOption(log.logSegments(0, cleanable.firstDirtyOffset)); long deleteHorizonMs = seg == null ? 0L : (seg.lastModified() - log.config.deleteRetentionMs); // group the segments and clean the groups logger.info("Cleaning log {} (discarding tombstones prior to {})...", log.name(), new Date(deleteHorizonMs)); for (List<LogSegment> group : groupSegmentsBySize(log.logSegments(0, endOffset), log.config.segmentSize, log.config.maxIndexSize)) cleanSegments(log, group, offsetMap, truncateCount, deleteHorizonMs); stats.allDone(); return endOffset; } /** * Clean a group of segments into a single replacement segment * * @param log The log being cleaned * @param segments The group of segments being cleaned * @param map The offset map to use for cleaning segments * @param expectedTruncateCount A count used to check if the log is being truncated and rewritten under our feet * @param deleteHorizonMs The time to retain delete tombstones */ void cleanSegments(Log log, List<LogSegment> segments, OffsetMap map, int expectedTruncateCount, long deleteHorizonMs) throws InterruptedException { // create a new segment with the suffix .cleaned appended to both the log and index name File logFile = new File(Utils.head(segments).log.file.getPath() + Logs.CleanedFileSuffix); logFile.delete(); File indexFile = new File(Utils.head(segments).index.file.getPath() + Logs.CleanedFileSuffix); indexFile.delete(); FileMessageSet messages = new FileMessageSet(logFile); OffsetIndex index = new OffsetIndex(indexFile, Utils.head(segments).baseOffset, Utils.head(segments).index.maxIndexSize); LogSegment cleaned = new LogSegment(messages, index, Utils.head(segments).baseOffset, Utils.head(segments).indexIntervalBytes, time); // clean segments into the new destination segment for (LogSegment old : segments) { boolean retainDeletes = old.lastModified() > deleteHorizonMs; logger.info("Cleaning segment {} in log {} (last modified {}) into {}, {} deletes.", old.baseOffset, log.name(), new Date(old.lastModified()), cleaned.baseOffset, (retainDeletes ? "retaining" : "discarding")); cleanInto(old, cleaned, map, retainDeletes); } // trim excess index index.trimToValidSize(); // flush new segment to disk before swap cleaned.flush(); // update the modification date to retain the last modified date of the original files long modified = Utils.last(segments).lastModified(); cleaned.lastModified(modified); // swap in new segment logger.info("Swapping in cleaned segment {} for segment(s) {} in log {}.", cleaned.baseOffset, Utils.mapList(segments, new Function1<LogSegment, Long>() { @Override public Long apply(LogSegment _) { return _.baseOffset; } }), log.name()); try { log.replaceSegments(cleaned, segments, expectedTruncateCount); } catch (OptimisticLockFailureException e) { cleaned.delete(); throw e; } } /** * Clean the given source log segment into the destination segment using the key=>offset mapping * provided * * @param source The dirty log segment * @param dest The cleaned log segment * @param map The key=>offset mapping * @param retainDeletes Should delete tombstones be retained while cleaning this segment * <p/> * TODO: Implement proper compression support */ private void cleanInto(LogSegment source, LogSegment dest, OffsetMap map, boolean retainDeletes) throws InterruptedException { int position = 0; while (position < source.log.sizeInBytes()) { checkDone(); // read a chunk of messages and copy any that are to be retained to the write buffer to be written out readBuffer.clear(); writeBuffer.clear(); ByteBufferMessageSet messages = new ByteBufferMessageSet(source.log.readInto(readBuffer, position)); throttler.maybeThrottle(messages.sizeInBytes()); // check each message to see if it is to be retained int messagesRead = 0; for (MessageAndOffset entry : messages) { messagesRead += 1; int size = MessageSets.entrySize(entry.message); position += size; stats.readMessage(size); ByteBuffer key = entry.message.key(); checkState(key != null, String.format("Found null key in log segment %s which is marked as dedupe.", source.log.file.getAbsolutePath())); long foundOffset = map.get(key); /* two cases in which we can get rid of a message: * 1) if there exists a message with the same key but higher offset * 2) if the message is a delete "tombstone" marker and enough time has passed */ boolean redundant = foundOffset >= 0 && entry.offset < foundOffset; boolean obsoleteDelete = !retainDeletes && entry.message.isNull(); if (!redundant && !obsoleteDelete) { ByteBufferMessageSets.writeMessage(writeBuffer, entry.message, entry.offset); stats.recopyMessage(size); } } // if any messages are to be retained, write them out if (writeBuffer.position() > 0) { writeBuffer.flip(); ByteBufferMessageSet retained = new ByteBufferMessageSet(writeBuffer); dest.append(Utils.head(retained).offset, retained); throttler.maybeThrottle(writeBuffer.limit()); } // if we read bytes but didn't get even one complete message, our I/O buffer is too small, grow it and try again if (readBuffer.limit() > 0 && messagesRead == 0) growBuffers(); } restoreBuffers(); } /** * Double the I/O buffer capacity */ public void growBuffers() { if (readBuffer.capacity() >= maxIoBufferSize || writeBuffer.capacity() >= maxIoBufferSize) throw new IllegalStateException(String.format("This log contains a message larger than maximum allowable size of %s.", maxIoBufferSize)); int newSize = Math.min(this.readBuffer.capacity() * 2, maxIoBufferSize); logger.info("Growing cleaner I/O buffers from " + readBuffer.capacity() + "bytes to " + newSize + " bytes."); this.readBuffer = ByteBuffer.allocate(newSize); this.writeBuffer = ByteBuffer.allocate(newSize); } /** * Restore the I/O buffer capacity to its original size */ public void restoreBuffers() { if (this.readBuffer.capacity() > this.ioBufferSize) this.readBuffer = ByteBuffer.allocate(this.ioBufferSize); if (this.writeBuffer.capacity() > this.ioBufferSize) this.writeBuffer = ByteBuffer.allocate(this.ioBufferSize); } /** * Group the segments in a log into groups totaling less than a given size. the size is enforced separately for the log data and the index data. * We collect a group of such segments together into a single * destination segment. This prevents segment sizes from shrinking too much. * * @param segments The log segments to group * @param maxSize the maximum size in bytes for the total of all log data in a group * @param maxIndexSize the maximum size in bytes for the total of all index data in a group * @return A list of grouped segments */ List<List<LogSegment>> groupSegmentsBySize(Iterable<LogSegment> segments, int maxSize, int maxIndexSize) { List<List<LogSegment>> grouped = Lists.newArrayList(); List<LogSegment> segs = Lists.newArrayList(segments); while (!segs.isEmpty()) { List<LogSegment> group = Lists.newArrayList(Utils.head(segs)); long logSize = Utils.head(segs).size(); int indexSize = Utils.head(segs).index.sizeInBytes(); segs = Utils.tail(segs); while (!segs.isEmpty() && logSize + Utils.head(segs).size() < maxSize && indexSize + Utils.head(segs).index.sizeInBytes() < maxIndexSize) { group.add(Utils.head(segs)); logSize += Utils.head(segs).size(); indexSize += Utils.head(segs).index.sizeInBytes(); segs = Utils.tail(segs); } grouped.add(group); } return grouped; } /** * Build a map of key_hash => offset for the keys in the dirty portion of the log to use in cleaning. * * @param log The log to use * @param start The offset at which dirty messages begin * @param end The ending offset for the map that is being built * @param map The map in which to store the mappings * @return The final offset the map covers */ long buildOffsetMap(Log log, long start, long end, OffsetMap map) throws InterruptedException { map.clear(); Collection<LogSegment> dirty = log.logSegments(start, end); logger.info("Building offset map for log {} for {} segments in offset range [{}, {}).", log.name(), dirty.size(), start, end); // Add all the dirty segments. We must take at least map.slots * load_factor, // but we may be able to fit more (if there is lots of duplication in the dirty section of the log) long offset = Utils.head(dirty).baseOffset; checkState(offset == start, String.format("Last clean offset is %d but segment base offset is %d for log %s.", start, offset, log.name())); long minStopOffset = (long) (start + map.slots() * this.dupBufferLoadFactor); for (LogSegment segment : dirty) { checkDone(); if (segment.baseOffset <= minStopOffset || map.utilization() < this.dupBufferLoadFactor) offset = buildOffsetMap(segment, map); } logger.info("Offset map for log {} complete.", log.name()); return offset; } /** * Add the messages in the given segment to the offset map * * @param segment The segment to index * @param map The map in which to store the key=>offset mapping * @return The final offset covered by the map */ private long buildOffsetMap(LogSegment segment, OffsetMap map) throws InterruptedException { int position = 0; long offset = segment.baseOffset; while (position < segment.log.sizeInBytes()) { checkDone(); readBuffer.clear(); ByteBufferMessageSet messages = new ByteBufferMessageSet(segment.log.readInto(readBuffer, position)); throttler.maybeThrottle(messages.sizeInBytes()); int startPosition = position; for (MessageAndOffset entry : messages) { Message message = entry.message; checkState(message.hasKey()); int size = MessageSets.entrySize(message); position += size; map.put(message.key(), entry.offset); offset = entry.offset; stats.indexMessage(size); } // if we didn't read even one complete message, our read buffer may be too small if (position == startPosition) growBuffers(); } restoreBuffers(); return offset; } /** * If we aren't running any more throw an AllDoneException */ private void checkDone() throws InterruptedException { if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); } }
true
5e2e56f8c760ca0c3ab6b47e4788e2218ec93714
Java
mghio/mghio-spring
/src/main/java/cn/mghio/beans/factory/config/ConfigurableBeanFactory.java
UTF-8
391
1.789063
2
[]
no_license
package cn.mghio.beans.factory.config; import java.util.List; /** * @author mghio * @since 2020-11-01 */ public interface ConfigurableBeanFactory extends AutowireCapableBeanFactory { void setClassLoader(ClassLoader classLoader); ClassLoader getClassLoader(); void addBeanPostProcessor(BeanPostProcessor processor); List<BeanPostProcessor> getBeanPostProcessors(); }
true
8b43aa02b46fa0a84b6cd0a20324cc6972017be7
Java
mainurrasel/BootcampCelloscope
/Java Basic/Java Begineer Code Practice/LearningClientServer/src/net/celloscope/binaryTo64/Server.java
UTF-8
1,870
3.171875
3
[]
no_license
package net.celloscope.binaryTo64; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Base64; public class Server { public static void main(String[] args) { int port = 8888; BufferedReader reader = null; OutputStream writer = null; try{ System.out.println("Connected to server Port: " + port); ServerSocket serverSocket = new ServerSocket(port); Socket socket = serverSocket.accept(); // Thread.sleep(10000); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = socket.getOutputStream(); String line = ""; line = reader.readLine(); if(line == null) { System.out.println("Nothing to read"); return; } while (line != null){ System.out.println("Server Received : " + line + "\n"); decoder(line, "/home/mainur/Desktop/base64/lalaladecode.jpg"); line = reader.readLine(); System.out.println("Decoded!"); } System.out.println("End of transmission"); writer.flush(); } catch (Exception e){ System.out.println(e.getMessage()); } } // decoder public static void decoder(String base64File, String pathFile) { try { FileOutputStream imageOutFile = new FileOutputStream(pathFile); byte[] imageByteArray = Base64.getDecoder().decode(base64File); imageOutFile.write(imageByteArray); } catch (FileNotFoundException e) { System.out.println("File not found" + e); } catch (IOException ioe) { System.out.println("Exception while reading the File " + ioe); } } }
true
54788d321a9c235b7f5ca5f6d254a6c3fa08e4a2
Java
aloisio/markup-calculator
/src/main/java/com/nupack/model/CommonItemTypes.java
UTF-8
407
2.546875
3
[]
no_license
package com.nupack.model; import java.math.BigDecimal; public enum CommonItemTypes implements ItemType { FOOD(13), DRUGS(7.5), ELECTRONICS(2), BOOKS(0), OTHER(0); private CommonItemTypes(double markupAsDouble) { this.markup = BigDecimal.valueOf(markupAsDouble); } private final BigDecimal markup; @Override public BigDecimal getMarkup() { return markup; } }
true
47176f93a5bf0077c547708fb09565b8e8c17473
Java
crispd/cs-studio
/core/plugins/org.csstudio.rap.core/src/org/csstudio/rap/core/security/LoginDialogCallbackHandler.java
UTF-8
3,513
2.375
2
[]
no_license
/******************************************************************************* * Copyright (c) 2013 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.rap.core.security; import javax.security.auth.callback.Callback; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.TextOutputCallback; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * Handles the callbacks to show a login dialog for the LoginModule. * * @author Xihui Chen * */ @SuppressWarnings("serial") public class LoginDialogCallbackHandler extends AbstractLoginDialog { public LoginDialogCallbackHandler(Display display) { this(display.getActiveShell()); } protected LoginDialogCallbackHandler(Shell parentShell) { super(parentShell); } protected Control createDialogArea(Composite parent) { Composite dialogarea = (Composite) super.createDialogArea(parent); dialogarea.setLayoutData(new GridData(GridData.FILL_BOTH)); dialogarea.setLayout(new GridLayout(2, false)); createCallbackHandlers(dialogarea); return dialogArea; } private void createCallbackHandlers(Composite composite) { Callback[] callbacks = getCallbacks(); for (int i = 0; i < callbacks.length; i++) { Callback callback = callbacks[i]; if (callback instanceof TextOutputCallback) { createTextOutputHandler(composite, (TextOutputCallback) callback); } else if (callback instanceof NameCallback) { createNameHandler(composite, (NameCallback) callback); } else if (callback instanceof PasswordCallback) { createPasswordHandler(composite, (PasswordCallback) callback); } } } private void createPasswordHandler(Composite composite, final PasswordCallback callback) { Label label = new Label(composite, SWT.NONE); label.setText(callback.getPrompt()); final Text passwordText = new Text(composite, SWT.SINGLE | SWT.LEAD | SWT.PASSWORD | SWT.BORDER); passwordText.setLayoutData(new GridData(GridData.FILL_BOTH)); passwordText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent event) { callback.setPassword(passwordText.getText().toCharArray()); } }); } private void createNameHandler(Composite composite, final NameCallback callback) { Label label = new Label(composite, SWT.NONE); label.setText(callback.getPrompt()); final Text text = new Text(composite, SWT.SINGLE | SWT.LEAD | SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL_BOTH)); text.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent event) { callback.setName(text.getText()); } }); } private void createTextOutputHandler(Composite composite, TextOutputCallback callback) { getShell().setText(callback.getMessage()); } }
true
cd59761d3b272df535abbe4aa7d5a017a78cfbac
Java
154518499/GOF
/src/factory/abstractFactory/CarFactory.java
UTF-8
204
2.203125
2
[]
no_license
package factory.abstractFactory; /** * @Auther: y * @Date: 2018/11/13 15:21 * @Description: */ public interface CarFactory { Engine createEngine(); Seat createSeat(); Tyre createTyre(); }
true
a4f3ec58319df13e7e18a2585d69600c15ec9bc9
Java
MISO4204-201520/homeAutomation
/Backend/src/com/uniandes/edu/co/homeAutomationSensores/SensorDeMovimiento.java
UTF-8
500
2.34375
2
[]
no_license
package com.uniandes.edu.co.homeAutomationSensores; import com.uniandes.edu.co.homeAutomation.Sensor; public class SensorDeMovimiento extends Sensor { private boolean alarmando; public SensorDeMovimiento(String id, int cuarto, boolean encendido, boolean alarmando) { super(id, cuarto, "sensorMovimiento", encendido); this.alarmando = alarmando; } public boolean getAlarmando() { return alarmando; } public void setAlarmando(boolean alarmando) { this.alarmando = alarmando; } }
true
5e4178c190b1ea31b2fce38d5e8cb1b8b49381d2
Java
dlopezp/SSDD.NoMeOlvides
/src/main/java/es/ssdd/Exceptions/NotFoundException.java
UTF-8
165
1.726563
2
[]
no_license
package es.ssdd.Exceptions; public class NotFoundException extends RuntimeException { private static final long serialVersionUID = -1062093942746509023L; }
true
8a77bcb77985a347943a57634b57c671a3c8543a
Java
Abigovin/CricBuzz_WebBrowserMobileTesting
/src/WebBrowser/capability.java
UTF-8
1,222
2.109375
2
[]
no_license
package WebBrowser; import java.io.File; import java.net.URL; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.remote.AndroidMobileCapabilityType; import io.appium.java_client.remote.MobileCapabilityType; public class capability { public static AndroidDriver<AndroidElement> desiredCapability() throws Exception { //Get path of apk file which is inside in src //File fs = new File("src/ApiDemos-debug.apk"); DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Abinaya device"); cap.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android"); // cap.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath()); cap.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome"); cap.setCapability(AndroidMobileCapabilityType.CHROMEDRIVER_EXECUTABLE,"C:\\Abinaya backup\\Abinaya\\Manipal Team course\\chromedriver.exe"); AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>( new URL("http://0.0.0.0:4723/wd/hub"),cap); return driver; } }
true
9f20c41c233a6232edd9b1149eb7947c8212d839
Java
wsdchigh/t0
/g_a_rely_static/src/main/java/com/wsdchigh/g_a_rely_static/utils/UStatus.java
UTF-8
1,230
2.46875
2
[]
no_license
package com.wsdchigh.g_a_rely_static.utils; import android.app.Activity; import android.view.View; import android.view.ViewGroup; public class UStatus { private static final UStatus instance = new UStatus(); public static UStatus getInstance(){ return instance; } /* * 获取状态栏的高度 */ public int getStatusHeight(Activity act){ int resourcesID = act.getResources().getIdentifier("status_bar_height", "dimen", "android"); int dimension = act.getResources().getDimensionPixelSize(resourcesID); return dimension; } /* * 获取屏幕参数 */ /* * 获取版本信息 */ /* * 移除沉浸式的 头部偏移 * <li> 如果版本不是5.0及以上,取消第一个header(如果有需要)的paddingTop */ public void removeStatusPaddingTop(View rootView,int offset){ if(rootView instanceof ViewGroup){ View view = ((ViewGroup) rootView).getChildAt(0); ViewGroup.LayoutParams params = view.getLayoutParams(); int top = view.getPaddingTop(); view.setPadding(0,0,0,0); params.height = params.height-top-offset; } } }
true
59eab83d15cb8c6a7e1b4c3d04f56a41b6addbc1
Java
frankielc/spring-boot-vue-template
/src/main/java/org/frankie/vue/Application.java
UTF-8
1,336
2.265625
2
[ "MIT" ]
permissive
package org.frankie.vue; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileTime; import java.time.Instant; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public CommandLineRunner commandLineRunner(@SuppressWarnings("unused") ApplicationContext ctx) { // reload trigger is updated on spring-changes, only serves the purpose of // letting browser-sync know something changed and auto-refresh browsers try { Path path = Paths.get("reload-trigger"); if (Files.exists(path)) { Files.setLastModifiedTime(path, FileTime.from(Instant.now())); } else { Files.createFile(path); } } catch (IOException e) { e.printStackTrace(); } return args -> System.out.println("Hello all from Spring boot!"); } }
true
0fa4d46fedf24920d72b1ff339b17fccd26e3515
Java
BlueCodeSystems/opensrp-server
/opensrp-core/src/main/java/org/opensrp/repository/BaseRepository.java
UTF-8
219
1.976563
2
[ "Apache-2.0" ]
permissive
package org.opensrp.repository; import java.util.List; public interface BaseRepository<T> { T get(String id); void add(T entity); void update(T entity); List<T> getAll(); void safeRemove(T entity); }
true
8d6e54493548afad28a4fbba47a68ec749d51cd8
Java
zhongxingyu/Seer
/Diff-Raw-Data/11/11_1b202fb956f86d6100d5e11344f7e5ceaaf8f07d/KernelTest/11_1b202fb956f86d6100d5e11344f7e5ceaaf8f07d_KernelTest_t.java
UTF-8
13,685
1.859375
2
[]
no_license
/** * */ package org.nuunframework.kernel; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; import org.fest.assertions.Fail; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.nuunframework.kernel.context.ContextInternal; import org.nuunframework.kernel.plugin.dummy1.Bean6; import org.nuunframework.kernel.plugin.dummy1.Bean9; import org.nuunframework.kernel.plugin.dummy1.BeanWithCustomSuffix; import org.nuunframework.kernel.plugin.dummy1.BeanWithParentType; import org.nuunframework.kernel.plugin.dummy1.DummyMarker; import org.nuunframework.kernel.plugin.dummy1.MarkerSample4; import org.nuunframework.kernel.plugin.dummy1.ParentClassWithCustomSuffix; import org.nuunframework.kernel.plugin.dummy1.ParentInterfaceWithCustomSuffix; import org.nuunframework.kernel.plugin.dummy23.DummyPlugin2; import org.nuunframework.kernel.plugin.dummy23.DummyPlugin3; import org.nuunframework.kernel.plugin.dummy4.DummyPlugin4; import org.nuunframework.kernel.plugin.dummy4.Pojo1; import org.nuunframework.kernel.plugin.dummy4.Pojo2; import org.nuunframework.kernel.sample.Holder; import org.nuunframework.kernel.sample.HolderForBeanWithParentType; import org.nuunframework.kernel.sample.HolderForContext; import org.nuunframework.kernel.sample.HolderForInterface; import org.nuunframework.kernel.sample.HolderForPlugin; import org.nuunframework.kernel.sample.HolderForPrefixWithName; import org.nuunframework.kernel.sample.ModuleInError; import org.nuunframework.kernel.sample.ModuleInterface; import org.nuunframework.kernel.scanner.sample.Ignore; import com.google.inject.AbstractModule; import com.google.inject.ConfigurationException; import com.google.inject.CreationException; import com.google.inject.Injector; import com.google.inject.Module; /** * @author Epo Jemba * */ public class KernelTest { Injector injector; static Kernel underTest; static DummyPlugin4 plugin4 = new DummyPlugin4(); @SuppressWarnings("unchecked") @BeforeClass public static void init() { underTest = Kernel.createKernel("dummy.plugin1", "WAZAAAA").build(); try { underTest.init(); assertThat(true).as("Should Get a Kernel Exeption for dependency problem").isFalse(); } catch (KernelException ke) { assertThat(ke.getMessage()).isEqualTo("plugin dummyPlugin misses the following plugin/s as dependency/ies [class org.nuunframework.kernel.plugin.dummy23.DummyPlugin2]"); underTest.addPlugins( DummyPlugin2.class); try { underTest.init(); assertThat(true).as("Should Get a Kernel Exeption for dependency problem").isFalse(); } catch (KernelException ke2) { assertThat(ke2.getMessage()).isEqualTo("plugin dummyPlugin2 misses the following plugin/s as dependency/ies [class org.nuunframework.kernel.plugin.dummy23.DummyPlugin3]"); underTest.addPlugins( DummyPlugin3.class); underTest.addPlugins( plugin4); underTest.init(); } } underTest.start(); } @Before public void before() { Module aggregationModule = new AbstractModule() { @Override protected void configure() { bind(Holder.class); bind(HolderForPlugin.class); bind(HolderForContext.class); bind(HolderForPrefixWithName.class); bind(HolderForBeanWithParentType.class); } }; injector = underTest.getMainInjector().createChildInjector(aggregationModule); } @Test public void logger_should_be_injected() { Holder holder = injector.getInstance(Holder.class); assertThat(holder.getLogger()).isNotNull(); holder.getLogger().error("MESSAGE FROM LOGGER."); } @Test public void logger_should_be_injected_with_metaannotation() { Holder holder = injector.getInstance(Holder.class); assertThat(holder.getLogger2()).isNotNull(); holder.getLogger().error("MESSAGE FROM LOGGER2."); } @Test public void plugin_shoud_be_detected() { HolderForPlugin holder = injector.getInstance(HolderForPlugin.class); assertThat(holder.value).isNotNull(); assertThat(holder.value).isEqualTo("lorem ipsum"); assertThat(holder.dummyService).isNotNull(); assertThat(holder.dummyService.dummy()).isEqualTo("dummyserviceinternal"); assertThat(holder.bean6).isNotNull(); assertThat(holder.bean6.sayHi()).isEqualTo("dummyserviceinternal2"); assertThat(holder.bean9).isNotNull(); assertThat(holder.bean9.value).isEqualTo("lorem ipsum"); } @Test(expected = CreationException.class) public void plugin_shoud_be_detected_error_case() { // Bean7 is not bound to the env because of @Ignore injector.createChildInjector(new ModuleInError()); } @Test public void injector_should_retrieve_context() { HolderForContext holder = injector.getInstance(HolderForContext.class); assertThat(holder.context).isNotNull(); assertThat(holder.context instanceof ContextInternal).isTrue(); ContextInternal contextInternal = (ContextInternal) holder.context; assertThat(contextInternal.mainInjector).isNotNull(); assertThat(holder.context.getClassAnnotatedWith(MarkerSample4.class)).isNotEmpty(); assertThat(holder.context.getClassAnnotatedWith(MarkerSample4.class)).hasSize(1); assertThat(holder.context.getClassAnnotatedWith(MarkerSample4.class)).containsOnly(Bean6.class); // TODO : faire pareil que pour les scans rechecher par regex assertThat(holder.context.getClassAnnotatedWithRegex(".*MarkerSample3")).isNotEmpty(); assertThat(holder.context.getClassAnnotatedWithRegex(".*MarkerSample3")).hasSize(1); assertThat(holder.context.getClassAnnotatedWithRegex(".*MarkerSample3")).containsOnly(Bean9.class); // TODO : aussi rajouter parent type by regex assertThat(holder.context.getClassWithParentType(DummyMarker.class)).isNotEmpty(); assertThat(holder.context.getClassWithParentType(DummyMarker.class)).hasSize(1); assertThat(holder.context.getClassWithParentType(DummyMarker.class)).containsOnly(BeanWithParentType.class); // TODO : faire pareil que pour les scans rechecher par regex assertThat(holder.context.getClassTypeByRegex(".*WithCustomSuffix")).isNotEmpty(); assertThat(holder.context.getClassTypeByRegex(".*WithCustomSuffix")).hasSize(3); // was 2 assertThat(holder.context.getClassTypeByRegex(".*WithCustomSuffix")).containsOnly(BeanWithCustomSuffix.class, ParentClassWithCustomSuffix.class, ParentInterfaceWithCustomSuffix.class); } @Test public void classpath_scan_by_specification_should_work() { assertThat(plugin4.collection).isNotNull(); assertThat(plugin4.collection).isNotEmpty(); assertThat(plugin4.collection).hasSize(1); assertThat(plugin4.collection).containsOnly(Pojo1.class); } @Test public void binding_by_specification_should_work () { assertThat( injector.getInstance(Pojo2.class) ).isNotNull(); // we check for the scope assertThat(injector.getInstance(Pojo2.class)).isEqualTo(injector.getInstance(Pojo2.class)); try { assertThat( injector.getInstance(Pojo1.class) ).isNull(); fail("Pojo1 should not be injector"); } catch (ConfigurationException ce) { String nl = System.getProperty("line.separator"); assertThat(ce.getMessage()).isEqualTo("Guice configuration errors:"+nl +nl +"1) Explicit bindings are required and org.nuunframework.kernel.plugin.dummy4.Pojo1 is not explicitly bound."+nl + " while locating org.nuunframework.kernel.plugin.dummy4.Pojo1"+nl +nl +"1 error" ); } } @Test public void bean_should_be_bind_by_name() { HolderForPrefixWithName holder = injector.getInstance(HolderForPrefixWithName.class); assertThat(holder.customBean).isNotNull(); assertThat(holder.customBean.name()).isNotNull(); assertThat(holder.customBean.name()).isEqualTo("I am John"); } @Test public void bean_should_be_bind_by_parent_type() { HolderForBeanWithParentType holder = injector.getInstance(HolderForBeanWithParentType.class); assertThat(holder.beanWithParentType).isNotNull(); assertThat(holder.beanWithParentType.name()).isNotNull(); assertThat(holder.beanWithParentType.name()).isEqualTo("I am Jane"); } @Test public void interface_can_be_injected_without_instance_if_declared_nullable() { Injector createChildInjector = injector.createChildInjector(new ModuleInterface()); HolderForInterface holder = createChildInjector.getInstance(HolderForInterface.class); assertThat(holder.customBean).isNull(); } @Test public void property_should_be_reachable_via_annotation() { Holder holder = injector.getInstance(Holder.class); assertThat(holder.user).isNotNull(); assertThat(holder.user).isEqualTo("ejemba"); assertThat(holder.id).isNotNull(); assertThat(holder.id).isEqualTo(123l); assertThat(holder.password).isNotNull(); assertThat(holder.password).isEqualTo("mypassword"); assertThat(holder._int).isNotNull(); assertThat(holder._int).isEqualTo(1); assertThat(holder._Integer).isNotNull(); assertThat(holder._Integer).isEqualTo(1); assertThat(holder.__Integer).isNotNull(); assertThat(holder.__Integer).isEqualTo("1"); assertThat(holder._long).isNotNull(); assertThat(holder._long).isEqualTo(2); assertThat(holder._Long).isNotNull(); assertThat(holder._Long).isEqualTo(2); assertThat(holder.__Long).isNotNull(); assertThat(holder.__Long).isEqualTo("2"); assertThat(holder._short).isNotNull(); assertThat(holder._short).isEqualTo((short) 3); assertThat(holder._Short).isNotNull(); assertThat(holder._Short).isEqualTo((short) 3); assertThat(holder.__Short).isNotNull(); assertThat(holder.__Short).isEqualTo("3"); assertThat(holder._byte).isNotNull(); assertThat(holder._byte).isEqualTo((byte) 4); assertThat(holder._Byte).isNotNull(); assertThat(holder._Byte).isEqualTo((byte) 4); assertThat(holder.__Byte).isNotNull(); assertThat(holder.__Byte).isEqualTo("4"); assertThat(holder._float).isNotNull(); assertThat(holder._float).isEqualTo(5.5f); assertThat(holder._Float).isNotNull(); assertThat(holder._Float).isEqualTo(5.5f); assertThat(holder.__Float).isNotNull(); assertThat(holder.__Float).isEqualTo("5.5"); assertThat(holder._double).isNotNull(); assertThat(holder._double).isEqualTo(6.6d); assertThat(holder._Double).isNotNull(); assertThat(holder._Double).isEqualTo(6.6d); assertThat(holder.__Double).isNotNull(); assertThat(holder.__Double).isEqualTo("6.6"); assertThat(holder._char).isNotNull(); assertThat(holder._char).isEqualTo('g'); assertThat(holder._Character).isNotNull(); assertThat(holder._Character).isEqualTo('g'); assertThat(holder.__Character).isNotNull(); assertThat(holder.__Character).isEqualTo("g"); assertThat(holder._booleanTrue).isNotNull(); assertThat(holder._booleanTrue).isEqualTo(true); assertThat(holder._BooleanTrue).isNotNull(); assertThat(holder._BooleanTrue).isEqualTo(true); assertThat(holder._BooleanTrue).isNotNull(); assertThat(holder.__BooleanTrue).isEqualTo("true"); assertThat(holder._booleanFalse).isNotNull(); assertThat(holder._booleanFalse).isEqualTo(false); assertThat(holder._BooleanFalse).isNotNull(); assertThat(holder._BooleanFalse).isEqualTo(false); assertThat(holder._BooleanFalse).isNotNull(); assertThat(holder.__BooleanFalse).isEqualTo("false"); // use of converter assertThat(holder.__special).isNotNull(); assertThat(holder.__special.content ).hasSize(7); assertThat(holder.__special.content ).containsOnly("epo" , "jemba", "the" , "master" , "of" , "the" , "universe"); assertThat(holder.__nothing).isNotNull(); assertThat(holder.__nothing).isEqualTo(""); } @AfterClass public static void clear() { underTest.stop(); } }
true
1b44f5bba721b43ce52659ef8a45104306021bfe
Java
vectronromania/skystone
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/hardware/Robot.java
UTF-8
1,410
2.0625
2
[ "BSD-3-Clause" ]
permissive
package org.firstinspires.ftc.teamcode.hardware; import com.qualcomm.robotcore.hardware.HardwareMap; import org.firstinspires.ftc.robotcore.internal.android.dx.ssa.LiteralOpUpgrader; import org.firstinspires.ftc.teamcode.systems.Arm; import org.firstinspires.ftc.teamcode.systems.Drivetrain; import org.firstinspires.ftc.teamcode.systems.Foundation; import org.firstinspires.ftc.teamcode.systems.Intake; import org.firstinspires.ftc.teamcode.systems.Lift; import org.firstinspires.ftc.teamcode.systems.Outtake; public class Robot { public Drivetrain drivetrain = new Drivetrain(); public Drivetrain.Autodrivetrain autodrivetrain = new Drivetrain.Autodrivetrain(); public Foundation foundation = new Foundation(); public Intake intake = new Intake(); public Lift lift = new Lift(); public Outtake outtake = new Outtake(); public Arm arm = new Arm(); public void initialize(HardwareMap hardwareMap) { drivetrain.getHardwareMap(hardwareMap); drivetrain.setDirections(); foundation.getHardwareMap(hardwareMap); foundation.setDirection(); intake.getHardwareMap(hardwareMap); intake.setDirections(); lift.getHardwareMap(hardwareMap); lift.setDirection(); outtake.getHardwareMap(hardwareMap); outtake.setDirection(); arm.getHardwareMap(hardwareMap); arm.setDirection(); } }
true
5e188d7a0a04ed81b7b433fde4eb6b3c073d493a
Java
kishoreccaus/QsuperMavenArchetype
/src/test/java/com/TestMavenArchetype/FirstModule/Day1.java
UTF-8
1,910
2.375
2
[]
no_license
package com.TestMavenArchetype.FirstModule; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.Test; //import com.TestMavenArchetype.PageObjects.HomePage; import com.TestMavenArchetype.lib.*; import com.TestMavenArchetype.PageObjects.HomePage; public class Day1 extends Archetype_SuperTestng{ String Class_Name = this.getClass().getName(); @Test(testName="FirstTest") public void Day1Test() throws InterruptedException, IOException{ //Declaring the Page Objects HomePage CHP = PageFactory.initElements(driver, HomePage.class); List<String> Displayed_Names = new ArrayList<String>(); List<String> Sorted_Names = new ArrayList<String>(); System.out.println("Launched the driver"); Assert.assertEquals(driver.getTitle(), "Home page"); //System.out.println("Verified the Assert"); CHP.getMobileLink().click(); Assert.assertEquals(driver.getTitle(), "Mobile"); //CHP.getSortByDropdown().sendKeys("Name"); CHP.SortBy_DropDown("Name"); Thread.sleep(2000); List<WebElement> Actual_List =driver.findElements(By.xpath("//h2[@class='product-name']/a")); for(int i =0;i<Actual_List.size();i++){ //Displayed_Names.add(i, Actual_List.get(i).getText()); Displayed_Names.add(Actual_List.get(i).getText()); Sorted_Names.add(Actual_List.get(i).getText()); } Collections.sort(Sorted_Names); Assert.assertEquals(Displayed_Names,Sorted_Names); if (Displayed_Names.equals(Sorted_Names)) { final String failedMsg ="Customer Names are in sorted order."; System.out.println(failedMsg); Archetype_SuperTestng.KG1.captureSS(driver, Class_Name+" - SortedScreenshot"); } KG1.enterLog("Completed the Day-1 Script"); } }
true
5a374603ce34a4139c4baf76780552a734ff924a
Java
ZhuolunZhou/Data-Strctures-and-Algorithms-in-Java
/DFS/src/laiOffer/AllFactors.java
UTF-8
1,573
2.96875
3
[]
no_license
package laiOffer; import java.util.*; public class AllFactors { public List<List<Integer>> combinations(int target) { List<List<Integer>> result = new ArrayList<>(); if (target <= 1) { return result; } List<Integer> factors = findFactors(target); Collections.sort(factors); List<Integer> cur = new ArrayList<>(); DFS(factors, 1, target, 0, cur, result); return result; } private void DFS(List<Integer> factors, int curProduct, int target, int index, List<Integer> cur, List<List<Integer>> result) { if (curProduct == target) { result.add(new ArrayList<Integer>(cur)); return; } if (index == factors.size()) { return; } int factor = factors.get(index); int product = curProduct; int idx = index; // not counting current number DFS(factors, curProduct, target, index + 1, cur, result); int i = 0; while (product <= target) { product *= factor; i++; for (int j = 0; j < i; j++) { cur.add(factor); } DFS(factors, product, target, index + 1, cur, result); for (int j = 0; j < i; j++) { cur.remove(cur.size() - 1); } } } private List<Integer> findFactors(int target) { List<Integer> result = new ArrayList<>(); for (int i = 2; i * i <= target; i++) { if (target % i == 0) { if (i * i != target) { result.add(i); } result.add(target / i); } } return result; } }
true
3bc5c8507c2d6edf69e31ae22fc8fb150f734f2e
Java
kbsaxena/Shopping
/src/main/java/com/shopping/controllers/RegisterController.java
UTF-8
2,809
2.40625
2
[]
no_license
package com.shopping.controllers; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import com.shopping.dto.UserDTO; import com.shopping.entities.Customer; import com.shopping.entities.Phone; import com.shopping.entities.User; import com.shopping.entities.UserState; import com.shopping.exceptions.InvalidDetailsException; import com.shopping.services.RegisterService; @Controller @CrossOrigin(origins = "http://localhost:4200") public class RegisterController { @Autowired private RegisterService registerService; @PostMapping(path = "/register") @ResponseBody public User register(@RequestBody UserDTO user) { if (isValidUser(user)) { Phone phone = new Phone(); phone.setCountryCode(user.getCountryCode()); phone.setMobileNumber(user.getMobileNumber()); Customer customer = new Customer(); customer.setFullName(user.getFullname()); customer.setEmail(user.getEmail()); customer.setDob(user.getDob()); customer.setPrimaryPhoneNumber(phone); User userObj = new User(); userObj.setCustomer(customer); userObj.setUsername(user.getUsername()); userObj.setPassword(user.getPassword()); userObj.setUserState(UserState.NEW); registerService.save(userObj); registerService.sendValidationLink(userObj); return userObj; } else { throw new InvalidDetailsException("provide valid details..!!!"); } } @PostMapping(path = "/validate-user") @ResponseBody public boolean validateUser(@RequestBody Long id) { boolean isValidated = false; if (id != null) { isValidated = registerService.updateUserStatus(id); } return isValidated; } @PostMapping(path = "/resend-validation-link") @ResponseBody public boolean resendValidationLink(@RequestBody String email) { boolean isSent = false; if (StringUtils.isNotBlank(email)) { isSent = registerService.resendValidationLinkUsingEmail(email); } return isSent; } private boolean isValidUser(UserDTO user) { boolean isValid = false; if (user != null && StringUtils.isNotBlank(user.getUsername()) && StringUtils.isNotBlank(user.getPassword()) && StringUtils.isNotBlank(user.getFullname()) && StringUtils.isNotBlank(user.getEmail()) && StringUtils.isNotBlank(user.getCountryCode()) && StringUtils.isNotBlank(user.getMobileNumber())) { isValid = true; } return isValid; } }
true
55b32b11c67453d24231aa923d63e84d04dd8674
Java
kaushikam/aspect
/src/main/java/com/kaushikam/aspect/HelloWorldAspect.java
UTF-8
302
2.15625
2
[]
no_license
package com.kaushikam.aspect; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; @Aspect public class HelloWorldAspect { @After("execution(* com.kaushikam.aspect.HelloWorld.sayHello(..))") public void hello() { System.out.println(" World!"); } }
true
ad7cb56560de2fd600a4cfabc7bcb5adb82c5952
Java
JeffJiang42/QuizApp
/app/src/main/java/com/example/jeffrey/quizapp_lesson1/ResultActivity.java
UTF-8
1,083
2.28125
2
[]
no_license
package com.example.jeffrey.quizapp_lesson1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.Arrays; public class ResultActivity extends AppCompatActivity { private ListView listView; private ArrayAdapter<String> listViewAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); listView = (ListView) findViewById(R.id.result_list_view); Intent i = getIntent(); if (i != null) { ArrayList<String> result = i.getStringArrayListExtra("results"); System.out.println(result); //Log.d("Debug arraylist",result.get(0)); listViewAdapter = new ArrayAdapter<>(this, R.layout.result_list_item, R.id.result_text_view, result); listView.setAdapter(listViewAdapter); } } }
true
26e6dee8a39edd8cfd4b82f79640098cc4455f22
Java
17302550114/Body
/app/src/main/java/com/example/smartfarming/MainActivity.java
UTF-8
11,207
2.15625
2
[]
no_license
package com.example.smartfarming; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; import com.google.gson.Gson; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.crypto.AEADBadTagException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private static final String DEVICEID = "598768194"; private static final String APIKEY = "ccOaQkJydurl7Frt0=jjvCbtrpM="; private static final String Turbidity01 = "tur01";//数据流名称 private static final String Water_Height = "water_height";//数据流名称 private float result = 0; private EditText mEditTur01; private EditText mEditWaterHeight_01; private Button mBtnGetData; private EditText mNode01Loss; //图表控件 private EchartView lineChart; //数据实时获取开关 private Switch mSwitchOntime; //实时获取数据线程对象 private Thread mThreadAutoData; //传感器值 public ArrayList<String> mTimeBuffer = new ArrayList<>(); public ArrayList<String> mTur01ValueBuffer = new ArrayList<>(); public ArrayList<String> mWaterHeightValueBuffer = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); event(); } public void event() { //ArrayList初始化; for(int k=0;k<7;k++) { mTur01ValueBuffer.add("0"); mTimeBuffer.add("0"); } //echart图表控件 lineChart.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); //最好在h5页面加载完毕后再加载数据,防止html的标签还未加载完成,不能正常显示 Object[] x = new Object[]{ "0", "1", "2", "3", "4", "5", "6" }; Object[] y = new Object[]{ 0, 0, 0, 0, 0, 0, 0 }; lineChart.refreshEchartsWithOption(EchartOptionUtil.getLineChartOptions(x, y)); } }); //获取实时数据开关 mSwitchOntime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mBtnGetData.setEnabled(false); startAutoData(); } else { mBtnGetData.setEnabled(true); stopAutoData(); } } }); //获取数据按钮(单次) mBtnGetData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Get(DEVICEID,Turbidity01,APIKEY); } }); } /** * 封装获取数据函数 * 1.发送请求 * 2.解析响应 * 3.数据存储 * 4.绘制表格 * */ // // public void GetData() // { // parseJSONWithGSON(Get(DEVICEID,Turbidity01,APIKEY)); // } /** * 使用okHttp从oneNet平台获取响应 * 参数列表 * 1.String datastream_id :数据流名称 * 返回值: 返回网页响应,供Gjson进行解析 */ public void Get(String deviceID, String dataStreamId, String apiKey) { new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request_tur = new Request.Builder().url("http://api.heclouds.com/devices/" + deviceID + "/datapoints?datastream_id=" + Turbidity01).header("api-key", apiKey).build(); Request request_wh = new Request.Builder().url("http://api.heclouds.com/devices/" + deviceID + "/datapoints?datastream_id=" + Water_Height).header("api-key", apiKey).build(); Response response_tur = client.newCall(request_tur).execute(); Response response_wh = client.newCall(request_wh).execute(); String responseDataTur = response_tur.body().string(); String responseDataWh = response_wh.body().string(); System.out.println(responseDataTur); parseJSONWithGSON(responseDataTur); parseJSONWithGSON_wh(responseDataWh); // float result = 0; // result += Float.parseFloat(mEditTur01.getText().toString()) * Float.parseFloat(mEditWaterHeight_01.getText().toString()); // mNode01Loss.setText(String.valueOf(result)); } catch (IOException e) { e.printStackTrace(); } } }).start(); } /** * 解析网页响应,返回传感器数值 * @param responseData:网页响应 * @return :返回解析结果——传感器值 */ private void parseJSONWithGSON(String responseData) { JsonRootBean app = new Gson().fromJson(responseData, JsonRootBean.class); List<Datastreams> streams = app.getData().getDatastreams(); List<Datapoints> points = streams.get(0).getDatapoints(); System.out.println("数据点大小为:" + points.size()); int count = app.getData().getCount();//获取数据的数量 for (int i = 0; i < points.size(); i++) { String mTur01Time = points.get(i).getAt().substring(11,19); String mTur01Value = points.get(i).getValue(); System.out.println(mTur01Time); System.out.println(mTur01Value); mTimeBuffer.add(0,mTur01Time); mTur01ValueBuffer.add(0,mTur01Value); System.out.println(mTimeBuffer.toString()); System.out.println(mTur01ValueBuffer.toString()); Object[] x = new Object[7]; Object[] y = new Object[7]; for (int j=0;j<x.length;j++) { x[x.length-1-j] = new String(mTimeBuffer.get(j)); y[x.length-1-j] = new String(mTur01ValueBuffer.get(j)); } runOnUiThread(new Runnable() { @Override public void run() { mEditTur01.setText(mTur01Value); lineChart.refreshEchartsWithOption(EchartOptionUtil.getLineChartOptions(x, y)); } }); } } /** * 解析网页响应,返回传感器数值 液位高度 * @param responseData:网页响应 * @return :返回解析结果——传感器值。。液位 */ private void parseJSONWithGSON_wh(String responseData) { JsonRootBean app = new Gson().fromJson(responseData, JsonRootBean.class); List<Datastreams> streams = app.getData().getDatastreams(); List<Datapoints> points = streams.get(0).getDatapoints(); System.out.println("数据点大小为:" + points.size()); int count = app.getData().getCount();//获取数据的数量 for (int i = 0; i < points.size(); i++) { String mTur01Time = points.get(i).getAt().substring(11,19); String mWhValue = points.get(i).getValue(); // System.out.println(mTur01Time); // System.out.println(mTur01Value); // // mTimeBuffer.add(0,mTur01Time); // mTur01ValueBuffer.add(0,mTur01Value); // System.out.println(mTimeBuffer.toString()); // System.out.println(mTur01ValueBuffer.toString()); // Object[] x = new Object[7]; Object[] y = new Object[7]; for (int j=0;j<x.length;j++) { x[x.length-1-j] = new String(mTimeBuffer.get(j)); y[x.length-1-j] = new String(mTur01ValueBuffer.get(j)); } // DecimalFormat fnum = new DecimalFormat("##0.00"); runOnUiThread(new Runnable() { @Override public void run() { mEditWaterHeight_01.setText(mWhValue); result += 0.1*(Float.parseFloat(mEditTur01.getText().toString()) * (Float.parseFloat(mEditWaterHeight_01.getText().toString())/1000)); // String dd=fnum.format(result); mNode01Loss.setText(String.valueOf(result)); lineChart.refreshEchartsWithOption(EchartOptionUtil.getLineChartOptions(x, y)); } }); } } /** * 绘制图表 * @param arrayListX: 坐标横轴:时间 * @param arrayListY:坐标纵轴:传感器值 */ // private void refreshLineChart(ArrayList<String> arrayListX, ArrayList<String> arrayListY){ // Object[] x = new Object[7]; // Object[] y = new Object[7]; // for (int j=0;j<x.length;j++) // { // x[x.length-1-j] = new String(arrayListX.get(j)); // y[x.length-1-j] = new String(arrayListY.get(j)); // } // lineChart.refreshEchartsWithOption(EchartOptionUtil.getLineChartOptions(x, y)); // } /** * 开始自动获取数据 */ private void startAutoData() { mThreadAutoData = new Thread(new Runnable() { @Override public void run() { while (!Thread.interrupted()) { Get(DEVICEID,Turbidity01,APIKEY); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }); mThreadAutoData.start(); } /** * 关闭自动获取数据 */ private void stopAutoData() { if (mThreadAutoData != null && !mThreadAutoData.isInterrupted()) { mThreadAutoData.interrupt(); } } //控件初始化 private void initView() { mEditTur01 = findViewById(R.id.et_Tur01); mEditWaterHeight_01 = findViewById(R.id.et_WaterHeight01); mBtnGetData = findViewById(R.id.btn_GetData); mNode01Loss = findViewById(R.id.et_node01Loss); // 图表初始化 lineChart = findViewById(R.id.lineChart); //初始化实时数据开关 mSwitchOntime = findViewById(R.id.sw_Ontime); } }
true
4da1ddbe2c8897d516e9d9029687bd056ae6492e
Java
ldj8683/javaBasic
/java2829/src/상속/영화에출연.java
UTF-8
569
3.078125
3
[]
no_license
package 상속; public class 영화에출연 { public static void main(String[] args) { 수퍼맨 sMan = new 수퍼맨(); sMan.name = "클라크"; //사람 sMan.age = 30000; //사람 sMan.speed = 1000; //맨 sMan.fly = true; //수퍼맨 sMan.먹다(); //사람 sMan.달리다(); //맨 sMan.우주를날다(); //수퍼맨 원더우먼 wWoman = new 원더우먼(); wWoman.name = "다이애나"; wWoman.age = 20000; wWoman.speed = 1200; wWoman.fly = true; wWoman.먹다(); wWoman.달리다(); wWoman.우주를날다(); } }
true
175fe94944d7399dcb5d0edcd5ce3d78182630ab
Java
tianyaleixiaowu/jipiao
/src/main/java/com/tianyalei/jipiao/core/manager/MemberBalanceCompanyManager.java
UTF-8
4,093
2.109375
2
[]
no_license
package com.tianyalei.jipiao.core.manager; import com.tianyalei.jipiao.core.model.MMemberBalanceCompanyEntity; import com.tianyalei.jipiao.core.repository.MemberBalanceCompanyRepository; import com.tianyalei.jipiao.core.request.MemberAddRequestModel; import com.tianyalei.jipiao.core.response.MemberBalanceListResponseVO; import com.tianyalei.jipiao.global.bean.SimplePage; import com.xiaoleilu.hutool.util.BeanUtil; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.stream.Collectors; /** * @author wuweifeng wrote on 2018/11/1. */ @Service public class MemberBalanceCompanyManager { @Resource private MemberBalanceCompanyRepository memberBalanceCompanyRepository; @Resource private CompanyManager companyManager; @Resource private MemberBalanceCompanySingleManager memberBalanceCompanySingleManager; @Resource private CompanyTravelLevelManager companyTravelLevelManager; public void addOrUpdate(MMemberBalanceCompanyEntity tempEntity) { MMemberBalanceCompanyEntity entity = memberBalanceCompanyRepository.findFirstByCardNumAndCompanyId (tempEntity.getCardNum(), tempEntity.getCompanyId()); if (entity == null) { entity = new MMemberBalanceCompanyEntity(); BeanUtil.copyProperties(tempEntity, entity); entity.setCompanyName(companyManager.findName(tempEntity.getCompanyId())); entity.setIsEnable(true); memberBalanceCompanySingleManager.add(entity); } else { BeanUtil.copyProperties(tempEntity, entity, "id"); entity.setCompanyName(companyManager.findName(tempEntity.getCompanyId())); memberBalanceCompanySingleManager.update(entity); } } public void addOrUpdate(MemberAddRequestModel memberAddRequestModel) { if (memberAddRequestModel.getTravelLevelId() == null || memberAddRequestModel.getTravelLevelId() == 0) { return; } MMemberBalanceCompanyEntity entity = new MMemberBalanceCompanyEntity(); BeanUtil.copyProperties(memberAddRequestModel, entity); entity.setCompanyName(companyManager.findName(memberAddRequestModel.getCompanyId())); addOrUpdate(entity); } public void delete(Integer id) { memberBalanceCompanyRepository.deleteById(id); } public MemberBalanceListResponseVO find(Integer id) { MMemberBalanceCompanyEntity entity = memberBalanceCompanyRepository.getOne(id); return parse(entity); } public List<MMemberBalanceCompanyEntity> findByCardNum(String cardNum) { return memberBalanceCompanyRepository.findByCardNumOrderByIdDesc (cardNum); } public MMemberBalanceCompanyEntity findByCardNumAndCompanyId(String cardNum, Integer companyId) { return memberBalanceCompanyRepository.findFirstByCardNumAndCompanyId(cardNum, companyId); } public SimplePage<MemberBalanceListResponseVO> list(String cardNum, Pageable pageable) { Page<MMemberBalanceCompanyEntity> page = memberBalanceCompanyRepository .findByCardNumOrderByIdDesc(cardNum, pageable); return new SimplePage<>(page.getTotalPages(), page.getTotalElements(), page.getContent().stream() .map(this::parse).collect(Collectors.toList())); } private MemberBalanceListResponseVO parse(MMemberBalanceCompanyEntity entity) { MemberBalanceListResponseVO vo = new MemberBalanceListResponseVO(); BeanUtil.copyProperties(entity, vo); vo.setTravelLevelName(companyTravelLevelManager.find(entity.getTravelLevelId()).getLevelName()); return vo; } public void updateEnable(String cardNum,Byte is){ List<MMemberBalanceCompanyEntity> list = findByCardNum(cardNum); if(list == null || list.size() == 0){ return; } memberBalanceCompanyRepository.updateIsEnable(cardNum,is); } }
true
0a7b4340a3cff35626cde14c9c375a2cf068dce9
Java
puck-ini/group3
/src/main/java/com/group3/group3/service/StudentScholarshipService.java
UTF-8
506
2
2
[]
no_license
package com.group3.group3.service; import com.group3.group3.entity.StudentScholarship; import java.util.List; public interface StudentScholarshipService { List<StudentScholarship> getStudentScholarship(Integer uid,Integer ssid); StudentScholarship insertStuScholarship(StudentScholarship studentScholarship); void deleteStuScholarship(Integer uid,Integer ssid); StudentScholarship updateStuScholarship(StudentScholarship studentScholarship); List<StudentScholarship> getAll(); }
true
fbb23248d3f0581b664b338d6acc2dcb4623846d
Java
zengyh/CodeLibary
/src/utils/MacUtils.java
UTF-8
1,349
2.671875
3
[]
no_license
package utils; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; /** * 文件名称: MacUtils.java * 编写人: yh.zeng * 编写时间: 13-11-5 * 文件描述: 获取MAC地址工具类 */ public class MacUtils { /** 取得日志记录器Logger */ public static Logger logger = Logger.getLogger(MacUtils.class); /** * 获取MAC地址 * @param request * @return */ public static String getMac(HttpServletRequest request) { String macAddress = ""; if (request.getHeader("x-forwarded-for") == null) { String ip = request.getRemoteAddr(); String str = ""; Process p; try { p = Runtime.getRuntime().exec("nbtstat -A " + ip); InputStreamReader ir = new InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); for (int i = 1; i < 100; i++) { str = input.readLine(); if (str != null) { if (str.indexOf("MAC Address") > 1) { macAddress = str.substring( str.indexOf("MAC Address") + 14, str.length()); break; } } } } catch (IOException e) { // TODO Auto-generated catch block logger.error("执行MacUtils类的getMac方法出错!"); } } return macAddress; } }
true
9acd71d3bb37cc1f0ccac600f4c0ae22afa66269
Java
Myzenvei/Docs
/custom/gpcommerce/gpcommercefacades/testsrc/com/gp/commerce/facades/wishlist/WishlistEntryBuilder.java
UTF-8
709
2.1875
2
[]
no_license
package com.gp.commerce.facades.wishlist; import de.hybris.platform.core.model.product.ProductModel; import de.hybris.platform.wishlist2.model.Wishlist2EntryModel; /** * Builder class to be used in WishlistEntry test data preparation * @author megverma * */ public class WishlistEntryBuilder { Wishlist2EntryModel entry = new Wishlist2EntryModel(); public WishlistEntryBuilder withProduct(ProductModel product) { this.entry.setProduct(product); return this; } public WishlistEntryBuilder withQuantity(Long quantity) { this.entry.setQuantity(quantity); return this; } public Wishlist2EntryModel build() { return entry; } }
true
d2bd345e82db7b97bcf82ca0de6288c337cf3484
Java
carlos-alexandrebp/objtos-figuras
/src/figura/Figura3D.java
UTF-8
585
2.453125
2
[]
no_license
package figura; public class Figura3D extends FigurasGeometricas{ private Double volume; private Double areaSuperficial; private Double perimetro; public Double getPerimetro() { return perimetro; } public void setPerimetro(Double perimetro) { this.perimetro = perimetro; } public Double getAreaSuperficial() { return areaSuperficial; } public void setAreaSuperficial(Double areaSuperficial) { this.areaSuperficial = areaSuperficial; } public Double getVolume() { return volume; } public void setVolume(Double volume) { this.volume = volume; } }
true
09dc3ccd54f885645e2f79b09741805ea29258ce
Java
vandersonmarocchio/trabalhos-2
/pss/RBC/src/main/java/rbc/gerenciadores/gerenciador_estoque/EstoqueDAO.java
UTF-8
1,034
2.484375
2
[]
no_license
package rbc.gerenciadores.gerenciador_estoque; import org.hibernate.Session; import rbc.infraestrutura.DataController; import java.util.ArrayList; import java.util.List; /** * Created by luis on 08/06/17. */ public class EstoqueDAO extends DataController { @Override public void addDatabase(Object o) throws Exception { super.addDatabase(o); } public void delete(Object o) throws Exception { super.delete(o); } public void update(Object o) throws Exception{ super.update(o); } public static List<Estoque> getEstoque() { List<Estoque> estoque; try (Session sessao = DataController.getSession().openSession()) { estoque = fromList(sessao.createQuery("from Estoque ").getResultList()); } return estoque; } static private List<Estoque> fromList(List list){ List<Estoque> estoque = new ArrayList<>(); for(Object o : list){ estoque.add((Estoque) o); } return estoque; } }
true
06b3c1d32b7f8c443768c883cdb0207f0bc7ae01
Java
LenivDmitry/epam-project-first-level
/src/main/java/com/epam/elearn/java_collections/mainTask/RunnerMainTask.java
UTF-8
647
2.59375
3
[]
no_license
package com.epam.elearn.java_collections.mainTask; import com.epam.elearn.java_collections.mainTask.entity.Gift; public class RunnerMainTask { public static void main(String[] args) { Gift gift = new Gift("Sugar boom"); gift.setGiftContent(gift.getGiftServiceImpl().addCandies(gift.getGiftContent())); gift.setGiftContent(gift.getGiftServiceImpl().addChocolate(gift.getGiftContent())); gift.setGiftContent(gift.getGiftServiceImpl().addZephyr(gift.getGiftContent())); System.out.println(gift.getGiftServiceImpl() .getSweetnessInGivenSugarDiapason(gift.getGiftContent(),9,20)); } }
true
1f063216c5bf91d625fdbc1417367985627d8339
Java
sgsavu/elusive
/src/game/entities/areas/TrackedScriptedDamageZoneSpawner.java
UTF-8
1,479
2.78125
3
[]
no_license
package game.entities.areas; import game.Level; import game.entities.GameObject; import game.entities.players.Player; import game.graphics.LevelState; import java.awt.*; import java.util.ArrayList; import java.util.LinkedList; import static game.Level.addToAddQueue; import static game.Level.getPlayers; public class TrackedScriptedDamageZoneSpawner extends GameObject { private float speed; private LinkedList<Point>pointz; private int startOffset; private String url; private ArrayList<Area>areasOfEffect; private boolean once=true; public TrackedScriptedDamageZoneSpawner(float x, float y, int width, int height, float speed, LinkedList<Point> points, ArrayList<Area> areasOfEffect, int startOffset, String url) { super(x, y,0, width, height); this.pointz=points; this.speed=speed; this.startOffset=startOffset; this.url=url; this.areasOfEffect=areasOfEffect; } /** * Spawns a single tracking object for each player when the game starts */ public void tick() { if (Level.getLevelState()== LevelState.Starting && once) { for (Player p : getPlayers()) { TrackedScriptedDamageZone trackedScriptedDamageZone = new TrackedScriptedDamageZone(x, y, 0, 0, speed, pointz, startOffset, p,url); for (Area a: areasOfEffect) { trackedScriptedDamageZone.addArea(a); } addToAddQueue(trackedScriptedDamageZone); } once=false; } } @Override public void render(Graphics g, float xOffset, float yOffset) { } }
true
40f4aa1f747c91c00022d867a09c8385407a5388
Java
zhaojl131415/learn-spring-starter
/spring_boot_zhao/spring_boot_autoconfigure/src/main/java/com/zhao/spring/boot/autoconfigure/config/PermissionImportBeanDefinitionRegistrar.java
UTF-8
845
2.140625
2
[]
no_license
package com.zhao.spring.boot.autoconfigure.config; import com.zhao.spring.boot.autoconfigure.entity.Permission; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; public class PermissionImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Permission.class); registry.registerBeanDefinition("permission", rootBeanDefinition); // 注册一个名字叫permission的bean定义 } }
true
118e2b0ea68ccc1ba771999c9d08268c7232c054
Java
bonfersen/Volvo
/SutranClientProject/src/main/java/com/wirelesscar/dynafleet/api/types/ApiDTMAlarmSettingTO.java
UTF-8
3,802
2.171875
2
[]
no_license
package com.wirelesscar.dynafleet.api.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Api_DTMAlarmSettingTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Api_DTMAlarmSettingTO"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="alarmOn" type="{http://wirelesscar.com/dynafleet/api/types}Api_Boolean"/> * &lt;element name="latestSendStatusTime" type="{http://wirelesscar.com/dynafleet/api/types}Api_Date"/> * &lt;element name="sendStatus" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="vehicleId" type="{http://wirelesscar.com/dynafleet/api/types}Api_VehicleId"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Api_DTMAlarmSettingTO", propOrder = { "alarmOn", "latestSendStatusTime", "sendStatus", "vehicleId" }) public class ApiDTMAlarmSettingTO { @XmlElement(required = true, nillable = true) protected ApiBoolean alarmOn; @XmlElement(required = true, nillable = true) protected ApiDate latestSendStatusTime; @XmlElement(required = true, nillable = true) protected String sendStatus; @XmlElement(required = true, nillable = true) protected ApiVehicleId vehicleId; /** * Gets the value of the alarmOn property. * * @return * possible object is * {@link ApiBoolean } * */ public ApiBoolean getAlarmOn() { return alarmOn; } /** * Sets the value of the alarmOn property. * * @param value * allowed object is * {@link ApiBoolean } * */ public void setAlarmOn(ApiBoolean value) { this.alarmOn = value; } /** * Gets the value of the latestSendStatusTime property. * * @return * possible object is * {@link ApiDate } * */ public ApiDate getLatestSendStatusTime() { return latestSendStatusTime; } /** * Sets the value of the latestSendStatusTime property. * * @param value * allowed object is * {@link ApiDate } * */ public void setLatestSendStatusTime(ApiDate value) { this.latestSendStatusTime = value; } /** * Gets the value of the sendStatus property. * * @return * possible object is * {@link String } * */ public String getSendStatus() { return sendStatus; } /** * Sets the value of the sendStatus property. * * @param value * allowed object is * {@link String } * */ public void setSendStatus(String value) { this.sendStatus = value; } /** * Gets the value of the vehicleId property. * * @return * possible object is * {@link ApiVehicleId } * */ public ApiVehicleId getVehicleId() { return vehicleId; } /** * Sets the value of the vehicleId property. * * @param value * allowed object is * {@link ApiVehicleId } * */ public void setVehicleId(ApiVehicleId value) { this.vehicleId = value; } }
true
c8d84361e3c90af379d422a52d1539812bf50057
Java
yjeandavid/IA_Projects
/wumpus/src/main/java/net/kolipass/wworld/agent/AIAgent.java
UTF-8
31,373
2.65625
3
[]
no_license
package main.java.net.kolipass.wworld.agent; import main.java.net.kolipass.gameEngine.Keyboard; import main.java.net.kolipass.wworld.Action; import main.java.net.kolipass.wworld.CaveNode; import main.java.net.kolipass.wworld.PriorityCaveNode; import main.java.net.kolipass.wworld.WumplusEnvironment; import java.awt.*; import java.util.Hashtable; import java.util.PriorityQueue; import java.util.Vector; /** * Created by kolipass on 11.12.13. */ public class AIAgent extends AbstractAgent { private boolean wantsToGoHome = false; private int knownWumpusX = -1; private int knownWumpusY = -1; private double supmuwFriendlyProbability = 0.5; private boolean supmuwFound = false; private boolean supmuwKilled = false; private int knownSupmuwX = -1; private int knownSupmuwY = -1; private boolean wumpusKilled = false; private boolean wumpusFound = false; private AgentBlog agentBlog = null; // we initially know nothing of the wumpus or supmuw's location. private int eastmostStench = -1; private int westmostStench = 12; private int northmostStench = -1; private int southmostStench = 12; private int eastmostMoo = -1; private int westmostMoo = 12; private int northmostMoo = -1; private int southmostMoo = 12; /** * @param agentBlog if null, records not be write */ public AIAgent(AgentBlog agentBlog) { this.agentBlog = agentBlog; } public String move(WumplusEnvironment we) { CaveNode curNode = we.grid.get(new Point(this.x, this.y)); CaveNode nextNode = we.getNextNode(curNode, direction); if (nextNode.hasStench) { if (nextNode.x < westmostStench) westmostStench = nextNode.x; if (nextNode.x > eastmostStench) eastmostStench = nextNode.x; if (nextNode.y < southmostStench) southmostStench = nextNode.y; if (nextNode.y > northmostStench) northmostStench = nextNode.y; } if (nextNode.hasMoo) { if (nextNode.x < westmostMoo) westmostMoo = nextNode.x; if (nextNode.x > eastmostMoo) eastmostMoo = nextNode.x; if (nextNode.y < southmostMoo) southmostMoo = nextNode.y; if (nextNode.y > northmostMoo) northmostMoo = nextNode.y; } return super.move(we); } private void addNewNote(String note) { if (agentBlog != null) agentBlog.note(note); } @Override public int getNextAction(WumplusEnvironment we, Keyboard keyboard) { { CaveNode curNode = we.grid.get(new Point(this.x, this.y)); addNewNote("My curNode: " + curNode.toShortString()); // use the agent's knowledge to attempt to deduce pit locations. this.checkAllForPits(we); // use the agent's knowledge to attempt to deduce the wumpus's location //if(!this.wumpusFound) this.checkAllForWumpus(we); // use the agent's knowledge to attempt to deduce the supmuw's location this.checkAllForSupmuw(we); // if the agent has deduced the wumpus's location, it will shoot it if it is convenient to do so. if (this.hasArrow && projectArrowShot(we)) { addNewNote("I has arrow and i shot."); return Action.SHOOT; } // go home if both gold and food were found. if (this.hasGold && this.hasFood) { addNewNote("I has gold and i has food, i go home."); this.wantsToGoHome = true; } // go home if have gold and supmuw has been deduced to be unfriendly. if (this.hasGold && this.supmuwFriendlyProbability == 0.0) { addNewNote("I has gold and Supmuw not Friendly, i go home."); this.wantsToGoHome = true; } // if we are in a square that has gold, grab the gold! if (curNode.hasGold) { addNewNote("curNode has gold and i grab the gold."); return Action.GRAB; } // if the agent wants to leave and is at entrance, climb out! if (this.wantsToGoHome && this.x == 1 && this.y == 1) { addNewNote("I wants to leave and I am at entrance, climb out!"); return Action.CLIMB; } // use A* search to visit reasonably safe unvisited nodes. char goDirection = 'I'; if (!this.wantsToGoHome) { if (!this.hasFood && supmuwFriendlyProbability == 1.0 && this.supmuwFound) { addNewNote("I not have food, supmuw is friendly and i found Supmuw. I go to Supmuw:(" + knownSupmuwX + "," + knownSupmuwY + ")"); goDirection = this.shortestSafePathToPoint(we, new Point(knownSupmuwX, knownSupmuwY)); } else { addNewNote(" I go to shortest Safe Path To Unvisited"); goDirection = this.shortestSafePathToUnvisited(we); } } // if the A* becomes too scared to try any more unvisited nodes, then it will head back to the entrance. if (goDirection == 'I') { addNewNote("goDirection is IDLE. I go home"); this.wantsToGoHome = true; goDirection = shortestSafePathToPoint(we, new Point(1, 1)); } addNewNote("My direction is: " + goDirection); if (goDirection == this.direction) { addNewNote("New and last directions equals. I go forward."); return Action.GOFORWARD; } else if (goDirection == getLeftDirection(this.direction)) { addNewNote("I turn left."); return Action.TURN_LEFT; } else if (goDirection == getRightDirection(this.direction) || goDirection == getBackDirection(this.direction)) { addNewNote("I turn right."); return Action.TURN_RIGHT; } addNewNote("My action is idle."); return Action.IDLE; } } /** * The agent checks if arrow would hit a known wall, known unfriendly supmuw, or known wumpus. Returns true if yes. */ private boolean projectArrowShot(WumplusEnvironment we) { Hashtable<Point, CaveNode> grid = we.grid; CaveNode target = grid.get(new Point(this.x, this.y)); //log.d("Wumpus deduced point: " + knownWumpusX + "," + knownWumpusY); //log.d("Supmuw deduced point: " + knownSupmuwX + "," + knownSupmuwY); while (true) { //log.d(target.x + " , " + target.y); if (target.x == this.knownWumpusX && target.y == this.knownWumpusY) { addNewNote("shoot the wumpus!"); wumpusKilled = true; return true; } if (target.x == this.knownSupmuwX && target.y == this.knownSupmuwY) { if (this.supmuwFriendlyProbability == 0.0) { addNewNote("shoot the supmuw!"); supmuwKilled = true; return true; } else return false; } if (target.hasObstacle && target.wasVisited) { return false; } if (!target.wasVisited) { return false; } target = we.getNextNode(target, direction); } } private void checkAllForPits(WumplusEnvironment we) { Hashtable<Point, CaveNode> grid = we.grid; for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { Point point = new Point(j, i); CaveNode node = grid.get(point); if (node.wasVisited ) {//&& !node.onceChangeProbability checkAreaForPits(we, node); } } } } private void checkAreaForPits(WumplusEnvironment we, CaveNode node) { Vector<CaveNode> neighbors = we.get4AdjacentNodes(node); if (!node.hasBreeze) // neighbors of this node cannot have pits. { for (CaveNode neighbor : neighbors) { neighbor.pitProbability = 0.0; } } else // this node is breezy { // initially assume that there is a 50% chance that a node adjacent to a // breeze has a pit unless it has been deduced to not have a pit. for (CaveNode neighbor : neighbors) { if (!neighbor.wasVisited && neighbor.pitProbability > 0.0 && neighbor.pitProbability < 1.0){ neighbor.pitProbability += 0.33; //node.onceChangeProbability = true; } else if (neighbor.pitProbability >= 1) neighbor.pitProbability = 1; } for (int i = 0; i < 4; i++) { CaveNode frontNode = neighbors.get(i); CaveNode rightNode = neighbors.get((i + 1) % 4); CaveNode backNode = neighbors.get((i + 2) % 4); CaveNode leftNode = neighbors.get((i + 3) % 4); boolean leftNoPit = (leftNode.pitProbability == 0.0); boolean backNoPit = (backNode.pitProbability == 0.0); boolean rightNoPit = (rightNode.pitProbability == 0.0); if (leftNoPit && rightNoPit && backNoPit) { frontNode.pitProbability = 1.0; // we can deduce for certain that frontNode is a pit if we know that the left, right, and back squares aren't pits. } } } } private void checkAllForWumpus(WumplusEnvironment we) { Hashtable<Point, CaveNode> grid = we.grid; for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { Point point = new Point(j, i); CaveNode node = grid.get(point); if (node.wasVisited) { if (checkAreaForWumpus(we, node)) return; } } } } private boolean checkAreaForWumpus(WumplusEnvironment we, CaveNode node) { Vector<CaveNode> neighbors = we.get4AdjacentNodes(node); if (!node.hasStench) // neighbors of this node cannot have the wumpus. { for (CaveNode neighbor : neighbors) { neighbor.wumpusProbability = 0.0; } } else // this node stinks { neighbors = we.get8AdjacentNodes(node); // initially assume that there is a 50% chance that a node adjacent to a // stench has a wumpus unless it has been deduced to not have a wumpus. for (CaveNode neighbor : neighbors) { if (!neighbor.wasVisited && neighbor.wumpusProbability > 0.0 && neighbor.wumpusProbability < 1.0) neighbor.wumpusProbability = 0.5; } for (int i = 0; i < 8; i += 2) { CaveNode frontNode = neighbors.get(i); CaveNode frontRightNode = neighbors.get((i + 1) % 8); CaveNode rightNode = neighbors.get((i + 2) % 8); CaveNode backRightNode = neighbors.get((i + 3) % 8); CaveNode backNode = neighbors.get((i + 4) % 8); CaveNode backLeftNode = neighbors.get((i + 5) % 8); CaveNode leftNode = neighbors.get((i + 6) % 8); CaveNode frontLeftNode = neighbors.get((i + 7) % 8); //log.d("Left : " + leftNode.x + "," + leftNode.y + " " + leftNode.wumpusProbability); //log.d("Right : " + rightNode.x + "," + rightNode.y + " " + rightNode.wumpusProbability); //log.d("Back : " + backNode.x + "," + backNode.y + " " + backNode.wumpusProbability); //log.d("Front : " + frontNode.x + "," + frontNode.y + " " + frontNode.wumpusProbability); boolean leftNoWumpus = (leftNode.wumpusProbability == 0.0); boolean backNoWumpus = (backNode.wumpusProbability == 0.0); boolean rightNoWumpus = (rightNode.wumpusProbability == 0.0); // Case 1 // // #W# // .S. // #.# // if (leftNode.wasVisited && !leftNode.hasStench && rightNode.wasVisited && !rightNode.hasStench && backNode.wasVisited && !backNode.hasStench) { //log.d("case 1"); pinPointWumpus(frontNode, we); return true; } // Case 2 // // #WS // #S. // ### // if (rightNoWumpus && frontRightNode.wasVisited && frontRightNode.hasStench) { // log.d("case 2"); pinPointWumpus(frontNode, we); return true; } // Case 3 // // SW# // .S# // ### // if (leftNoWumpus && frontLeftNode.wasVisited && frontLeftNode.hasStench) { // log.d("case 3"); pinPointWumpus(frontNode, we); return true; } } } return false; } /** * updates agent knowledge when it deduces the wumpus's location. */ private void pinPointWumpus(CaveNode wumpusNode, WumplusEnvironment we) { Hashtable<Point, CaveNode> grid = we.grid; for (int i = 0; i <= 11; i++) { for (int j = 0; j <= 11; j++) { Point point = new Point(j, i); CaveNode node = grid.get(point); node.wumpusProbability = 0.0; } } if (!this.hasArrow) wumpusNode.wumpusProbability = 1.0; // If the agent ever finds itself in a position // where it's about to move into the wumpus's square, the agent now knows to shoot it first anyways. wumpusFound = true; this.knownWumpusX = wumpusNode.x; this.knownWumpusY = wumpusNode.y; } /** * updates the player's knowledge of the supmuw's whereabouts */ private void checkAllForSupmuw(WumplusEnvironment we) { Hashtable<Point, CaveNode> grid = we.grid; // try to deduce supmuw probabilities for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { Point point = new Point(j, i); CaveNode node = grid.get(point); if (node.wasVisited) { if (checkAreaForSupmuw(we, node)) { // return; } } } } // use known extreme positions of stenches and moos to deduce whether or not the Supmuw is friendly. if (this.supmuwFriendlyProbability > 0.0 && this.supmuwFriendlyProbability < 1.0 && eastmostMoo != -1) { if (this.knownSupmuwX != -1 && Math.abs(this.knownSupmuwX - this.knownWumpusX) == 1 && Math.abs(this.knownSupmuwY - this.knownWumpusY) == 0) { addNewNote("Deduced that Supmuw is murderous. X adjacent."); this.supmuwFriendlyProbability = 0.0; CaveNode supmuwNode = grid.get(new Point(this.knownSupmuwX, this.knownSupmuwY)); if (this.hasArrow) { supmuwNode.supmuwProbability = 0; } } else if (this.knownSupmuwX != -1 && Math.abs(this.knownSupmuwX - this.knownWumpusX) == 0 && Math.abs(this.knownSupmuwY - this.knownWumpusY) == 1) { addNewNote("Deduced that Supmuw is murderous. Y adjacent."); this.supmuwFriendlyProbability = 0.0; CaveNode supmuwNode = grid.get(new Point(this.knownSupmuwX, this.knownSupmuwY)); if (this.hasArrow) { supmuwNode.supmuwProbability = 0; } } else if (this.knownSupmuwX != -1 && this.knownWumpusX != -1 && this.knownSupmuwX < eastmostStench - 1) { this.supmuwFriendlyProbability = 1.0; addNewNote("Deduced that Supmuw is friendly. Too far west."); } else if (this.knownSupmuwX != -1 && this.knownWumpusX != -1 && this.knownSupmuwX > westmostStench + 1) { this.supmuwFriendlyProbability = 1.0; addNewNote("Deduced that Supmuw is friendly. Too far east."); } else if (this.knownSupmuwX != -1 && this.knownWumpusX != -1 && this.knownSupmuwY < southmostStench - 1) { this.supmuwFriendlyProbability = 1.0; addNewNote("Deduced that Supmuw is friendly. Too far south."); } else if (this.knownSupmuwX != -1 && this.knownWumpusX != -1 && this.knownSupmuwY > northmostStench + 1) { this.supmuwFriendlyProbability = 1.0; addNewNote("Deduced that Supmuw is friendly. Too far north."); } else { addNewNote("Cannot deduce Supmuw's friendliness."); } } } private boolean checkAreaForSupmuw(WumplusEnvironment we, CaveNode node) { Vector<CaveNode> neighbors = we.get8AdjacentNodes(node); if (!node.hasMoo) // neighbors of this node cannot have the wupmuw. { for (CaveNode neighbor : neighbors) { neighbor.supmuwProbability = 0.0; } } else // can hear moo { //log.d("heard a moo"); // initially assume that there is a 50% chance that a node adjacent to a // moo has a supmuw unless it has been deduced to not have a supmuw. for (CaveNode neighbor : neighbors) { if (!neighbor.wasVisited && neighbor.supmuwProbability > 0.0 && neighbor.supmuwProbability < 1.0) neighbor.supmuwProbability = 0.5; } for (int i = 0; i < 8; i += 2) { CaveNode frontNode = neighbors.get(i); CaveNode frontRightNode = neighbors.get((i + 1) % 8); CaveNode rightNode = neighbors.get((i + 2) % 8); CaveNode backRightNode = neighbors.get((i + 3) % 8); CaveNode backNode = neighbors.get((i + 4) % 8); CaveNode backLeftNode = neighbors.get((i + 5) % 8); CaveNode leftNode = neighbors.get((i + 6) % 8); CaveNode frontLeftNode = neighbors.get((i + 7) % 8); //log.d("Left : " + leftNode.x + "," + leftNode.y + " " + leftNode.wumpusProbability); //log.d("Right : " + rightNode.x + "," + rightNode.y + " " + rightNode.wumpusProbability); //log.d("Back : " + backNode.x + "," + backNode.y + " " + backNode.wumpusProbability); //log.d("Front : " + frontNode.x + "," + frontNode.y + " " + frontNode.wumpusProbability); boolean leftNoSupmuw = (leftNode.supmuwProbability == 0.0); boolean backNoSupmuw = (backNode.supmuwProbability == 0.0); boolean rightNoSupmuw = (rightNode.supmuwProbability == 0.0); // Case 1 // // #.# // MMM // #S# // if (leftNode.wasVisited && leftNode.hasMoo && rightNode.wasVisited && rightNode.hasMoo && backNoSupmuw) { pinPointSupmuw(frontNode, we); // log.d("case 1"); return true; } // Case 2 // // ### // #M# // MSM // if (frontRightNode.wasVisited && frontRightNode.hasMoo && frontLeftNode.wasVisited && frontLeftNode.hasMoo && frontNode.wasVisited && frontNode.hasMoo) { pinPointSupmuw(frontNode, we); // log.d("case 2"); return true; } // Case 3 // // #.# // MMM // MSM // if (frontLeftNode.wasVisited && frontLeftNode.hasMoo && frontRightNode.wasVisited && frontRightNode.hasMoo && leftNode.wasVisited && leftNode.hasMoo && rightNode.wasVisited && rightNode.hasMoo) { pinPointSupmuw(frontNode, we); log.d("case 3"); return true; } // Case 4 // // #.# // #M. // S## // if (leftNode.wasVisited && !leftNode.hasMoo && backNode.wasVisited && !backNode.hasMoo) { pinPointSupmuw(frontRightNode, we); // log.d("case 4"); return true; } // Case 5 // // #.# // .M# // ##S // if (rightNode.wasVisited && !rightNode.hasMoo && backNode.wasVisited && !backNode.hasMoo) { pinPointSupmuw(frontLeftNode, we); // log.d("case 5"); return true; } } } return false; } /** * updates agent knowledge when it deduces the wupmuw's location. */ private void pinPointSupmuw(CaveNode supmuwNode, WumplusEnvironment we) { Hashtable<Point, CaveNode> grid = we.grid; for (int i = 0; i <= 11; i++) { for (int j = 0; j <= 11; j++) { Point point = new Point(j, i); CaveNode node = grid.get(point); node.supmuwProbability = 0.0; } } // log.d("Deduced supmuw's location: " + supmuwNode.x + "," + supmuwNode.y); supmuwNode.supmuwProbability = 1.0; supmuwFound = true; this.knownSupmuwX = supmuwNode.x; this.knownSupmuwY = supmuwNode.y; } /** * shortestSafePathToUnvisited(WumplusEnvironment we) * determines which direction to go to get to the current least-cost unvisited node. * Returns N S E or W if an unvisited node can be reached with little or no chance of death */ private char shortestSafePathToUnvisited(WumplusEnvironment we) { // initialize visited nodes list so that we don't revisited nodes we've already visited in this bfs. Hashtable<Point, Boolean> isExhausted = new Hashtable<Point, Boolean>(); // log.d("****************************************Path to unvisited Start A* search******************************************"); for (int i = 0; i <= 11; i++) { for (int j = 0; j <= 11; j++) { isExhausted.put(new Point(j, i), false); } } // initialize other things PriorityQueue<PriorityCaveNode> pq = new PriorityQueue<PriorityCaveNode>(); Hashtable<Point, CaveNode> grid = we.grid; PriorityCaveNode first = new PriorityCaveNode(grid.get(new Point(this.x, this.y)), 0, new Vector<Character>(), this.direction); pq.add(first); // A* Search while (!pq.isEmpty()) { // initialize this step. PriorityCaveNode curPNode = pq.remove(); CaveNode node = curPNode.node; char curDir = curPNode.directions.lastElement().charValue(); int curCost = curPNode.cost; Point curPoint = new Point(node.x, node.y); // If we have reached a node that was not visited, then we'll return the direction taken to get to it! if (node.wasVisited == false) { try { return curPNode.directions.get(1).charValue(); } catch (Exception e) { return 'I'; } } // proceed if current node hasn't been visited in the bfs yet and it isn't a wall. if (!isExhausted.get(curPoint).booleanValue() && !node.hasObstacle) { char leftDir = getLeftDirection(curDir); char rightDir = getRightDirection(curDir); char backDir = getBackDirection(curDir); // attempt to travel in all directions. Account for cost of turning. aStarTravel(pq, we, curPNode, curDir, curCost, null); aStarTravel(pq, we, curPNode, leftDir, curCost + 1, null); aStarTravel(pq, we, curPNode, rightDir, curCost + 1, null); aStarTravel(pq, we, curPNode, backDir, curCost + 2, null); } isExhausted.put(curPoint, true); } return 'I'; // I for IDLE : it was not possible to safely reach an unvisited node } /** * performs a step through an A* search for the agent */ private void aStarTravel(PriorityQueue<PriorityCaveNode> pq, WumplusEnvironment we, PriorityCaveNode pNode, char direction, int curCost, Point destinationPoint) { CaveNode node = pNode.node; CaveNode nextNode = we.getNextNode(node, direction); // determine cost of moving foward into the next node. double chanceOfFriendlySupmuw = nextNode.supmuwProbability * this.supmuwFriendlyProbability; double chanceOfMurderousSupmuw = nextNode.supmuwProbability * (1 - this.supmuwFriendlyProbability); if (this.supmuwKilled) chanceOfMurderousSupmuw = 0.0; double chanceOfWumpusDeath = (nextNode.wumpusProbability); if (wumpusKilled) chanceOfWumpusDeath = 0.0; double chanceOfDeath = 1.0 - ((1.0 - nextNode.pitProbability) * (1.0 - chanceOfWumpusDeath) * (1.0 - chanceOfMurderousSupmuw)); if (chanceOfDeath == 1.0) return; double chanceOfGold = 1.0 / we.unvisitedNodes.size(); if (this.hasGold) chanceOfGold = 0.0; if (this.hasFood) chanceOfFriendlySupmuw = 0.0; int moveForwardCost = (int) (1 + chanceOfDeath * 1000 + chanceOfGold * -1000 + chanceOfFriendlySupmuw * -100); //log.d("chanceDeath: " + (chanceOfDeath) + " Gold: " + (chanceOfGold) + " FriendSupmuw: " + chanceOfFriendlySupmuw); //log.d("chancePit: " + (nextNode.pitProbability) + " Wumpus: " + (nextNode.wumpusProbability) + " UnFriendSupmuw: " + chanceOfMurderousSupmuw); // add weight to unvisited nodes if (nextNode.wasVisited && destinationPoint == null) { // log.d("was visited"); moveForwardCost += 100; } if (destinationPoint != null) { // log.d("heading to point " + destinationPoint); moveForwardCost += Math.abs(nextNode.x - destinationPoint.x) + Math.abs(nextNode.y - destinationPoint.y); if (!nextNode.wasVisited) { moveForwardCost += 100; } } // add the next node to our priority queue if the agent isn't likely to die by doing so. if (moveForwardCost < 500 + 1) { //log.d("cost to move " + direction + " to " + nextNode.x + "," + nextNode.y + " : " + (curCost + moveForwardCost) + " : " + curCost + " " + moveForwardCost); PriorityCaveNode nextPNode = new PriorityCaveNode(nextNode, curCost + moveForwardCost, pNode.directions, direction); pq.add(nextPNode); } } private char getLeftDirection(char curDir) { if (curDir == 'N') return 'W'; if (curDir == 'W') return 'S'; if (curDir == 'S') return 'E'; if (curDir == 'E') return 'N'; return 'I'; } private char getRightDirection(char curDir) { if (curDir == 'N') return 'E'; if (curDir == 'W') return 'N'; if (curDir == 'S') return 'W'; if (curDir == 'E') return 'S'; return 'I'; } private char getBackDirection(char curDir) { if (curDir == 'N') return 'S'; if (curDir == 'W') return 'E'; if (curDir == 'S') return 'N'; if (curDir == 'E') return 'W'; return 'I'; } /** * shortestSafePathToUnvisited(WumplusEnvironment we) * determines which direction to go to get to the current least-cost unvisited node. * Returns N S E or W if an unvisited node can be reached with little or no chance of death */ private char shortestSafePathToPoint(WumplusEnvironment we, Point point) { // initialize visited nodes list so that we don't revisited nodes we've already visited in this bfs. Hashtable<Point, Boolean> isExhausted = new Hashtable<Point, Boolean>(); // log.d("####################Path to Point " + point + " start A* search ####################################"); for (int i = 0; i <= 11; i++) { for (int j = 0; j <= 11; j++) { isExhausted.put(new Point(j, i), false); } } // initialize other things PriorityQueue<PriorityCaveNode> pq = new PriorityQueue<PriorityCaveNode>(); Hashtable<Point, CaveNode> grid = we.grid; PriorityCaveNode first = new PriorityCaveNode(grid.get(new Point(this.x, this.y)), 0, new Vector<Character>(), this.direction); pq.add(first); // A* Search while (!pq.isEmpty()) { //log.d("Entered A* Search"); // initialize this step. PriorityCaveNode curPNode = pq.remove(); CaveNode node = curPNode.node; char curDir = curPNode.directions.lastElement().charValue(); int curCost = curPNode.cost; Point curPoint = new Point(node.x, node.y); // If we have reached a node that was not visited, then we'll return the direction taken to get to it! if (node.x == point.x && node.y == point.y) { try { return curPNode.directions.get(1).charValue(); } catch (Exception e) { return 'I'; } } // proceed if current node hasn't been visited in the bfs yet and it isn't a wall. if (!isExhausted.get(curPoint).booleanValue() && !node.hasObstacle) { char leftDir = getLeftDirection(curDir); char rightDir = getRightDirection(curDir); char backDir = getBackDirection(curDir); // attempt to travel in all directions. Account for cost of turning. aStarTravel(pq, we, curPNode, curDir, curCost, point); aStarTravel(pq, we, curPNode, leftDir, curCost + 1, point); aStarTravel(pq, we, curPNode, rightDir, curCost + 1, point); aStarTravel(pq, we, curPNode, backDir, curCost + 2, point); } isExhausted.put(curPoint, true); } return 'I'; // I for IDLE : it was not possible to safely reach an unvisited node } }
true
37f17b184d8a2a9a438c6123a6c5893edc43c2d6
Java
AgarwalVibhor/Spring_1_Crud
/src/com/tcs/dao/EmployeeDaoImpl.java
UTF-8
4,935
2.640625
3
[]
no_license
package com.tcs.dao; import java.util.Date; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tcs.model.Employee; @Repository public class EmployeeDaoImpl implements EmployeeDaoInterface { @Autowired private SessionFactory sf; private static final Logger logger = LoggerFactory.getLogger(EmployeeDaoImpl.class); @Override public int addEmployee(Employee employee) { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); int result = (Integer) session.save(employee); t.commit(); logger.info("Employee saved successfully. Employee Details : " + employee); return result; } @Override public Employee validEmployee(int employeeId, String email) { Employee emp = null; Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "from Employee where employeeId = ? and email = ?"; Query q = session.createQuery(hql); q.setInteger(0, employeeId); q.setString(1, email); emp = (Employee) q.uniqueResult(); t.commit(); if(emp == null) { System.out.println("Such employee does not exist."); return null; } else { System.out.println("An employee with employee id :" + employeeId + " exists."); return emp; } } @Override public boolean updateEmployee(Employee employee) { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "update Employee set fname=?, lname=?, dob=?, email=?, mobile=?," + "address=?, salary=?, password=? where employeeId=?"; Query q = session.createQuery(hql); q.setString(0, employee.getFname()); q.setString(1, employee.getLname()); q.setDate(2, employee.getDob()); q.setString(3, employee.getEmail()); q.setString(4, employee.getMobile()); q.setString(5, employee.getAddress()); q.setDouble(6, employee.getSalary()); q.setString(7, employee.getPassword()); q.setInteger(8, employee.getEmployeeId()); int affect = q.executeUpdate(); t.commit(); if(affect == 1) { System.out.println("Updation successful."); return true; } else { System.out.println("Employee not updated."); return false; } } @Override public boolean deleteEmployee(int employeeId) { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "delete Employee where employeeId = ?"; Query q = session.createQuery(hql); q.setInteger(0, employeeId); int affect = q.executeUpdate(); t.commit(); if(affect == 1) { System.out.println("Deletion successful."); return true; } else { System.out.println("Deletion not successful."); return false; } } @Override public Employee checkId(int employeeId) { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "from Employee where id = ?"; Query q = session.createQuery(hql); q.setInteger(0, employeeId); Employee emp = (Employee) q.uniqueResult(); t.commit(); return emp; } @SuppressWarnings("unchecked") @Override public List<Employee> getAllEmployees() { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "from Employee"; Query q = session.createQuery(hql); List<Employee> employees = q.list(); t.commit(); return employees; } @SuppressWarnings("unchecked") @Override public List<Employee> getEmployeesByFname(String fname) { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "from Employee where fname = :fname"; /* * The positional parameters have been deprecated. Give the name of the variable with :fname */ Query q = session.createQuery(hql); q.setString("fname", fname); List<Employee> employees = q.list(); t.commit(); return employees; } @SuppressWarnings("unchecked") @Override public List<Employee> getEmployeesByDob(Date dob) { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "from Employee where dob = :dob"; Query q = session.createQuery(hql); q.setDate("dob", dob); List<Employee> employees = q.list(); t.commit(); return employees; } @SuppressWarnings("unchecked") @Override public List<Employee> getEmployeesBySalary(double salary) { Session session = sf.getCurrentSession(); Transaction t = session.beginTransaction(); String hql = "from Employee where salary = :salary"; Query q = session.createQuery(hql); q.setDouble("salary", salary); List<Employee> employees = q.list(); t.commit(); return employees; } }
true
572bdc2d0e40ebecb50031e207d722689f9d5e8e
Java
JiangnanFu/design-patterns
/com/bridge/example/Ps3.java
GB18030
385
2.234375
2
[]
no_license
package com.bridge.example; /** * Ps3 * @author liuiqian * */ public class Ps3 extends Host { public Ps3(Handle handle, GameContainer gameContainer) { super(handle, gameContainer); } @Override public void work() { // TODO Auto-generated method stub System.out.println("Ps3ʼˣ"); //ίз this.gameLoad(); this.handleWork(); } }
true