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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9c31727660e4e144c2bb349b771f3b43203ec875 | Java | opentechgeeks/QASelenium | /src/main/java/com/lowes/qa/selenium/components/HomeProfile_Dim.java | UTF-8 | 16,356 | 1.765625 | 2 | [] | no_license | package com.lowes.qa.selenium.components;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import com.cognizant.framework.Status;
import com.lowes.qa.selenium.support.ReusableLibrary;
import com.lowes.qa.selenium.support.ScriptHelper;
import com.lowes.qa.selenium.uimap.UIMapFunctionalComponents;
import com.lowes.qa.selenium.uimap.UIMapMyLowes;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.server.handler.FindElement;
import org.openqa.selenium.remote.server.handler.SendKeys;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class HomeProfile_Dim extends ReusableLibrary
{
String baseurl = dataTable.getData("General_Data", "URL");
Selenium selenium = new WebDriverBackedSelenium(driver, baseurl);
public HomeProfile_Dim(ScriptHelper scriptHelper)
{
super(scriptHelper);
}
//ProductSearch ps = new ProductSearch(scriptHelper);
//PS2 ps2=new PS2(scriptHelper);
FunctionalComponents fc=new FunctionalComponents(scriptHelper);
//MyLowes2 mid=new MyLowes2(scriptHelper);
//CheckOut_CM cm= new CheckOut_CM(scriptHelper);
public void clickGetQuickAccurateLink() throws Exception
{
ClickCustomize("linkText", "Get Quick, Accurate Measurements");
Thread.sleep(2000);
String oldTab = driver.getWindowHandle();
ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
newTab.remove(oldTab);
// change focus to new tab
driver.switchTo().window(newTab.get(0));
Thread.sleep(5000);
fc.chkPagetitle("MyLowe's Laser Measuring Video Tutorial");
fc.chkElementDisplayed("xpath", UIMapMyLowes.webElmntBoschToolVideo, "Bosch Tool Video");
driver.close();
driver.switchTo().window(oldTab);
}
/**Checks batch delete checkBox**/
public void chkCalcBatchDeleteChkBox() throws Exception
{
//selecting batch delete
ClickCustomize("id", UIMapMyLowes.chkBoxCalcBatchDelete);
Thread.sleep(2000);
int varCount=fc.countWebElement(UIMapMyLowes.chkBoxCalcAll);
int i=0;
String varChecked=null;
for(i=1;i<=varCount;i++)
{
try{
varChecked=driver.findElement(By.xpath("//*[@id='calculationsContainer']/div[2]/div[3]/div["+i+"]/div[2]/input")).getAttribute("checked");
if(varChecked.equals("true"))
{
continue;
}
else
{
System.out.println("Not True for:"+i+varChecked);
break;
}
}
catch(Exception e)
{
System.out.println("Not True for:"+i+varChecked);
report.updateTestLog("Checking All Calc checkboxes on clicking Batch Delete", "All Calc NOT selected", Status.FAIL);
break;
}
}
if(i>varCount)
report.updateTestLog("Checking All Calc checkboxes on clicking Batch Delete", "All Calc selected", Status.PASS);
else
report.updateTestLog("Checking All Calc checkboxes on clicking Batch Delete", "All Calc NOT selected", Status.FAIL);
//deselecting batch delete
ClickCustomize("id", UIMapMyLowes.chkBoxCalcBatchDelete);
Thread.sleep(2000);
for(i=1;i<=varCount;i++)
{
try{
varChecked=driver.findElement(By.xpath("//*[@id='calculationsContainer']/div[2]/div[3]/div["+i+"]/div[2]/input")).getAttribute("checked");
if(varChecked.equals("true"))
{
System.out.println("True for:"+i+varChecked);
break;
}
else
{
continue;
}
}
catch(Exception e)
{
continue;
}
}
if(i>varCount)
report.updateTestLog("Checking All Calc checkboxes on Deselecting Batch Delete", "All Calc deselected", Status.PASS);
else
report.updateTestLog("Checking All Calc checkboxes on Deselecting Batch Delete", "All Calc NOT deselected", Status.FAIL);
}
/**Checks Calculation page layout with atleast one calculation**/
public void chkCalcPgLayoutWithCalcAdded() throws Exception
{
int varCount=fc.countWebElement(UIMapMyLowes.webElmntAllCalc);
System.out.println(varCount);
int i=0;
for(i=1;i<=varCount;i++)
{
fc.chkElementDisplayed("xpath", "//*[@id='calculationsContainer']/div[2]/div[3]/div["+i+"]/div[2]/div[2]/div[1]/h5", "Calculation Name for Calc"+i);
fc.chkText("//*[@id='calculationsContainer']/div[2]/div[3]/div["+i+"]/div[2]/div[2]/div[1]/div/a[1]", "Show Details");
fc.chkElementDisplayed("xpath", "//*[@id='calculationsContainer']/div[2]/div[3]/div["+i+"]/div[2]/div[2]/div[1]/div/a[2]/img", "Trashcan icon for Calc"+i);
fc.chkElementDisplayed("xpath", "//*[@id='calculationsContainer']/div[2]/div[3]/div["+i+"]/div[2]/input", "Checkbox for Calc"+i);
}
}
/**Clicks Hide details for a calculation**/
public void clickHideDetails() throws Exception
{
ClickCustomize("partialLinkText", "Hide Details");
Thread.sleep(2000);
String varClass=driver.findElement(By.xpath(UIMapMyLowes.webElmntCalc1Drawer)).getAttribute("class");
if(varClass.equals("drawer closed"))
report.updateTestLog("Clicking Hide Details", "Calc Drawer closed", Status.PASS);
else
{
report.updateTestLog("Clicking Hide Details", "Calc Drawer NOT closed:"+varClass, Status.FAIL);
}
}
/**checks Calculator Sort bar when space is having atleast 1 Paint calculation**/
public void checkCalcSortBar() throws Exception
{
fc.chkElementDisplayed("xpath", UIMapMyLowes.webElmntTotalCalc, "Calculations count");
fc.chkText(UIMapMyLowes.webElmntGoToPrjctCalc, "Go to Project Calculators");
fc.chkText(UIMapMyLowes.webElmntCalcShowLabel, "Show:");
fc.chkElementDisplayed("xpath", UIMapMyLowes.webElmntCalcShow, "Show Mechanism");
fc.chkElementDisplayed("id", UIMapMyLowes.chkBoxCalcBatchDelete, "Batch Delete CheckBox");
fc.chkElementDisplayed("xpath", UIMapMyLowes.webElmntActions, "Actions Drop-down");
}
/**Check Custom Shape **/
public void chkCustomShape() throws Exception
{
ClickCustomize("id", UIMapMyLowes.webElmntCustomShape);
Thread.sleep(2000);
fc.chkText(UIMapMyLowes.labelCustomShapeMsg, "Select another square below or beside this square to draw a wall.");
//drawing horizontal line-undo
ClickCustomize("id", "cell_14_2");
Thread.sleep(2000);
fc.chkElementDisplayed("xpath", "//*[@id='cell_2_2']/div[2]", "Horizontal Line");
ClickCustomize("xpath", UIMapMyLowes.btnCustomShapeUndo);
Thread.sleep(2000);
String varClass=driver.findElement(By.xpath(UIMapMyLowes.btnCustomShapeUndo)).getAttribute("disabled");
System.out.println(varClass);
if(varClass.equals("true"))
report.updateTestLog("Selecting Undo After drawing horizontal line", "Undo disabled", Status.PASS);
else
report.updateTestLog("Selecting Undo After drawing horizontal line", "Undo disabled", Status.FAIL);
try{
if(driver.findElement(By.xpath("//*[@id='cell_2_2']/div[2]")).isDisplayed())
report.updateTestLog("Selecting Undo After drawing horizontal line", "Horizontal line still displayed", Status.FAIL);
else
report.updateTestLog("Selecting Undo After drawing horizontal line", "Horizontal line NOT displayed", Status.PASS);
}
catch(Exception e)
{
report.updateTestLog("Selecting Undo After drawing horizontal line", "Horizontal line NOT displayed", Status.PASS);
}
//drawing horizontal line-vertical line-undo
ClickCustomize("id", "cell_14_2");
Thread.sleep(2000);
fc.chkElementDisplayed("xpath", "//*[@id='cell_2_2']/div[2]", "Horizontal Line");
ClickCustomize("id", "cell_14_10");
Thread.sleep(2000);
fc.chkElementDisplayed("xpath", "//*[@id='cell_14_2']/div", "Vertical Line");
ClickCustomize("xpath", UIMapMyLowes.btnCustomShapeUndo);
Thread.sleep(2000);
try{
varClass=driver.findElement(By.xpath(UIMapMyLowes.btnCustomShapeUndo)).getAttribute("disabled");
System.out.println(varClass);
if(varClass.equals("true"))
report.updateTestLog("Selecting Undo After drawing Vertical line", "Undo disabled", Status.FAIL);
else
report.updateTestLog("Selecting Undo After drawing Vertical line", "Undo NOT disabled", Status.PASS);
}
catch(Exception e)
{
report.updateTestLog("Selecting Undo After drawing Vertical line", "Undo NOT disabled", Status.PASS);
}
try{
if(driver.findElement(By.xpath("//*[@id='cell_14_2']/div[2]")).isDisplayed())
report.updateTestLog("Selecting Undo After drawing Vertical line", "Vertical line still displayed", Status.FAIL);
else
report.updateTestLog("Selecting Undo After drawing Vertical line", "Vertical line NOT displayed", Status.PASS);
}
catch(Exception e)
{
report.updateTestLog("Selecting Undo After drawing Vertical line", "Vertical line NOT displayed", Status.PASS);
}
try{
if(driver.findElement(By.xpath("//*[@id='cell_2_2']/div[2]")).isDisplayed())
report.updateTestLog("Selecting Undo After drawing Vertical line", "Horizontal line displayed", Status.PASS);
else
report.updateTestLog("Selecting Undo After drawing Vertical line", "Horizontal line NOT displayed", Status.FAIL);
}
catch(Exception e)
{
report.updateTestLog("Selecting Undo After drawing Vertical line", "Horizontal line NOT displayed", Status.FAIL);
}
//drawing additional lines till shape is complete
ClickCustomize("id", "cell_14_10");
Thread.sleep(2000);
ClickCustomize("id", "cell_9_10");
Thread.sleep(2000);
ClickCustomize("id", "cell_9_7");
Thread.sleep(2000);
ClickCustomize("id", "cell_5_7");
Thread.sleep(2000);
ClickCustomize("id", "cell_5_5");
Thread.sleep(2000);
ClickCustomize("id", "cell_2_5");
Thread.sleep(2000);
ClickCustomize("xpath", "//*[@id='cell_2_2']/div[1]");
Thread.sleep(5000);
fc.chkText(UIMapMyLowes.labelCustomShapeMsg2, "Once you've finished selecting the shape and position of your room, select Continue.");
varClass=driver.findElement(By.xpath(UIMapMyLowes.btnRotate1)).getAttribute("class");
String varClass2=driver.findElement(By.xpath(UIMapMyLowes.btnRotate2)).getAttribute("class");
if(varClass.contains("disabled") || varClass2.contains("disabled"))
report.updateTestLog("Checking Rotate buttons after Custom shape is drawn", "Rotate buttons Disabled", Status.FAIL);
else
report.updateTestLog("Checking Rotate buttons after Custom shape is drawn", "Rotate buttons Enabled", Status.PASS);
varClass=driver.findElement(By.xpath(UIMapMyLowes.btnFlip1)).getAttribute("class");
varClass2=driver.findElement(By.xpath(UIMapMyLowes.btnFlip2)).getAttribute("class");
if(varClass.contains("disabled") || varClass2.contains("disabled"))
report.updateTestLog("Checking Flip buttons after Custom shape is drawn", "Flip buttons Disabled", Status.FAIL);
else
report.updateTestLog("Checking Flip buttons after Custom shape is drawn", "Flip buttons Enabled", Status.PASS);
if(driver.findElement(By.xpath(UIMapMyLowes.btnCustomShapeContinue)).isEnabled())
report.updateTestLog("Checking Continue button after Custom shape is drawn", "Continue button Enabled", Status.PASS);
else
report.updateTestLog("Checking Continue button after Custom shape is drawn", "Continue button Disabled", Status.PASS);
}
/**Store Negative space value in data sheet**/
public void storeInvalidNegSpaceInDataSheet() throws Exception
{
dataTable.putData("General_Data", "NegSpaceArea", "200");
}
public void documentUploadInSpace() throws Exception
{
int varCount=fc.countWebElement(UIMapMyLowes.webElmntDocsCount);
System.out.println(varCount);
try{
driver.findElement(By.xpath(UIMapMyLowes.btnUploadDocInSpace)).click();
}
catch(Exception e)
{
driver.findElement(By.xpath(UIMapMyLowes.btnUploadFrstDocInSpace)).click();
}
Thread.sleep(5000);
Robot r = new Robot();
r.keyPress(KeyEvent.VK_D); // D
r.keyRelease(KeyEvent.VK_D);
r.keyPress(KeyEvent.VK_SHIFT); // : (colon)
r.keyPress(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_BACK_SLASH ); // \ (back slash)
r.keyRelease(KeyEvent.VK_BACK_SLASH );
r.keyPress(KeyEvent.VK_T); // T
r.keyRelease(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_PERIOD);
r.keyRelease(KeyEvent.VK_PERIOD);
r.keyPress(KeyEvent.VK_T); // t
r.keyRelease(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_X); // x
r.keyRelease(KeyEvent.VK_X);
r.keyPress(KeyEvent.VK_T); // t
r.keyRelease(KeyEvent.VK_T);
Thread.sleep(2000);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
String successfulUpload=driver.findElement(By.xpath(UIMapMyLowes.webElmntDocsUploadSuccessMsg)).getText();
Thread.sleep(2000);
if(successfulUpload.contains("Upload complete"))
{
int divCount=fc.countWebElement("html/body/div");
System.out.println("//div["+(divCount-((varCount*2)+1))+"]/div[1]/a/span");
driver.findElement(By.xpath("//div["+(divCount-((varCount*2)+1))+"]/div[1]/a/span")).click();
}
else if(successfulUpload.contains("Server error. Try again."))
report.updateTestLog("Trying to upload Document","Upload Failed. Server Error",Status.FAIL);
else
{
report.updateTestLog("Trying to attach a document","Document attachment failed",Status.FAIL);
}
Thread.sleep(5000);
//document 2 upload
varCount=fc.countWebElement(UIMapMyLowes.webElmntDocsCount);
System.out.println(varCount);
try{
driver.findElement(By.xpath(UIMapMyLowes.btnUploadDocInSpace)).click();
}
catch(Exception e)
{
driver.findElement(By.xpath(UIMapMyLowes.btnUploadFrstDocInSpace)).click();
}
Thread.sleep(5000);
r = new Robot();
r.keyPress(KeyEvent.VK_D); // D
r.keyRelease(KeyEvent.VK_D);
r.keyPress(KeyEvent.VK_SHIFT); // : (colon)
r.keyPress(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SEMICOLON);
r.keyRelease(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_BACK_SLASH ); // \ (back slash)
r.keyRelease(KeyEvent.VK_BACK_SLASH );
r.keyPress(KeyEvent.VK_A); // A
r.keyRelease(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_PERIOD);
r.keyRelease(KeyEvent.VK_PERIOD);
r.keyPress(KeyEvent.VK_T); // t
r.keyRelease(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_X); // x
r.keyRelease(KeyEvent.VK_X);
r.keyPress(KeyEvent.VK_T); // t
r.keyRelease(KeyEvent.VK_T);
Thread.sleep(2000);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
successfulUpload=driver.findElement(By.xpath(UIMapMyLowes.webElmntDocsUploadSuccessMsg)).getText();
Thread.sleep(2000);
if(successfulUpload.contains("Upload complete"))
{
int divCount=fc.countWebElement("html/body/div");
System.out.println("//div["+(divCount-((varCount*2)+1))+"]/div[1]/a/span");
driver.findElement(By.xpath("//div["+(divCount-((varCount*2)+1))+"]/div[1]/a/span")).click();
}
else if(successfulUpload.contains("Server error. Try again."))
report.updateTestLog("Trying to upload Document","Upload Failed. Server Error",Status.FAIL);
else
{
report.updateTestLog("Trying to attach a document","Document attachment failed",Status.FAIL);
}
Thread.sleep(5000);
}
/**Clicks on Show Mechanism on HP page and selects Products**/
public void showAllProducts() throws Exception
{
ClickCustomize("xpath",UIMapMyLowes.drpDownShow);
Thread.sleep(1000);
driver.findElement(By.xpath(UIMapMyLowes.webElmntShowAllProducts)).click();
Thread.sleep(5000);
}
}
| true |
cbd4fa7eec34efdf5bdc266f76d337befbb532f1 | Java | jpaw/bonaparte-java | /bonaparte-refs/src/main/java/de/jpaw/bonaparte/refsw/impl/AbstractRequestContext.java | UTF-8 | 4,813 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package de.jpaw.bonaparte.refsw.impl;
import java.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.jpaw.bonaparte.pojos.api.PersistenceProviders;
import de.jpaw.bonaparte.refs.PersistenceProvider;
import de.jpaw.bonaparte.refsw.RequestContext;
/** Base implementation of some request's environment, usually enhanced by specific applications.
*
* For every request, one of these is created.
* Additional ones may be created for the asynchronous log writers (using dummy or null internalHeaderParameters)
*
* Any functionality relating to customization has been moved to a separate class (separation of concerns).
*/
public class AbstractRequestContext implements RequestContext, AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRequestContext.class);
private static final int MAX_PERSISTENCE_PROVIDERS = PersistenceProviders.values().length; // how many different persistence providers may participate?
public static boolean AUTOCLOSE_ON_ROLLBACK_OR_COMMIT = true; // could be adjusted by external parties
public final String userId;
public final String tenantId;
public final Long userRef;
public final Long tenantRef;
public final long requestRef;
public final Instant executionStart; // to avoid checking the time repeatedly (takes 33 ns every time we do it), a timestamp is taken when the request processing starts
private final PersistenceProvider [] persistenceUnits = new PersistenceProvider[MAX_PERSISTENCE_PROVIDERS];
private int maxPersistenceProvider = -1; // high water mark for the maximum index of a provider
public AbstractRequestContext(Instant executionStart, String userId, String tenantId, Long userRef, Long tenantRef, long requestRef) {
this.tenantId = tenantId;
this.userId = userId;
this.tenantRef = tenantRef;
this.userRef = userRef;
this.requestRef = requestRef;
this.executionStart = executionStart != null ? executionStart : Instant.now();
if (LOGGER.isDebugEnabled())
LOGGER.debug("Starting RequestContext for user {}, tenant {}, processRef {}", userId, tenantId, Long.valueOf(requestRef));
}
// persistence services
/** Informs the request context that the provider named participates in the transaction. */
@Override
public void addPersistenceContext(PersistenceProvider pprovider) {
int ind = pprovider.getPriority();
if (persistenceUnits[ind] == null) {
persistenceUnits[ind] = pprovider;
if (ind > maxPersistenceProvider)
maxPersistenceProvider = ind;
pprovider.open(); // first time this request has seen it, open it!
}
}
@Override
public PersistenceProvider getPersistenceProvider(int priority) {
return persistenceUnits[priority];
}
protected void closeAll(final boolean nullUnit) throws Exception {
for (int i = 0; i <= maxPersistenceProvider; ++i) {
if (persistenceUnits[i] != null) {
persistenceUnits[i].close();
if (nullUnit)
persistenceUnits[i] = null;
}
}
}
@Override
public void commit() throws Exception {
for (int i = 0; i <= maxPersistenceProvider; ++i) {
try {
if (persistenceUnits[i] != null)
persistenceUnits[i].commit();
} catch (Exception e) {
// if the commit fails, we have to roll back the others as well
rollback();
throw e; // throw the original exception here (or convert to return code?)
}
}
if (AUTOCLOSE_ON_ROLLBACK_OR_COMMIT)
closeAll(false);
}
@Override
public void rollback() throws Exception {
for (int i = 0; i <= maxPersistenceProvider; ++i)
if (persistenceUnits[i] != null)
persistenceUnits[i].rollback();
if (AUTOCLOSE_ON_ROLLBACK_OR_COMMIT)
closeAll(false);
}
@Override
public void close() throws Exception {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Closing RequestContext for user {}, tenant {}, processRef {}", userId, tenantId, Long.valueOf(requestRef));
closeAll(true);
maxPersistenceProvider = -1;
}
// standard getters as defined in the interface
@Override
public Long getTenantRef() {
return tenantRef;
}
@Override
public Long getUserRef() {
return userRef;
}
@Override
public long getRequestRef() {
return requestRef;
}
@Override
public Instant getExecutionStart() {
return executionStart;
}
}
| true |
d60620540299e14b6798955f0c17bda0d8f02433 | Java | kSuroweczka/jdk | /com/sun/tools/javac/tree/DocCommentTable.java | UTF-8 | 618 | 2.078125 | 2 | [] | no_license | package com.sun.tools.javac.tree;
import com.sun.tools.javac.parser.Tokens.Comment;
public abstract interface DocCommentTable
{
public abstract boolean hasComment(JCTree paramJCTree);
public abstract Tokens.Comment getComment(JCTree paramJCTree);
public abstract String getCommentText(JCTree paramJCTree);
public abstract DCTree.DCDocComment getCommentTree(JCTree paramJCTree);
public abstract void putComment(JCTree paramJCTree, Tokens.Comment paramComment);
}
/* Location: D:\dt\jdk\tools.jar
* Qualified Name: com.sun.tools.javac.tree.DocCommentTable
* JD-Core Version: 0.6.2
*/ | true |
a4820148f2f64a0d66a1c1a64534c9238774949f | Java | ITSubmariner/Chat | /src/main/java/com/pet/chat/repository/GroupRepository.java | UTF-8 | 1,792 | 2.453125 | 2 | [] | no_license | package com.pet.chat.repository;
import com.pet.chat.domain.Group;
import com.pet.chat.domain.User;
import com.pet.chat.exception.NoPermissionException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Repository
@Transactional
public class GroupRepository {
@PersistenceContext
private EntityManager entityManager;
public void create(String name, long adminId) {
User admin = entityManager.find(User.class, adminId);
Group group = new Group();
group.setName(name);
group.setAdmin(admin);
group.getUsers().add(admin);
entityManager.persist(group);
}
public void remove(long groupId, long adminId) {
Group group = find(groupId);
if (group.getId() == adminId) {
entityManager.remove(group);
entityManager.createQuery("delete from Message m where m.group_id=:group_id").setParameter("group_id", groupId).executeUpdate();
} else throw new NoPermissionException();
}
public List<Group> findAll() {
return entityManager.createNativeQuery("select * from GROUPS", Group.class).getResultList();
}
public Group find(long id) {
return entityManager.find(Group.class, id);
}
public void addUser(long groupId, long userId) {
Group group = find(groupId);
User user = entityManager.find(User.class, userId);
group.getUsers().add(user);
}
public void removeUser(long groupId, long userId) {
Group group = find(groupId);
User user = entityManager.find(User.class, userId);
group.getUsers().remove(user);
}
}
| true |
5625babc155ce3d8fd1a59b7a1030c4ae47f9a84 | Java | drag0sd0g/ezDL | /dlservices/src/main/java/de/unidue/inf/is/ezdl/dlservices/library/manager/referencesystems/ReferenceSystemException.java | UTF-8 | 2,855 | 2.203125 | 2 | [] | no_license | /*
* Copyright 2009-2011 Universität Duisburg-Essen, Working Group
* "Information Engineering"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems;
/** Exception class which is used by the referencesystems */
public class ReferenceSystemException extends Exception {
private static final long serialVersionUID = 5814006182634753113L;
public static int MENDELEY_VERIFIER_REQUIRED = 1;
private String httpCode;
private String errordescription;
private int otherRequired;
private String url;
public ReferenceSystemException() {
super();
httpCode = "";
}
/**
* a user action is required like the mendeley vierfier have to be sent
*
* @param otherRequired
* required type. for exampel
* ReferenceSystemException.MENDELEY_VERIFIER_REQUIRED
* @param url
* for example authentication url for mendeley
*/
public ReferenceSystemException(int otherRequired, String url) {
this.otherRequired = otherRequired;
this.url = url;
}
public ReferenceSystemException(String errordescription, String exceptionmsg) {
super(exceptionmsg);
this.errordescription = errordescription;
httpCode = "";
otherRequired = 0;
url = null;
}
public ReferenceSystemException(String httpCode, String errordescription, String exceptionmsg) {
super(exceptionmsg);
this.errordescription = errordescription;
this.httpCode = httpCode;
otherRequired = 0;
url = null;
}
/** Returns the http Code of the error description */
public String getHttpCode() {
return this.httpCode;
}
/** Returns the error description */
public String getErrordescription() {
return this.errordescription;
}
/**
* returns the required user action like
* ReferenceSystemException.MENDELEY_VERIFIER_REQUIRED
*/
public int getOtherRequired() {
return otherRequired;
}
/** Returns the url for the required user action. null if there is no url */
public String getUrl() {
return url;
}
}
| true |
c94c66c177b2bdc94b5ba34c74779c0446fd28b6 | Java | marclx/tmdm-server-se | /org.talend.mdm.core/src/com/amalto/core/webservice/WSStartProcessInstanceVariableEntry.java | UTF-8 | 908 | 1.84375 | 2 | [] | no_license | // This class was generated by the JAXRPC SI, do not edit.
// Contents subject to change without notice.
// JAX-RPC Standard Implementation (1.1.2_01,编译版 R40)
// Generated source version: 1.1.2
package com.amalto.core.webservice;
public class WSStartProcessInstanceVariableEntry {
protected java.lang.String key;
protected java.lang.String value;
public WSStartProcessInstanceVariableEntry() {
}
public WSStartProcessInstanceVariableEntry(java.lang.String key, java.lang.String value) {
this.key = key;
this.value = value;
}
public java.lang.String getKey() {
return key;
}
public void setKey(java.lang.String key) {
this.key = key;
}
public java.lang.String getValue() {
return value;
}
public void setValue(java.lang.String value) {
this.value = value;
}
}
| true |
c16e462d4439aacbee84b33c43764c1073357a17 | Java | shanghaif/YiGou | /YiGou_Item/src/main/java/com/breeze/yigo/item/service/ItemCatService.java | UTF-8 | 281 | 1.578125 | 2 | [] | no_license | package com.breeze.yigo.item.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.breeze.yigo.item.entity.ItemCat;
import com.qf.common.vo.R;
public interface ItemCatService extends IService<ItemCat> {
R queryParent();
R queryChild(int id);
}
| true |
a8d87e45e6ec7b246a7bd457d82f406615e81bc7 | Java | ZehraAsal/DayTwo | /workTwo/src/workTwo/Student.java | UTF-8 | 310 | 2.90625 | 3 | [] | no_license | package workTwo;
public class Student extends User{
private String pasword;
public Student(int id, String name, String pasword) {
super(id, name);
this.pasword = pasword;
}
public String getPasword() {
return pasword;
}
public void setPasword(String pasword) {
this.pasword = pasword;
}
}
| true |
6e14eefb1055c8d251203bebf9fab7eb80266f09 | Java | hzka/HDOJ-Java80 | /1996/src/Main.java | UTF-8 | 371 | 3 | 3 | [] | no_license | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc_01 = new Scanner(System.in);
int line_num=sc_01.nextInt();
for(int i = 0;i< line_num;i++){
int test_num = sc_01.nextInt();
double result = Math.pow(3,test_num);
System.out.println((long) result);
}
}
}
| true |
8149b8287b2883a844b1b5023823af2093bb22b8 | Java | lispwu/thinkinjava | /src/holding/E01_Gerbil.java | UTF-8 | 586 | 3.75 | 4 | [] | no_license | package holding;
import java.util.ArrayList;
import java.util.List;
class Gerbil{
private int gerbilNumber;
public Gerbil(int gerbilNumber){
this.gerbilNumber = gerbilNumber;
}
void hop(){
System.out.println("Gerbil " + gerbilNumber + " is hopping!");
}
}
public class E01_Gerbil {
public static void main(String[] args){
List<Gerbil> list = new ArrayList<Gerbil>();
for (int i = 0;i < 10;i++){
list.add(new Gerbil(i));
}
for(int i = 0;i < 10;i++){
list.get(i).hop();
}
}
}
| true |
46a37c6cbd039b3ec65c1f92b445ad998387ffcb | Java | Ritesh786/CONDOMANAGEMENT123 | /app/src/main/java/com/infoservices/lue/fragments/ReturnToHomeFragment.java | UTF-8 | 1,410 | 2.140625 | 2 | [] | no_license | package com.infoservices.lue.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.infoservices.lue.condomanagement.R;
/**
* A simple {@link Fragment} subclass.
*/
public class ReturnToHomeFragment extends Fragment {
Button button_retn_home;
public ReturnToHomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_return_to_home, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated( view, savedInstanceState );
button_retn_home=(Button)getActivity().findViewById( R.id.button_retn_home );
button_retn_home.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText( getActivity(),"Payment made Successfully!!!",Toast.LENGTH_LONG ).show();
getActivity().finish();
}
} );
}
}
| true |
2f736c8c32ac4f8010d0b92b64eca5af74b06b96 | Java | ebruogdur/ticket-app | /src/main/java/com/ticketing/app/demo/dto/base/BaseDto.java | UTF-8 | 828 | 2.0625 | 2 | [] | no_license | package com.ticketing.app.demo.dto.base;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ticketing.app.demo.enums.Status;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public abstract class BaseDto implements Serializable {
private static final long serialVersionUID = 436853142306266121L;
private UUID uuid;
@JsonIgnore
private Long companyId;
private Long createdBy;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
private Date createdTime;
private Long lastUpdatedBy;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
private Date lastUpdatedTime;
private int status = Status.ACTIVE.getCode();
}
| true |
0ee2fb2b38065e252461da68a04c5bdebd928077 | Java | 845146913/RSBot-Scripts | /src/stumpy3toes/scripts/stumpyisland/tasks/Chat.java | UTF-8 | 2,515 | 2.703125 | 3 | [] | no_license | package stumpy3toes.scripts.stumpyisland.tasks;
import org.powerbot.script.Condition;
import org.powerbot.script.Random;
import org.powerbot.script.rt4.ChatOption;
import org.powerbot.script.rt4.Component;
import stumpy3toes.api.script.ClientContext;
import stumpy3toes.api.task.Task;
public class Chat extends Task {
private static final int OLD_CHAT_CONTINUE_WIDGET_ID = 162;
private static final int[][] CHAT_CONTINUES = {
{11, 3},
{OLD_CHAT_CONTINUE_WIDGET_ID, 33},
{193, 2},
{233, 2}
};
private static final String[] CHAT_OPTIONS = {"I am brand new! This is my first time here.","I've played in the past, but not recently.","I am an experienced player."};
public Chat(ClientContext ctx) {
super(ctx, "Chat");
}
@Override
public boolean checks() {
return ctx.chat.canContinue() || getContinueComponent() != null || ctx.chat.chatOptions().size() > 0;
}
@Override
public void poll() {
setStatus("Skipping through chat");
if (ctx.chat.canContinue()) {
ctx.chat.clickContinue(true);
} else if(!ctx.chat.select().text(CHAT_OPTIONS).isEmpty()) {
ChatOption experienceOption = ctx.chat.select().text(CHAT_OPTIONS[Random.nextInt(1, CHAT_OPTIONS.length - 1)]).poll();
experienceOption.select();
} else if(!ctx.chat.select().text("No, I'm not planning to do that.").isEmpty()){
ChatOption ironManOption = ctx.chat.select().text("No, I'm not planning to do that.").poll();
ironManOption.select();
} else if (!ctx.chat.select().text("Yes.").isEmpty()) {
ChatOption bankOption = ctx.chat.select().text("Yes").poll();
bankOption.select();
} else {
Component continueComponent = getContinueComponent();
if (continueComponent != null) {
if (continueComponent.widget().id() == OLD_CHAT_CONTINUE_WIDGET_ID) {
continueComponent.click();
} else {
ctx.input.send(" ");
}
}
}
Condition.sleep(500);
}
private Component getContinueComponent() {
for (int[] chatContinues : CHAT_CONTINUES) {
Component continueComponent = ctx.widgets.component(chatContinues[0], chatContinues[1]);
if (continueComponent.visible()) {
return continueComponent;
}
}
return null;
}
}
| true |
cba94ad0bec23b4939267c23cc5ab16e485cda38 | Java | countree/learn-spring-cloud | /consumer-client/src/main/java/yyh/learn/spring/boot/ClientMainStart.java | UTF-8 | 560 | 1.898438 | 2 | [] | no_license | package yyh.learn.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
/**
* Spring Boot 应用启动类
*
* @author yyh
*/
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class ClientMainStart {
public static void main(String[] args) {
SpringApplication.run(ClientMainStart.class, args);
}
}
| true |
ab6db64f80d7822c5679d2fb83abdc3eae4f4973 | Java | yuanhaocn/Fu-Zusheng-Java | /99.我的案例/Day14_Utils/day14_Utils/src/com/syc/utils/queryrunner04/QueryRunnerDemo.java | UTF-8 | 5,469 | 2.9375 | 3 | [] | no_license | package com.syc.utils.queryrunner04;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.junit.Test;
import com.syc.utils.JdbcUtil;
import com.syc.utils.bean.User;
public class QueryRunnerDemo {
@Test
public void query01() {
Connection conn = JdbcUtil.getConnection();
String sql = "select * from user where username=?";
try {
// 创建一个QueryRunner对象
QueryRunner qr = new QueryRunner();
// 执行查询.ResultSetHandler,结果集处理器
// ResultSetHandler就是接口回调.
User user = qr.query(conn, sql, new ResultSetHandler<User>() {
@Override
public User handle(ResultSet rs) throws SQLException {
if (rs != null) {
if (rs.next()) {
try {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
User user = new User();
BeanUtils.setProperty(user, "id", id);
BeanUtils.setProperty(user, "username", username);
BeanUtils.setProperty(user, "password", password);
return user;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
return null;
}
}, "土鳖");
System.out.println(user.toString());
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
DbUtils.close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Test
public void queryByIdTest() {
try {
Connection conn = JdbcUtil.getConnection();
String sql = "select * from user where id=?";
QueryRunner qr = new QueryRunner();
// BeanHandler:将查询结果集的第一行封装为Bean.
User user = qr.query(conn, sql, new BeanHandler<>(User.class), 2);
System.out.println(user.toString());
DbUtils.close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void queryAllTest() {
try {
Connection conn = JdbcUtil.getConnection();
String sql = "select * from user";
QueryRunner qr = new QueryRunner();
// BeanListHandler:将查询结果集的每一行封装为Bean,并且会把每一个Bean都填充到List中.
List<User> users = qr.query(conn, sql, new BeanListHandler<>(User.class));
for (User user : users) {
System.out.println(user.toString());
}
DbUtils.close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void queryTest() {
try {
Connection conn = JdbcUtil.getConnection();
//String sql = "select * from user";
QueryRunner qr = new QueryRunner();
// ArrayHandler:将查询结果集的第一行封装为Array.
//Object[] query = qr.query(conn, sql, new ArrayHandler());
//将数组变为集合
//System.out.println(Arrays.asList(query));
//ArrayListHandler,将查询结果集的每一行封装为Array,并且会把每一个Array都填充到List中.
//List<Object[]> users = qr.query(conn, sql, new ArrayListHandler());
//for(Object[] objs: users){
// System.out.println(Arrays.asList(objs));
//}
//ScalarHandler:将查询结果集中的某一列给返回,该Handler常与聚合函数配合使用.
//String sql = "select count(*) from user";
//Long count = qr.query(conn, sql, new ScalarHandler<Long>());
//System.out.println("员工数量="+count);
//String sql = "select * from user where id=?";
//String username = qr.query(conn, sql, new ScalarHandler<String>("username"),2);
//System.out.println("员工姓名="+username);
//MapHandler:将结果集中的第一行,封装为Map进行输出.Map的key是列名.
String sql = "select * from user";
//Map<String, Object> map = qr.query(conn, sql, new MapHandler());
//System.out.println(map.get("username"));
//MapListHandler:将结果集中的每一行都封装为Map进行,并且把map封装到一个List中.
//Map的key是列名
//List<Map<String, Object>> maps = qr.query(conn, sql,
//new MapListHandler());
//System.out.println(maps.get(0).get("password"));
//ColumnListHandler:将结果集中的每一行的对应列的封装到一个集合中
//List<Object> names = qr.query(conn, sql, new ColumnListHandler<>("username"));
//System.out.println(names.get(1));
//BeanMapHandler:将查询结果集的每一行都封装进一个Map中.
//Map<Object, User> map = qr.query(conn, sql, new BeanMapHandler<>(User.class));
//默认情况下,Map的key是User类的id.
//System.out.println(map.get(2).getUsername());
//KeyedHandler:将查询结果集的每一行都封装为一个map,并且将这个map再封装进一个map中,外面map的key是指定的列的值.
Map<Object, Map<String, Object>> maps = qr.query(conn, sql, new KeyedHandler<>("username"));
System.out.println(maps.get("土鳖").get("password"));
DbUtils.close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true |
2c6b846aec8a8146f99b7b07190d93cadc7af2da | Java | magnayn/maven | /maven-core/src/main/java/org/apache/maven/lifecycle/statemgmt/EndForkedExecutionMojo.java | UTF-8 | 1,099 | 2.296875 | 2 | [] | no_license | package org.apache.maven.lifecycle.statemgmt;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
/**
* Restore the lifecycle execution context's current-project, and set the project instance from the
* forked execution to project.getExecutionProject() for the forking mojo to use.
*
* @author jdcasey
*
*/
public class EndForkedExecutionMojo
extends AbstractMojo
{
private int forkId = -1;
private MavenSession session;
public void execute()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Ending forked execution [fork id: " + forkId + "]" );
MavenProject executionProject = session.removeForkedProject();
MavenProject project = session.getCurrentProject();
if ( ( project != null ) && ( executionProject != null ) )
{
project.setExecutionProject( executionProject );
}
}
}
| true |
b65f3dfb010595627eb265d446b8b171b5df3c5a | Java | EBI-Metagenomics/ebi-metagenomics | /memi/memi-web/src/main/java/uk/ac/ebi/interpro/metagenomics/memi/controller/studies/DownloadStudyController.java | UTF-8 | 7,811 | 1.8125 | 2 | [] | no_license | package uk.ac.ebi.interpro.metagenomics.memi.controller.studies;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import uk.ac.ebi.interpro.metagenomics.memi.controller.MGPortalURLCollection;
import uk.ac.ebi.interpro.metagenomics.memi.controller.ModelProcessingStrategy;
import uk.ac.ebi.interpro.metagenomics.memi.dao.hibernate.AnalysisJobDAO;
import uk.ac.ebi.interpro.metagenomics.memi.dao.hibernate.PipelineReleaseDAO;
import uk.ac.ebi.interpro.metagenomics.memi.exceptionHandling.EntryNotFoundException;
import uk.ac.ebi.interpro.metagenomics.memi.model.hibernate.Study;
import uk.ac.ebi.interpro.metagenomics.memi.services.MemiDownloadService;
import uk.ac.ebi.interpro.metagenomics.memi.springmvc.model.ViewModel;
import uk.ac.ebi.interpro.metagenomics.memi.springmvc.model.analysisPage.DownloadableFileDefinition;
import uk.ac.ebi.interpro.metagenomics.memi.springmvc.model.study.DownloadViewModel;
import uk.ac.ebi.interpro.metagenomics.memi.springmvc.modelbuilder.ViewModelBuilder;
import uk.ac.ebi.interpro.metagenomics.memi.springmvc.modelbuilder.study.StudyDownloadViewModelBuilder;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Map;
/**
* Download tab on the project page.
*/
@Controller
public class DownloadStudyController extends AbstractStudyViewController {
private static final Log log = LogFactory.getLog(DownloadStudyController.class);
@Resource
protected AnalysisJobDAO analysisJobDAO;
@Resource
private PipelineReleaseDAO pipelineReleaseDAO;
@Resource
private MemiDownloadService downloadService;
@Resource
protected Map<String, DownloadableFileDefinition> fileDefinitionsMap;
@Autowired
ServletContext servletContext;
protected String getModelViewName() {
return "tabs/study/download";
}
private ModelProcessingStrategy<Study> createNewModelProcessingStrategy() {
return new ModelProcessingStrategy<Study>() {
@Override
public void processModel(ModelMap model, Study study) {
log.info("Building download view model...");
populateModel(model, study);
}
};
}
/**
* Request method for the download tab on the sample view page.
*
* @throws java.io.IOException
*/
@RequestMapping(value = MGPortalURLCollection.PROJECT_DOWNLOAD)
public ModelAndView ajaxLoadDownloadTab(@PathVariable final String studyId,
final ModelMap model) {
return checkAccessAndBuildModel(createNewModelProcessingStrategy(), model, getSecuredEntity(studyId), getModelViewName());
}
protected void populateModel(final ModelMap model, final Study study) {
if (study == null) {
throw new EntryNotFoundException();
}
final String pageTitle = "Download view: " + study.getStudyId();
final ViewModelBuilder<DownloadViewModel> builder = new StudyDownloadViewModelBuilder(
userManager,
getEbiSearchForm(),
pageTitle, // Not really needed as this is within an AJAX tab anyway?
getBreadcrumbs(study), // Not really needed as this is within an AJAX tab anyway?
propertyContainer,
fileDefinitionsMap,
study,
pipelineReleaseDAO);
final DownloadViewModel downloadViewModel = builder.getModel();
downloadViewModel.changeToHighlightedClass(ViewModel.TAB_CLASS_PROJECTS_VIEW); // Not really needed as this is within an AJAX tab anyway?
model.addAttribute(ViewModel.MODEL_ATTR_NAME, downloadViewModel);
}
/**
* Perform the project summary file download.
*
* @param studyId
* @param releaseVersion
* @param exportValue
* @param response
* @param request
* @throws IOException
*/
@RequestMapping(value = MGPortalURLCollection.PROJECT_SUMMARY_EXPORT)
public void doHandleSummaryExports(@PathVariable final String studyId,
@PathVariable final String releaseVersion,
@RequestParam(required = true, value = "exportValue") final String exportValue,
final HttpServletResponse response,
final HttpServletRequest request) throws IOException {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
response.setLocale(Locale.ENGLISH);
Study study = getSecuredEntity(studyId);
if (study != null) {
if (isAccessible(study)) {
File file = getDownloadFile(study, releaseVersion, exportValue);
if (file != null) {
final String filename = studyId + "_" + exportValue + "_v" + releaseVersion + ".tsv";
downloadService.openDownloadDialog(response, request, file, filename, false);
} else {//analysis job is NULL
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
} else {//access denied
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.sendRedirect("/metagenomics/projects/" + studyId + "/accessDenied");
}
} else {//run is NULL
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
private File getDownloadFile(final Study study, final String version, final String exportValue) {
String filename = getAbsResultDirPath(study) + File.separator + "version_" + version + File.separator + "project-summary" + File.separator + exportValue;
if (!exportValue.equals("diversity")) {
filename += "_v" + version;
}
filename += ".tsv";
return new File(filename);
}
private String getAbsResultDirPath(final Study study) {
final String rootPath = propertyContainer.getPathToAnalysisDirectory();
return rootPath + study.getResultDirectory();
}
@RequestMapping(value = MGPortalURLCollection.PROJECT_DOWNLOAD_PCA,
produces = "image/svg+xml")
public
@ResponseBody
byte[] pcaImage(@PathVariable final String studyId,
@PathVariable final String releaseVersion,
final HttpServletResponse response) throws IOException {
final Study study = getSecuredEntity(studyId);
if (isAccessible(study)) {
final String filename = getAbsResultDirPath(study) + File.separator + "version_" + releaseVersion + File.separator + "project-summary" + File.separator + "pca.svg";
InputStream input = new FileInputStream(filename);
return IOUtils.toByteArray(input);
} else {//access denied
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.sendRedirect("/metagenomics/accessDenied");
return new byte[0];
}
}
}
| true |
f82c658b5ec777c39aba4514c1f330f94681bd59 | Java | jbrimlow/Veriwolf-monitoring | /database/app/src/main/java/com/google/firebase/quickstart/database/PhotoReviewActivity.java | UTF-8 | 5,183 | 2.125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0",
"LicenseRef-scancode-other-permissive"
] | permissive | package com.google.firebase.quickstart.database;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.models.Photo;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import org.w3c.dom.Text;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by john on 12/22/16.
*/
public class PhotoReviewActivity extends BaseActivity {
private DatabaseReference mPhotoReference;
private ValueEventListener mPhotoListener;
FirebaseStorage storage;
StorageReference storageReference;
public static final String EXTRA_PHOTO_KEY = "photo_key";
private ImageView photoView;
private TextView description;
private String mPhotoKey;
private String firebasePath;
private Button done;
private TextView contractor;
private TextView date;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_review);
mPhotoKey = getIntent().getStringExtra(EXTRA_PHOTO_KEY);
if (mPhotoKey == null) {
throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
}
mPhotoReference = FirebaseDatabase.getInstance().getReference().child("photos").child(mPhotoKey);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReferenceFromUrl("gs://veriwolf-test.appspot.com");
photoView = (ImageView) findViewById(R.id.imageView2);
description = (TextView) findViewById(R.id.descView);
contractor = (TextView) findViewById(R.id.contractorView);
date = (TextView) findViewById(R.id.dateView);
done = (Button) findViewById(R.id.doneButton);
}
@Override
public void onStart() {
super.onStart();
ValueEventListener photoListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Photo photo = dataSnapshot.getValue(Photo.class);
//photoView.setImageBitmap(decodeDatabaseImage(photo.getImgBase64()));
firebasePath = photo.getFilepath();
try {
final File localFile = File.createTempFile("images", "png");
storageReference.child(firebasePath).getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
photoView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
description.setText(photo.getDescription());
contractor.setText("Contractor: " + photo.getContractor());
if (photo.getScantime() != null) {
date.setText("Taken on: " + photo.getScantime().toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mPhotoReference.addValueEventListener(photoListener);
// Keep copy of photo listener so we can remove it when app stops
mPhotoListener = photoListener;
}
@Override
public void onResume(){
super.onResume();
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
public void onStop() {
super.onStop();
// clean up photo listener
if (mPhotoListener != null) {
mPhotoReference.removeEventListener(mPhotoListener);
}
}
public static Bitmap decodeDatabaseImage(String encode) {
byte[] byteArrayDecoded = android.util.Base64.decode(encode, android.util.Base64.DEFAULT);
InputStream inputStream = new ByteArrayInputStream(byteArrayDecoded);
return BitmapFactory.decodeStream(inputStream);
}
}
| true |
75aae87eb131dce04637339468ecee0a7c4f9c3e | Java | cjeanMa/RestSpringBoot | /src/main/java/com/jmcastle/platziCurso/web/controller/ProductController.java | UTF-8 | 2,375 | 2.28125 | 2 | [] | no_license | package com.jmcastle.platziCurso.web.controller;
import com.jmcastle.platziCurso.domain.Product;
import com.jmcastle.platziCurso.domain.service.ProductService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestControllerAdvice
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/all")
@ApiOperation("Get all products of the store")
@ApiResponse(code = 200, message="OK")
public ResponseEntity<List<Product>> getAll(){
return new ResponseEntity<>(productService.getAll(), HttpStatus.OK);
};
@GetMapping("/{id}")
@ApiOperation("Get product by idProduct")
@ApiResponses({
@ApiResponse(code = 200, message = "product found"),
@ApiResponse(code = 404, message = "product not found")
})
public ResponseEntity<Product> getProduct(
@ApiParam(value="Id of the product", required = true, example = "2")
@PathVariable("id") int productId){
return productService.getProduct(productId)
.map(product -> new ResponseEntity<>(product, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@GetMapping("/categoria/{catId}")
public ResponseEntity<List<Product>> getByCategory(@PathVariable("catId") int categoryId){
return productService.getByCategory(categoryId)
.map(products -> new ResponseEntity<>(products, HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping("/save")
public ResponseEntity<Product> save(@RequestBody Product product){
return new ResponseEntity<>(productService.save(product),HttpStatus.CREATED);
}
@DeleteMapping("/delete/{id}")
public ResponseEntity delete(@PathVariable("id") int productId){
return productService.delete(productId)?new ResponseEntity<>(HttpStatus.OK):new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
| true |
59ac24770bd2b366302eeba93a4bb03ad2219054 | Java | peesusanthosh/Weather-App | /Weather App/app/src/main/java/com/example/hw05/CityWeatherActivity.java | UTF-8 | 7,043 | 2.078125 | 2 | [] | no_license | package com.example.hw05;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class CityWeatherActivity extends AppCompatActivity implements GetWeatherDataAsync.IData{
String state,city;
ArrayList<StorageDetails> favouriteslist=new ArrayList<StorageDetails>();
ArrayList<StorageDetails> tfavouriteslist=new ArrayList<StorageDetails>();
int minimumtemperature,maximumtemperature;
ArrayList<WeatherItems> WeatherItems= new ArrayList<WeatherItems>();
ProgressDialog pd;
ListView mylistview;
TextView currentlocation;
GetWeatherDataAsync gwda=new GetWeatherDataAsync(CityWeatherActivity.this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_weather);
mylistview=(ListView) findViewById(R.id.mylistview);
if (getIntent().getExtras() != null) {
tfavouriteslist = (ArrayList<StorageDetails>) getIntent().getExtras().getSerializable(MainActivity.FAVOURITES_ARRAY);
if(tfavouriteslist!=null && tfavouriteslist.size()!=0){
favouriteslist=tfavouriteslist;
}
pd=new ProgressDialog(this);
pd.setCancelable(false);
pd.setMessage("Loading Hourly Data");
currentlocation=(TextView) findViewById(R.id.currentlocation);
state=getIntent().getExtras().getString("State");
city=getIntent().getExtras().getString("City");
if (city.contains(" ")){
city=city.replace(" ","_");
}
String jsonurl="http://api.wunderground.com/api/53641d79875235dc/hourly/q/" + state + "/" + city + ".json";
if (city.contains("_")){
city=city.replace("_"," ");
}
gwda.execute(jsonurl);
}
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent in = new Intent(CityWeatherActivity.this, DetailsActivity.class);
in.putExtra("Items", WeatherItems.get(i));
in.putExtra("State", state);
in.putExtra("City", city);
in.putExtra("MaxTemp", maximumtemperature);
in.putExtra("MinTemp", minimumtemperature);
startActivity(in);
}
});
}
@Override
public void maintainWeatherItemsList(ArrayList<WeatherItems> weatherItemses) {
if(weatherItemses!=null) {
WeatherItems = weatherItemses;
MyAdapter adapter = new MyAdapter(this, R.layout.row_layout, WeatherItems);
mylistview.setAdapter(adapter);
adapter.setNotifyOnChange(true);
currentlocation.setText("Current Location: " + city + ", " + state + "");
calculateMaxandMin();
}
else {
WeatherItems=null;
Toast.makeText(CityWeatherActivity.this,"No cities match your query",Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
final Intent mainIntent = new Intent(CityWeatherActivity.this, MainActivity.class);
CityWeatherActivity.this.startActivity(mainIntent);
CityWeatherActivity.this.finish();
}
}, 5000);
}
}
private void calculateMaxandMin() {
minimumtemperature=Integer.parseInt(WeatherItems.get(0).getTemperature());
maximumtemperature=Integer.parseInt(WeatherItems.get(0).getTemperature());
for (int i=0;i<WeatherItems.size();i++){
if(Integer.parseInt(WeatherItems.get(i).getTemperature())< minimumtemperature){
minimumtemperature=Integer.parseInt(WeatherItems.get(i).getTemperature());
}
if(Integer.parseInt(WeatherItems.get(i).getTemperature())> maximumtemperature){
maximumtemperature=Integer.parseInt(WeatherItems.get(i).getTemperature());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
String date= sdf.format(cal.getTime()).toString();
StorageDetails sd=new StorageDetails(city,state,WeatherItems.get(0).getTemperature().toString(),date);
if(favouriteslist!=null && favouriteslist.size()!=0) {
for (int i = 0; i < favouriteslist.size(); i++) {
if (favouriteslist.get(i).city.toString().equals(sd.city.toString()) && favouriteslist.get(i).state.toString().equals(sd.state.toString())) {
favouriteslist.remove(i);
favouriteslist.add(i, sd);
Toast.makeText(CityWeatherActivity.this, "Updated Favourites Record.", Toast.LENGTH_LONG).show();
}
}
}
if(!favouriteslist.contains(sd) || favouriteslist.size()==0 || favouriteslist==null){
favouriteslist.add(sd);
Toast.makeText(CityWeatherActivity.this, "Added to Favourites", Toast.LENGTH_LONG).show();
}
int id = item.getItemId();
if (id == R.id.add_f) {
if(WeatherItems!=null) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(favouriteslist);
prefsEditor.putString("MyWeaherObject", json);
prefsEditor.commit();
}
else{
Toast.makeText(CityWeatherActivity.this, "Sorry! The list is empty and cannot be added to favourites.", Toast.LENGTH_LONG).show();
}
}
return true;
}
@Override
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
}
| true |
2a1cc60f640e501ce6e1806036120ac6510cd829 | Java | big-mouth-cn/senon2 | /senon-common/src/main/java/org/bigmouth/senon/commom/zookeeper/listener/Change.java | UTF-8 | 375 | 1.945313 | 2 | [] | no_license | package org.bigmouth.senon.commom.zookeeper.listener;
import org.bigmouth.senon.commom.zookeeper.listener.children.ChildrenMonitor;
public interface Change {
void add(ChildrenMonitor monitor, String path, byte[] data);
void update(ChildrenMonitor monitor, String path, byte[] data);
void remove(ChildrenMonitor monitor, String path, byte[] data);
}
| true |
cb5e4e0badff1de0588d9b5646c19f9d1340fbd6 | Java | lanshifu/FFmpegDemo | /src/main/java/net/vidageek/mirror/invoke/MethodHandlerByMethod.java | UTF-8 | 2,234 | 2.75 | 3 | [] | no_license | package net.vidageek.mirror.invoke;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import net.vidageek.mirror.invoke.dsl.MethodHandler;
import net.vidageek.mirror.provider.MethodReflectionProvider;
import net.vidageek.mirror.provider.ReflectionProvider;
public final class MethodHandlerByMethod implements MethodHandler {
private final Class<?> clazz;
private final Method method;
private final ReflectionProvider provider;
private final Object target;
public MethodHandlerByMethod(ReflectionProvider reflectionProvider, Object obj, Class<?> cls, Method method) {
if (cls == null) {
throw new IllegalArgumentException("clazz cannot be null");
} else if (method == null) {
throw new IllegalArgumentException("method cannot be null");
} else if (method.getDeclaringClass().isAssignableFrom(cls)) {
this.provider = reflectionProvider;
this.target = obj;
this.clazz = cls;
this.method = method;
} else {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("method ");
stringBuilder.append(method);
stringBuilder.append(" cannot be invoked on clazz ");
stringBuilder.append(cls.getName());
throw new IllegalArgumentException(stringBuilder.toString());
}
}
public Object withArgs(Object... objArr) {
if (this.target != null || Modifier.isStatic(this.method.getModifiers())) {
MethodReflectionProvider methodReflectionProvider = this.provider.getMethodReflectionProvider(this.target, this.clazz, this.method);
methodReflectionProvider.setAccessible();
return methodReflectionProvider.invoke(objArr);
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("attempt to call instance method ");
stringBuilder.append(this.method.getName());
stringBuilder.append(" on class ");
stringBuilder.append(this.clazz.getName());
throw new IllegalStateException(stringBuilder.toString());
}
public Object withoutArgs() {
return withArgs(new Object[0]);
}
}
| true |
f767ccbe549ccb0c60da90b6804b1b29fd9d5345 | Java | tinhCaoDuy/WebBlogMVC | /src/blog/entity/MailForm.java | UTF-8 | 1,794 | 2.140625 | 2 | [] | no_license | package blog.entity;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "MAILFORM")
public class MailForm {
@Id
@GeneratedValue
@Column(name = "MAMAIL")
private int maMail;
@Column(name = "MAILFROM")
private String mailFrom;
@Column(name = "MAILSUBJECT")
private String mailSubject;
@Column(name = "MAILBODY")
private String mailBody;
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Column(name = "THOIGIAN")
private Date thoiGian;
@OneToMany(mappedBy="maMail",fetch = FetchType.EAGER)
private Collection<ThongBao> thongBao;
public Collection<ThongBao> getThongBao() {
return thongBao;
}
public void setThongBao(Collection<ThongBao> thongBao) {
this.thongBao = thongBao;
}
public MailForm() {
}
public int getMaMail() {
return maMail;
}
public void setMaMail(int maMail) {
this.maMail = maMail;
}
public String getMailFrom() {
return mailFrom;
}
public void setMailFrom(String mailFrom) {
this.mailFrom = mailFrom;
}
public String getMailSubject() {
return mailSubject;
}
public void setMailSubject(String mailSubject) {
this.mailSubject = mailSubject;
}
public String getMailBody() {
return mailBody;
}
public void setMailBody(String mailBody) {
this.mailBody = mailBody;
}
public Date getThoiGian() {
return thoiGian;
}
public void setThoiGian(Date thoiGian) {
this.thoiGian = thoiGian;
}
}
| true |
4dd1e425dadb685b19cc2d6e22e537390eb79226 | Java | xiaop1ng/PlayWithSpringBoot | /src/main/java/com/xiaoping/cmdtest/TimeTest.java | UTF-8 | 326 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | package com.xiaoping.cmdtest;
import java.util.Date;
public class TimeTest {
public static void main(String[] args) {
Date expireTime = new Date();
System.out.println(expireTime);
expireTime.setTime(expireTime.getTime() + 1000*60*30); // 半小时
System.out.println(expireTime);
}
}
| true |
487caa2ae066349dca4244442abe40e5b89afdb2 | Java | FurtosStelianEmanuel/SmartHomeSystem-mobile | /app/src/main/java/com/example/smarthomesystem/FragmentOnConnectAutomation.java | UTF-8 | 12,765 | 2.234375 | 2 | [] | no_license | package com.example.smarthomesystem;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class FragmentOnConnectAutomation extends Fragment {
private static class Time implements Serializable {
int ora, minut;
public Time(int ora, int minut) {
set(ora, minut);
}
/**
* @param time format HH:mm
*/
public Time(String time) {
String ar[] = time.split(":");
this.ora = Integer.valueOf(ar[0]);
this.minut = Integer.valueOf(ar[1]);
}
public final void set(int ora, int minut) {
this.ora = ora;
this.minut = minut;
}
public String toString() {
return (ora < 10 ? "0" + ora : ora + "") + ":" + (minut < 10 ? "0" + minut : minut + "");
}
}
private Time disconnectTime;
public void notifyConnectionLost() {
disconnectTime = new Time(FragmentOnConnectAutomation.CURRENT_TIME());
}
public static class Store implements Serializable {
Time oraStart, oraStop;
/**
* 'aprinde luminile doar daca am fost plecat mai mult de 20 de minute'
*/
int timeout;
boolean enabled;
public Store(Time oraStart, Time oraStop, int timeout, boolean enabled) {
this.oraStart = oraStart;
this.oraStop = oraStop;
this.timeout = timeout;
this.enabled = enabled;
}
static Store getDefault() {
return new Store(new Time(22, 00), new Time(23, 59), 20, false);
}
}
public static int getMinuteDifference(String t1, String t2) throws ParseException {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(new SimpleDateFormat("HH:mm").parse(t1));
Calendar stopCalendar = Calendar.getInstance();
stopCalendar.setTime(new SimpleDateFormat("HH:mm").parse(t2));
Calendar diffCalendar = Calendar.getInstance();
diffCalendar.setTime(new Date(stopCalendar.getTimeInMillis() - startCalendar.getTimeInMillis() - 7200000));
int ore = diffCalendar.get(Calendar.HOUR_OF_DAY);
int minute = diffCalendar.get(Calendar.MINUTE);
int total = minute;
while (ore > 0) {
total += 60;
ore--;
}
return total;
}
public static boolean timeoutChecked(String disconnectTime, String currentTime, int timeout) throws ParseException {
return getMinuteDifference(disconnectTime, currentTime) >= timeout;
}
public static boolean isSecondDay(String startTime, String stopTime) throws ParseException {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(new SimpleDateFormat("HH:mm").parse(startTime));
Calendar stopCalendar = Calendar.getInstance();
stopCalendar.setTime(new SimpleDateFormat("HH:mm").parse(stopTime));
return stopCalendar.before(startCalendar);
}
public static boolean isBetweenHours(String startTime, String stopTime, String currentTime) throws ParseException {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(new SimpleDateFormat("HH:mm").parse(startTime));
startCalendar.add(Calendar.DATE, 1);
Calendar stopCalendar = Calendar.getInstance();
stopCalendar.setTime(new SimpleDateFormat("HH:mm").parse(stopTime));
stopCalendar.add(Calendar.DATE, 1);
Calendar calendarCurrent = Calendar.getInstance();
calendarCurrent.setTime(new SimpleDateFormat("HH:mm").parse(currentTime));
calendarCurrent.add(Calendar.DATE, 1);
Date x = calendarCurrent.getTime();
if (isSecondDay(startTime, stopTime)) {
return x.after(startCalendar.getTime()) || x.compareTo(startCalendar.getTime()) == 0
|| x.before(stopCalendar.getTime()) || x.compareTo(stopCalendar.getTime()) == 0;
} else {
return (x.after(startCalendar.getTime()) || x.compareTo(startCalendar.getTime()) == 0)
&& (x.before(stopCalendar.getTime()) || x.compareTo(stopCalendar.getTime()) == 0);
}
}
public static String CURRENT_TIME() {
return new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
}
//<editor-fold desc="Varibaible" defaultstate="collapsed">
/**
* Initializat in {@link MainActivity}
*/
public static Store ON_CONNECT_AUTOMATION_SETTINGS;
MainActivity main;
TimePickerDialog intervalStartDialog, intervalStopDialog;
Switch enabledSwitch;
TextView intervalOrarTextView, timeoutTextView;
//</editor-fold>
public FragmentOnConnectAutomation() {
// Required empty public constructor
}
public FragmentOnConnectAutomation(MainActivity main) {
this.main = main;
}
public void nightModePreset(View v) {
((ImageView) (v.findViewById(R.id.icon2))).setImageResource(R.drawable.icon_on_connect_automatizare_night);
((TextView) (v.findViewById(R.id.textView15))).setTextColor(App.NIGHT_MODE_TEXT);
((TextView) (v.findViewById(R.id.textView18))).setTextColor(App.NIGHT_MODE_TEXT);
v.findViewById(R.id.reconectare_lumini_switch).setBackgroundColor(App.NIGHT_MODE_BUTTON_BACKGROUND);
((Switch) (v.findViewById(R.id.reconectare_lumini_switch))).setTextColor(App.NIGHT_MODE_TEXT);
v.findViewById(R.id.modifica_interval_orar).setBackgroundColor(App.NIGHT_MODE_BUTTON_BACKGROUND);
((Button) (v.findViewById(R.id.modifica_interval_orar))).setTextColor(App.NIGHT_MODE_TEXT);
v.findViewById(R.id.modifica_minute_plecate).setBackgroundColor(App.NIGHT_MODE_BUTTON_BACKGROUND);
((Button) (v.findViewById(R.id.modifica_minute_plecate))).setTextColor(App.NIGHT_MODE_TEXT);
}
public void setIntervalOrarText(Time oraStart, Time oraStop) {
intervalOrarTextView.setText("Aprinde luminile doar in intervalul orar " + oraStart.toString() + "-" + oraStop.toString());
}
public void setTimeoutText(int timeout) {
timeoutTextView.setText("Aprinde luminile doar daca am fost plecat mai mult de " + timeout + " " + (timeout == 1 ? "minut" : "minute"));
}
/**
* Apelat cand UI-ul a fost actualizat sub vreo forma (switch,timepicker), actualizeaza si textul pentru textView-uri
* Actualizeaza {@link #ON_CONNECT_AUTOMATION_SETTINGS} si apeleaza {@link MainActivity#saveOnConnectAutomationSettings()}
*/
public void onChange(Time startTime, Time stopTime, int timeout) {
if (startTime != null) {
ON_CONNECT_AUTOMATION_SETTINGS.oraStart = startTime;
}
if (stopTime != null) {
ON_CONNECT_AUTOMATION_SETTINGS.oraStop = stopTime;
}
if (timeout >= 0) {
ON_CONNECT_AUTOMATION_SETTINGS.timeout = timeout;
}
ON_CONNECT_AUTOMATION_SETTINGS.enabled = enabledSwitch.isChecked();
//inca pentru timeout nu este un UI
setIntervalOrarText(ON_CONNECT_AUTOMATION_SETTINGS.oraStart, ON_CONNECT_AUTOMATION_SETTINGS.oraStop);
setTimeoutText(ON_CONNECT_AUTOMATION_SETTINGS.timeout);
try {
main.saveOnConnectAutomationSettings();
} catch (IOException e) {
Log.println(Log.ASSERT, "EROARE", "Nu am putut salva setarile pentru onConnectAutomation");
e.printStackTrace();
}
}
public boolean shouldAutoLightOn() {
try {
return
ON_CONNECT_AUTOMATION_SETTINGS.enabled
&& FragmentOnConnectAutomation.isBetweenHours(ON_CONNECT_AUTOMATION_SETTINGS.oraStart.toString(), ON_CONNECT_AUTOMATION_SETTINGS.oraStop.toString(), FragmentOnConnectAutomation.CURRENT_TIME())
&& FragmentOnConnectAutomation.timeoutChecked(disconnectTime.toString(), FragmentOnConnectAutomation.CURRENT_TIME(), ON_CONNECT_AUTOMATION_SETTINGS.timeout);
} catch (ParseException ex) {
Log.println(Log.ASSERT, "eroare", ex.toString());
ex.printStackTrace();
return false;
}
}
public void arduinoConnected() {
//Log.println(Log.ASSERT,"interval",ON_CONNECT_AUTOMATION_SETTINGS.ora);
if (shouldAutoLightOn()) {
main.pcReader.aprindeCuloareUsa();
Log.println(Log.ASSERT, "ATENTIE", "A fost pornita lumina din OnConnectAutomation");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_on_connect_automation, container, false);
final NumberPickerDialog numberPickerDialog = new NumberPickerDialog();
numberPickerDialog.setValueChangeListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
onChange(null,null,newVal);
}
});
intervalStartDialog = new TimePickerDialog(v.getContext(), AlarmFragment.getTimePickerDialogType(),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(view.getContext(), "Setează ora de final", Toast.LENGTH_SHORT).show();
intervalStopDialog.show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
onChange(new Time(view.getHour(), view.getMinute()), null, -1);
}
}
},
0, 0, true);
intervalStopDialog = new TimePickerDialog(v.getContext(), AlarmFragment.getTimePickerDialogType(),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
onChange(null, new Time(view.getHour(), view.getMinute()), -1);
}
}
},
0, 0, true);
v.findViewById(R.id.modifica_interval_orar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View _v) {
Toast.makeText(_v.getContext(), "Setează ora de început", Toast.LENGTH_SHORT).show();
intervalStartDialog.show();
}
});
v.findViewById(R.id.modifica_minute_plecate).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getFragmentManager() != null) {
numberPickerDialog.show(getFragmentManager(),"numberpicker");
}else{
Log.println(Log.ASSERT,"eroare","afisare numberpicker");
}
}
});
enabledSwitch = v.findViewById(R.id.reconectare_lumini_switch);
intervalOrarTextView = v.findViewById(R.id.textView15);
timeoutTextView = v.findViewById(R.id.textView18);
enabledSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
onChange(null, null, -1);
}
});
enabledSwitch.setChecked(ON_CONNECT_AUTOMATION_SETTINGS.enabled);
setIntervalOrarText(ON_CONNECT_AUTOMATION_SETTINGS.oraStart, ON_CONNECT_AUTOMATION_SETTINGS.oraStop);
setTimeoutText(ON_CONNECT_AUTOMATION_SETTINGS.timeout);
if (App.NIGHT_MODE_ENABLED) {
nightModePreset(v);
}
return v;
}
}
| true |
636ffbf5a9f69f50e32ea7b8d812245ba95b227d | Java | jnchen/shiro-demo | /src/main/java/com/example/demo/config/ShiroConfig.java | UTF-8 | 2,936 | 2.203125 | 2 | [] | no_license | package com.example.demo.config;
import com.example.demo.security.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by caojingchen on 2018/1/23.
*/
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
System.out.println("ShiroConfiguration.shiroFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/doLogin","anon");
filterChainDefinitionMap.put("/login","anon");
filterChainDefinitionMap.put("/static/**","anon");
filterChainDefinitionMap.put("/logout","logout");
filterChainDefinitionMap.put("/**","authc");
// filterChainDefinitionMap.put("/**","anon");
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
return hashedCredentialsMatcher;
}
@Bean
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return shiroRealm;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
return securityManager;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
| true |
0d515115b01285841c0f312854ac16ed7b791992 | Java | monisha321/TestAutomation | /JavaDemoPrograms/src/com/sgtesting/assgn4/ArrayshortFor.java | UTF-8 | 205 | 2.671875 | 3 | [] | no_license | package com.sgtesting.assgn4;
public class ArrayshortFor {
public static void main(String[] args) {
short a[]= {109,108,107};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
| true |
f675de8107e6cf33bac1fa634523138cc54fe060 | Java | egemenozdag/friendship-digraph-java | /FriendshipAnalyzer.java | UTF-8 | 4,292 | 3.109375 | 3 | [] | no_license | import edu.princeton.cs.algs4.Graph;
import edu.princeton.cs.algs4.Queue;
//-----------------------------------------------------
//Title: FriendshipGraph Analyzer
//Author: Egemen OZDAG
//ID: 47755722122
//Section: 1
//Assignment: 1
//Description: This class is analyzer of the friendshipGraph class.
//-----------------------------------------------------
public class FriendshipAnalyzer {
private int E;
private final int V;
private FriendshipGraph[][] adj;
private boolean[] marked;
private int[] id;
private int[] edgeTo;
private int[] distTo;
private int count;
public FriendshipAnalyzer(FriendshipGraph graph){
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Summary: This method is introducing the FriendshipGraph class to FrienshipAnalyzer class.
// Precondition: graph is the graph.
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
V = graph.V();
E = graph.E();
adj = graph.adj();
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Summary: This method is finding the average number of friends.
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
public double avgNumOfFr(){return ((double)this.E / (2 * (double)adj.length));}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Summary: This method is finding the connected components.
// Precondition: marked is looking is the verticles(V) marked, and id is like serial number of V, count is taking total connection number per verticles.
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
public int connectedComp(){
marked = new boolean[V];
id = new int[V];
for (int v = 0; v < V; v++){
if (!marked[v]){
depthFirstSearch(G, v);
count++;
}
}
return 1;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Summary: This method is finding the distance.
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
public int findDist(String kul1, String kul2){return Integer.MAX_VALUE;}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Summary: This method is depth first search method, G is the graph and s is the verticles.
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
private void depthFirstSearch(FriendshipGraph G, String v){
marked[V] = true;
id[V] = count;
for (int w : G.adj())if (!marked[w])depthFirstSearch(G, w);
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Summary: This method is breath first search method, G is the graph and s is the verticles.
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
private void breadthFirstSearch(Graph G, int s){
Queue<Integer> q = new Queue<Integer>();
q.enqueue(s);
marked[s] = true;
distTo[s] = 0;
while (!q.isEmpty()) { int v = q.dequeue();
for (int w : G.adj(v)) {
if (!marked[w]) {
q.enqueue(w);
marked[w] = true;
edgeTo[w] = v;
distTo[w] = distTo[v] + 1;
}
}
}
}
}
| true |
b3f37ca7709ff90a89bf76cc3cc36952f3b034c2 | Java | HosseinEynloo/RasaMedia | /app/src/main/java/com/rasa/computerman/WebService/Medias/GetMedia/iGetMedia.java | UTF-8 | 630 | 2.15625 | 2 | [] | no_license | package com.rasa.computerman.WebService.Medias.GetMedia;
import com.rasa.computerman.WebService.Medias.GetMedia.Model.ResponseGetMedia;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface iGetMedia {
void doGetGetMedia(int mediaId,String deviceId);
interface iResult {
void onSuccessGetMedia(ResponseGetMedia getMedia);
void onFailedGetMedia(int errorId, String ErrorMessage);
}
interface apiRequest {
@GET("Medias/GetMedia")
Call<ResponseGetMedia> GetMedia(@Query("mediaId")int mediaId, @Query("deviceId")String deviceId);
}
}
| true |
b11fb57602694fb3fd324ccc20f5f368a5a5fdc7 | Java | hayasam/lightweight-effectiveness | /projects/checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MissingSwitchDefaultCheck.java | UTF-8 | 3,355 | 2.546875 | 3 | [
"MIT",
"Apache-2.0",
"LGPL-2.1-only"
] | permissive | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2018 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import com.puppycrawl.tools.checkstyle.StatelessCheck;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* <p>
* Checks that switch statement has "default" clause.
* </p>
* <p>
* Rationale: It's usually a good idea to introduce a
* default case in every switch statement. Even if
* the developer is sure that all currently possible
* cases are covered, this should be expressed in the
* default branch, e.g. by using an assertion. This way
* the code is protected against later changes, e.g.
* introduction of new types in an enumeration type.
* </p>
* <p>
* An example of how to configure the check is:
* </p>
* <pre>
* <module name="MissingSwitchDefault"/>
* </pre>
*/
@StatelessCheck
public class MissingSwitchDefaultCheck extends AbstractCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "missing.switch.default";
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.LITERAL_SWITCH};
}
@Override
public void visitToken(DetailAST ast) {
final DetailAST firstCaseGroupAst = ast.findFirstToken(TokenTypes.CASE_GROUP);
if (!containsDefaultSwitch(firstCaseGroupAst)) {
log(ast.getLineNo(), MSG_KEY);
}
}
/**
* Checks if the case group or its sibling contain the 'default' switch.
* @param caseGroupAst first case group to check.
* @return true if 'default' switch found.
*/
private static boolean containsDefaultSwitch(DetailAST caseGroupAst) {
DetailAST nextAst = caseGroupAst;
boolean found = false;
while (nextAst != null) {
if (nextAst.findFirstToken(TokenTypes.LITERAL_DEFAULT) != null) {
found = true;
break;
}
nextAst = nextAst.getNextSibling();
}
return found;
}
}
| true |
8c9082c3f6eaf43e0e69ce8ad92370085d82ae6b | Java | zondahuman/algorithm-svr | /algorithm-leetcode/src/main/java/com/abin/lee/algorithm/leetcode/arrarer/LongestCommonPrefix.java | UTF-8 | 1,703 | 3.859375 | 4 | [
"Apache-2.0"
] | permissive | package com.abin.lee.algorithm.leetcode.arrarer;
import org.junit.Test;
/**
* Created by abin on 2018/9/15.
* 14. Longest Common Prefix
* https://leetcode.com/problems/longest-common-prefix/description/
*/
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}
/**
* Java中indexOf的用法
* indexOf有四种用法:
* 1.indexOf(int ch) 在给定字符串中查找字符(ASCII),找到返回字符数组所对应的下标找不到返回-1
* 2.indexOf(String str)在给定符串中查找另一个字符串。。。
* 3.indexOf(int ch,int fromIndex)从指定的下标开始查找某个字符,查找到返回下标,查找不到返回-1
* 4.indexOf(String str,int fromIndex)从指定的下标开始查找某个字符串。。。
*
* @param args
*/
public static void main(String[] args) {
String[] param = new String[]{"flower", "flow", "flight"};
// String[] param = new String[] {"dog","racecar","car"};
String result = new LongestCommonPrefix().longestCommonPrefix(param);
System.out.println("result=" + result);
}
@Test
public void test() {
String param1 = "ab";
String param2 = "abc";
System.out.println(param2.indexOf(param1));
System.out.println(param1.indexOf(param2));
}
}
| true |
27784423b0e478f94e8d1e93f213ea94cb214320 | Java | nxzh/algs | /src/exercise/java/me/siduzy/ch01/sec01/E010127.java | UTF-8 | 1,555 | 3.40625 | 3 | [] | no_license | package me.siduzy.ch01.sec01;
public class E010127 {
private static long count = 0;
/*
if n = 100, k = 50:
1st: (N-1, k, p) + (N-1, k-1, p)
2nd: (N-2, k, p) + (N-2, k-1, p) | (N-2, k-1, p) + (N-2, k-2, p)
3rd: (N-3, k, p) + (N-3, k-1, p) | (N-3, k-1, p) + (N-3, k-2, p) | (N-3, k-1, p) + (N-3, k-2, p) | (N-3, k-2, p) + (N-3, k-3, p)
100th: 2 ^ (100+1)
Nth: 2 ^ (N+1)
*/
public static double binomial(int N, int k, double p) {
count++;
if (N == 0 && k == 0) return 1.0;
if (N < 0 || k < 0) return 0.0;
return (1.0 - p) * binomial(N - 1, k, p) + p * binomial(N - 1, k - 1, p);
}
public static double binomial2(int N, int k, double p) {
Double[][] cache = new Double[N + 1][k + 1];
return binomialWithCache(N, k, p, cache);
}
public static double binomialWithCache(int N, int k, double p, Double[][] cache) {
count++;
if (N == 0 && k == 0) return 1.0;
if (N < 0 || k < 0) return 0.0;
if (cache[N][k] == null) {
cache[N][k] = (1.0 - p) * binomialWithCache(N - 1, k, p, cache) + p * binomialWithCache(N - 1, k - 1, p, cache);
}
return cache[N][k];
}
public static void main(String[] args) {
System.out.println(binomial(10, 5, 0.25));
System.out.println(count);
count = 0;
System.out.println("--------------------------------------------");
System.out.println(binomial2(10, 5, 0.25));
System.out.println(count);
}
}
| true |
c0c728fa22299d362d44bcfb61fff87e716e2c42 | Java | shenke93/LinkedForever | /src/com/uvsq/idao/IBasicDAO.java | UTF-8 | 361 | 2.15625 | 2 | [] | no_license | package com.uvsq.idao;
import java.util.List;
public interface IBasicDAO
{
public void add(Object o);
public void delete(Class<?> clazz, int id);
public void update(Object o);
public List<Object> executeQuery(String hql, Object[] parameters);
public Object findById(Class<?> clazz, int id);
public Object uniqueQuery(String hql, Object[] parameters);
} | true |
d10b8121e1dcd83336607dc5ecf1dd3cffd1ba30 | Java | userxiaya/eeMusic | /plugins/eeui/audio/android/src/main/java/eeui/android/audio/service/BackService.java | UTF-8 | 1,676 | 1.96875 | 2 | [
"MIT"
] | permissive | package eeui.android.audio.service;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.StrictMode;
import android.widget.RemoteViews;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.instapp.nat.media.audio.BuildConfig;
import eeui.android.audio.R;
import eeui.android.audio.event.AudioEvent;
public class BackService extends Service {
private static Context appContext;
@Nullable
@Override
public IBinder onBind(Intent intent) {
String url = intent.getStringExtra("url");
boolean bool = intent.getBooleanExtra("bool", false);
MusicService.getService().play(url);
MusicService.getService().setLoop(bool);
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String url = intent.getStringExtra("url");
boolean bool = intent.getBooleanExtra("bool", false);
MusicService.getService().play(url);
MusicService.getService().setLoop(bool);
} else {
MusicService.getService().stop();
}
return super.onStartCommand(intent, flags, startId);
}
@SuppressLint("NewApi")
@Override
public void onCreate() {
super.onCreate();
appContext = getApplicationContext();
}
public static Context getContext () {
return appContext;
}
} | true |
576239c287f37b863a051ca5be4f8bd3ab433aae | Java | dxm36500/heroku | /SpringPractice/src/main/java/com/myspring/project/SpringTest.java | UTF-8 | 464 | 2.109375 | 2 | [] | no_license | package com.myspring.project;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//Constructor Injection
public class SpringTest {
public static void main(String args[])
{
ApplicationContext context=new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
Triangle triangle =(Triangle) context.getBean("triangle");
triangle.draw();
}
}
| true |
67bfebef600850b1510273c1e8c752d9722451b7 | Java | bmenezes13/GroupPorject | /src/mainclasses/Account.java | UTF-8 | 986 | 2.578125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mainclasses;
/**
*
* @author user
*/
public class Account {
private String fname;
private String lname;
private String email;
private String uname;
private String pword;
public Account(String first, String last, String addy, String user, String pass){
this.fname = first;
this.lname = last;
this.email = addy;
this.uname = user;
this.pword = pass;
}
public String getFirst(){return this.fname;}
public String getLast(){return this.lname;}
public String getEmail(){return this.email;}
public void setEmail(String email){this.email = email;}
public String getUser(){return this.uname;}
public String getPass(){return this.pword;}
public void setPass(String word){this.pword = word;}
}
| true |
c845d6e28660e8c68665584dba49cd25edc06c5e | Java | cacurio/ApiClima | /src/main/java/com/arcos/servicio/EndPontClimaApplicationProperties.java | UTF-8 | 801 | 2.171875 | 2 | [] | no_license | package com.arcos.servicio;
import javax.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("app.clima")
public class EndPontClimaApplicationProperties {
private final Api api = new Api();
public Api getApi() {
return this.api;
}
//********************************
/*
* Clase estatica de los parametros
*/
//********************************
public static class Api {
@NotNull
private String key;
@NotNull
private String url;
/*
* GET y SET
*/
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
| true |
302014e7148c6635dd60ec63e05edcc9b20fdc88 | Java | gediineko/person-management-angular2 | /src/main/java/io/github/gediineko/services/util/RoleUtil.java | UTF-8 | 424 | 2.265625 | 2 | [] | no_license | package io.github.gediineko.services.util;
import io.github.gediineko.model.entities.Role;
import io.github.gediineko.model.ref.RoleType;
import java.util.Set;
/**
* Created by NazIsEvil on 15/10/2016.
*/
public class RoleUtil {
public static boolean isAdmin (Set<Role> roles){
return roles.stream()
.map(Role::getRoleType)
.anyMatch(r -> r.equals(RoleType.ADMIN));
}
}
| true |
09032ff444d2141066c727791ff6da833618d18f | Java | kazuooooo/NidoneAlarm2 | /AlarmClock/src/main/java/com/better/alarm/model/AlarmsManager.java | UTF-8 | 1,802 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2007 The Android Open Source Project
* Copyright (C) 2012 Yuriy Kulikov yuriy.kulikov.87@gmail.com
*
* 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.better.alarm.model;
import org.acra.ACRA;
import android.content.Context;
import com.better.alarm.model.interfaces.IAlarmsManager;
import com.github.androidutils.logger.Logger;
/**
* The AlarmsManager provider supplies info about AlarmCore Clock settings
*/
public class AlarmsManager {
private static Alarms sModelInstance;
public static IAlarmsManager getAlarmsManager() {
if (sModelInstance == null) throw new NullPointerException("AlarmsManager not initialized yet");
return sModelInstance;
}
static Alarms getInstance() {
if (sModelInstance == null) throw new NullPointerException("AlarmsManager not initialized yet");
return sModelInstance;
}
public static void init(Context context, Logger logger) {
if (sModelInstance == null) {
sModelInstance = new Alarms(context, logger, new AlarmsScheduler(context, logger));
} else {
sModelInstance = new Alarms(context, logger, new AlarmsScheduler(context, logger));
ACRA.getErrorReporter().handleException(new Exception("Attept to reinitialize!"));
}
}
}
| true |
c10a77e47f83bd6cc68ecdcb41b22387de8b56a9 | Java | MINDS-i/Dashboard | /src/ui/ninePatch/TransparentPanel.java | UTF-8 | 1,555 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | package com.ui.ninePatch;
import com.Context;
import java.awt.*;
import java.awt.event.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* A transparent border panel
* Child nodes will have to call repaint on this node instead of repainting
* themselves directly or else they will draw over the border
* Child nodes will be panned and clipped correctly so they automatically
* draw within the center region
* At some point patches should carry some metadata so this panel isn't
* limited to use with a single specific patch.
*/
public class TransparentPanel extends JPanel {
//Margin Consts
private final int LEFT_MARGIN = 8;
private final int RIGHT_MARGIN = 8;
private final int TOP_MARGIN = 8;
private final int BOTTOM_MARGIN = 8;
//Vars
private Rectangle drawRect;
private NinePatch np;
private int size;
public TransparentPanel(Context ctx, int size){
this.size = size;
np = ctx.theme.horizonBorder;
drawRect = new Rectangle(LEFT_MARGIN, TOP_MARGIN,
(size - RIGHT_MARGIN - LEFT_MARGIN),
(size - BOTTOM_MARGIN - TOP_MARGIN));
setPreferredSize(new Dimension(size, size));
setOpaque(false);
setBorder(new EmptyBorder(TOP_MARGIN, LEFT_MARGIN, BOTTOM_MARGIN, RIGHT_MARGIN));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
}
@Override
public void paint(Graphics g) {
super.paint(g);
np.paintIn(g, getWidth(), getHeight());
}
}
| true |
99661a34742b820794137bdd374b0317171e446e | Java | TangliziGit/leetcode | /java/84.largest-rectangle-in-histogram.267660858.ac.java | UTF-8 | 772 | 3.15625 | 3 | [] | no_license | class Solution {
public int largestRectangleArea(int[] hei) {
if (hei == null || hei.length == 0) return 0;
int[] left = new int[hei.length];
int[] right= new int[hei.length];
left[0]=-1; right[hei.length-1]=hei.length;
for (int i=1; i<hei.length; i++){
int ptr=i-1;
while (ptr>=0 && hei[ptr]>=hei[i]) ptr=left[ptr];
left[i]=ptr;
}
for (int i=hei.length-2; i>=0; i--){
int ptr=i+1;
while (ptr<hei.length && hei[ptr]>=hei[i]) ptr=right[ptr];
right[i]=ptr;
}
int ans=0;
for (int i=0; i<hei.length; i++)
ans=Math.max(ans, (right[i]-left[i]-1)*hei[i]);
return ans;
}
}
| true |
a4296ac77caa906b0872f0b618c6f716f7dc97cd | Java | jazzyF/lowesquiz | /src/main/java/com/lowes/service/QuizService.java | UTF-8 | 503 | 1.703125 | 2 | [] | no_license | package com.lowes.service;
import com.lowes.dto.QuizApiResponse;
import com.lowes.dto.QuizDto;
import com.lowes.model.Quiz;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Mono;
import java.util.List;
public interface QuizService {
Mono<Quiz> getQuiz(MultiValueMap<String, String> queryParams);
Mono<QuizApiResponse> getQuizApiResponse(List<MultiValueMap<String, String>> queryParams);
Mono<QuizDto> getQuizDto(MultiValueMap<String, String> queryParams);
}
| true |
bb454f6f19a28b88ba2b55893cbeb137022024c2 | Java | cmcalado/ChuckNorris | /app/src/main/java/com/davidpradosm/chuckjokes/MainActivity.java | UTF-8 | 4,772 | 2.1875 | 2 | [] | no_license | package com.davidpradosm.chuckjokes;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
//TAB1
private TextView txt;
private TextView txt_tab2;
private Button btn;
private ImageView iv;
private Bitmap loadedImage;
private String logo = "https://assets.chucknorris.host/img/chucknorris_logo_coloured_small@2x.png";
//TAB2
private RecyclerView recyclerView;
private ArrayList<Result> data;
private Adaptador adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
Picasso.with(this).load(logo).into(iv);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadJSON();
}
});
loadTabs();
initViews();
}
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.chucknorris.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ChuckJokesServices request = retrofit.create(ChuckJokesServices.class);
Call<Joke> call = request.getJoke();
call.enqueue(new Callback<Joke>() {
@Override
public void onResponse(Call<Joke> call, Response<Joke> response) {
Joke joke = response.body();
txt = (TextView) findViewById(R.id.tv);
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/Roboto-Bold.ttf");
txt.setTypeface(face);
txt.setText(joke.getValue());
}
@Override
public void onFailure(Call<Joke> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
private void loadTabs(){
Resources res = getResources();
TabHost tabs =(TabHost)findViewById(android.R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec=tabs.newTabSpec("mitab1");
spec.setContent(R.id.tab1);
spec.setIndicator("Aleatorio");
tabs.addTab(spec);
spec=tabs.newTabSpec("mitab2");
spec.setContent(R.id.tab2);
spec.setIndicator("Categoria");
tabs.addTab(spec);
tabs.setCurrentTab(0);
}
private void initViews(){
recyclerView = (RecyclerView)findViewById(R.id.RecView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadJSONRecycler();
}
private void loadJSONRecycler(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.chucknorris.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ChuckJokesServices request = retrofit.create(ChuckJokesServices.class);
Call<QuerySport> call = request.getSports();
call.enqueue(new Callback<QuerySport>() {
@Override
public void onResponse(Call<QuerySport> call, Response<QuerySport> response) {
/*
txt_tab2 = (TextView) findViewById(R.id.tv_tab2);
txt_tab2.setText("Hola");
*/
QuerySport joke = response.body();
data = new ArrayList<>(Arrays.asList(joke.getResult()));
adapter = new Adaptador(data);
recyclerView.setAdapter(adapter);
}
@Override
public void onFailure(Call<QuerySport> call, Throwable t) {
Toast toast1 =
Toast.makeText(getApplicationContext(),
"Error", Toast.LENGTH_SHORT);
toast1.show();
}
});
}
}
| true |
852a4868373d8ab3823c549069e8d8ae74386eba | Java | humyna/springdemo | /sia-springidol/src/test/java/info/zoio/tec/java/springinaction/springidol/JugglerMain.java | UTF-8 | 801 | 2.390625 | 2 | [] | no_license | package info.zoio.tec.java.springinaction.springidol;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 构造器注入
*
* @author humyna
*
*/
public class JugglerMain {
public static void main(String[] args) throws PerformanceException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-idol.xml");
// ApplicationContext ctx = new ClassPathXmlApplicationContext("springidol-context-2.xml");//構造器注入
// Performer performer = (Performer)ctx.getBean("duke");
//构造注入对象引用
// Performer performer = (Performer)ctx.getBean("poeicDuke");
//Spring EL
Performer performer = (Performer)ctx.getBean("carl");
performer.perform();
}
}
| true |
70da599e67b012fa5680dae6d67dea7ba479f3e8 | Java | Nicovross/Parcial2Lab1 | /Empleado.java | UTF-8 | 1,234 | 2.953125 | 3 | [] | no_license | /*Clase: Empleado
Atributos: nombreCompleto (String), legajo (int), salario (double), nivelAcademico
(NivelAcademico)
*/
package parcial2nicolásvargas;
import java.util.*;
public class Empleado {
String nombreCompleto;
int legajo;
double salario;
NivelAcademico nivelAcademico;
public String getNombreCompleto() {
return nombreCompleto;
}
public void setNombreCompleto(String nombreCompleto) {
this.nombreCompleto = nombreCompleto;
}
public int getLegajo() {
return legajo;
}
public void setLegajo(int legajo) {
this.legajo = legajo;
}
public double getSalario() {
return salario;
}
public void setSalario(double salario) {
this.salario = salario;
}
public NivelAcademico getNivelAcademico() {
return nivelAcademico;
}
public void setNivelAcademico(NivelAcademico nivelAcademico) {
this.nivelAcademico = nivelAcademico;
}
public static double salarioTotalCalculado(Empleado e){
double salarioTotal;
salarioTotal = e.getSalario() + (e.getSalario() * (e.getNivelAcademico().getPorcentajeAumento()/100));
return salarioTotal;
}
}
| true |
52cef57d85a23eec918d2f62b44fa33a432a68b2 | Java | piyushdubeygithub/Educational-DP-Contest | /src/main/java/interview/JailServiceImpl.java | UTF-8 | 292 | 2.609375 | 3 | [] | no_license | package interview;
public class JailServiceImpl implements JailService{
@Override
public void deductAmount(User user, Integer amount) {
Jail jail = new Jail();
int userAmount = user.getAmount();
userAmount -= 150;
user.setAmount(userAmount);
}
}
| true |
57c122258da7a9b51d23ceca29e443764878bd1f | Java | samuelvazcal/Java-RelearningSessions-Exercises | /Section19/src/com/samuelvazquez/firstexample/PokemonJDBC.java | UTF-8 | 1,777 | 3.171875 | 3 | [] | no_license | package com.samuelvazquez.firstexample;
import java.sql.*;
public class PokemonJDBC {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/pokemondb","root","root");
// connection.setAutoCommit(false);
Statement statement = connection.createStatement();
//ResultSet resultSet = statement.executeQuery("SELECT * FROM pokemon");
statement.execute("CREATE TABLE IF NOT EXISTS favpokemon (id INT, name VARCHAR(16))");
// statement.execute("INSERT INTO favpokemon (id, name)" +
// "VALUES (25,'Pikachu')," +
// "(16,'Pidgey')," + "(60, 'Poliwag')");
// statement.execute("INSERT INTO favpokemon (id, name) VALUES(43,'Oddish')");
// statement.execute("INSERT INTO favpokemon (id, name) VALUES(27,'Sandshrew')");
// statement.execute("INSERT INTO favpokemon (id, name) VALUES(7,'Squirtle')");
// statement.execute("INSERT INTO favpokemon (id, name) VALUES(132,'Weedle')");
// statement.execute("UPDATE favpokemon SET id = 13 WHERE id = 132");
// statement.execute("DELETE FROM favpokemon WHERE id = 13");
statement.execute("SELECT * FROM favpokemon");
ResultSet resultSet = statement.getResultSet();
while(resultSet.next()) {
System.out.println(resultSet.getString("id") + " " + resultSet.getString("name"));
}
resultSet.close();
statement.close();
connection.close();
} catch(SQLException e) {
System.out.println("Something went wrong: " + e.getMessage());
}
}
}
| true |
580b6d7b72142b293dc7707fedab83ef1fc27e86 | Java | Jerryzhzy/java_pro | /src/main/java/com/lzc/gstore/vocabulary/entity/Demo.java | UTF-8 | 556 | 2.140625 | 2 | [] | no_license | package com.lzc.gstore.vocabulary.entity;
import com.lzc.core.datasource.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable;
/**
* Created by ziyu.zhang on 2017/6/30.
*/
@Entity
public class Demo extends IdEntity implements Serializable {
private String name;
@Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true |
80b3573e25ba0555c31933a43dc0740e25e5d680 | Java | SebastianHenaoSanchez/MicroservicioNegocio | /spring-server/src/main/java/io/swagger/repository/UserRepository.java | UTF-8 | 582 | 1.601563 | 2 | [] | no_license | package io.swagger.repository;
import java.util.List;
import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.springframework.data.repository.CrudRepository;
import io.swagger.model.RegistrarRequest;
@EnableScan
public interface UserRepository extends CrudRepository<RegistrarRequest, String>{
//public List<RegistrarRequest> findByEmail(String email);
public List<RegistrarRequest> findByIdadmin(String idadmin);
public List<RegistrarRequest> findByIdnegocio(String idnegocio);
public List<RegistrarRequest> findByTiponegocio(String tiponegocio);
}
| true |
cf326c770ff51049adea0425a0b80fc48a65f162 | Java | Alexandre35-cyber/FileFinder | /src/main/java/org/maison/filefinder/view/MainWindow.java | UTF-8 | 21,987 | 2.234375 | 2 | [] | no_license | package org.maison.filefinder.view;
import org.maison.filefinder.model.*;
import org.maison.filefinder.model.criteria.SearchCriteria;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
public class MainWindow extends JFrame implements SearchListener, TextualSearch, Preferences {
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.yellow);
private boolean ascending = false;
private static final String TITLE = "File Finder";
private static final Dimension DIMENSION = new Dimension(800,600);
private static int MAX_RESULTS = 100;
private java.util.List<ResultLine> lines = new ArrayList<ResultLine>();
private JTextField textFieldDirectory;
private JTextField textFieldFilter;
private JEditorPane area;
private SearchEngine engine;
private StringBuilder builder = new StringBuilder();
private ActionListener listener;
private int cpt = -1;
private boolean warningShown = false;
private boolean endForced = false;
private JScrollPane pane;
private JPanel filterPanel;
private JPanel directoryPanel;
private JPanel resultsPanel;
private SearchDialog dialog;
private int lignesMax = MAX_RESULTS;
int pos = 0;
int nbOccurences = 0;
private FileOpener opener;
private PreferencesDialog prefsDialog;
public MainWindow(SearchEngine engine, FileOpener opener){
super(TITLE);
this.opener = opener;
this.engine = engine;
setPreferredSize(DIMENSION);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu menuFichier = new JMenu("Fichier");
JMenuItem menuItemRechecher = new JMenuItem("Rechercher");
menuItemRechecher.addActionListener(e->{
MainWindow.this.setDialogVisible();
});
menuFichier.add(menuItemRechecher);
JMenu menuPreferences = new JMenu("Préferences");
JMenuItem itemPreferences = new JMenuItem("Définir");
itemPreferences.addActionListener(e->{
MainWindow.this.setPreferencesDialogVisible();
});
menuPreferences.add(itemPreferences);
menuBar.add(menuFichier);
menuBar.add(menuPreferences);
setJMenuBar(menuBar);
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10,10,5,10);
filterPanel = createFilterZone();
getContentPane().add(filterPanel, c );
c.gridy = 1;
c.insets = new Insets(5,10,10,10);
directoryPanel = createDirectoryZone();
getContentPane().add(directoryPanel,c );
c.gridy = 2;
getContentPane().add(createGraphicalCriterias(), c);
c.gridx = 0;
c.gridy = 3;
c.weightx = 1.0;
c.weighty = 1.0;
c.fill = GridBagConstraints.BOTH;
resultsPanel = createResultsZone();
getContentPane().add(resultsPanel, c);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
JButton button = new JButton("Lancer la recherche");
button.addActionListener(getActionListener());
panel.add(button);
c.gridy = 4;
c.weightx = 1.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
getContentPane().add(panel,c);
pack();
center(this);
this.dialog = new SearchDialog(this, this);
center(this.dialog);
this.prefsDialog = new PreferencesDialog(this, this);
center(this.prefsDialog);
}
private JPanel createGraphicalCriterias(){
int cpty = 0;
JPanel criteriaPanel = new JPanel();
criteriaPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = cpty;
c.weightx = 1.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.BOTH;
// c.insets = new Insets(10,10,10,10);
GraphicalSearchCriteriaFactory f = new GraphicalSearchCriteriaFactory();
for (SearchCriteria criteria: engine.getCriterias()){
try {
criteria.accept(f);
} catch (Exception e){
e.printStackTrace();
}
JPanel p = f.getPanel();
p.setBorder(BorderFactory.createEtchedBorder());
criteriaPanel.add(p, c);
cpty++;
c.gridy = cpty;
}
criteriaPanel.setBorder(BorderFactory.createTitledBorder("Critères"));
return criteriaPanel;
}
private void center(Container component) {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = (dim.width - component.getPreferredSize().width )/2;
int y = (dim.height - component.getPreferredSize().height)/2;
component.setLocation(x,y);
}
@Override
public void search(String text) {
if ("".equals(text) || text == null) return;
highlight(area, text);
}
@Override
public void reset() {
area.setText("");
}
public void display(){
setVisible(true);
}
public void setDialogVisible(){
this.dialog.setVisible(true);
}
public void setPreferencesDialogVisible(){
this.prefsDialog.setVisible(true);
}
private JPanel createResultsZone(){
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
area = new JEditorPane();
area.addMouseListener(new SearchMouseAdapter(this));
area.setEditable(false);
area.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED){
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
try {
if (e.getURL().toString().contains("file-sort")){
MainWindow.this.sortResultsFile(!MainWindow.this.ascending);
MainWindow.this.refresh();
MainWindow.this.ascending = !MainWindow.this.ascending;
return;
}
if (e.getURL().toString().contains("date-sort")){
MainWindow.this.sortResultsDate(!MainWindow.this.ascending);
MainWindow.this.refresh();
MainWindow.this.ascending = !MainWindow.this.ascending;
return;
}
if (e.getURL().toString().contains("size-sort")){
MainWindow.this.sortResultsSize(!MainWindow.this.ascending);
MainWindow.this.refresh();
MainWindow.this.ascending = !MainWindow.this.ascending;
return;
}
//Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+ e.getURL());
MainWindow.this.opener.open(e.getURL().getFile().substring(1));
} catch (Exception e1){
e1.printStackTrace();
}
}
}
}
});
area.setContentType("text/html");
pane = new JScrollPane(area);
p.add(pane, c);
return p;
}
private void sortResultsFile(boolean ascending){
lines.sort(new Comparator<ResultLine>() {
@Override
public int compare(ResultLine o1, ResultLine o2) {
if (ascending) {
return o1.getFile().compareTo(o2.getFile());
}
return o2.getFile().compareTo(o1.getFile());
}
});
}
private void sortResultsDate(boolean ascending){
lines.sort((o1, o2) -> {
return ascending ? o1.getDate().compareTo(o2.getDate()) : o2.getDate().compareTo(o1.getDate());
});
}
private void sortResultsSize(boolean ascending){
lines.sort((o1, o2) -> {
if (o1.getSize() < o2.getSize()){
return ascending ? -1:1;
}
if (o1.getSize() > o2.getSize()){
return ascending ? 1:-1;
}
if (o1.getSize() == o2.getSize()) {
return 0;
}
return -1;
});
}
private JPanel createDirectoryZone(){
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
JLabel label = new JLabel("Entrer le reprtoire de recherche:");
c.weightx = 0.0;
p.add(label, c);
c.insets = new Insets(0,5,0,0);
textFieldDirectory = new JTextField();
//textFieldDirectory.addActionListener(getActionListener());
textFieldDirectory.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File file = new File(textFieldDirectory.getText());
if (file.isDirectory() && file.exists()) {
System.out.println("Repertoire entré: " + file.getAbsolutePath());
UserSelectionMgr.get().setDirectorySelected(textFieldDirectory.getText());
}
}});
c.weightx = 1;
c.gridx = 1;
p.add(textFieldDirectory, c);
p.setBorder(BorderFactory.createEtchedBorder());
JButton button = new JButton("...");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(MainWindow.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
textFieldDirectory.setText(file.getAbsolutePath());
UserSelectionMgr.get().setDirectorySelected(textFieldDirectory.getText());
}
}
});
c.weightx = 0.1;
c.gridx = 2;
c.insets = new Insets(2,5,2,0);
p.add(button, c);
return p;
}
private ActionListener getActionListener() {
if (listener == null){
listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (checkDirectory()) {
if (checkFileFilter()) {
launchSearch();
}else{
System.out.println("bad filefilter");
}
}else{
System.out.println("bad directory");
}
}
};
}
return listener;
}
public void launchSearch(){
try {
this.engine.reset();
area.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (textFieldFilter.getText().contains("*.")){
this.engine.searchWithExtension(textFieldDirectory.getText(), textFieldFilter.getText());
}else{
this.engine.searchWithFile(textFieldDirectory.getText(), textFieldFilter.getText());
}
} catch (FileFinderException e){
JOptionPane.showMessageDialog(MainWindow.this, e.getMessage());
}
}
public void searchStarted(){
lines.clear();
cpt = -1;
warningShown = false;
endForced = false;
builder = new StringBuilder();
area.setText("<html><b>"+DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss").format(LocalDateTime.now()) + "- Recherche en cours...</b>\n<html>");
}
@Override
public void searchEnded() {
if (!endForced) {
String text = area.getText();
text = text.replaceAll("<html>", "");
text = text.replaceAll("</html>", "");
text = text.replaceAll("</body>", "");
String finTable = "</table></center>";
String textFinal = "<html>" + text + builder.toString() + (builder.toString().contains("<table")? finTable:"")+ "<br><b>" + DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss").format(LocalDateTime.now()) + "- Recherche terminée.</b></body></html>";
area.setText(textFinal);
System.out.println(textFinal);
updateUI();
System.out.println(">>>>>>>>>>>>>>>>>>MAINWINDOW END<<<<<<<<<<<<<<<<<");
area.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
public void addResult(String results, long size, String date){
date = date.replaceAll("T"," ");
System.out.println("DATE>>>>" + date);
if (date.indexOf('.')!=-1) {
date = date.substring(0, date.indexOf('.'));
}else {
date = date.substring(0, date.indexOf('Z'));
}
cpt++;
ResultLine line;
if (cpt==0){
builder.append("<center><table border=\"1\"><tr><th><a href=file:///file-sort>Fichier</a></th><a href=file:///date-sort>Date</a></th><th><a href=file:///size-sort>Taille</a></th></tr>");
}
String color = (cpt%2!=0?"style=\"background-color:white;\"":"style=\"background-color:#ada2a1;\"");
if (cpt < getLignesMax()) {
line = new ResultLine(date, results, size);
lines.add(line);
//builder.append("<br/><a href=file:///" + results + ">" + results + "</a> "+size);
builder.append("<tr><td "+color+"><a href=file:///" + line.getFile() + ">" + line.getFile() + "</a></td><td "+color+">"+line.getDate()+"</td><td "+color+">"+ UIUtils.convertToStringRepresentation(line.getSize())+"</td></tr>");
}else {
if (warningShown == false){
JOptionPane.showMessageDialog(null, "Seuls les "+getLignesMax()+" premiers résultats seront affichés.");
warningShown = true;
forceEnd();
}
}
}
private void refresh(){
area.setText("");
builder = new StringBuilder();
builder.append("<html><b>"+DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss").format(LocalDateTime.now()) + "- Recherche en cours...</b>\n");
builder.append("<center><table border=\"1\"><tr><th><a href=file:///file-sort>Fichier</a></th><a href=file:///date-sort>Date</a></th><th><a href=file:///size-sort>Taille</a></th></tr>");
ResultLine line;
for (int i=0; i < lines.size(); i++){
line = lines.get(i);
String color = (i%2!=0?"style=\"background-color:white;\"":"style=\"background-color:#ada2a1;\"");
builder.append("<tr><td "+color+"><a href=file:///" + line.getFile() + ">" + line.getFile() + "</a></td><td "+color+">"+line.getDate()+"</td><td "+color+">"+UIUtils.convertToStringRepresentation(line.getSize())+"</td></tr>");
}
endForced = false;
searchEnded();
}
private void updateUI(){
area.update(area.getGraphics());
area.repaint();
pane.update(pane.getGraphics());
pane.repaint();
filterPanel.update(filterPanel.getGraphics());
filterPanel.repaint();
directoryPanel.update(directoryPanel.getGraphics());
directoryPanel.repaint();
resultsPanel.update(resultsPanel.getGraphics());
resultsPanel.repaint();
MainWindow.this.validate();
}
public void forceEnd(){
endForced = false;
engine.stopSearch();
searchEnded();
endForced = true;
}
private boolean checkDirectory() {
String text = textFieldDirectory.getText();
if ("".equals(text) || text == null){
JOptionPane.showMessageDialog(null, "Vous devez entrer un nom de répertoire existant sur la machine.");
return false;
}else{
File directory = new File(text);
if (!directory.exists() || !directory.canRead() || !directory.isDirectory()){
JOptionPane.showMessageDialog(null, "Verifier l'existence du répertoire '" + text + "' ou les droits d'accès en lecture.");
return false;
}
UserSelectionMgr.get().setDirectorySelected(textFieldDirectory.getText());
UserSelectionMgr.get().setSelectedExtension(textFieldFilter.getText());
}
return true;
}
private boolean checkFileFilter() {
String filterText = textFieldFilter.getText();
if ("".equals(filterText) || filterText == null){
JOptionPane.showMessageDialog(null, "Vous devez entrer une extension de fichier (Ex:*.jpg)");
return false;
}
else{
if (filterText.contains("*")) {
if (!filterText.matches("\\*\\.(([A-Za-z0-9]+)|([\\.\\*]))")) {
JOptionPane.showMessageDialog(null, "Vous devez entrer une extension de fichier au format '*.ABC(D)' ou '*.abc(d)'");
return false;
}
}
}
return true;
}
public void resetTextualSearch(){
// First remove all old highlights
removeHighlights(area);
pos = 0;
nbOccurences = 0;
}
private JPanel createFilterZone(){
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weighty = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
JLabel label = new JLabel("Entrer l'extension de fichiers ou un nom de fichier:");
c.weightx = 0.0;
p.add(label, c);
c.insets = new Insets(0,5,0,0);
textFieldFilter = new JTextField();
textFieldFilter.addActionListener(getActionListener());
c.weightx = 1.0;
p.add(textFieldFilter, c);
p.setBorder(BorderFactory.createEtchedBorder());
return p;
}
@Override
public void setLignesMax(int lignesMax) {
this.lignesMax = lignesMax;
}
@Override
public int getLignesMax() {
return this.lignesMax;
}
// A private subclass of the default highlight painter
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter
{
public MyHighlightPainter(Color color)
{
super(color);
}
}
// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern)
{
// First remove all old highlights
try
{
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
//int pos = 0;
// Search for pattern
// see I have updated now its not case sensitive
//while ((pos = text.toUpperCase().indexOf(pattern.toUpperCase(), pos)) >= 0)
if ((pos = text.indexOf(pattern, pos)) >= 0)
{
// Create highlighter using private painter and apply around pattern
hilite.addHighlight(pos, pos+pattern.length(), myHighlightPainter);
area.setCaretPosition(pos+1);
pos += pattern.length();
nbOccurences++;
} else{
pos = 0;
JOptionPane.showMessageDialog(this, nbOccurences + " occurences de la chaîne '"+pattern+"' trouvées.");
nbOccurences = 0;
}
} catch (BadLocationException e) {
}
}
// Removes only our private highlights
public void removeHighlights(JTextComponent textComp)
{
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i=0; i<hilites.length; i++)
{
if (hilites[i].getPainter() instanceof MyHighlightPainter)
{
hilite.removeHighlight(hilites[i]);
}
}
}
}
| true |
77adcd5ad4b8b302bce46b5d678edf7cfa888b51 | Java | zhongxingyu/Seer | /Diff-Raw-Data/26/26_41741db1c9bc4cbe51869fcc030451d7712099ba/ThroughputVsThreadsGui/26_41741db1c9bc4cbe51869fcc030451d7712099ba_ThroughputVsThreadsGui_s.java | UTF-8 | 2,349 | 2.515625 | 3 | [] | no_license | package kg.apc.jmeter.vizualizers;
import java.awt.Color;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.gui.RateRenderer;
public class ThroughputVsThreadsGui
extends AbstractGraphPanelVisualizer
{
public ThroughputVsThreadsGui()
{
super();
graphPanel.getGraphObject().setDrawCurrentX(true);
graphPanel.getGraphObject().setyAxisLabelRenderer(new RateRenderer("#.0"));
}
public String getLabelResource()
{
return this.getClass().getSimpleName();
}
@Override
public String getStaticLabel()
{
return "Transaction Throughput vs Threads";
}
public void add(SampleResult res)
{
String label = res.getSampleLabel();
String averageLabel = "Average " + res.getSampleLabel();
GraphRowAverages row;
GraphRowOverallAverages avgRow;
if (!model.containsKey(label))
{
final Color nextColor = colors.getNextColor();
row = getNewRow(label, nextColor);
avgRow = getNewAveragesRow(averageLabel, nextColor);
}
else
{
row = (GraphRowAverages) model.get(label);
avgRow = (GraphRowOverallAverages) model.get(averageLabel);
}
int allThreads = res.getAllThreads();
double throughput = (double) allThreads * 1000 / res.getTime();
row.add(allThreads, throughput);
avgRow.add(allThreads, throughput);
graphPanel.getGraphObject().setCurrentX(allThreads);
updateGui(null);
}
private GraphRowOverallAverages getNewAveragesRow(String averageLabel, final Color nextColor)
{
GraphRowOverallAverages avgRow = new GraphRowOverallAverages();
avgRow.setLabel(averageLabel);
avgRow.setColor(nextColor);
avgRow.setMarkerSize(AbstractGraphRow.MARKER_SIZE_BIG);
avgRow.setDrawValueLabel(true);
avgRow.setShowInLegend(false);
model.put(averageLabel, avgRow);
return avgRow;
}
private GraphRowAverages getNewRow(String label, final Color nextColor)
{
GraphRowAverages row = new GraphRowAverages();
row.setLabel(label);
row.setColor(nextColor);
row.setDrawLine(true);
row.setMarkerSize(AbstractGraphRow.MARKER_SIZE_SMALL);
model.put(label, row);
return row;
}
}
| true |
e83d5f63cfa743299b4925619d66b703650fbc94 | Java | ahtrun/FastVLayout | /fastlayout/src/main/java/com/lhp/fastvlayout/listener/OnDisplayImageL.java | UTF-8 | 183 | 1.8125 | 2 | [] | no_license | package com.lhp.fastvlayout.listener;
import android.widget.ImageView;
public interface OnDisplayImageL {
void onDisplayImage(Object object,int position,ImageView imageView);
}
| true |
e7284624860ce657fa6d83c168ee54bb2e241964 | Java | kevroletin/toy-java-serializer | /src/test/java/io/github/kevroletin/json/adapters/DoubleAdapterTest.java | UTF-8 | 1,201 | 2.5 | 2 | [] | no_license | package io.github.kevroletin.json.adapters;
import io.github.kevroletin.json.AST.DoubleNode;
import io.github.kevroletin.json.AST.NullNode;
import io.github.kevroletin.json.AST.StringNode;
import io.github.kevroletin.json.Deserializer;
import io.github.kevroletin.json.Location;
import io.github.kevroletin.json.utils.Maybe;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
public class DoubleAdapterTest {
@Test
public void testDeserialize() {
Deserializer d = new Deserializer();
DoubleAdapter adapter = new DoubleAdapter(true);
List<String> err = new ArrayList();
assertEquals(
Maybe.just(123.0),
adapter.deserialize(d, err, Location.empty(), new DoubleNode("123.0"), Double.class)
);
assertEquals(
Maybe.nothing(),
adapter.deserialize(d, err, Location.empty(), new StringNode("123"), Double.class)
);
assertEquals(
Maybe.just(null),
adapter.deserialize(d, err, Location.empty(), NullNode.getInstance(), Double.class)
);
}
@Test
public void testSerialize() {
}
}
| true |
e1272b2b96d43ff41060deff45b9ab1db96f052e | Java | ilgun/unifiedissuetrackers | /src/main/java/Model/SocialMedia/Email.java | UTF-8 | 940 | 2.625 | 3 | [] | no_license | package Model.SocialMedia;
import com.google.common.base.Optional;
public class Email {
private final Optional<Boolean> isImportant;
private final Optional<Boolean> isSpam;
private Email(Optional<Boolean> isImportant, Optional<Boolean> isSpam) {
this.isImportant = isImportant;
this.isSpam = isSpam;
}
public static class Builder {
private Optional<Boolean> isImportant;
private Optional<Boolean> isSpam;
private Builder() {
}
public static Builder anEmail() {
return new Builder();
}
public Builder isImportant(Optional<Boolean> value) {
isImportant = value;
return this;
}
public Builder isSpam(Optional<Boolean> value) {
isSpam = value;
return this;
}
public Email build() {
return new Email(isImportant, isSpam);
}
}
} | true |
f29d5cbcdf183be629a770eb4f8c9adaec0c9205 | Java | JiaxingGeng/cs4321 | /src/cs4321/project3/IO/HumanReadableWriter.java | UTF-8 | 994 | 3.46875 | 3 | [] | no_license | package cs4321.project3.IO;
import cs4321.project2.operator.Tuple;
import java.io.PrintWriter;
import java.io.IOException;
/**
* Use BufferedWriter to write outputs that are human readable
* @author Jiaxing Geng (jg755), Yangyi Hao (yh326)
*
*/
public class HumanReadableWriter implements TupleWriter {
private PrintWriter writer;
/**
* Constructor of Human Readable Writer
* @param dataPath location to write file
* @throws IOException
*/
public HumanReadableWriter(String dataPath) throws IOException{
writer = new PrintWriter(dataPath, "UTF-8");
}
/**
* Write Tuple t
* @param t tuple to be written
*/
@Override
public void write(Tuple t) throws IOException{
int num = t.getColumns();
String[] attributes = t.getAttributes();
for (int i =0;i<num-1;i++)
writer.print(attributes[i]+",");
writer.print(attributes[num-1]);
writer.println();
}
/**
* close the writer buffer
*/
@Override
public void close() throws IOException{
writer.close();
}
}
| true |
cd3f2a2089dd96720ff7725020db227a95360740 | Java | Polar-Pumpkin/Shoal | /PrefixMe/src/main/java/net/shoal/parrot/prefixme/Command.java | UTF-8 | 5,090 | 2.015625 | 2 | [] | no_license | package net.shoal.parrot.prefixme;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.shoal.parrot.prefixme.subcommand.GetCommand;
import net.shoal.parrot.prefixme.subcommand.SetCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.serverct.parrot.parrotx.command.CommandHandler;
import org.serverct.parrot.parrotx.command.PCommand;
import org.serverct.parrot.parrotx.command.subcommands.DebugCommand;
import org.serverct.parrot.parrotx.command.subcommands.HelpCommand;
import org.serverct.parrot.parrotx.command.subcommands.ReloadCommand;
import org.serverct.parrot.parrotx.command.subcommands.VersionCommand;
import org.serverct.parrot.parrotx.utils.JsonChatUtil;
import org.serverct.parrot.parrotx.utils.i18n.I18n;
public class Command extends CommandHandler {
public Command() {
super(PrefixMe.getInst(), "prefixme");
register(new GetCommand());
register(new SetCommand());
register(new DebugCommand(plugin, "PrefixMe.command.debug"));
register(new ReloadCommand(plugin, "PrefixMe.command.reload"));
register(new VersionCommand(plugin));
register(new HelpCommand(plugin));
}
@Override
public boolean onCommand(@NotNull CommandSender sender, org.bukkit.command.@NotNull Command command, @NotNull String label, String[] args) {
if (args.length == 0) {
sender.sendMessage(plugin.getLang().data.get(plugin.localeKey, "Message.Empty"));
// PCommand defCommand = commands.get((Objects.isNull(defaultCmd) ? "help" : defaultCmd));
// if (defCommand == null) {
// // plugin.lang.getHelp(plugin.localeKey).forEach(sender::sendMessage);
// formatHelp().forEach(sender::sendMessage);
// } else {
// boolean hasPerm = (defCommand.getPermission() == null || defCommand.getPermission().equals("")) || sender.hasPermission(defCommand.getPermission());
// if (hasPerm) {
// return defCommand.execute(sender, args);
// }
//
// String msg = plugin.getLang().data.warn("您没有权限这么做.");
// if (sender instanceof Player) {
// TextComponent text = JsonChatUtil.getFromLegacy(msg);
// text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(I18n.color("&7所需权限 ▶ &c" + defCommand.getPermission()))));
// ((Player) sender).spigot().sendMessage(text);
// } else sender.sendMessage(msg);
// }
return true;
}
PCommand pCommand = commands.get(args[0].toLowerCase());
if (pCommand == null) {
if (sender instanceof Player) {
if (!sender.hasPermission("PrefixMe.use")) {
sender.sendMessage(plugin.getLang().data.getInfo("Plugin.NoPerm"));
return true;
}
final StringBuilder builder = new StringBuilder();
for (String arg : args) {
builder.append(arg).append(" ");
}
final String content = builder.toString().trim();
if (content.length() <= 0) {
plugin.getLang().sender.error((Player) sender, "Message.Empty");
return true;
}
if (content.length() > Conf.limit) {
plugin.getLang().sender.error((Player) sender, "Message.Limit");
return true;
}
PrefixManager.getInst().set(((Player) sender).getUniqueId(), content);
sender.sendMessage(plugin.getLang().data.get(plugin.localeKey, "Message", "Set", content));
}
// sender.sendMessage(plugin.getLang().data.warn("未知命令, 请检查您的命令拼写是否正确."));
// plugin.getLang().log.error(I18n.EXECUTE, "子命令/" + args[0], sender.getName() + " 尝试执行未注册子命令");
return true;
}
boolean hasPerm = (pCommand.getPermission() == null || pCommand.getPermission().equals("")) || sender.hasPermission(pCommand.getPermission());
if (hasPerm) {
String[] newArg = new String[args.length - 1];
if (args.length >= 2) {
System.arraycopy(args, 1, newArg, 0, args.length - 1);
}
return pCommand.execute(sender, newArg);
}
String msg = plugin.getLang().data.warn("您没有权限这么做.");
if (sender instanceof Player) {
TextComponent text = JsonChatUtil.getFromLegacy(msg);
text.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(I18n.color("&7所需权限 ▶ &c" + pCommand.getPermission()))));
((Player) sender).spigot().sendMessage(text);
} else sender.sendMessage(msg);
return true;
}
}
| true |
1e82ecc2f7c0c00854ac458823d2ae3c3e96f627 | Java | rayhan-ferdous/code2vec | /codebase/dataset/t3/418_frag1.java | UTF-8 | 635 | 2.421875 | 2 | [] | no_license | public void writeChanges() {
if (log.isDebugEnabled()) log.debug("writeChanges() invoked");
if (!isChanged()) return;
onlyChanges = true;
if (getReadOnly()) log.error("unexpected write operation when readOnly is set");
setBusy(true);
super.setState(STORED);
if (_progState != IDLE) log.warn("Programming state " + _progState + ", not IDLE, in write()");
isReading = false;
isWriting = true;
_progState = -1;
retries = 0;
if (log.isDebugEnabled()) log.debug("start series of write operations");
writeNext();
}
| true |
db4a51d26c49b6b63ccd64b223b91f39380ca6ff | Java | lentiummmx/syar | /servlets/syar-web/src/main/java/mx/com/vepormas/syar/web/cfg/AppInitializer.java | UTF-8 | 1,446 | 1.710938 | 2 | [] | no_license | /**
*
*/
package mx.com.vepormas.syar.web.cfg;
import javax.servlet.Filter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* @author phoenix
*
*/
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/* (non-Javadoc)
* @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getRootConfigClasses()
*/
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class[] {AppConfiguration.class};
}
/* (non-Javadoc)
* @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getServletConfigClasses()
*/
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletMappings()
*/
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/*"};
}
/* (non-Javadoc)
* @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletFilters()
*/
@Override
protected Filter[] getServletFilters() {
// TODO Auto-generated method stub
//return super.getServletFilters();
Filter[] filters = { new CORSFilter() };
return filters;
}
}
| true |
2b6ec84fd720c792543aecf447c3bbb889b6d180 | Java | moutainhigh/travle | /seven_plus/domain_service/src/main/java/com/domain/plus/entity/ExtractCash.java | UTF-8 | 14,717 | 2.3125 | 2 | [] | no_license | package com.domain.plus.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
/**
*
* @author zhoudu
*/
public class ExtractCash implements Serializable {
private static final long serialVersionUID = 1535512751274L;
/**
* 主键
*
* isNullAble:0,defaultVal:0
*/
private Long id;
/**
* 用户Id
* isNullAble:1
*/
private Long userId;
/**
* 提现金额
* isNullAble:1
*/
private Long money;
/**
* 创建时间
* isNullAble:1
*/
private Long createTime;
public void setId(Long id){this.id = id;}
public Long getId(){return this.id;}
public void setUserId(Long userId){this.userId = userId;}
public Long getUserId(){return this.userId;}
public void setMoney(Long money){this.money = money;}
public Long getMoney(){return this.money;}
public void setCreateTime(Long createTime){this.createTime = createTime;}
public Long getCreateTime(){return this.createTime;}
@Override
public String toString() {
return "ExtractCash{" +
"id='" + id + '\'' +
"userId='" + userId + '\'' +
"money='" + money + '\'' +
"createTime='" + createTime + '\'' +
'}';
}
public static Builder Build(){return new Builder();}
public static ConditionBuilder ConditionBuild(){return new ConditionBuilder();}
public static UpdateBuilder UpdateBuild(){return new UpdateBuilder();}
public static QueryBuilder QueryBuild(){return new QueryBuilder();}
public static class UpdateBuilder {
private ExtractCash set;
private ConditionBuilder where;
public UpdateBuilder set(ExtractCash set){
this.set = set;
return this;
}
public ExtractCash getSet(){
return this.set;
}
public UpdateBuilder where(ConditionBuilder where){
this.where = where;
return this;
}
public ConditionBuilder getWhere(){
return this.where;
}
public UpdateBuilder build(){
return this;
}
}
public static class QueryBuilder extends ExtractCash{
/**
* 需要返回的列
*/
private Map<String,Object> fetchFields;
public Map<String,Object> getFetchFields(){return this.fetchFields;}
private List<Long> idList;
public List<Long> getIdList(){return this.idList;}
private Long idSt;
private Long idEd;
public Long getIdSt(){return this.idSt;}
public Long getIdEd(){return this.idEd;}
private List<Long> userIdList;
public List<Long> getUserIdList(){return this.userIdList;}
private Long userIdSt;
private Long userIdEd;
public Long getUserIdSt(){return this.userIdSt;}
public Long getUserIdEd(){return this.userIdEd;}
private List<Long> moneyList;
public List<Long> getMoneyList(){return this.moneyList;}
private Long moneySt;
private Long moneyEd;
public Long getMoneySt(){return this.moneySt;}
public Long getMoneyEd(){return this.moneyEd;}
private List<Long> createTimeList;
public List<Long> getCreateTimeList(){return this.createTimeList;}
private Long createTimeSt;
private Long createTimeEd;
public Long getCreateTimeSt(){return this.createTimeSt;}
public Long getCreateTimeEd(){return this.createTimeEd;}
private QueryBuilder (){
this.fetchFields = new HashMap<>();
}
public QueryBuilder idBetWeen(Long idSt,Long idEd){
this.idSt = idSt;
this.idEd = idEd;
return this;
}
public QueryBuilder idGreaterEqThan(Long idSt){
this.idSt = idSt;
return this;
}
public QueryBuilder idLessEqThan(Long idEd){
this.idEd = idEd;
return this;
}
public QueryBuilder id(Long id){
setId(id);
return this;
}
public QueryBuilder idList(Long ... id){
this.idList = solveNullList(id);
return this;
}
public QueryBuilder idList(List<Long> id){
this.idList = id;
return this;
}
public QueryBuilder fetchId(){
setFetchFields("fetchFields","id");
return this;
}
public QueryBuilder excludeId(){
setFetchFields("excludeFields","id");
return this;
}
public QueryBuilder userIdBetWeen(Long userIdSt,Long userIdEd){
this.userIdSt = userIdSt;
this.userIdEd = userIdEd;
return this;
}
public QueryBuilder userIdGreaterEqThan(Long userIdSt){
this.userIdSt = userIdSt;
return this;
}
public QueryBuilder userIdLessEqThan(Long userIdEd){
this.userIdEd = userIdEd;
return this;
}
public QueryBuilder userId(Long userId){
setUserId(userId);
return this;
}
public QueryBuilder userIdList(Long ... userId){
this.userIdList = solveNullList(userId);
return this;
}
public QueryBuilder userIdList(List<Long> userId){
this.userIdList = userId;
return this;
}
public QueryBuilder fetchUserId(){
setFetchFields("fetchFields","userId");
return this;
}
public QueryBuilder excludeUserId(){
setFetchFields("excludeFields","userId");
return this;
}
public QueryBuilder moneyBetWeen(Long moneySt,Long moneyEd){
this.moneySt = moneySt;
this.moneyEd = moneyEd;
return this;
}
public QueryBuilder moneyGreaterEqThan(Long moneySt){
this.moneySt = moneySt;
return this;
}
public QueryBuilder moneyLessEqThan(Long moneyEd){
this.moneyEd = moneyEd;
return this;
}
public QueryBuilder money(Long money){
setMoney(money);
return this;
}
public QueryBuilder moneyList(Long ... money){
this.moneyList = solveNullList(money);
return this;
}
public QueryBuilder moneyList(List<Long> money){
this.moneyList = money;
return this;
}
public QueryBuilder fetchMoney(){
setFetchFields("fetchFields","money");
return this;
}
public QueryBuilder excludeMoney(){
setFetchFields("excludeFields","money");
return this;
}
public QueryBuilder createTimeBetWeen(Long createTimeSt,Long createTimeEd){
this.createTimeSt = createTimeSt;
this.createTimeEd = createTimeEd;
return this;
}
public QueryBuilder createTimeGreaterEqThan(Long createTimeSt){
this.createTimeSt = createTimeSt;
return this;
}
public QueryBuilder createTimeLessEqThan(Long createTimeEd){
this.createTimeEd = createTimeEd;
return this;
}
public QueryBuilder createTime(Long createTime){
setCreateTime(createTime);
return this;
}
public QueryBuilder createTimeList(Long ... createTime){
this.createTimeList = solveNullList(createTime);
return this;
}
public QueryBuilder createTimeList(List<Long> createTime){
this.createTimeList = createTime;
return this;
}
public QueryBuilder fetchCreateTime(){
setFetchFields("fetchFields","createTime");
return this;
}
public QueryBuilder excludeCreateTime(){
setFetchFields("excludeFields","createTime");
return this;
}
private <T>List<T> solveNullList(T ... objs){
if (objs != null){
List<T> list = new ArrayList<>();
for (T item : objs){
if (item != null){
list.add(item);
}
}
return list;
}
return null;
}
public QueryBuilder fetchAll(){
this.fetchFields.put("AllFields",true);
return this;
}
public QueryBuilder addField(String ... fields){
List<String> list = new ArrayList<>();
if (fields != null){
for (String field : fields){
list.add(field);
}
}
this.fetchFields.put("otherFields",list);
return this;
}
@SuppressWarnings("unchecked")
private void setFetchFields(String key,String val){
Map<String,Boolean> fields= (Map<String, Boolean>) this.fetchFields.get(key);
if (fields == null){
fields = new HashMap<>();
}
fields.put(val,true);
this.fetchFields.put(key,fields);
}
public ExtractCash build(){return this;}
}
public static class ConditionBuilder{
private List<Long> idList;
public List<Long> getIdList(){return this.idList;}
private Long idSt;
private Long idEd;
public Long getIdSt(){return this.idSt;}
public Long getIdEd(){return this.idEd;}
private List<Long> userIdList;
public List<Long> getUserIdList(){return this.userIdList;}
private Long userIdSt;
private Long userIdEd;
public Long getUserIdSt(){return this.userIdSt;}
public Long getUserIdEd(){return this.userIdEd;}
private List<Long> moneyList;
public List<Long> getMoneyList(){return this.moneyList;}
private Long moneySt;
private Long moneyEd;
public Long getMoneySt(){return this.moneySt;}
public Long getMoneyEd(){return this.moneyEd;}
private List<Long> createTimeList;
public List<Long> getCreateTimeList(){return this.createTimeList;}
private Long createTimeSt;
private Long createTimeEd;
public Long getCreateTimeSt(){return this.createTimeSt;}
public Long getCreateTimeEd(){return this.createTimeEd;}
public ConditionBuilder idBetWeen(Long idSt,Long idEd){
this.idSt = idSt;
this.idEd = idEd;
return this;
}
public ConditionBuilder idGreaterEqThan(Long idSt){
this.idSt = idSt;
return this;
}
public ConditionBuilder idLessEqThan(Long idEd){
this.idEd = idEd;
return this;
}
public ConditionBuilder idList(Long ... id){
this.idList = solveNullList(id);
return this;
}
public ConditionBuilder idList(List<Long> id){
this.idList = id;
return this;
}
public ConditionBuilder userIdBetWeen(Long userIdSt,Long userIdEd){
this.userIdSt = userIdSt;
this.userIdEd = userIdEd;
return this;
}
public ConditionBuilder userIdGreaterEqThan(Long userIdSt){
this.userIdSt = userIdSt;
return this;
}
public ConditionBuilder userIdLessEqThan(Long userIdEd){
this.userIdEd = userIdEd;
return this;
}
public ConditionBuilder userIdList(Long ... userId){
this.userIdList = solveNullList(userId);
return this;
}
public ConditionBuilder userIdList(List<Long> userId){
this.userIdList = userId;
return this;
}
public ConditionBuilder moneyBetWeen(Long moneySt,Long moneyEd){
this.moneySt = moneySt;
this.moneyEd = moneyEd;
return this;
}
public ConditionBuilder moneyGreaterEqThan(Long moneySt){
this.moneySt = moneySt;
return this;
}
public ConditionBuilder moneyLessEqThan(Long moneyEd){
this.moneyEd = moneyEd;
return this;
}
public ConditionBuilder moneyList(Long ... money){
this.moneyList = solveNullList(money);
return this;
}
public ConditionBuilder moneyList(List<Long> money){
this.moneyList = money;
return this;
}
public ConditionBuilder createTimeBetWeen(Long createTimeSt,Long createTimeEd){
this.createTimeSt = createTimeSt;
this.createTimeEd = createTimeEd;
return this;
}
public ConditionBuilder createTimeGreaterEqThan(Long createTimeSt){
this.createTimeSt = createTimeSt;
return this;
}
public ConditionBuilder createTimeLessEqThan(Long createTimeEd){
this.createTimeEd = createTimeEd;
return this;
}
public ConditionBuilder createTimeList(Long ... createTime){
this.createTimeList = solveNullList(createTime);
return this;
}
public ConditionBuilder createTimeList(List<Long> createTime){
this.createTimeList = createTime;
return this;
}
private <T>List<T> solveNullList(T ... objs){
if (objs != null){
List<T> list = new ArrayList<>();
for (T item : objs){
if (item != null){
list.add(item);
}
}
return list;
}
return null;
}
public ConditionBuilder build(){return this;}
}
public static class Builder {
private ExtractCash obj;
public Builder(){
this.obj = new ExtractCash();
}
public Builder id(Long id){
this.obj.setId(id);
return this;
}
public Builder userId(Long userId){
this.obj.setUserId(userId);
return this;
}
public Builder money(Long money){
this.obj.setMoney(money);
return this;
}
public Builder createTime(Long createTime){
this.obj.setCreateTime(createTime);
return this;
}
public ExtractCash build(){return obj;}
}
}
| true |
fd979e41844d7a648aa244f1724767e812d14f28 | Java | m01ten/testArithmeticProject | /src/test/java/ru/sber/operandtest/TestDiv.java | WINDOWS-1251 | 2,124 | 2.75 | 3 | [] | no_license | package ru.sber.operandtest;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Title;
@Title(" ")
public class TestDiv {
private int oper1;
private int oper2;
private final String OPERATION = "/";
private double summFromFile;
ArrayList<HashMap<String, String>> allStringFromFile;
@Before
public void setUp() throws Exception {
LoadFromFile stringFromFile = new LoadFromFile();
allStringFromFile = stringFromFile.loadStringForOperation(OPERATION);
}
@Title(" ")
@Test
public void test() {
for (int i = 0; i < allStringFromFile.size(); i++) {
Map<String, String> map = allStringFromFile.get(i);
summFromFile = Double.parseDouble(map.get("result"));
oper1 = Integer.parseInt(map.get("oper1"));
oper2 = Integer.parseInt(map.get("oper2"));
getString(oper1, oper2, summFromFile);
double expectedSumm = getResult(oper1, oper2);
validate(expectedSumm, summFromFile);
}
}
@Step(" {0}" + OPERATION + "{1}={2}")
public void getString(int oper1, int oper2, double summFromFile) {
// empty. For Allure report.
}
@Step(" {0} " + OPERATION + " {1}")
public double getResult(double oper1, double oper2) {
assertFalse(" 0.", oper2 == 0);
double result = oper1 / oper2;
return result;
}
@Step(" = {0} = {1}")
public void validate(double expectedSumm, double summFromFile) {
assertTrue(" : " + expectedSumm
+ " " + summFromFile,
(Double.compare(expectedSumm, summFromFile) == 0));
}
} | true |
785d4d7b2739e647ec9972bd082aba9f0a6ec3c9 | Java | Uniandes-MISO4203-backup/mpfreelancer-back-201610 | /m-p-freelancer-logic/src/main/java/co/edu/uniandes/csw/mpfreelancer/api/IAgreementLogic.java | UTF-8 | 1,192 | 1.875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.csw.mpfreelancer.api;
import co.edu.uniandes.csw.mpfreelancer.entities.AgreementEntity;
import java.util.List;
/**
*
* @author jc.nino11
*/
public interface IAgreementLogic {
public int countAgreements();
public List<AgreementEntity> getAgreements();
public List<AgreementEntity> getAgreements(Integer page, Integer maxRecords);
public AgreementEntity getAgreement(Long id);
public AgreementEntity createAgreement(AgreementEntity entity);
public AgreementEntity updateAgreement(AgreementEntity entity);
public void deleteAgreement(Long id);
public List<AgreementEntity> getByFreelancer(Long id);
public List<AgreementEntity> getByProject(Long id);
public List<AgreementEntity> getProjectAcepted (Long id);
public List<AgreementEntity> getByStatus1(Long id);
public List<AgreementEntity> getByStatus2(Long id);
public List<AgreementEntity> getByStatus3(Long id);
public List<AgreementEntity> getByStatus4(Long id);
}
| true |
67af85d8f7f3155f0970dfa3e8a45f6a504bdf7f | Java | rloman/ski | /src/main/java/nl/example/app/streams/solution/ApplicationLambdas.java | UTF-8 | 926 | 3.09375 | 3 | [] | no_license | package nl.example.app.streams.solution;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class ApplicationLambdas {
public static void main(String[] args) {
Person kevin = new Person("Kevin");
Person annemarije = new Person("Annemarije");
List<Person> people = Arrays.asList(kevin, annemarije);
Set<Person> peopleWithAnAInName = people
.stream()
.filter(p -> p.getName().contains("A") || p.getName().contains("a"))
.map(p -> {
String name = p.getName();
name = new StringBuilder(name).reverse().toString();
p.setName(name);
return p;
}).collect(Collectors.toSet());
System.out.println(peopleWithAnAInName);
}
}
| true |
9646936f1edd0157bdd7c1c9377618c0b09b90e3 | Java | 0xflotus/cyclops-react | /cyclops-pure/src/main/java/cyclops/instances/jdk/OptionalInstances.java | UTF-8 | 10,392 | 2.5 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package cyclops.instances.jdk;
import com.oath.cyclops.hkt.DataWitness.optional;
import com.oath.cyclops.hkt.Higher;
import cyclops.companion.Optionals;
import cyclops.control.Either;
import cyclops.control.Maybe;
import cyclops.control.Option;
import cyclops.function.Function3;
import cyclops.function.Monoid;
import cyclops.instances.control.MaybeInstances;
import cyclops.kinds.OptionalKind;
import cyclops.arrow.MonoidKs;
import cyclops.typeclasses.functor.Functor;
import cyclops.typeclasses.instances.General;
import lombok.experimental.UtilityClass;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import cyclops.typeclasses.InstanceDefinitions;
import cyclops.typeclasses.Pure;
import cyclops.typeclasses.comonad.Comonad;
import cyclops.typeclasses.foldable.Foldable;
import cyclops.typeclasses.foldable.Unfoldable;
import cyclops.arrow.MonoidK;
import cyclops.typeclasses.monad.*;
/**
* Companion class for creating Type Class instances for working with Optionals
* @author johnmccleanP
*
*/
@UtilityClass
public class OptionalInstances {
public static InstanceDefinitions<optional> definitions(){
return new InstanceDefinitions<optional>() {
@Override
public <T, R> Functor<optional> functor() {
return OptionalInstances.functor();
}
@Override
public <T> Pure<optional> unit() {
return OptionalInstances.unit();
}
@Override
public <T, R> Applicative<optional> applicative() {
return OptionalInstances.applicative();
}
@Override
public <T, R> Monad<optional> monad() {
return OptionalInstances.monad();
}
@Override
public <T, R> Option<MonadZero<optional>> monadZero() {
return Option.some(OptionalInstances.monadZero());
}
@Override
public <T> Option<MonadPlus<optional>> monadPlus() {
return Option.some(OptionalInstances.monadPlus());
}
@Override
public <T> MonadRec<optional> monadRec() {
return OptionalInstances.monadRec();
}
@Override
public <T> Option<MonadPlus<optional>> monadPlus(MonoidK<optional> m) {
return Option.some(OptionalInstances.monadPlus(m));
}
@Override
public <C2, T> Traverse<optional> traverse() {
return OptionalInstances.traverse();
}
@Override
public <T> Foldable<optional> foldable() {
return OptionalInstances.foldable();
}
@Override
public <T> Option<Comonad<optional>> comonad() {
return Maybe.just(OptionalInstances.comonad());
}
@Override
public <T> Option<Unfoldable<optional>> unfoldable() {
return Maybe.nothing();
}
};
}
/**
*
* Transform a list, mulitplying every element by 2
*
* <pre>
* {@code
* OptionalKind<Integer> list = Optionals.functor().map(i->i*2, OptionalKind.widen(Arrays.asOptional(1,2,3));
*
* //[2,4,6]
*
*
* }
* </pre>
*
* An example fluent api working with Optionals
* <pre>
* {@code
* OptionalKind<Integer> list = Optionals.unit()
.unit("hello")
.applyHKT(h->Optionals.functor().map((String v) ->v.length(), h))
.convert(OptionalKind::narrowK3);
*
* }
* </pre>
*
*
* @return A functor for Optionals
*/
public static <T,R>Functor<optional> functor(){
BiFunction<OptionalKind<T>,Function<? super T, ? extends R>,OptionalKind<R>> map = OptionalInstances::map;
return General.functor(map);
}
/**
* <pre>
* {@code
* OptionalKind<String> list = Optionals.unit()
.unit("hello")
.convert(OptionalKind::narrowK3);
//Arrays.asOptional("hello"))
*
* }
* </pre>
*
*
* @return A factory for Optionals
*/
public static <T> Pure<optional> unit(){
return General.<optional,T>unit(OptionalInstances::of);
}
/**
*
* <pre>
* {@code
* import static com.aol.cyclops.hkt.jdk.OptionalKind.widen;
* import static com.aol.cyclops.util.function.Lambda.l1;
* import static java.util.Arrays.asOptional;
*
Optionals.zippingApplicative()
.ap(widen(asOptional(l1(this::multiplyByTwo))),widen(asOptional(1,2,3)));
*
* //[2,4,6]
* }
* </pre>
*
*
* Example fluent API
* <pre>
* {@code
* OptionalKind<Function<Integer,Integer>> listFn =Optionals.unit()
* .unit(Lambda.l1((Integer i) ->i*2))
* .convert(OptionalKind::narrowK3);
OptionalKind<Integer> list = Optionals.unit()
.unit("hello")
.applyHKT(h->Optionals.functor().map((String v) ->v.length(), h))
.applyHKT(h->Optionals.applicative().ap(listFn, h))
.convert(OptionalKind::narrowK3);
//Arrays.asOptional("hello".length()*2))
*
* }
* </pre>
*
*
* @return A zipper for Optionals
*/
public static <T,R> Applicative<optional> applicative(){
BiFunction<OptionalKind< Function<T, R>>,OptionalKind<T>,OptionalKind<R>> ap = OptionalInstances::ap;
return General.applicative(functor(), unit(), ap);
}
/**
*
* <pre>
* {@code
* import static com.aol.cyclops.hkt.jdk.OptionalKind.widen;
* OptionalKind<Integer> list = Optionals.monad()
.flatMap(i->widen(OptionalX.range(0,i)), widen(Arrays.asOptional(1,2,3)))
.convert(OptionalKind::narrowK3);
* }
* </pre>
*
* Example fluent API
* <pre>
* {@code
* OptionalKind<Integer> list = Optionals.unit()
.unit("hello")
.applyHKT(h->Optionals.monad().flatMap((String v) ->Optionals.unit().unit(v.length()), h))
.convert(OptionalKind::narrowK3);
//Arrays.asOptional("hello".length())
*
* }
* </pre>
*
* @return Type class with monad arrow for Optionals
*/
public static <T,R> Monad<optional> monad(){
BiFunction<Higher<optional,T>,Function<? super T, ? extends Higher<optional,R>>,Higher<optional,R>> flatMap = OptionalInstances::flatMap;
return General.monad(applicative(), flatMap);
}
/**
*
* <pre>
* {@code
* OptionalKind<String> list = Optionals.unit()
.unit("hello")
.applyHKT(h->Optionals.monadZero().filter((String t)->t.startsWith("he"), h))
.convert(OptionalKind::narrowK3);
//Arrays.asOptional("hello"));
*
* }
* </pre>
*
*
* @return A filterable monad (with default value)
*/
public static <T,R> MonadZero<optional> monadZero(){
return General.monadZero(monad(), OptionalKind.empty());
}
public static MonadRec<optional> monadRec() {
return new MonadRec<optional>(){
@Override
public <T, R> Higher<optional, R> tailRec(T initial, Function<? super T, ? extends Higher<optional, ? extends Either<T, R>>> fn) {
Optional<R> x = Optionals.tailRec(initial, fn.andThen(a -> OptionalKind.narrowK(a)));
return OptionalKind.widen(x);
}
};
}
/**
*
* <pre>
* {@code
* OptionalKind<Integer> list = Optionals.<Integer>monadPlus()
.plus(OptionalKind.widen(Arrays.asOptional()), OptionalKind.widen(Arrays.asOptional(10)))
.convert(OptionalKind::narrowK3);
//Arrays.asOptional(10))
*
* }
* </pre>
* @return Type class for combining Optionals by concatenation
*/
public static <T> MonadPlus<optional> monadPlus(){
return General.monadPlus(monadZero(), MonoidKs.firstPresentOptional());
}
/**
*
* <pre>
* {@code
* Monoid<OptionalKind<Integer>> m = Monoid.of(OptionalKind.widen(Arrays.asOptional()), (a,b)->a.isEmpty() ? b : a);
OptionalKind<Integer> list = Optionals.<Integer>monadPlus(m)
.plus(OptionalKind.widen(Arrays.asOptional(5)), OptionalKind.widen(Arrays.asOptional(10)))
.convert(OptionalKind::narrowK3);
//Arrays.asOptional(5))
*
* }
* </pre>
*
* @param m2 Monoid to use for combining Optionals
* @return Type class for combining Optionals
*/
public static <T> MonadPlus<optional> monadPlus(MonoidK<optional> m2){
return General.monadPlus(monadZero(),m2);
}
/**
* @return Type class for traversables with traverse / sequence operations
*/
public static <C2,T> Traverse<optional> traverse(){
return General.traverseByTraverse(applicative(), OptionalInstances::traverseA);
}
/**
*
* <pre>
* {@code
* int sum = Optionals.foldable()
.foldLeft(0, (a,b)->a+b, OptionalKind.widen(Arrays.asOptional(1,2,3,4)));
//10
*
* }
* </pre>
*
*
* @return Type class for folding / reduction operations
*/
public static <T,R> Foldable<optional> foldable(){
BiFunction<Monoid<T>,Higher<optional,T>,T> foldRightFn = (m, l)-> OptionalKind.narrow(l).orElse(m.zero());
BiFunction<Monoid<T>,Higher<optional,T>,T> foldLeftFn = (m, l)-> OptionalKind.narrow(l).orElse(m.zero());
Function3<Monoid<R>, Function<T, R>, Higher<optional, T>, R> foldMapFn = (m, f, l)->OptionalKind.narrowK(l).map(f).orElseGet(()->m.zero());
return General.foldable(foldRightFn, foldLeftFn,foldMapFn);
}
public static <T> Comonad<optional> comonad(){
Function<? super Higher<optional, T>, ? extends T> extractFn = maybe -> maybe.convert(OptionalKind::narrow).get();
return General.comonad(functor(), unit(), extractFn);
}
private <T> OptionalKind<T> of(T value){
return OptionalKind.widen(Optional.of(value));
}
private static <T,R> OptionalKind<R> ap(OptionalKind<Function< T, R>> lt, OptionalKind<T> list){
return OptionalKind.widen(MaybeInstances.fromOptionalKind(lt).zip(MaybeInstances.fromOptionalKind(list), (a, b)->a.apply(b)).toOptional());
}
private static <T,R> Higher<optional,R> flatMap(Higher<optional,T> lt, Function<? super T, ? extends Higher<optional,R>> fn){
return OptionalKind.widen(OptionalKind.narrow(lt).flatMap(fn.andThen(OptionalKind::narrowK)));
}
private static <T,R> OptionalKind<R> map(OptionalKind<T> lt, Function<? super T, ? extends R> fn){
return OptionalKind.narrow(lt).map(fn);
}
private static <C2,T,R> Higher<C2, Higher<optional, R>> traverseA(Applicative<C2> applicative, Function<? super T, ? extends Higher<C2, R>> fn,
Higher<optional, T> ds){
Optional<T> opt = OptionalKind.narrowK(ds);
return opt.isPresent() ? applicative.map(OptionalKind::of, fn.apply(opt.get())) :
applicative.unit(OptionalKind.empty());
}
}
| true |
ab0eed67e1e809f3b0f56138de84ef2fd7e6bfa7 | Java | tomerasulin/springBootAppWithKafka-BH | /messageService/src/main/java/il/asulin/messageService/services/MessageListener.java | UTF-8 | 179 | 1.671875 | 2 | [] | no_license | package il.asulin.messageService.services;
import org.json.JSONObject;
public interface MessageListener {
void notifyOnMessageReceived(JSONObject json, String key);
}
| true |
4fa37aa77b57f45eeed39704d7b7bf3068720d14 | Java | monkeycc321/research | /RoutePlanning/src/main/java/edu/swfu/routeplanning/service/PlanningRouteServiceImpl.java | UTF-8 | 4,079 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package edu.swfu.routeplanning.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oracle.spatial.geometry.JGeometry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import edu.swfu.gis.entity.TMultiLine;
import edu.swfu.gis.entity.TPoint;
import edu.swfu.routeplanning.dao.IDirectRouteDao;
import edu.swfu.routeplanning.entity.DirectRoute;
import edu.swfu.routeplanning.entity.PlanningRoute;
@Service
public class PlanningRouteServiceImpl implements IPlanningRouteService {
// @Autowired
// private IPlanningRouteDao dao;
@Autowired
private IDirectRouteDao directRouteDao;
// @Override
// public IFeatureDao getDao() {
// return this.dao;
// }
private void slicingGeo(DirectRoute dr) {
TMultiLine multiline=(TMultiLine) dr.getGeometry();
double[][] coordinates=Arrays.copyOfRange(multiline.toCoordinates(),dr.getStopSn1()-1, dr.getStopSn2()-1);
TMultiLine newGeo=new TMultiLine(multiline.getSrs(),multiline.getDim(),coordinates);
dr.setGeometry(newGeo);
}
public List<PlanningRoute> selectDirect(Float x1,Float y1,Float x2,Float y2,Integer srid,Integer distance) throws Exception {
Map<String,Object> para=new HashMap<String,Object>();
para.put("origin", new JGeometry(x1,y1,srid));
para.put("destination", new JGeometry(x2,y2,srid));
para.put("distance",distance);
TPoint origin=new TPoint(x1,y1);
TPoint destination=new TPoint(x2,y2);
Double radius=new Double(distance);
List<DirectRoute> drs = this.directRouteDao.selectByMethod("selectDirect", para);
List<PlanningRoute> result = new ArrayList<PlanningRoute>();
for (DirectRoute dr : drs) {
PlanningRoute pr = new PlanningRoute();
pr.setOrigin(origin);
pr.setDestination(destination);
pr.setSearchRadius(radius);
this.slicingGeo(dr);
pr.getDirectRoutes().add(dr);
result.add(pr);
}
return result;
}
public List<PlanningRoute> selectTransfer1(Float x1,Float y1,Float x2,Float y2,Integer srid,Integer distance) throws Exception {
Map<String,Object> para=new HashMap<String,Object>();
para.put("origin", new JGeometry(x1,y1,srid));
para.put("destination", new JGeometry(x2,y2,srid));
para.put("distance",distance);
TPoint origin=new TPoint(x1,y1);
TPoint destination=new TPoint(x2,y2);
Double radius=new Double(distance);
List<DirectRoute> drs=this.directRouteDao.selectByMethod("selectTransfer1",para);
List<PlanningRoute> result=new ArrayList<PlanningRoute>();
int n=1;
PlanningRoute pr=null;
for (DirectRoute dr:drs) {
if (n++%2==1) {
pr=new PlanningRoute();
pr.setOrigin(origin);
pr.setDestination(destination);
pr.setSearchRadius(radius);
result.add(pr);
}
this.slicingGeo(dr);
pr.getDirectRoutes().add(dr);
}
return result;
}
public List<PlanningRoute> selectTransfer2(Float x1,Float y1,Float x2,Float y2,Integer srid,Integer distance) throws Exception {
Map<String,Object> para=new HashMap<String,Object>();
para.put("origin", new JGeometry(x1,y1,srid));
para.put("destination", new JGeometry(x2,y2,srid));
para.put("distance",distance);
TPoint origin=new TPoint(x1,y1);
TPoint destination=new TPoint(x2,y2);
Double radius=new Double(distance);
List<DirectRoute> drs=this.directRouteDao.selectByMethod("selectTransfer2",para);
List<PlanningRoute> result=new ArrayList<PlanningRoute>();
int n=1;
PlanningRoute pr=null;
for (DirectRoute dr:drs) {
if (n++%3==1) {
pr=new PlanningRoute();
pr.setOrigin(origin);
pr.setDestination(destination);
pr.setSearchRadius(radius);
result.add(pr);
}
this.slicingGeo(dr);
pr.getDirectRoutes().add(dr);
}
return result;
}
public List<Map<String, Object>> selectPath() throws Exception {
// TODO Auto-generated method stub
return null;
}
} | true |
cf84e4b8964ebc23b307c278f9012fbc72dc31c9 | Java | Planckcons/Divided-P-O-T-A-T-O | /Logigs/DP/src/ShipParts.java | UTF-8 | 387 | 2.796875 | 3 | [] | no_license |
public class ShipParts {
int condition;
int weight;
int array_place;
String name;
String type;
ShipParts(int condition, int weight, String name, String type, int array_place)
{
this.condition = condition;
this.name = name;
this.type = type;
this.weight = weight;
this.array_place = array_place;
}
void ConditionChange(int amount)
{
condition += amount;
}
}
| true |
267c4514f56b2b89fafc64b8e572f8070128e28c | Java | alidili/Demos | /DataBindingDemo/app/src/main/java/com/yl/databindingdemo/ui/MainActivity.java | UTF-8 | 2,935 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | package com.yl.databindingdemo.ui;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.yl.databindingdemo.R;
import com.yl.databindingdemo.databinding.ActivityMainBinding;
/**
* 主页
* Created by yangle on 2017/7/7.
* <p>
* Website:http://www.yangle.tech
* GitHub:https://github.com/alidili
* CSDN:http://blog.csdn.net/kong_gu_you_lan
* JianShu:http://www.jianshu.com/u/34ece31cd6eb
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.btn_base_use: // 基本使用
intent = new Intent(MainActivity.this, BaseUseActivity.class);
break;
case R.id.btn_layout_detail: // 布局详情
intent = new Intent(MainActivity.this, LayoutDetailActivity.class);
break;
case R.id.btn_observable: // 动态更新
intent = new Intent(MainActivity.this, ObservableActivity.class);
break;
case R.id.btn_double_binding: // 双向绑定
intent = new Intent(MainActivity.this, DoubleBindingActivity.class);
break;
case R.id.btn_event_handling: // 事件处理
intent = new Intent(MainActivity.this, EventHandlingActivity.class);
break;
case R.id.btn_recycler_view: // RecyclerView
intent = new Intent(MainActivity.this, RecyclerViewActivity.class);
break;
case R.id.btn_multi_recycler_view: // 多布局RecyclerView
intent = new Intent(MainActivity.this, MultiRecyclerViewActivity.class);
break;
case R.id.btn_custom_attribute: // 自定义属性
intent = new Intent(MainActivity.this, CustomAttributeActivity.class);
break;
case R.id.btn_view_stub: // ViewStub
intent = new Intent(MainActivity.this, ViewStubActivity.class);
break;
default:
break;
}
if (intent != null) {
startActivity(intent);
}
}
});
}
}
| true |
1cb39c3dd1cd0b56f9a8773b88c13802f8e86621 | Java | tanhuaqiang/mycode | /src/test/java/com/dalingjia/myThreadPool/Future.java | UTF-8 | 197 | 1.9375 | 2 | [] | no_license | package com.dalingjia.myThreadPool;
public interface Future<T> {
/**
* 获取
* @return 结果
* @throws InterruptedException
*/
T get() throws InterruptedException;
} | true |
b0007c473be070beb6150e6b4a5ee3e61a803a1a | Java | savitendersinghrajput/e-bell | /app/src/main/java/com/saurav/qrgenerater/ScannerActivity.java | UTF-8 | 4,553 | 2.03125 | 2 | [] | no_license | package com.saurav.qrgenerater;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.budiyev.android.codescanner.CodeScanner;
import com.budiyev.android.codescanner.CodeScannerView;
import com.budiyev.android.codescanner.DecodeCallback;
import com.google.zxing.Result;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
public class ScannerActivity extends AppCompatActivity {
CodeScanner codeScanner;
TextView textView;
CodeScannerView scanView;
EditText edtNo;
String sMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
scanView=findViewById(R.id.codeScannerView);
codeScanner =new CodeScanner(this,scanView);
textView=findViewById(R.id.txtView);
edtNo=findViewById(R.id.edtNo);
codeScanner.setDecodeCallback(new DecodeCallback() {
@Override
public void onDecoded(@NonNull Result result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
sMessage=result.getText().toString();
textView.setText(sMessage);
}
});
}
});
scanView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
codeScanner.startPreview();
}
});
}
@Override
protected void onResume() {
super.onResume();
// codeScanner.startPreview();
requestForCamera();
}
private void requestForCamera() {
Dexter.withContext(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
@Override public void onPermissionGranted(PermissionGrantedResponse response) {
codeScanner.startPreview();
}
@Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(ScannerActivity.this, "Camera permission is required", Toast.LENGTH_SHORT).show();
}
@Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
public void btnSend(View view) {
if (ContextCompat.checkSelfPermission(ScannerActivity.this,Manifest.permission.SEND_SMS)== PackageManager.PERMISSION_GRANTED){
sendMessage();
}else {
ActivityCompat.requestPermissions(ScannerActivity.this,new String[]{Manifest.permission.SEND_SMS},100);
}
}
private void sendMessage() {
String sphone=edtNo.getText().toString().trim();
// String sMessage=textView.getText().toString().trim();
if (!sphone.equals("")&&!sMessage.equals("")){
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(sphone,null,sMessage,null,null);
Toast.makeText(this, "SMS sent successfully....", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Enter value first...", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==100&&grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
sendMessage();
}else {
Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
}
}
} | true |
f54a641532000570994451868bf1adf9fd1cbffc | Java | georgemoralis/arcadeflex-037b7-deprecated | /emulator_dev/src/main/java/gr/codebb/arcadeflex/WIP/v037b7/drivers/astrocde.java | UTF-8 | 43,137 | 1.546875 | 2 | [] | no_license | /*
* ported to v0.37b7
* using automatic conversion tool v0.01
*/
package gr.codebb.arcadeflex.WIP.v037b7.drivers;
import static gr.codebb.arcadeflex.WIP.v037b7.machine.astrocde.*;
import static gr.codebb.arcadeflex.WIP.v037b7.sndhrdw.astrocde.*;
import static gr.codebb.arcadeflex.WIP.v037b7.sndhrdw.gorf.*;
import static gr.codebb.arcadeflex.WIP.v037b7.sound.astrocde.*;
import static gr.codebb.arcadeflex.WIP.v037b7.sound.astrocdeH.*;
import static gr.codebb.arcadeflex.WIP.v037b7.vidhrdw.astrocde.*;
import static gr.codebb.arcadeflex.v037b7.mame.driverH.*;
import static gr.codebb.arcadeflex.WIP.v037b7.mame.cpuintrf.*;
import static gr.codebb.arcadeflex.WIP.v037b7.sound.samplesH.*;
import static gr.codebb.arcadeflex.v037b7.common.fucPtr.*;
import static gr.codebb.arcadeflex.WIP.v037b7.mame.commonH.*;
import static gr.codebb.arcadeflex.WIP.v037b7.mame.drawgfxH.*;
import static gr.codebb.arcadeflex.WIP.v037b7.mame.inptport.*;
import static gr.codebb.arcadeflex.WIP.v037b7.mame.inptportH.*;
import static gr.codebb.arcadeflex.WIP.v037b7.mame.memory.*;
import static gr.codebb.arcadeflex.WIP.v037b7.mame.memoryH.*;
import static gr.codebb.arcadeflex.v037b7.mame.sndintrfH.*;
import static gr.codebb.arcadeflex.WIP.v037b7.vidhrdw.generic.*;
public class astrocde {
static MemoryReadAddress seawolf2_readmem[]
= {
new MemoryReadAddress(0x0000, 0x1fff, MRA_ROM),
new MemoryReadAddress(0x4000, 0x7fff, MRA_RAM),
new MemoryReadAddress(0xc000, 0xcfff, MRA_RAM),
new MemoryReadAddress(-1) /* end of table */};
static MemoryWriteAddress seawolf2_writemem[]
= {
new MemoryWriteAddress(0x0000, 0x3fff, wow_magicram_w),
new MemoryWriteAddress(0x4000, 0x7fff, wow_videoram_w, wow_videoram, videoram_size),
new MemoryWriteAddress(0xc000, 0xcfff, MWA_RAM),
new MemoryWriteAddress(-1) /* end of table */};
static MemoryReadAddress readmem[]
= {
new MemoryReadAddress(0x0000, 0x3fff, MRA_ROM),
new MemoryReadAddress(0x4000, 0x7fff, MRA_RAM),
new MemoryReadAddress(0x8000, 0xcfff, MRA_ROM),
new MemoryReadAddress(0xd000, 0xdfff, MRA_RAM),
new MemoryReadAddress(-1) /* end of table */};
static MemoryWriteAddress writemem[]
= {
new MemoryWriteAddress(0x0000, 0x3fff, wow_magicram_w),
new MemoryWriteAddress(0x4000, 0x7fff, wow_videoram_w, wow_videoram, videoram_size), /* ASG */
new MemoryWriteAddress(0x8000, 0xcfff, MWA_ROM),
new MemoryWriteAddress(0xd000, 0xdfff, MWA_RAM),
new MemoryWriteAddress(-1) /* end of table */};
static MemoryReadAddress robby_readmem[]
= {
new MemoryReadAddress(0x0000, 0x3fff, MRA_ROM),
new MemoryReadAddress(0x4000, 0x7fff, MRA_RAM),
new MemoryReadAddress(0x8000, 0xdfff, MRA_ROM),
new MemoryReadAddress(0xe000, 0xffff, MRA_RAM),
new MemoryReadAddress(-1) /* end of table */};
static MemoryWriteAddress robby_writemem[]
= {
new MemoryWriteAddress(0x0000, 0x3fff, wow_magicram_w),
new MemoryWriteAddress(0x4000, 0x7fff, wow_videoram_w, wow_videoram, videoram_size),
new MemoryWriteAddress(0x8000, 0xdfff, MWA_ROM),
new MemoryWriteAddress(0xe000, 0xffff, MWA_RAM),
new MemoryWriteAddress(-1) /* end of table */};
static MemoryReadAddress profpac_readmem[]
= {
new MemoryReadAddress(0x0000, 0x3fff, MRA_ROM),
new MemoryReadAddress(0x8000, 0xdfff, MRA_ROM),
new MemoryReadAddress(0xe000, 0xffff, MRA_RAM),
new MemoryReadAddress(-1) /* end of table */};
static MemoryWriteAddress profpac_writemem[]
= {
new MemoryWriteAddress(0x0000, 0x3fff, wow_magicram_w),
new MemoryWriteAddress(0x4000, 0x7fff, wow_videoram_w, wow_videoram, videoram_size),
new MemoryWriteAddress(0x8000, 0xdfff, MWA_ROM),
new MemoryWriteAddress(0xe000, 0xffff, MWA_RAM),
new MemoryWriteAddress(-1) /* end of table */};
static IOReadPort readport[]
= {
new IOReadPort(0x08, 0x08, wow_intercept_r),
new IOReadPort(0x0e, 0x0e, wow_video_retrace_r),
new IOReadPort(0x10, 0x10, input_port_0_r),
new IOReadPort(0x11, 0x11, input_port_1_r),
new IOReadPort(0x12, 0x12, input_port_2_r),
new IOReadPort(0x13, 0x13, input_port_3_r),
new IOReadPort(-1) /* end of table */};
static IOWritePort seawolf2_writeport[]
= {
new IOWritePort(0x00, 0x07, astrocde_colour_register_w),
new IOWritePort(0x08, 0x08, astrocde_mode_w),
new IOWritePort(0x09, 0x09, astrocde_colour_split_w),
new IOWritePort(0x0a, 0x0a, astrocde_vertical_blank_w),
new IOWritePort(0x0b, 0x0b, astrocde_colour_block_w),
new IOWritePort(0x0c, 0x0c, astrocde_magic_control_w),
new IOWritePort(0x0d, 0x0d, interrupt_vector_w),
new IOWritePort(0x0e, 0x0e, astrocde_interrupt_enable_w),
new IOWritePort(0x0f, 0x0f, astrocde_interrupt_w),
new IOWritePort(0x19, 0x19, astrocde_magic_expand_color_w),
new IOWritePort(-1) /* end of table */};
static IOWritePort writeport[]
= {
new IOWritePort(0x00, 0x07, astrocde_colour_register_w),
new IOWritePort(0x08, 0x08, astrocde_mode_w),
new IOWritePort(0x09, 0x09, astrocde_colour_split_w),
new IOWritePort(0x0a, 0x0a, astrocde_vertical_blank_w),
new IOWritePort(0x0b, 0x0b, astrocde_colour_block_w),
new IOWritePort(0x0c, 0x0c, astrocde_magic_control_w),
new IOWritePort(0x0d, 0x0d, interrupt_vector_w),
new IOWritePort(0x0e, 0x0e, astrocde_interrupt_enable_w),
new IOWritePort(0x0f, 0x0f, astrocde_interrupt_w),
new IOWritePort(0x10, 0x18, astrocade_sound1_w),
new IOWritePort(0x19, 0x19, astrocde_magic_expand_color_w),
new IOWritePort(0x50, 0x58, astrocade_sound2_w),
new IOWritePort(0x5b, 0x5b, MWA_NOP), /* speech board ? Wow always sets this to a5*/
new IOWritePort(0x78, 0x7e, astrocde_pattern_board_w),
/* new IOWritePort( 0xf8, 0xff, MWA_NOP ), */ /* Gorf uses these */
new IOWritePort(-1) /* end of table */};
static InputPortPtr input_ports_seawolf2 = new InputPortPtr() {
public void handler() {
PORT_START();
/* IN0 */
PORT_ANALOG(0x3f, 0x20, IPT_PADDLE | IPF_REVERSE | IPF_PLAYER1, 20, 5, 0, 0x3f);
PORT_DIPNAME(0x40, 0x00, "Language 1");
PORT_DIPSETTING(0x00, "Language 2");
PORT_DIPSETTING(0x40, "French");
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_BUTTON1 | IPF_PLAYER1);
PORT_START();
/* IN1 */
PORT_ANALOG(0x3f, 0x20, IPT_PADDLE | IPF_REVERSE | IPF_PLAYER2, 20, 5, 0, 0x3f);
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_BUTTON1 | IPF_PLAYER2);
PORT_START();
/* IN2 */
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_COIN1);
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_START1);
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_START2);
PORT_DIPNAME(0x08, 0x00, "Language 2");
PORT_DIPSETTING(0x00, "English");
PORT_DIPSETTING(0x08, "German");
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN);
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN);
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN);
PORT_START();
/* Dip Switch */
PORT_DIPNAME(0x01, 0x01, DEF_STR("Coinage"));
PORT_DIPSETTING(0x00, DEF_STR("2C_1C"));
PORT_DIPSETTING(0x01, DEF_STR("1C_1C"));
PORT_DIPNAME(0x06, 0x00, "Play Time");
PORT_DIPSETTING(0x06, "40");
PORT_DIPSETTING(0x04, "50");
PORT_DIPSETTING(0x02, "60");
PORT_DIPSETTING(0x00, "70");
PORT_DIPNAME(0x08, 0x08, "2 Players Game");
PORT_DIPSETTING(0x00, "1 Credit");
PORT_DIPSETTING(0x08, "2 Credits");
PORT_DIPNAME(0x30, 0x00, "Extended Play");
PORT_DIPSETTING(0x10, "5000");
PORT_DIPSETTING(0x20, "6000");
PORT_DIPSETTING(0x30, "7000");
PORT_DIPSETTING(0x00, "None");
PORT_DIPNAME(0x40, 0x40, "Monitor");
PORT_DIPSETTING(0x40, "Color");
PORT_DIPSETTING(0x00, "B/W");
PORT_SERVICE(0x80, IP_ACTIVE_LOW);
INPUT_PORTS_END();
}
};
static InputPortPtr input_ports_spacezap = new InputPortPtr() {
public void handler() {
PORT_START();
/* IN0 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_COIN1);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_COIN2);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_TILT);
PORT_SERVICE(0x08, IP_ACTIVE_LOW);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_START1);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_START2);
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* IN1 */
PORT_START();
/* IN2 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_BUTTON1);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* Dip Switch */
PORT_DIPNAME(0x01, 0x01, DEF_STR("Coin_A"));
PORT_DIPSETTING(0x00, DEF_STR("2C_1C"));
PORT_DIPSETTING(0x01, DEF_STR("1C_1C"));
PORT_DIPNAME(0x06, 0x06, DEF_STR("Coin_B"));
PORT_DIPSETTING(0x04, DEF_STR("2C_1C"));
PORT_DIPSETTING(0x06, DEF_STR("1C_1C"));
PORT_DIPSETTING(0x02, DEF_STR("1C_3C"));
PORT_DIPSETTING(0x00, DEF_STR("1C_5C"));
PORT_DIPNAME(0x08, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x08, DEF_STR("On"));
PORT_DIPNAME(0x10, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x10, DEF_STR("On"));
PORT_DIPNAME(0x20, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x20, DEF_STR("On"));
PORT_DIPNAME(0x40, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x40, DEF_STR("On"));
PORT_DIPNAME(0x80, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x80, DEF_STR("On"));
INPUT_PORTS_END();
}
};
static InputPortPtr input_ports_ebases = new InputPortPtr() {
public void handler() {
PORT_START();
/* IN0 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_BUTTON1);
PORT_BIT(0x0c, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_START1);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_START2);
PORT_BIT(0xc0, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_COIN1);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_COIN2);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_TILT);
PORT_DIPNAME(0x08, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x08, DEF_STR("On"));
PORT_DIPNAME(0x10, 0x00, "Monitor");
PORT_DIPSETTING(0x00, "Color");
PORT_DIPSETTING(0x10, "B/W");
PORT_DIPNAME(0x20, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x20, DEF_STR("On"));
PORT_DIPNAME(0x40, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x40, DEF_STR("On"));
PORT_DIPNAME(0x80, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x80, DEF_STR("On"));
PORT_START();
/* Dip Switch */
PORT_DIPNAME(0x01, 0x00, "2 Players Game");
PORT_DIPSETTING(0x00, "1 Credit");
PORT_DIPSETTING(0x01, "2 Credits");
PORT_DIPNAME(0x02, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x02, DEF_STR("On"));
PORT_DIPNAME(0x04, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x04, DEF_STR("On"));
PORT_DIPNAME(0x08, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x08, DEF_STR("On"));
PORT_DIPNAME(0x10, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x10, DEF_STR("On"));
PORT_DIPNAME(0x20, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x20, DEF_STR("On"));
PORT_DIPNAME(0x40, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x40, DEF_STR("On"));
PORT_DIPNAME(0x80, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x80, DEF_STR("On"));
PORT_START();
PORT_ANALOGX(0xff, 0x00, IPT_TRACKBALL_X | IPF_PLAYER2 | IPF_CENTER, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE);
PORT_START();
PORT_ANALOGX(0xff, 0x00, IPT_TRACKBALL_Y | IPF_PLAYER2 | IPF_CENTER, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE);
PORT_START();
PORT_ANALOGX(0xff, 0x00, IPT_TRACKBALL_X | IPF_CENTER, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE);
PORT_START();
PORT_ANALOGX(0xff, 0x00, IPT_TRACKBALL_Y | IPF_CENTER, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE);
INPUT_PORTS_END();
}
};
static InputPortPtr input_ports_wow = new InputPortPtr() {
public void handler() {
PORT_START();
/* IN0 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_COIN1);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_COIN2);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_COIN3);
PORT_SERVICE(0x08, IP_ACTIVE_LOW);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_TILT);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_START1);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_START2);
PORT_DIPNAME(0x80, 0x80, DEF_STR("Flip_Screen"));
PORT_DIPSETTING(0x80, DEF_STR("Off"));
PORT_DIPSETTING(0x00, DEF_STR("On"));
PORT_START();
/* IN1 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2);
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_BUTTON2 | IPF_PLAYER2);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* IN2 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY);
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_BUTTON2);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_BUTTON1);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN);/* speech status */
PORT_START();
/* Dip Switch */
PORT_DIPNAME(0x01, 0x01, DEF_STR("Coin_A"));
PORT_DIPSETTING(0x00, DEF_STR("2C_1C"));
PORT_DIPSETTING(0x01, DEF_STR("1C_1C"));
PORT_DIPNAME(0x06, 0x06, DEF_STR("Coin_B"));
PORT_DIPSETTING(0x04, DEF_STR("2C_1C"));
PORT_DIPSETTING(0x06, DEF_STR("1C_1C"));
PORT_DIPSETTING(0x02, DEF_STR("1C_3C"));
PORT_DIPSETTING(0x00, DEF_STR("1C_5C"));
PORT_DIPNAME(0x08, 0x08, "Language");
PORT_DIPSETTING(0x08, "English");
PORT_DIPSETTING(0x00, "Foreign (NEED ROM)");
PORT_DIPNAME(0x10, 0x00, DEF_STR("Lives"));
PORT_DIPSETTING(0x10, "2 / 5");
PORT_DIPSETTING(0x00, "3 / 7");
PORT_DIPNAME(0x20, 0x20, DEF_STR("Bonus_Life"));
PORT_DIPSETTING(0x20, "3rd Level");
PORT_DIPSETTING(0x00, "4th Level");
PORT_DIPNAME(0x40, 0x40, DEF_STR("Free_Play"));
PORT_DIPSETTING(0x40, DEF_STR("Off"));
PORT_DIPSETTING(0x00, DEF_STR("On"));
PORT_DIPNAME(0x80, 0x80, DEF_STR("Demo_Sounds"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x80, DEF_STR("On"));
INPUT_PORTS_END();
}
};
static InputPortPtr input_ports_gorf = new InputPortPtr() {
public void handler() {
PORT_START();
/* IN0 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_COIN1);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_COIN2);
PORT_SERVICE(0x04, IP_ACTIVE_LOW);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_TILT);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_START1);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_START2);
PORT_DIPNAME(0x40, 0x40, DEF_STR("Cabinet"));
PORT_DIPSETTING(0x40, DEF_STR("Upright"));
PORT_DIPSETTING(0x00, DEF_STR("Cocktail"));
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* IN1 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* IN2 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_BUTTON1);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN);/* speech status */
PORT_START();
/* Dip Switch */
PORT_DIPNAME(0x01, 0x01, DEF_STR("Coin_A"));
PORT_DIPSETTING(0x00, DEF_STR("2C_1C"));
PORT_DIPSETTING(0x01, DEF_STR("1C_1C"));
PORT_DIPNAME(0x06, 0x06, DEF_STR("Coin_B"));
PORT_DIPSETTING(0x04, DEF_STR("2C_1C"));
PORT_DIPSETTING(0x06, DEF_STR("1C_1C"));
PORT_DIPSETTING(0x02, DEF_STR("1C_3C"));
PORT_DIPSETTING(0x00, DEF_STR("1C_5C"));
PORT_DIPNAME(0x08, 0x08, "Language");
PORT_DIPSETTING(0x08, "English");
PORT_DIPSETTING(0x00, "Foreign (NEED ROM)");
PORT_DIPNAME(0x10, 0x00, "Lives per Credit");
PORT_DIPSETTING(0x10, "2");
PORT_DIPSETTING(0x00, "3");
PORT_DIPNAME(0x20, 0x00, DEF_STR("Bonus_Life"));
PORT_DIPSETTING(0x00, "Mission 5");
PORT_DIPSETTING(0x20, "None");
PORT_DIPNAME(0x40, 0x40, DEF_STR("Free_Play"));
PORT_DIPSETTING(0x40, DEF_STR("Off"));
PORT_DIPSETTING(0x00, DEF_STR("On"));
PORT_DIPNAME(0x80, 0x80, DEF_STR("Demo_Sounds"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x80, DEF_STR("On"));
INPUT_PORTS_END();
}
};
static InputPortPtr input_ports_robby = new InputPortPtr() {
public void handler() {
PORT_START();
/* IN0 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_COIN1);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_COIN2);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_SERVICE(0x08, IP_ACTIVE_LOW);
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_TILT);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_START1);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_START2);
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* IN1 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_COCKTAIL);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_COCKTAIL);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_COCKTAIL);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_COCKTAIL);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* IN2 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY);
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY);
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY);
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY);
PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_BUTTON1);
PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNKNOWN);
PORT_START();
/* Dip Switch */
PORT_DIPNAME(0x01, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x01, DEF_STR("On"));
PORT_DIPNAME(0x02, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x02, DEF_STR("On"));
PORT_DIPNAME(0x04, 0x04, DEF_STR("Free_Play"));
PORT_DIPSETTING(0x04, DEF_STR("Off"));
PORT_DIPSETTING(0x00, DEF_STR("On"));
PORT_DIPNAME(0x08, 0x08, DEF_STR("Cabinet"));
PORT_DIPSETTING(0x08, DEF_STR("Upright"));
PORT_DIPSETTING(0x00, DEF_STR("Cocktail"));
PORT_DIPNAME(0x10, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x10, DEF_STR("On"));
PORT_DIPNAME(0x20, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x20, DEF_STR("On"));
PORT_DIPNAME(0x40, 0x00, DEF_STR("Unknown"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x40, DEF_STR("On"));
PORT_DIPNAME(0x80, 0x80, DEF_STR("Demo_Sounds"));
PORT_DIPSETTING(0x00, DEF_STR("Off"));
PORT_DIPSETTING(0x80, DEF_STR("On"));
INPUT_PORTS_END();
}
};
static Samplesinterface wow_samples_interface = new Samplesinterface(
8, /* 8 channels */
25, /* volume */
wow_sample_names
);
static Samplesinterface gorf_samples_interface = new Samplesinterface(
8, /* 8 channels */
25, /* volume */
gorf_sample_names
);
static astrocade_interface astrocade_2chip_interface = new astrocade_interface(
2, /* Number of chips */
1789773, /* Clock speed */
new int[]{255, 255} /* Volume */
);
static astrocade_interface astrocade_1chip_interface = new astrocade_interface(
1, /* Number of chips */
1789773, /* Clock speed */
new int[]{255} /* Volume */
);
static CustomSound_interface gorf_custom_interface = new CustomSound_interface(
gorf_sh_start,
null,
gorf_sh_update
);
static CustomSound_interface wow_custom_interface = new CustomSound_interface(
wow_sh_start,
null,
wow_sh_update
);
static MachineDriver machine_driver_seawolf2 = new MachineDriver(
/* basic machine hardware */
new MachineCPU[]{
new MachineCPU(
CPU_Z80,
1789773, /* 1.789 MHz */
seawolf2_readmem, seawolf2_writemem, readport, seawolf2_writeport,
wow_interrupt, 256
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
320, 204, new rectangle(0, 320 - 1, 0, 204 - 1),
null, /* no gfxdecodeinfo - bitmapped display */
256, 0,
astrocde_init_palette,
VIDEO_TYPE_RASTER,
null,
astrocde_vh_start,
astrocde_vh_stop,
seawolf2_vh_screenrefresh,
/* sound hardware */
0, 0, 0, 0, null
);
static MachineDriver machine_driver_spacezap = new MachineDriver(
/* basic machine hardware */
new MachineCPU[]{
new MachineCPU(
CPU_Z80,
1789773, /* 1.789 MHz */
readmem, writemem, readport, writeport,
wow_interrupt, 256
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
320, 204, new rectangle(0, 320 - 1, 0, 204 - 1),
null, /* no gfxdecodeinfo - bitmapped display */
256, 0,
astrocde_init_palette,
VIDEO_TYPE_RASTER,
null,
astrocde_vh_start,
astrocde_vh_stop,
astrocde_vh_screenrefresh,
/* sound hardware */
0, 0, 0, 0,
new MachineSound[]{
new MachineSound(
SOUND_ASTROCADE,
astrocade_2chip_interface
)
}
);
static MachineDriver machine_driver_ebases = new MachineDriver(
/* basic machine hardware */
new MachineCPU[]{
new MachineCPU(
CPU_Z80,
1789773, /* 1.789 MHz */
readmem, writemem, readport, writeport,
wow_interrupt, 256
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
320, 204, new rectangle(0, 320 - 1, 0, 204 - 1),
null, /* no gfxdecodeinfo - bitmapped display */
256, 0,
astrocde_init_palette,
VIDEO_TYPE_RASTER,
null,
astrocde_vh_start,
astrocde_vh_stop,
astrocde_vh_screenrefresh,
/* sound hardware */
0, 0, 0, 0,
new MachineSound[]{
new MachineSound(
SOUND_ASTROCADE,
astrocade_1chip_interface
)
}
);
static MachineDriver machine_driver_wow = new MachineDriver(
/* basic machine hardware */
new MachineCPU[]{
new MachineCPU(
CPU_Z80,
1789773, /* 1.789 MHz */
readmem, writemem, readport, writeport,
wow_interrupt, 256
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
320, 204, new rectangle(0, 320 - 1, 0, 204 - 1),
null, /* no gfxdecodeinfo - bitmapped display */
256, 0,
astrocde_init_palette,
VIDEO_TYPE_RASTER,
null,
astrocde_stars_vh_start,
astrocde_vh_stop,
astrocde_vh_screenrefresh,
/* sound hardware */
0, 0, 0, 0,
new MachineSound[]{
new MachineSound(
SOUND_ASTROCADE,
astrocade_2chip_interface
),
new MachineSound(
SOUND_SAMPLES,
wow_samples_interface
),
new MachineSound(
SOUND_CUSTOM, /* actually plays the samples */
wow_custom_interface
)
}
);
static MachineDriver machine_driver_gorf = new MachineDriver(
/* basic machine hardware */
new MachineCPU[]{
new MachineCPU(
CPU_Z80,
1789773, /* 1.789 MHz */
readmem, writemem, readport, writeport,
gorf_interrupt, 256
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
/* it may look like the right hand side of the screen needs clipping, but */
/* this isn't the case: cocktail mode would be clipped on the wrong side */
320, 204, new rectangle(0, 320 - 1, 0, 204 - 1),
null, /* no gfxdecodeinfo - bitmapped display */
256, 0,
astrocde_init_palette,
VIDEO_TYPE_RASTER,
null,
astrocde_stars_vh_start,
astrocde_vh_stop,
astrocde_vh_screenrefresh,
/* sound hardware */
0, 0, 0, 0,
new MachineSound[]{
new MachineSound(
SOUND_ASTROCADE,
astrocade_2chip_interface
),
new MachineSound(
SOUND_SAMPLES,
gorf_samples_interface
),
new MachineSound(
SOUND_CUSTOM, /* actually plays the samples */
gorf_custom_interface
)
}
);
static MachineDriver machine_driver_robby = new MachineDriver(
/* basic machine hardware */
new MachineCPU[]{
new MachineCPU(
CPU_Z80,
1789773, /* 1.789 MHz */
robby_readmem, robby_writemem, readport, writeport,
wow_interrupt, 256
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
320, 204, new rectangle(0, 320 - 1, 0, 204 - 1),
null, /* no gfxdecodeinfo - bitmapped display */
256, 0,
astrocde_init_palette,
VIDEO_TYPE_RASTER,
null,
astrocde_vh_start,
astrocde_vh_stop,
astrocde_vh_screenrefresh,
/* sound hardware */
0, 0, 0, 0,
new MachineSound[]{
new MachineSound(
SOUND_ASTROCADE,
astrocade_2chip_interface
)
}
);
static MachineDriver machine_driver_profpac = new MachineDriver(
/* basic machine hardware */
new MachineCPU[]{
new MachineCPU(
CPU_Z80,
1789773, /* 1.789 MHz */
profpac_readmem, profpac_writemem, readport, writeport,
wow_interrupt, 256
)
},
60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1, /* single CPU, no need for interleaving */
null,
/* video hardware */
320, 204, new rectangle(0, 320 - 1, 0, 204 - 1),
null, /* no gfxdecodeinfo - bitmapped display */
256, 0,
astrocde_init_palette,
VIDEO_TYPE_RASTER,
null,
astrocde_vh_start,
astrocde_vh_stop,
astrocde_vh_screenrefresh,
/* sound hardware */
0, 0, 0, 0,
new MachineSound[]{
new MachineSound(
SOUND_ASTROCADE,
astrocade_2chip_interface
)
}
);
static RomLoadPtr rom_seawolf2 = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("sw2x1.bin", 0x0000, 0x0800, 0xad0103f6);
ROM_LOAD("sw2x2.bin", 0x0800, 0x0800, 0xe0430f0a);
ROM_LOAD("sw2x3.bin", 0x1000, 0x0800, 0x05ad1619);
ROM_LOAD("sw2x4.bin", 0x1800, 0x0800, 0x1a1a14a2);
ROM_END();
}
};
static RomLoadPtr rom_spacezap = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("0662.01", 0x0000, 0x1000, 0xa92de312);
ROM_LOAD("0663.xx", 0x1000, 0x1000, 0x4836ebf1);
ROM_LOAD("0664.xx", 0x2000, 0x1000, 0xd8193a80);
ROM_LOAD("0665.xx", 0x3000, 0x1000, 0x3784228d);
ROM_END();
}
};
static RomLoadPtr rom_ebases = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("m761a", 0x0000, 0x1000, 0x34422147);
ROM_LOAD("m761b", 0x1000, 0x1000, 0x4f28dfd6);
ROM_LOAD("m761c", 0x2000, 0x1000, 0xbff6c97e);
ROM_LOAD("m761d", 0x3000, 0x1000, 0x5173781a);
ROM_END();
}
};
static RomLoadPtr rom_wow = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("wow.x1", 0x0000, 0x1000, 0xc1295786);
ROM_LOAD("wow.x2", 0x1000, 0x1000, 0x9be93215);
ROM_LOAD("wow.x3", 0x2000, 0x1000, 0x75e5a22e);
ROM_LOAD("wow.x4", 0x3000, 0x1000, 0xef28eb84);
ROM_LOAD("wow.x5", 0x8000, 0x1000, 0x16912c2b);
ROM_LOAD("wow.x6", 0x9000, 0x1000, 0x35797f82);
ROM_LOAD("wow.x7", 0xa000, 0x1000, 0xce404305);
/* ROM_LOAD( "wow.x8", 0xc000, 0x1000, ? );here would go the foreign language ROM */
ROM_END();
}
};
static RomLoadPtr rom_gorf = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("gorf-a.bin", 0x0000, 0x1000, 0x5b348321);
ROM_LOAD("gorf-b.bin", 0x1000, 0x1000, 0x62d6de77);
ROM_LOAD("gorf-c.bin", 0x2000, 0x1000, 0x1d3bc9c9);
ROM_LOAD("gorf-d.bin", 0x3000, 0x1000, 0x70046e56);
ROM_LOAD("gorf-e.bin", 0x8000, 0x1000, 0x2d456eb5);
ROM_LOAD("gorf-f.bin", 0x9000, 0x1000, 0xf7e4e155);
ROM_LOAD("gorf-g.bin", 0xa000, 0x1000, 0x4e2bd9b9);
ROM_LOAD("gorf-h.bin", 0xb000, 0x1000, 0xfe7b863d);
ROM_END();
}
};
static RomLoadPtr rom_gorfpgm1 = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("873a", 0x0000, 0x1000, 0x97cb4a6a);
ROM_LOAD("873b", 0x1000, 0x1000, 0x257236f8);
ROM_LOAD("873c", 0x2000, 0x1000, 0x16b0638b);
ROM_LOAD("873d", 0x3000, 0x1000, 0xb5e821dc);
ROM_LOAD("873e", 0x8000, 0x1000, 0x8e82804b);
ROM_LOAD("873f", 0x9000, 0x1000, 0x715fb4d9);
ROM_LOAD("873g", 0xa000, 0x1000, 0x8a066456);
ROM_LOAD("873h", 0xb000, 0x1000, 0x56d40c7c);
ROM_END();
}
};
static RomLoadPtr rom_robby = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("rotox1.bin", 0x0000, 0x1000, 0xa431b85a);
ROM_LOAD("rotox2.bin", 0x1000, 0x1000, 0x33cdda83);
ROM_LOAD("rotox3.bin", 0x2000, 0x1000, 0xdbf97491);
ROM_LOAD("rotox4.bin", 0x3000, 0x1000, 0xa3b90ac8);
ROM_LOAD("rotox5.bin", 0x8000, 0x1000, 0x46ae8a94);
ROM_LOAD("rotox6.bin", 0x9000, 0x1000, 0x7916b730);
ROM_LOAD("rotox7.bin", 0xa000, 0x1000, 0x276dc4a5);
ROM_LOAD("rotox8.bin", 0xb000, 0x1000, 0x1ef13457);
ROM_LOAD("rotox9.bin", 0xc000, 0x1000, 0x370352bf);
ROM_LOAD("rotox10.bin", 0xd000, 0x1000, 0xe762cbda);
ROM_END();
}
};
static RomLoadPtr rom_profpac = new RomLoadPtr() {
public void handler() {
ROM_REGION(0x10000, REGION_CPU1);
ROM_LOAD("pps1", 0x0000, 0x2000, 0xa244a62d);
ROM_LOAD("pps2", 0x2000, 0x2000, 0x8a9a6653);
ROM_LOAD("pps7", 0x8000, 0x2000, 0xf9c26aba);
ROM_LOAD("pps8", 0xa000, 0x2000, 0x4d201e41);
ROM_LOAD("pps9", 0xc000, 0x2000, 0x17a0b418);
ROM_REGION(0x04000, REGION_USER1);
ROM_LOAD("pps3", 0x0000, 0x2000, 0x15717fd8);
ROM_LOAD("pps4", 0x0000, 0x2000, 0x36540598);
ROM_LOAD("pps5", 0x0000, 0x2000, 0x8dc89a59);
ROM_LOAD("pps6", 0x0000, 0x2000, 0x5a2186c3);
ROM_LOAD("ppq1", 0x0000, 0x4000, 0xdddc2ccc);
ROM_LOAD("ppq2", 0x0000, 0x4000, 0x33bbcabe);
ROM_LOAD("ppq3", 0x0000, 0x4000, 0x3534d895);
ROM_LOAD("ppq4", 0x0000, 0x4000, 0x17e3581d);
ROM_LOAD("ppq5", 0x0000, 0x4000, 0x80882a93);
ROM_LOAD("ppq6", 0x0000, 0x4000, 0xe5ddaee5);
ROM_LOAD("ppq7", 0x0000, 0x4000, 0xc029cd34);
ROM_LOAD("ppq8", 0x0000, 0x4000, 0xfb3a1ac9);
ROM_LOAD("ppq9", 0x0000, 0x4000, 0x5e944488);
ROM_LOAD("ppq10", 0x0000, 0x4000, 0xed72a81f);
ROM_LOAD("ppq11", 0x0000, 0x4000, 0x98295020);
ROM_LOAD("ppq12", 0x0000, 0x4000, 0xe01a8dbe);
ROM_LOAD("ppq13", 0x0000, 0x4000, 0x87165d4f);
ROM_LOAD("ppq14", 0x0000, 0x4000, 0xecb861de);
ROM_END();
}
};
public static InitDriverPtr init_seawolf2 = new InitDriverPtr() {
public void handler() {
install_port_read_handler(0, 0x10, 0x10, seawolf2_controller2_r);
install_port_read_handler(0, 0x11, 0x11, seawolf2_controller1_r);
}
};
public static InitDriverPtr init_ebases = new InitDriverPtr() {
public void handler() {
install_port_read_handler(0, 0x13, 0x13, ebases_trackball_r);
install_port_write_handler(0, 0x28, 0x28, ebases_trackball_select_w);
}
};
public static InitDriverPtr init_wow = new InitDriverPtr() {
public void handler() {
install_port_read_handler(0, 0x12, 0x12, wow_port_2_r);
install_port_read_handler(0, 0x15, 0x15, wow_io_r);
install_port_read_handler(0, 0x17, 0x17, wow_speech_r);
}
};
public static InitDriverPtr init_gorf = new InitDriverPtr() {
public void handler() {
install_mem_read_handler(0, 0xd0a5, 0xd0a5, gorf_timer_r);
install_port_read_handler(0, 0x12, 0x12, gorf_port_2_r);
install_port_read_handler(0, 0x15, 0x16, gorf_io_r);
install_port_read_handler(0, 0x17, 0x17, gorf_speech_r);
}
};
public static GameDriver driver_seawolf2 = new GameDriver("1978", "seawolf2", "astrocde.java", rom_seawolf2, null, machine_driver_seawolf2, input_ports_seawolf2, init_seawolf2, ROT0, "Midway", "Sea Wolf II", GAME_NO_SOUND);
public static GameDriver driver_spacezap = new GameDriver("1980", "spacezap", "astrocde.java", rom_spacezap, null, machine_driver_spacezap, input_ports_spacezap, null, ROT0, "Midway", "Space Zap");
public static GameDriver driver_ebases = new GameDriver("1980", "ebases", "astrocde.java", rom_ebases, null, machine_driver_ebases, input_ports_ebases, init_ebases, ROT0, "Midway", "Extra Bases");
public static GameDriver driver_wow = new GameDriver("1980", "wow", "astrocde.java", rom_wow, null, machine_driver_wow, input_ports_wow, init_wow, ROT0, "Midway", "Wizard of Wor");
public static GameDriver driver_gorf = new GameDriver("1981", "gorf", "astrocde.java", rom_gorf, null, machine_driver_gorf, input_ports_gorf, init_gorf, ROT270, "Midway", "Gorf");
public static GameDriver driver_gorfpgm1 = new GameDriver("1981", "gorfpgm1", "astrocde.java", rom_gorfpgm1, driver_gorf, machine_driver_gorf, input_ports_gorf, init_gorf, ROT270, "Midway", "Gorf (Program 1)");
public static GameDriver driver_robby = new GameDriver("1981", "robby", "astrocde.java", rom_robby, null, machine_driver_robby, input_ports_robby, null, ROT0, "Bally Midway", "Robby Roto");
public static GameDriver driver_profpac = new GameDriver("1983", "profpac", "astrocde.java", rom_profpac, null, machine_driver_profpac, input_ports_gorf, null, ROT0, "Bally Midway", "Professor PacMan");
}
| true |
58ef03ccc5adccaa9fdd5edbdbe8198b3a35a970 | Java | Logeshvarshith/SeleniumProjects | /AmazonSearch.java | UTF-8 | 3,626 | 2.03125 | 2 | [] | no_license | package com.amazon.testcases;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.amazon.base.TestBase;
import com.amazon.pages.AddToCartPage;
import com.amazon.pages.AddToWishList;
import com.amazon.pages.LoginPage;
import com.amazon.util.WebEventListener;
import com.amazon.util.captureScreenshot;
import com.util.ReadExcel;
public class AmazonSearch extends TestBase{
WebDriver driver;
LoginPage LP;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventListener;
public AmazonSearch() {
super();
}
@BeforeMethod
public void launchBrowser() {
initialization();
//System.setProperty("org.freemarker.loggerLibrary", "none");
}
@Test
public void LoginToApp() throws Exception {
LP = new LoginPage(driver);
LP.Login();
}
/*
@Test(priority = 1)
public void Login() throws Exception {
System.out.println("TC01_Login to Amazon");
LP = new LoginPage(driver);
LP.Login();
String actualresult = driver.findElement(By.xpath("//*[@id=\"nav-link-accountList\"]/span[1]")).getText();
Assert.assertEquals(actualresult, "Hello, Yamuna");
System.out.println("Registered user successfully logged in to the application");
}
/*
// Test to search the product from 'Shop By Category' and 'Add to Cart'
@Test(priority = 2)
public void searchByCategoryCarttest() throws Exception {
System.out.println("TC02_Verify that registered user is able to Search the product from Category and Add it to cart");
AddToCartPage cart = new AddToCartPage(driver);
cart.searchByCategorytest();
cart.AddtoCart();
}
//Test to search the product from 'Shop By Text' and 'Add to Wishlist'
@Test(priority = 3, dataProvider = "getData")
public void searchbyTextWLtest(String product) throws Exception {
//extent.attachReporter(reporter);
// ExtentTest logger = extent.createTest("Search the product from search textbox and Add to Wishlist");
//logger.log(Status.INFO, "Search the product from search texbox and 'Add to Wislist'");
System.out.println("TC03_Verify that registered user is able to search the product from search textbox and Add it to Wishlist");
AddToWishList wl = new AddToWishList(driver);
wl.searchByText(product);
wl.Wishlist();
}
@DataProvider
public Object[][] getData() throws IOException{
//String currentDirectory = System.getProperty("user.dir");
String datafile ="C:\\Yamuna Selenium\\AmazonSearch\\src\\main\\java\\com\\amazon\\testdata\\TestData.xlsx";
System.out.println(datafile);
Object[][] myTestData = ReadExcel.readTestData(datafile);
return myTestData;
}
@AfterMethod
public void tearDown(ITestResult result) throws IOException
{
if(result.getStatus()==ITestResult.FAILURE)
{
String temp=captureScreenshot.getScreenshot(driver);
//logger.fail(result.getThrowable().getMessage(), MediaEntityBuilder.createScreenCaptureFromPath(temp).build());
}
//extent.flush();
//driver.quit();
}
*/
}
| true |
ceaf7c4b178ccad37f8ffc0a71d32a0a4783dcad | Java | deepankarsharma/jaque | /src/java/net/frodwith/jaque/truffle/jet/ops/MinkNode.java | UTF-8 | 682 | 2.328125 | 2 | [] | no_license | package net.frodwith.jaque.truffle.jet.ops;
import com.oracle.truffle.api.dsl.NodeField;
import com.oracle.truffle.api.dsl.Specialization;
import net.frodwith.jaque.data.Cell;
import net.frodwith.jaque.truffle.Context;
import net.frodwith.jaque.truffle.jet.BinaryOpNode;
@NodeField(name="context", type=Context.class)
public abstract class MinkNode extends BinaryOpNode {
public abstract Context getContext();
@Specialization
protected Object mink(Cell busfol, Cell gul) {
Object subject = busfol.head;
Cell formula = Cell.orBail(busfol.tail);
Context context = getContext();
return context.softRun(gul, () -> context.nock(subject, formula));
}
} | true |
4bd9aea6806152fdb96b23a0f4e3a56ca8126ba7 | Java | zhangdhu/server | /api/src/main/java/com/zdh/api/config/SwaggerConifg.java | UTF-8 | 1,846 | 2.1875 | 2 | [] | no_license | package com.zdh.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConifg {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zdh.api.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("张")
.description("个人构建 RESTful APIs")
.contact(new Contact("张大虎", "111.230.132.225", "200715251@qq.com"))
.version("1.0.0")
.build();
}
@Bean
public UiConfiguration getUiConfig() {
return new UiConfiguration(null,// url,暂不用
"list", // docExpansion => none | list
"alpha", // apiSorter => alpha
"schema", // defaultModelRendering => schema
null,
false, // enableJsonEditor => true | false
true,
5000L); // showRequestHeaders => true | false
}
}
| true |
ec979401e5966c2f9f9989c0624125b12378715e | Java | VinsentY/JavaPratice | /Java中的按值传递.java | UTF-8 | 572 | 3.5625 | 4 | [] | no_license | package seven;
public class Seven {
public static void changeString(StringBuilder string) {
string.delete(0,string.length());
string.append("You're Changed");
}
public static void cannotChange(String string) {
string = "You're Changed";
}
public static void main(String[] args) {
StringBuilder string = new StringBuilder("Yikai");
changeString(string);
System.out.println(string);
String string1 = "You're Changed by the world";
cannotChange(string1); //可不是我说不会变就不会变得哦!
System.out.println(string1);
}
}
| true |
14de92043416b5fbde536f768973b2bea37ae4d2 | Java | polozgai/szakdolgozat | /src/test/java/hu/elte/algorithm/AlgorithmTest.java | UTF-8 | 891 | 2.125 | 2 | [] | no_license | package hu.elte.algorithm;
import hu.elte.graph.Edge;
import hu.elte.graph.Graph;
import hu.elte.graph.Vertex;
import org.apache.activemq.broker.BrokerService;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class AlgorithmTest {
@Test
public void computeAlgorithm() {
BrokerService brokerService=new BrokerService();
try {
brokerService.addConnector("tcp://localhost:61616");
brokerService.start();
} catch (Exception e) {
e.printStackTrace();
}
Algorithm algorithm=new Algorithm();
algorithm.computeAlgorithm("a","c",false);
String msg="[a, b, c] 2.0";
try {
brokerService.stop();
} catch (Exception e) {
e.printStackTrace();
}
assertEquals(msg,algorithm.getMinRouteWithWeight());
}
} | true |
2ba35a3101073c3de12104f6c8f9a8adf380e57c | Java | KleeGroup/vertigo | /vertigo-core/src/main/java/io/vertigo/core/node/config/BootConfigBuilder.java | UTF-8 | 6,603 | 1.90625 | 2 | [
"Apache-2.0"
] | permissive | /**
* vertigo - application development platform
*
* Copyright (C) 2013-2020, Vertigo.io, team@vertigo.io
*
* 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 io.vertigo.core.node.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import io.vertigo.core.analytics.AnalyticsManager;
import io.vertigo.core.daemon.DaemonManager;
import io.vertigo.core.impl.analytics.AnalyticsConnectorPlugin;
import io.vertigo.core.impl.analytics.AnalyticsManagerImpl;
import io.vertigo.core.impl.daemon.DaemonManagerImpl;
import io.vertigo.core.impl.locale.LocaleManagerImpl;
import io.vertigo.core.impl.param.ParamManagerImpl;
import io.vertigo.core.impl.resource.ResourceManagerImpl;
import io.vertigo.core.lang.Assertion;
import io.vertigo.core.lang.Builder;
import io.vertigo.core.locale.LocaleManager;
import io.vertigo.core.node.component.AopPlugin;
import io.vertigo.core.node.component.Component;
import io.vertigo.core.node.component.Plugin;
import io.vertigo.core.param.Param;
import io.vertigo.core.param.ParamManager;
import io.vertigo.core.plugins.analytics.log.SmartLoggerAnalyticsConnectorPlugin;
import io.vertigo.core.plugins.analytics.log.SocketLoggerAnalyticsConnectorPlugin;
import io.vertigo.core.plugins.component.aop.javassist.JavassistAopPlugin;
import io.vertigo.core.resource.ResourceManager;
/**
* Configuration.
*
* @author npiedeloup, pchretien
*/
public final class BootConfigBuilder implements Builder<BootConfig> {
private Optional<LogConfig> myLogConfigOpt = Optional.empty(); //par défaut
private boolean myVerbose;
private AopPlugin myAopPlugin = new JavassistAopPlugin(); //By default
private final List<ComponentConfig> myComponentConfigs = new ArrayList<>();
private final List<PluginConfig> myPluginConfigs = new ArrayList<>();
/**
* @param nodeConfigBuilder Parent NodeConfig builder
*/
BootConfigBuilder() {
}
/**
* Opens the boot module.
* There is exactly one BootConfig per NodeConfig.
*
* @param locales a string which contains all the locales separated with a simple comma : ',' .
* @return this builder
*/
public BootConfigBuilder withLocales(final String locales) {
addComponent(
LocaleManager.class,
LocaleManagerImpl.class,
Param.of("locales", locales));
return this;
}
/**
* Opens the boot module.
* There is exactly one BootConfig per NodeConfig.
* With a default ZoneId for DateTime formatter.
*
* @param locales a string which contains all the locales separated with a simple comma : ',' .
* @param defaultZoneId a string which contains defaultZoneId.
* @return this builder
*/
public BootConfigBuilder withLocalesAndDefaultZoneId(final String locales, final String defaultZoneId) {
addComponent(
LocaleManager.class,
LocaleManagerImpl.class,
Param.of("locales", locales),
Param.of("defaultZoneId", defaultZoneId));
return this;
}
/**
* Ajout de paramètres
* @param logConfig Config of logs
* @return this builder
*/
public BootConfigBuilder withLogConfig(final LogConfig logConfig) {
Assertion.check()
.isNotNull(logConfig);
//-----
myLogConfigOpt = Optional.of(logConfig);
return this;
}
/**
* Enables verbosity during startup
* @return this builder
*/
public BootConfigBuilder verbose() {
myVerbose = true;
return this;
}
/**
* @param aopPlugin AopPlugin
* @return this builder
*/
public BootConfigBuilder withAopEngine(final AopPlugin aopPlugin) {
Assertion.check()
.isNotNull(aopPlugin);
//-----
myAopPlugin = aopPlugin;
return this;
}
@Feature("analytics.socketLoggerConnector")
public BootConfigBuilder withSocketLoggerAnalyticsConnector(final Param... params) {
addPlugin(SocketLoggerAnalyticsConnectorPlugin.class, params);
return this;
}
@Feature("analytics.smartLoggerConnector")
public BootConfigBuilder withSmartLoggerAnalyticsConnector(final Param... params) {
addPlugin(SmartLoggerAnalyticsConnectorPlugin.class, params);
return this;
}
/**
* Adds a AnalyticsConnectorPlugin
* @param analyticsConnectorPluginClass the plugin to use
* @param params the params
* @return these features
*/
public BootConfigBuilder addAnalyticsConnectorPlugin(final Class<? extends AnalyticsConnectorPlugin> analyticsConnectorPluginClass, final Param... params) {
return addPlugin(analyticsConnectorPluginClass, params);
}
/**
* Adds a component defined by an api and an implementation.
* @param apiClass api of the component
* @param implClass impl of the component
* @param params the list of params
* @return this builder
*/
private BootConfigBuilder addComponent(final Class<? extends Component> apiClass, final Class<? extends Component> implClass, final Param... params) {
final ComponentConfig componentConfig = ComponentConfig.of(apiClass, implClass, params);
myComponentConfigs.add(componentConfig);
return this;
}
/**
* Adds a plugin defined by its implementation.
* @param pluginImplClass impl of the plugin
* @param params the list of params
* @return this builder
*/
public BootConfigBuilder addPlugin(final Class<? extends Plugin> pluginImplClass, final Param... params) {
return addPlugin(new PluginConfig(ConfigUtil.getPluginApi(pluginImplClass), pluginImplClass, Arrays.asList(params)));
}
/**
* Adds a plugin defined by its builder.
* @param pluginConfig the plugin-config
* @return this builder
*/
public BootConfigBuilder addPlugin(final PluginConfig pluginConfig) {
Assertion.check()
.isNotNull(pluginConfig);
//---
myPluginConfigs.add(pluginConfig);
return this;
}
/**
* @return BootConfig
*/
@Override
public BootConfig build() {
addComponent(ResourceManager.class, ResourceManagerImpl.class)
.addComponent(ParamManager.class, ParamManagerImpl.class)
.addComponent(DaemonManager.class, DaemonManagerImpl.class)
.addComponent(AnalyticsManager.class, AnalyticsManagerImpl.class);
return new BootConfig(
myLogConfigOpt,
myComponentConfigs,
myPluginConfigs,
myAopPlugin,
myVerbose);
}
}
| true |
6eaf5933273c37551890d78d0cecdf991e1379ee | Java | busgo/fc | /fc-biz/src/main/java/com/busgo/fc/biz/component/HouseComponent.java | UTF-8 | 1,044 | 2.3125 | 2 | [] | no_license | package com.busgo.fc.biz.component;
import com.busgo.fc.inner.dao.HouseDao;
import com.busgo.fc.inner.model.House;
import com.busgo.fc.inner.query.HouseQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* @author busgo
* @date 2019-11-18 15:28
*/
@Component
public class HouseComponent {
@Autowired
private HouseDao houseDao;
/**
* 根据业务房屋id、来源查询详情
*
* @param bizId 业务id
* @param source 来源
* @return
*/
public House findHouseByBizIdAndSource(Long bizId, Integer source) {
HouseQuery query = new HouseQuery();
query.setBizId(bizId);
query.setSource(source);
query.setOffset(0);
query.setRows(1);
List<House> houseList = this.houseDao.queryListByParam(query);
if (CollectionUtils.isEmpty(houseList)) return null;
return houseList.get(0);
}
}
| true |
c01b58d06b14a490bb265704f20ff46025ed88a5 | Java | VoidShaper/bookstorecomparator | /src/main/java/com/matski/infractructure/jsoup/JsoupRetrieveResult.java | UTF-8 | 112 | 1.648438 | 2 | [] | no_license | package com.matski.infractructure.jsoup;
public interface JsoupRetrieveResult {
boolean wasSuccessful();
}
| true |
bd7344806130312678398b052531f8bc9103a701 | Java | jorge-luque/hb | /sources/p118io/presage/core/C6298e2.java | UTF-8 | 2,001 | 1.71875 | 2 | [] | no_license | package p118io.presage.core;
import admost.sdk.base.AdMost;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
/* renamed from: io.presage.core.e2 */
public abstract class C6298e2 extends JobService {
public boolean IIIIIIII;
public BroadcastReceiver IIIIIIIl;
/* renamed from: io.presage.core.e2$IIIIIIII */
public class IIIIIIII extends BroadcastReceiver {
public IIIIIIII(C6298e2 e2Var) {
}
public void onReceive(Context context, Intent intent) {
intent.getAction();
if (intent.getAction().equals("android.intent.action.USER_PRESENT")) {
IIIIlIll.IIIIIIII(context, 400);
}
}
}
public void onDestroy() {
if (!this.IIIIIIII) {
try {
if (this.IIIIIIIl != null) {
unregisterReceiver(this.IIIIIIIl);
}
} catch (IllegalArgumentException unused) {
}
} else {
IIIIlIll.IIIIIIII(getApplicationContext(), IIIIllIl.IIIIIIII(getApplicationContext()).IIIIIIII(), false);
}
}
public boolean onStartJob(JobParameters jobParameters) {
IIIIlIll.IIIIIIII((Context) this, (int) AdMost.AD_ERROR_INCOMPATIBLE_APP_ZONE_ID);
this.IIIIIIII = true;
if (jobParameters.getExtras().containsKey("25dfee1e")) {
this.IIIIIIII = jobParameters.getExtras().getBoolean("25dfee1e", true);
}
if (this.IIIIIIII) {
jobFinished(jobParameters, false);
} else {
this.IIIIIIIl = new IIIIIIII(this);
registerReceiver(this.IIIIIIIl, new IntentFilter("android.intent.action.USER_PRESENT"));
}
return !this.IIIIIIII;
}
public boolean onStopJob(JobParameters jobParameters) {
return !this.IIIIIIII;
}
}
| true |
782d5c8eecdc9329ef95806e65013703ec7d7a78 | Java | Florence-ops/Tuko | /src/test/java/Tests/Tests.java | UTF-8 | 2,096 | 2.140625 | 2 | [] | no_license | package Tests;
import Pages.HomePage;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Tests {
private static final WebDriver driver = new ChromeDriver();
@BeforeSuite
public static void main(String[]args){
System.setProperty("webdriver.chrome.driver","Utils.CHROME_DRIVER_LOCATION") ;
}
@Test(testName = "Tuko Automation")
public static void load() throws InterruptedException {
driver.manage().window().maximize();
driver.get("https://www.tuko.co.ke/408263-mikel-arteta-pin-points-decision-cost-arsenal-win-slavia-prague.html");
HomePage hp = new HomePage(driver);
hp.clickSports();
Thread.sleep(9000);
hp.clickNews();
Thread.sleep(8000);
hp.clickFacebookIcon();
Thread.sleep(5000);
hp.loginToFacebook();
Thread.sleep(10000);
hp.comment();
Thread.sleep(15000);
String ACTUAL_TITLE = driver.getTitle();
String EXPECTED_TITLE = driver.getTitle();
Assert.assertEquals(ACTUAL_TITLE,EXPECTED_TITLE);
}
@AfterSuite
public static void tearDown(){
Date d = new Date();
System.out.println(d.toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File("D:\\Screenshots\\"+sdf.format(d)+".png"));
} catch (IOException e) {
e.printStackTrace();
}
driver.manage().deleteAllCookies();
driver.close();
}
}
| true |
3c5032c0df2f879b48cb0037117a6e5765f44398 | Java | pramodaya/spring-lesson | /dependency-injection/constructor-injection/FortuneService.java | UTF-8 | 98 | 1.617188 | 2 | [] | no_license | package com.luv2code.springdemo;
public interface FortuneService {
public String geFortune();
}
| true |
57b342fa5fe756d398d642dd7b10140a61c47c5c | Java | wangjianminks/Maven-Spring | /src/main/java/com/cheer/spring/ioc/annotation/dao/impl/MasterDaoImpl.java | UTF-8 | 933 | 2.3125 | 2 | [] | no_license | /**
* 文件名 :MasterDaoImpl.java
*作者 :WangJianmin
*建立时间:2017年11月9日
*/
package com.cheer.spring.ioc.annotation.dao.impl;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import com.cheer.spring.ioc.annotation.dao.MasterDao;
/**
*简述功能
* @author WangJianmin
* @version MasterDaoImpl
*上午10:05:27
*/
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Repository("masterDaoImpl")
public class MasterDaoImpl implements MasterDao
{
/* (non-Javadoc)
* @see com.cheer.spring.ioc.annotation.dao.MasterDao#findMaster(java.lang.String, java.lang.String)
*/
@Override
public int findMaster(String name, String password)
{
if ("scott".equals(name) && "tiger".equals(password))
{
return 1;
}
return 0;
}
}
| true |
39e6dfc5ccd89c8847a3f7688dc9690f17589afd | Java | ramdanks/jwork | /src/main/java/RamadhanKalih/jwork/Handshake.java | UTF-8 | 1,711 | 2.84375 | 3 | [] | no_license | package RamadhanKalih.jwork;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
import javax.crypto.Cipher;
public class Handshake
{
private KeyPair keyPair;
public Handshake() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
keyPair = generator.generateKeyPair();
} catch (Exception e) {
System.err.println(e);
return;
}
}
public String encryptMessage(String message) {
byte[] msg = message.getBytes(StandardCharsets.UTF_8);
return encryptMessage(msg);
}
public String encryptMessage(byte[] message) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
byte[] cipherMsg = cipher.doFinal(message);
return Base64.getEncoder().encodeToString(cipherMsg);
} catch (Exception e) {
System.err.println(e);
return new String();
}
}
public String decryptMessage(String message) {
byte[] msg = message.getBytes(StandardCharsets.UTF_8);
return decryptMessage(msg);
}
public String decryptMessage(byte[] message) {
try {
byte[] plain = Base64.getDecoder().decode(message);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
return new String(cipher.doFinal(plain));
} catch (Exception e) {
System.err.println(e);
return new String();
}
}
}
| true |
a6e99ef99041dc5856c3c1cbb4282504316944f0 | Java | BliZZeRxD/JavaOOP | /lab4/src/Week_8_A/AbstractShapes.java | UTF-8 | 130 | 2.296875 | 2 | [] | no_license | package Week_8_A;
abstract class AbstractShapes {
abstract double volume();
abstract double surfaceArea();
}
| true |
f47411b719b89dcc816769084b22737455cec7c2 | Java | barchetta/helidon | /config/config-mp/src/test/java/io/helidon/config/mp/MpConfigReferenceTest.java | UTF-8 | 2,935 | 1.953125 | 2 | [
"Apache-2.0",
"APSL-1.0",
"LicenseRef-scancode-protobuf",
"GPL-1.0-or-later",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference",
"CC-PDDC",
"LicenseRef-scancode-generic-export-compliance",
"LicenseRef-scancode-unicode",
"EPL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL... | permissive | /*
* Copyright (c) 2020, 2023 Oracle and/or its affiliates.
*
* 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 io.helidon.config.mp;
import java.util.NoSuchElementException;
import java.util.Optional;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class MpConfigReferenceTest {
private static final String VALUE_1 = "value";
private static final String VALUE_2 = "hodnota";
private static Config config;
@BeforeAll
static void initClass() {
System.setProperty("value2", VALUE_2);
config = ConfigProviderResolver.instance()
.getBuilder()
.addDefaultSources()
.build();
}
@Test
void testValue1() {
test("1", VALUE_1);
}
@Test
void testValue2() {
test("2", VALUE_2);
}
@Test
void testBoth() {
test("3", "1", VALUE_1 + "-" + VALUE_2);
}
@Test
void testMissingRefs() {
// since Config 2.0, missing references must throw an exception
assertThrows(NoSuchElementException.class, () -> config.getValue("referencing4-1", String.class));
assertThrows(NoSuchElementException.class, () -> config.getValue( "referencing4-2", String.class));
}
@Test
void testOptionalMissingRefs() {
assertThat(config.getOptionalValue("referencing4-1", String.class), is(Optional.empty()));
assertThat(config.getOptionalValue("referencing4-2", String.class), is(Optional.empty()));
}
private void test(String prefix, String value) {
test(prefix, "1", value);
test(prefix, "2", value + "-ref");
test(prefix, "3", "ref-" + value);
test(prefix, "4", "ref-" + value + "-ref");
}
private void test(String prefix, String suffix, String value) {
String key = "referencing" + prefix + "-" + suffix;
String configured = config.getValue(key, String.class);
assertThat("Value for key " + key, configured, notNullValue());
assertThat("Value for key " + key, configured, is(value));
}
}
| true |
fa72081a07b3a7bf6a23f5581e18540f400db9a1 | Java | GaryHua226/leetcode-garyGlh | /src/Prob897.java | UTF-8 | 521 | 2.734375 | 3 | [] | no_license | import leetcodeUtil.TreeNode;
public class Prob897 {
private TreeNode resNode;
public TreeNode increasingBST(TreeNode root) {
TreeNode dummyNode = new TreeNode(-1);
resNode = dummyNode;
inorder(root);
return dummyNode.right;
}
public void inorder(TreeNode node) {
if (node == null) {
return ;
}
inorder(node.left);
resNode.right = node;
node.left = null;
resNode = node;
inorder(node.right);
}
}
| true |
6937f7f97e7da25a388af2740b933cd6b375f3bb | Java | driouxg/Water-Pls-Mobile | /app/src/main/java/com/dryox/water_pls_mobile/domain/StompCommandEnum.java | UTF-8 | 1,115 | 2.578125 | 3 | [] | no_license | package com.dryox.water_pls_mobile.domain;
public enum StompCommandEnum {
/* Stomp Client Commands */
SEND("SEND"),
CONNECT("CONNECT"),
SUBSCRIBE("SUBSCRIBE"),
UNSUBSCRIBE("UNSUBSCRIBE"),
COMMIT("COMMIT"),
BEGIN("BEGIN"),
ABORT("ABORT"),
ACK("ACK"),
NACK("NACK"),
DISCONNECT("DISCONNECT"),
/* Stomp Server Commands */
CONNECTED("CONNECTED"),
MESSAGE("MESSAGE"),
RECEIPT("RECEIPT"),
ERROR("ERROR");
private String command;
StompCommandEnum(String command) {
this.command = command;
}
public static StompCommandEnum fromString(String resourceKey) {
for (StompCommandEnum resource : StompCommandEnum.values()) {
if (resource.command.equals(resourceKey)) {
return resource;
}
}
return null;
}
public static boolean isStompCommand(String command) {
for (StompCommandEnum resource : StompCommandEnum.values()) {
if (resource.command.equals(command)) {
return true;
}
}
return false;
}
}
| true |
3451e4cee70bffcb14d7c410cb1801c80dc60e1d | Java | Xiao-Fan-x/Github-on-Linux | /LanQiao/src/PAT/Main.java | UTF-8 | 1,120 | 3.25 | 3 | [] | no_license | package PAT;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
int[][] num = new int[n][2];
int[] sum = new int[n];
for (int i = 0; i < n; i++) {
String[] s = in.readLine().split("\\s+");
num[i][0] = Integer.parseInt(s[0]);
num[i][1] = Integer.parseInt(s[1]);
sum[i] = num[i][1];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (num[i][0] == num[j][0]) {
sum[i] += num[j][1];
}
}
}
int max = 0;
int flag = 0;
int len = sum.length;
for (int i = 0; i < len; i++) {
if (sum[i] > max) {
max = sum[i];
flag = i;
}
}
System.out.print(num[flag][0] + " " + max);
}
} | true |
9b7252ddcb5429b982cddb8b19e50bbce36169c2 | Java | whatafree/JCoffee | /benchmark/bigclonebenchdata_completed/19193813.java | UTF-8 | 1,787 | 2.828125 | 3 | [] | no_license |
class c19193813 {
public MyHelperClass STATE_OK;
public MyHelperClass deleteTemporaryFile(){ return null; }
public void writeTo(File f) throws IOException {
MyHelperClass state = new MyHelperClass();
if (state != STATE_OK) throw new IllegalStateException("Upload failed");
MyHelperClass tempLocation = new MyHelperClass();
if (tempLocation == null) throw new IllegalStateException("File already saved");
MyHelperClass filename = new MyHelperClass();
if ((boolean)(Object)f.isDirectory()) f = new File(f, filename);
// MyHelperClass tempLocation = new MyHelperClass();
FileInputStream fis = new FileInputStream(tempLocation);
FileOutputStream fos = new FileOutputStream(f);
MyHelperClass BUFFER_SIZE = new MyHelperClass();
byte[] buf = new byte[(int)(Object)BUFFER_SIZE];
try {
int i = 0;
while ((i =(int)(Object) fis.read(buf)) != -1) fos.write(buf, 0, i);
} finally {
deleteTemporaryFile();
fis.close();
fos.close();
}
}
}
// Code below this line has been added to remove errors
class MyHelperClass {
}
class File {
File(File o0, MyHelperClass o1){}
File(){}
public MyHelperClass isDirectory(){ return null; }}
class IOException extends Exception{
public IOException(String errorMessage) { super(errorMessage); }
}
class FileInputStream {
FileInputStream(MyHelperClass o0){}
FileInputStream(){}
public MyHelperClass read(byte[] o0){ return null; }
public MyHelperClass close(){ return null; }}
class FileOutputStream {
FileOutputStream(File o0){}
FileOutputStream(){}
public MyHelperClass write(byte[] o0, int o1, int o2){ return null; }
public MyHelperClass close(){ return null; }}
| true |
16bbc390a567da0387407877831fa9dfcf9dd94e | Java | yosinhasan/socialnetwork | /src/main/java/com/kindhope/dao/MessageDAO.java | UTF-8 | 443 | 2.046875 | 2 | [] | no_license | package com.kindhope.dao;
import com.kindhope.entity.Message;
import java.math.BigInteger;
import java.util.List;
/**
* @author Yosin_Hasan<yosinhasan@gmail.com>
* @version 0.0.1
*/
public interface MessageDAO extends GenericDAO<Message> {
List<Message> findConversationMessages(BigInteger conversationId);
Message findLastMessage(BigInteger conversationId);
boolean addSeenAtTimestamp(BigInteger conversationId, BigInteger userId);
}
| true |
57e672cd5ff04398f445ba7d8100a66b39c4eb7f | Java | coronalabs/corona | /platform/android/sdk/src/com/ansca/corona/CoronaStatusBarApiHandler.java | UTF-8 | 1,775 | 2.40625 | 2 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-free-unknown"
] | permissive | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
package com.ansca.corona;
/** The interface has all the funcations that are activity specific and aren't implemented by default. */
class CoronaStatusBarApiHandler implements com.ansca.corona.listeners.CoronaStatusBarApiListener{
private CoronaActivity fActivity;
public CoronaStatusBarApiHandler(CoronaActivity activity) {
fActivity = activity;
}
@Override
public CoronaStatusBarSettings getStatusBarMode() {
if (fActivity == null) {
return CoronaStatusBarSettings.HIDDEN;
}
return fActivity.getStatusBarMode();
}
@Override
public void setStatusBarMode(CoronaStatusBarSettings mode) {
if (fActivity == null) {
return;
}
final CoronaStatusBarSettings finalMode = mode;
fActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (fActivity != null) {
fActivity.setStatusBarMode(finalMode);
}
}
});
}
@Override
public int getStatusBarHeight() {
if (fActivity == null) {
return 0;
}
return fActivity.getStatusBarHeight();
}
@Override
public int getNavigationBarHeight(){
if (fActivity == null) {
return 0;
}
return fActivity.resolveNavBarHeight();
}
@Override
public boolean IsAndroidTV(){
if (fActivity == null) {
return false;
}
return fActivity.IsAndroidTV();
}
@Override
public boolean HasSoftwareKeys()
{
if (fActivity == null)
return false;
return fActivity.HasSoftwareKeys();
}
}
| true |
d05031ed0ba9200465432aa7e2791bf4c02d30be | Java | JIANLAM/learn_springboot | /springbootdemo/src/main/java/com/learn/springbootdemo/main/testMethod.java | UTF-8 | 857 | 3.28125 | 3 | [] | no_license | package com.learn.springbootdemo.main;
/**
* @Author: linzj
* @Date: 2019/5/28 11:21
* @Desciption
*/
public class testMethod {
public static void main(String[] args) {
int[] array =new int[]{2,5,5,11};
int target = 10;
int[] ints = twoSum(array, target);
for (int anInt : ints) {
System.out.println(anInt);
}
}
public static int[] twoSum(int[] nums, int target) {
int[] newArrarys = new int[2];
for(int i= 0;i < nums.length;i++){
for(int j= i+1;j < nums.length;j++){
if(target == nums[i] + nums[j]){
newArrarys[0] = i;
newArrarys[1] = j;
return newArrarys;
}
}
}
throw new IllegalArgumentException("找不到符合的数据");
}
}
| true |
189ff71fb644cc43a0d4885a3aadd8e8a86bc61a | Java | orchids-li/data-mapping | /src/main/java/cn/ting/er/datamapping/listener/ReadListener.java | UTF-8 | 413 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | package cn.ting.er.datamapping.listener;
import cn.ting.er.datamapping.context.MappingContext;
import cn.ting.er.datamapping.exception.ReadException;
/**
* @author wenting.Li
* @version 0.0.1
* @since JDK 8
*/
public interface ReadListener<T> {
void onReadHeader(MappingContext context);
void onReadRow(T t, MappingContext context);
void onError(T t, MappingContext context, ReadException e);
}
| true |
6f34cb80a28b9fd3947d706b5d1b235fc24fc385 | Java | krissivam/java-batch197 | /src/Day6/MainOOP.java | UTF-8 | 1,155 | 2.625 | 3 | [] | no_license | package Day6;
import Day5.StudyCase.Orang;
public class MainOOP {
public static void main(String[] args) {
Mahasiswa mhs = new Mahasiswa();
mhs.id = 1;
mhs.nama = "Joni";
mhs.alamat = "Bojong Soang";
mhs.jk= "Pria";
mhs.noTelp= "080989999";
mhs.nim = "1215031007";
mhs.jurusan = "Teknik Nuklir";
mhs.fakultas = "Teknik";
mhs.angkatan = "2012";
mhs.ipk = 2.5;
mhs.cetakData();
System.out.println();
Dosen dsn = new Dosen();
dsn.id = 2;
dsn.nama = "Bambang Widodo";
dsn.alamat = "Jepara";
dsn.jk = "Pria";
dsn.noTelp = "072176767676";
dsn.nik = "DSN0001";
dsn.spesialis = "Teknik Elektro";
dsn.gaji = 9000000;
dsn.jabatan = "Kepala Lab. Elektronika";
Day6.Materi.Orang org01 = new Day6.Materi.Orang();
dsn.fakultas = org01;
dsn.cetakData();
System.out.println();
Staff stf = new Staff();
stf.id = 3;
stf.nama = "Marteen";
stf.alamat = "Kuningan";
stf.jk = "Pria";
stf.noTelp = "09877890098";
stf.nik = "STF00001";
stf.jabatan = "OB";
stf.gaji = 7000000;
stf.departemen = "Tata Usaha";
Day6.Materi.Orang org02 = new Day6.Materi.Orang();
stf.atasan = org02;
stf.cetakData();
}
}
| true |
d3016512234bab9220d54999f73c47e3231e96c1 | Java | rad-navid/pinglish | /src/gui/PinglishTextBox.java | UTF-8 | 1,832 | 2.484375 | 2 | [] | no_license | package gui;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
public class PinglishTextBox extends EditText {
public interface onSelectionChangedListener {
public void onSelectionChanged(int selStart, int selEnd);
}
public interface onKeyPressed {
public void keyPressed(int keyCode, KeyEvent event);
}
private List<onSelectionChangedListener> CursorListeners;
private List<onKeyPressed> KeyListeners;
public PinglishTextBox(Context context) {
super(context);
}
public PinglishTextBox(Context context, AttributeSet attrs){
super(context, attrs);
}
public PinglishTextBox(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
public void addOnSelectionChangedListener(onSelectionChangedListener o){
if(CursorListeners==null)
CursorListeners=new ArrayList<PinglishTextBox.onSelectionChangedListener>(1);
CursorListeners.add(o);
}
protected void onSelectionChanged(int selStart, int selEnd){
super.onSelectionChanged(selStart, selEnd);
if(CursorListeners!=null)
for (onSelectionChangedListener l : CursorListeners)
l.onSelectionChanged(selStart, selEnd);
}
public boolean onKeyDown(int keyCode,KeyEvent event)
{
super.onKeyDown(keyCode, event);
try{
if(KeyListeners!=null)
for(onKeyPressed listener:KeyListeners)
if(listener!=null)
listener.keyPressed(keyCode, event);
}
catch(Exception e)
{
}
return false;
}
public void setOnKeyPressedListener(onKeyPressed input)
{
if(KeyListeners==null)
KeyListeners=new ArrayList<PinglishTextBox.onKeyPressed>();
KeyListeners.add(input);
}
}
| true |
317e2863cf498cd120f937a30548e35c46570091 | Java | gzxishan/OftenPorter | /Porter-Core/src/main/java/cn/xishan/oftenporter/porter/core/advanced/PortUtil.java | UTF-8 | 18,766 | 1.859375 | 2 | [
"Apache-2.0"
] | permissive | package cn.xishan.oftenporter.porter.core.advanced;
import cn.xishan.oftenporter.porter.core.ContextPorter;
import cn.xishan.oftenporter.porter.core.annotation.MixinOnly;
import cn.xishan.oftenporter.porter.core.annotation.MixinTo;
import cn.xishan.oftenporter.porter.core.annotation.PortIn;
import cn.xishan.oftenporter.porter.core.annotation.deal.AnnoUtil;
import cn.xishan.oftenporter.porter.core.annotation.param.Nece;
import cn.xishan.oftenporter.porter.core.annotation.param.Unece;
import cn.xishan.oftenporter.porter.core.annotation.sth.One;
import cn.xishan.oftenporter.porter.core.base.InNames;
import cn.xishan.oftenporter.porter.core.base.InNames.Name;
import cn.xishan.oftenporter.porter.core.base.OftenObject;
import cn.xishan.oftenporter.porter.core.base.ParamSource;
import cn.xishan.oftenporter.porter.core.exception.InitException;
import cn.xishan.oftenporter.porter.core.init.SeekPackages;
import cn.xishan.oftenporter.porter.core.util.LogUtil;
import cn.xishan.oftenporter.porter.core.util.OftenTool;
import cn.xishan.oftenporter.porter.core.util.proxy.ProxyUtil;
import cn.xishan.oftenporter.porter.simple.DefaultFailedReason;
import org.slf4j.Logger;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.regex.Pattern;
/**
* 接口处理的工具类。
* Created by https://github.com/CLovinr on 2016/7/23.
*/
public class PortUtil {
private static final String TIED_ACCEPTED = "^[a-zA-Z0-9%_.$&=\\-]+$";
private static final Pattern TIED_NAME_PATTERN = Pattern.compile(TIED_ACCEPTED);
private final Logger LOGGER;
public PortUtil() {
LOGGER = LogUtil.logger(PortUtil.class);
}
/**
* 是否忽略某些类的高级处理。
*
* @param clazz
* @return
*/
public static final boolean willIgnoreAdvanced(Class clazz) {
Package pkg = clazz.getPackage();
String pkgName = pkg != null ? pkg.getName() : null;
if (pkgName != null && (pkgName.startsWith("java.") || pkgName.startsWith("javax.") || clazz.isPrimitive())) {
return true;
} else {
return false;
}
}
/**
* 得到类的绑定名。
*
* @param portIn
* @param clazz
* @return
*/
public static String[] tieds(PortIn portIn, Class<?> clazz, SeekPackages.Tiedfix classTiedfix,
boolean enableDefaultValue) {
String[] names = tieds(portIn);
for (int i = 0; i < names.length; i++) {
String name = names[i];
if (OftenTool.isEmpty(name)) {
if (!enableDefaultValue) {
throw new InitException("default value is not enable for " + clazz);
}
name = tiedIgnorePortIn(clazz);
}
if (classTiedfix != null) {
if (classTiedfix.getPrefix() != null &&
(!classTiedfix.isCheckExists() || !name.startsWith(classTiedfix.getPrefix()))) {
name = classTiedfix.getPrefix() + name;
}
if (classTiedfix.getSuffix() != null &&
(!classTiedfix.isCheckExists() || !name.endsWith(classTiedfix.getSuffix()))) {
name += classTiedfix.getSuffix();
}
}
names[i] = checkTied(name);
}
return names;
}
public static Class<?> getRealClass(Object object) {
// if (object instanceof AutoSetObjForAspectOfNormal.IOPProxy)
// {
// AutoSetObjForAspectOfNormal.IOPProxy iopProxy =
// (AutoSetObjForAspectOfNormal.IOPProxy) object;
// return iopProxy.get_R_e_a_l_C_l_a_s_s();
// } else
// {
// return object.getClass();
// }
return getRealClass(object.getClass());
}
public static Class<?> getRealClass(Class mayProxyChildClass) {
// if (OftenTool.isAssignable(mayProxyChildClass, AutoSetObjForAspectOfNormal.IOPProxy.class))
// {
// return mayProxyChildClass.getSuperclass();
// } else
// {
// return mayProxyChildClass;
// }
return ProxyUtil.unwrapProxyForGeneric(mayProxyChildClass);
}
/**
* 得到函数的绑定名。
*
* @param portIn
* @param method
* @return
*/
public static String[] tieds(ContextPorter.SrcPorter srcPorter, PortIn portIn, Method method,
boolean enableDefaultValue) {
String[] names = tieds(portIn);
for (int i = 0; i < names.length; i++) {
String name = names[i];
if (OftenTool.isEmpty(name)) {
if (!enableDefaultValue) {
throw new InitException("default value is not enable for " + method);
}
name = method.getName();
}
if (OftenTool.notEmpty(srcPorter.getFunTiedPrefix())) {
name = srcPorter.getFunTiedPrefix() + name;
}
if (OftenTool.notEmpty(srcPorter.getFunTiedSuffix())) {
name = name + srcPorter.getFunTiedSuffix();
}
names[i] = checkTied(name);
}
return names;
}
private static String tied(PortIn portIn) {
String name = portIn.value();
if (OftenTool.isEmpty(name)) {
name = portIn.tied();
}
return name;
}
private static String[] tieds(PortIn portIn) {
String[] tieds = portIn.tieds();
if (tieds.length == 0) {
String name = portIn.value();
if (OftenTool.isEmpty(name)) {
name = portIn.tied();
}
tieds = new String[]{name};
}
return tieds;
}
public static String tied(Unece unece, Field field, boolean enableDefaultValue) {
String name = unece.value();
String varName = unece.varName();
return getTied(unece, name, varName, field, enableDefaultValue);
}
private static String getTied(Object neceOrUnece, String name, String varName, Field field,
boolean enableDefaultValue) {
if (OftenTool.isEmptyOfAll(name, varName)) {
if (!enableDefaultValue) {
throw new InitException("default value is not enable for " + neceOrUnece + " in field '" + field + "'");
}
name = field.getName();
} else if (OftenTool.isEmpty(name)) {
name = varName;
}
return name;
}
public static String tied(Nece nece, Field field, boolean enableDefaultValue) {
String name = nece.value();
String varName = nece.varName();
return getTied(nece, name, varName, field, enableDefaultValue);
}
/**
* 得到类的绑定名。
*
* @param portIn
* @param clazz
* @return
*/
public static String tied(PortIn portIn, Class<?> clazz, boolean enableDefaultValue) {
String name = tied(portIn);
if (OftenTool.isEmpty(name)) {
if (!enableDefaultValue) {
throw new InitException("default value is not enable for " + clazz);
}
return tiedIgnorePortIn(clazz);
} else {
return checkTied(name);
}
}
public static String tied(Class<?> clazz) {
PortIn portIn = AnnoUtil.getAnnotation(clazz, PortIn.class);
String tiedName = portIn != null ? tied(portIn) : null;
if (OftenTool.isEmpty(tiedName)) {
tiedName = tiedIgnorePortIn(clazz);
}
return tiedName;
}
public static String tiedIgnorePortIn(Class<?> clazz) {
String className = clazz.getSimpleName();
if (className.endsWith("WPort")) {
className = className.substring(0, className.length() - 4);
} else if (className.endsWith("Porter")) {
className = className.substring(0, className.length() - 6);
}
if (className.equals("")) {
className = clazz.getSimpleName();
}
return checkTied(className);
}
/**
* 判断是否是接口类。
*
* @param clazz 要判断的类。
* @return
*/
public static boolean isJustPortInClass(Class<?> clazz) {
return !Modifier.isAbstract(clazz.getModifiers()) && AnnoUtil.isOneOfAnnotationsPresent(clazz, PortIn.class) &&
!AnnoUtil.isOneOfAnnotationsPresent(clazz, MixinOnly.class) && getMixinTos(clazz).length == 0;
}
/**
* 是否是Porter或混入Porter。
*
* @param clazz
* @return
*/
public static boolean isPorter(Class clazz) {
return isJustPortInClass(clazz) || isMixinPortClass(clazz);
}
/**
* 判断是否是接口类。
*
* @param clazz 要判断的类。
* @return
*/
public static boolean isMixinPortClass(Class<?> clazz) {
return !Modifier.isAbstract(clazz.getModifiers()) &&
(AnnoUtil.isOneOfAnnotationsPresent(clazz, PortIn.class, MixinOnly.class) ||
getMixinTos(clazz).length > 0);
}
public static MixinTo[] getMixinTos(Class<?> clazz) {
MixinTo[] mixinTos = AnnoUtil.getRepeatableAnnotations(clazz, MixinTo.class);
return mixinTos;
}
public static boolean enableMixinByMixinTo(Class<?> clazz) {
MixinTo[] mixinTos = getMixinTos(clazz);
boolean enable = true;
for (MixinTo mixinTo : mixinTos) {
if (!mixinTo.enableMixin()) {
enable = false;
break;
}
}
return enable;
}
/**
* 检查名称是否含有非法字符。
*
* @param name
* @return
*/
public static void checkName(String name) throws RuntimeException {
checkTied(name);
}
private static String checkTied(String tiedName) {
if (!TIED_NAME_PATTERN.matcher(tiedName).find()) {
throw new RuntimeException("Illegal value '" + tiedName + "'(accepted-pattern:" + TIED_ACCEPTED + ")");
}
return tiedName;
}
public static Object[] newArray(Name[] names) {
if (names.length == 0) {
return OftenTool.EMPTY_OBJECT_ARRAY;
} else {
return new Object[names.length];
}
}
/**
* 返回结果不为null。
* 返回{@linkplain ParamDealt.FailedReason}表示失败,否则成功。
*/
public Object paramDealOne(OftenObject oftenObject, boolean ignoreTypeParser, ParamDealt paramDealt, One one,
String optionKey, ParamSource paramSource, TypeParserStore currentTypeParserStore) {
return paramDealOne(oftenObject, ignoreTypeParser, paramDealt, one, optionKey, paramSource,
currentTypeParserStore, "");
}
/**
* 返回结果不为null。
* 返回{@linkplain ParamDealt.FailedReason}表示失败,否则成功。
*/
private Object paramDealOne(OftenObject oftenObject, boolean ignoreTypeParser, ParamDealt paramDealt, One one,
String optionKey, ParamSource paramSource, TypeParserStore currentTypeParserStore, String namePrefix) {
Object obj;
try {
{
Object value = null;
if (OftenTool.notEmpty(optionKey)) {
value = paramSource.getParam(optionKey);
}
if (value == null) {
value = paramSource.getParam(one.clazz.getName());
}
if (value != null && OftenTool.isAssignable(value.getClass(), one.clazz)) {
Name[] neces = one.inNames.nece;
//判断必须值
for (int i = 0; i < neces.length; i++) {
Field f = one.neceObjFields[i];
if (neces[i].isNece(oftenObject) && OftenTool.isNullOrEmptyCharSequence(f.get(value))) {
value = DefaultFailedReason.lackNecessaryParams("Lack necessary params!", neces[i].varName);
break;
}
}
if (!(value instanceof ParamDealt.FailedReason)) {
//转换内嵌对象
Object fieldObject =
parseInnerOnes(oftenObject, ignoreTypeParser, paramDealt, one, paramSource, value,
currentTypeParserStore, namePrefix);//见DefaultParamDealt.getParam
if (fieldObject instanceof ParamDealt.FailedReason) {
value = fieldObject;
}
}
return value;//如果获取的变量是相应类型,直接返回。
}
}
Object[] neces = PortUtil.newArray(one.inNames.nece);
Object[] uneces = PortUtil.newArray(one.inNames.unece);
Object reason =
paramDeal(oftenObject, ignoreTypeParser, paramDealt, one.inNames, neces, uneces, paramSource,
currentTypeParserStore, namePrefix);
if (reason == null) {
Object object = OftenTool.newObject(one.clazz);
for (int k = 0; k < neces.length; k++) {
one.neceObjFields[k].set(object, neces[k]);
}
for (int k = 0; k < uneces.length; k++) {
if (uneces[k] != null) {
one.unneceObjFields[k].set(object, uneces[k]);
}
}
obj = object;
//转换内嵌对象
Object fieldObject = parseInnerOnes(oftenObject, ignoreTypeParser, paramDealt, one, paramSource, object,
currentTypeParserStore, namePrefix);
if (fieldObject instanceof ParamDealt.FailedReason) {
obj = fieldObject;
}
} else {
obj = reason;
}
} catch (Exception e) {
LOGGER.warn(e.getMessage(), e);
obj = DefaultFailedReason.parseOftenEntitiesException(OftenTool.getMessage(e));
}
return obj;
}
private Object parseInnerOnes(OftenObject oftenObject, boolean ignoreTypeParser, ParamDealt paramDealt, One one,
ParamSource paramSource, Object object, TypeParserStore currentTypeParserStore, String namePrefix)
throws Exception {
Object obj = null;
//转换内嵌对象
for (int i = 0; i < one.jsonObjFields.length; i++) {
Object fieldObject =
paramDealOne(oftenObject, ignoreTypeParser, paramDealt, one.jsonObjOnes[i], null, paramSource,
currentTypeParserStore, namePrefix + one.jsonObjVarnames[i] + ".");
if (fieldObject instanceof ParamDealt.FailedReason) {
obj = fieldObject;
break;
} else {
one.jsonObjFields[i].set(object, fieldObject);
}
}
return obj;
}
/**
* 参数处理
*
* @return 返回null表示转换成功,否则表示失败。
*/
public ParamDealt.FailedReason paramDeal(OftenObject oftenObject, boolean ignoreTypeParser, ParamDealt paramDealt,
InNames inNames, Object[] nece, Object[] unece, ParamSource paramSource,
TypeParserStore currentTypeParserStore) {
return paramDeal(oftenObject, ignoreTypeParser, paramDealt, inNames, nece, unece, paramSource,
currentTypeParserStore, "");
}
/**
* 参数处理
*
* @return 返回null表示转换成功,否则表示失败。
*/
private ParamDealt.FailedReason paramDeal(OftenObject oftenObject, boolean ignoreTypeParser, ParamDealt paramDealt,
InNames inNames, Object[] nece, Object[] unece, ParamSource paramSource,
TypeParserStore currentTypeParserStore, String namePrefix) {
ParamDealt.FailedReason reason = null;
try {
if (ignoreTypeParser) {
Name[] names = inNames.nece;
for (int i = 0; i < nece.length; i++) {
Name name = names[i];
Object v;
if (name.isNece(oftenObject)) {
if (name.isRequestData()) {
v = oftenObject == null ? null : oftenObject.getRequestData(namePrefix + name.varName);
if (OftenTool.isNullOrEmptyCharSequence(v)) {
v = DefaultFailedReason
.lackNecessaryParams("Lack necessary data!", namePrefix + name.varName);
}
} else {
v = paramSource.getNeceParam(namePrefix + name.varName);
}
} else {
if (name.isRequestData()) {
v = oftenObject == null ? null : oftenObject.getRequestData(namePrefix + name.varName);
} else {
v = paramSource.getParam(namePrefix + name.varName);
}
}
nece[i] = name.dealString(v);
}
names = inNames.unece;
for (int i = 0; i < unece.length; i++) {
Name name = names[i];
Object v;
if (name.isRequestData()) {
v = oftenObject == null ? null : oftenObject.getRequestData((namePrefix + name.varName));
} else {
v = paramSource.getParam(namePrefix + name.varName);
}
unece[i] = name.dealString(v);
}
} else {
reason = paramDealt
.deal(oftenObject, inNames.nece, nece, true, paramSource, currentTypeParserStore, namePrefix);
if (reason == null) {
reason = paramDealt
.deal(oftenObject, inNames.unece, unece, false, paramSource, currentTypeParserStore,
namePrefix);
}
}
} catch (Exception e) {
LOGGER.warn(e.getMessage(), e);
reason = DefaultFailedReason.parseOftenEntitiesException(OftenTool.getMessage(e));
}
return reason;
}
}
| true |
7d1aec767e937ffa15ead54cd01cfc145e1a9f6c | Java | KennethMLee/CaregiverSpring | /src/com/caregiver/DaoI/EventServicesDaoi.java | UTF-8 | 373 | 2.015625 | 2 | [] | no_license | package com.caregiver.DaoI;
import java.util.List;
import com.caregiver.entities.Event;
public interface EventServicesDaoi {
boolean addEvent(Event event);
List<Event> getAllEvents();
List<Event> getEventByUsername(String username);
boolean removeEvent(int eventId);
boolean updateEvent(Event event);
Event getEventById(int eventId);
}
| true |
45b0019569d029300701da59969c227df7de7f79 | Java | lctx/ProyectoZapateria | /src/proyectozapateria/venta.java | UTF-8 | 20,591 | 2.234375 | 2 | [] | no_license | package proyectozapateria;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author dell
*/
public class venta extends javax.swing.JFrame {
/** Creates new form venta */
public venta() {
initComponents();
bloquearBotonesInicio();
BloquearTexto();
}
public void cargarClientes(String txtp) {
Conexion cn = new Conexion();
Connection cc = (Connection) cn.conectar();
String sql = "";
sql = "Select ID_CLIENTE from cliente";
try {
Statement psd = (Statement) cc.createStatement();
ResultSet rs = psd.executeQuery(sql);
while (rs.next()) {
jComboBoxCliente.addItem(rs.getString("ID_CLIENTE").trim());
}
jComboBoxCliente.setSelectedItem(txtp.trim());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "No se pudo cargar las Placas");
}
}
public void cargarVendedor(String txtp) {
Conexion cn = new Conexion();
Connection cc = (Connection) cn.conectar();
String sql = "";
sql = "Select ID_VENDEDOR from vendedor";
try {
Statement psd = (Statement) cc.createStatement();
ResultSet rs = psd.executeQuery(sql);
while (rs.next()) {
jComboBoxCliente.addItem(rs.getString("ID_VENDEDOR").trim());
}
jComboBoxCliente.setSelectedItem(txtp.trim());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "No se pudo cargar las Vendedor");
}
}
public void bloquearBotonesInicio() {
btnNuevo.setEnabled(true);
btnGuardar.setEnabled(false);
}
public void cargarProducto(String txtp) {
Conexion cn = new Conexion();
Connection cc = (Connection) cn.conectar();
String sql = "";
sql = "Select PRO_ID from productos";
try {
Statement psd = (Statement) cc.createStatement();
ResultSet rs = psd.executeQuery(sql);
while (rs.next()) {
jComboBoxProducto.addItem(rs.getString("PRO_ID").trim());
}
jComboBoxProducto.setSelectedItem(txtp.trim());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "No se pudo cargar las Productos");
}
}
public void limpiarTexto() {
jTextFieldID.setText("");
jTextFieldFecha.setText("");
jTextFieldValor.setText("");
}
public void BloquearTexto() {
jTextFieldID.setEnabled(false);
jTextFieldFecha.setEnabled(false);
jTextFieldValor.setEnabled(false);
jComboBoxCliente.setEnabled(false);
jComboBoxVendedor.setEnabled(false);
jComboBoxProducto.setEnabled(false);
}
public void Texto() {
jTextFieldID.setEnabled(true);
jTextFieldFecha.setEnabled(true);
jTextFieldValor.setEnabled(true);
jComboBoxCliente.setEnabled(true);
jComboBoxVendedor.setEnabled(true);
jComboBoxProducto.setEnabled(true);
}
public void bloquearBotonesNuevo() {
btnNuevo.setEnabled(false);
btnGuardar.setEnabled(true);
}
public void GuardarProducto() {
if (jTextFieldID.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Ingrese la ID");
jTextFieldID.requestFocus(true);
} else if (jTextFieldFecha.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Ingrese la Fecha");
jTextFieldFecha.requestFocus(true);
} else if (jTextFieldValor.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Ingrese la Valor");
jTextFieldValor.requestFocus(true);
} else {
String ID_VENTA, VEN_FECHA, VEN_VALOR, ID_CLIENTE, ID_VENDEDOR;
ID_VENTA = jTextFieldID.getText();
VEN_FECHA = jTextFieldFecha.getText();
VEN_VALOR = jTextFieldValor.getText();
Conexion cc = new Conexion();
Connection cn = (Connection) cc.conectar();
String sql = "";
sql = "insert into productos (ID_VENTA, VEN_FECHA, VEN_VALOR, ID_CLIENTE, ID_VENDEDOR) values (?,?,?,?,?) ";
try {
java.sql.PreparedStatement psd = cn.prepareStatement(sql);
psd.setString(1, ID_VENTA);
psd.setString(2, VEN_FECHA);
psd.setString(3, VEN_VALOR);
int n = psd.executeUpdate();
if (n > 0) {
JOptionPane.showMessageDialog(null, "Se Inserto el dato correctamente");
limpiarTexto();
BloquearTexto();
bloquearBotonesInicio();
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Se Inserto el dato correctamente");
}
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanelProducto = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jTextFieldID = new javax.swing.JTextField();
jTextFieldFecha = new javax.swing.JTextField();
jComboBoxCliente = new javax.swing.JComboBox();
jTextFieldValor = new javax.swing.JTextField();
jComboBoxVendedor = new javax.swing.JComboBox();
jComboBoxProducto = new javax.swing.JComboBox();
btnNuevo = new javax.swing.JButton();
btnGuardar = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jLabel1.setText("jLabel1");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel2.setText("ID:");
jLabel3.setText("Fecha:");
jLabel4.setText("Valor:");
jLabel5.setText("ID_Cliente:");
jLabel6.setText("ID_Vendedor:");
jLabel7.setText("ID_Producto:");
jTextFieldValor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldValorActionPerformed(evt);
}
});
jTextFieldValor.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextFieldValorKeyTyped(evt);
}
});
jComboBoxVendedor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxVendedorActionPerformed(evt);
}
});
btnNuevo.setText("Nuevo");
btnNuevo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNuevoActionPerformed(evt);
}
});
btnGuardar.setText("Guardar");
btnGuardar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGuardarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelProductoLayout = new javax.swing.GroupLayout(jPanelProducto);
jPanelProducto.setLayout(jPanelProductoLayout);
jPanelProductoLayout.setHorizontalGroup(
jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductoLayout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel5)
.addComponent(jLabel4)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addGap(21, 21, 21)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBoxProducto, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBoxVendedor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextFieldValor)
.addComponent(jComboBoxCliente, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextFieldFecha)
.addComponent(jTextFieldID, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(btnNuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(19, 19, 19))
);
jPanelProductoLayout.setVerticalGroup(
jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelProductoLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextFieldID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnNuevo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextFieldFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnGuardar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanelProductoLayout.createSequentialGroup()
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextFieldValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5))
.addComponent(jComboBoxCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jComboBoxVendedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelProductoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jComboBoxProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(14, Short.MAX_VALUE))
);
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"# Venta", "Producto", "Cantidad", "Valor"
}
));
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(7, Short.MAX_VALUE)))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 168, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(268, Short.MAX_VALUE)))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelProducto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanelProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextFieldValorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldValorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldValorActionPerformed
private void jComboBoxVendedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxVendedorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBoxVendedorActionPerformed
private void jTextFieldValorKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldValorKeyTyped
// TODO add your handling code here:
solonumeros(evt);
}//GEN-LAST:event_jTextFieldValorKeyTyped
private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
// TODO add your handling code here:
bloquearBotonesNuevo();
Texto();
}//GEN-LAST:event_btnNuevoActionPerformed
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
// TODO add your handling code here:
GuardarProducto();
}//GEN-LAST:event_btnGuardarActionPerformed
public void solonumeros(KeyEvent evt) {
char c = evt.getKeyChar();
if (Character.isLetter(c)) {
evt.consume();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(venta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(venta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(venta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(venta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new venta().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnGuardar;
private javax.swing.JButton btnNuevo;
private javax.swing.JComboBox jComboBoxCliente;
private javax.swing.JComboBox jComboBoxProducto;
private javax.swing.JComboBox jComboBoxVendedor;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanelProducto;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextFieldFecha;
private javax.swing.JTextField jTextFieldID;
private javax.swing.JTextField jTextFieldValor;
// End of variables declaration//GEN-END:variables
}
| true |
91b3ab515db5636b0d2ebefb330beb07bea89070 | Java | taDachs/faxcoin | /node/src/main/java/com/faxcoin/server/node/Node.java | UTF-8 | 586 | 2.15625 | 2 | [] | no_license | package com.faxcoin.server.node;
import com.faxcoin.communication.Message;
import com.faxcoin.communication.messenger.MessengerAddress;
import java.util.Collection;
import java.util.List;
public interface Node {
void sendMessage(Message msg);
void receiveMessage(Message msg);
NodeAddress getAddress();
Collection<Node> getNeighbours();
void registerNeighbour(NodeAddress node);
void registerMessenger(MessengerAddress messenger);
List<Message> getMessageQueue(MessengerAddress address);
void addToGroup(MessengerAddress group, MessengerAddress messengerAddress);
}
| true |
bab0ac8078868474da1484e15b63e7ea87d3c01c | Java | IsaiahEhlis/APCS | /Labs/lab21_BlackJack_GUI/Player.java | UTF-8 | 379 | 2.34375 | 2 | [] | no_license | // A+ Computer Science - www.apluscompsci.com
//Name -
//Date -
//Class -
//Lab -
package lab21_BlackJack_GUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import lab21_BlackJack_GUI.AbstractPlayer;
public class Player extends AbstractPlayer {
//constructors
public boolean hit() {
return false;
}
} | true |