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
1096b9089a446f3cd7d64a6de9a3ca01c2122610
Java
aht-group/jeesl
/util/src/main/java/org/jeesl/factory/ejb/module/hd/EjbHdEventFactory.java
UTF-8
2,981
1.984375
2
[]
no_license
package org.jeesl.factory.ejb.module.hd; import java.util.Date; import org.jeesl.factory.builder.module.HdFactoryBuilder; import org.jeesl.interfaces.facade.JeeslFacade; import org.jeesl.interfaces.model.module.hd.JeeslHdCategory; import org.jeesl.interfaces.model.module.hd.event.JeeslHdEvent; import org.jeesl.interfaces.model.module.hd.event.JeeslHdEventType; import org.jeesl.interfaces.model.module.hd.resolution.JeeslHdLevel; import org.jeesl.interfaces.model.module.hd.resolution.JeeslHdPriority; import org.jeesl.interfaces.model.module.hd.ticket.JeeslHdTicket; import org.jeesl.interfaces.model.module.hd.ticket.JeeslHdTicketStatus; import org.jeesl.interfaces.model.system.security.user.JeeslSimpleUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EjbHdEventFactory<TICKET extends JeeslHdTicket<?,EVENT,?,?>, CAT extends JeeslHdCategory<?,?,?,CAT,?>, STATUS extends JeeslHdTicketStatus<?,?,?,STATUS,?>, EVENT extends JeeslHdEvent<TICKET,CAT,STATUS,TYPE,LEVEL,PRIORITY,USER>, TYPE extends JeeslHdEventType<?,?,TYPE,?>, LEVEL extends JeeslHdLevel<?,?,?,LEVEL,?>, PRIORITY extends JeeslHdPriority<?,?,?,PRIORITY,?>, USER extends JeeslSimpleUser> { final static Logger logger = LoggerFactory.getLogger(EjbHdEventFactory.class); private final HdFactoryBuilder<?,?,?,?,TICKET,CAT,STATUS,EVENT,TYPE,LEVEL,PRIORITY,?,?,?,?,?,?,?,?,?,USER> fbHd; public EjbHdEventFactory(HdFactoryBuilder<?,?,?,?,TICKET,CAT,STATUS,EVENT,TYPE,LEVEL,PRIORITY,?,?,?,?,?,?,?,?,?,USER> fbHd) { this.fbHd = fbHd; } public EVENT build(TICKET ticket, CAT category, STATUS status, LEVEL level, PRIORITY priority, USER reporter) { try { EVENT ejb = fbHd.getClassEvent().newInstance(); ejb.setTicket(ticket); ejb.setCategory(category); ejb.setStatus(status); ejb.setLevel(level); ejb.setRecord(new Date()); ejb.setReporter(reporter); ejb.setInitiator(reporter); ejb.setReporterPriority(priority); ejb.setSupporterPriority(priority); return ejb; } catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} return null; } public void converter(JeeslFacade facade, EVENT event) { if(event.getCategory()!=null) {event.setCategory(facade.find(fbHd.getClassCategory(),event.getCategory()));} if(event.getStatus()!=null) {event.setStatus(facade.find(fbHd.getClassTicketStatus(),event.getStatus()));} if(event.getLevel()!=null) {event.setLevel(facade.find(fbHd.getClassLevel(),event.getLevel()));} if(event.getSupporter()!=null) {event.setSupporter(facade.find(fbHd.getClassUser(),event.getSupporter()));} if(event.getReporterPriority()!=null) {event.setReporterPriority(facade.find(fbHd.getClassPriority(),event.getReporterPriority()));} if(event.getSupporterPriority()!=null) {event.setSupporterPriority(facade.find(fbHd.getClassPriority(),event.getSupporterPriority()));} } }
true
2346c6402a075079a3fe516448e932dd7cf37464
Java
djdapz/EecsSportsBotWithTests
/src/main/java/sportsbot/service/PositionsService.java
UTF-8
1,055
2.375
2
[]
no_license
package sportsbot.service; import org.springframework.stereotype.Service; import sportsbot.enums.Sport; import sportsbot.exception.PositionNotFoundException; import sportsbot.model.QuestionContext; import sportsbot.model.position.Position; import sportsbot.model.position.Positions; import sportsbot.model.position.PositionsBaseball; import java.util.HashMap; /** * Created by devondapuzzo on 5/28/17. */ @Service public class PositionsService { private HashMap<Sport, Positions> positionsHashMap = new HashMap<>(); public PositionsService(){ positionsHashMap.put(Sport.BASEBALL, new PositionsBaseball()); } public Position findPosition(QuestionContext questionContext) throws PositionNotFoundException{ return positionsHashMap.get(questionContext.getSport()).searchQueryForPosition(questionContext.getQuestion().toLowerCase()); } public Position findPosition(Sport sport, String query) throws PositionNotFoundException { return positionsHashMap.get(sport).searchQueryForPosition(query); } }
true
5b978ff862dada5d97d405f235440ca0750be1c0
Java
danieleavolio/Gestione-Segreteria
/src/main/persistence/dao/jdbc/CorsoDiLaureaDAOJDBC.java
UTF-8
2,959
2.59375
3
[]
no_license
package main.persistence.dao.jdbc; import main.Model.CorsoDiLaurea; import main.Model.Studente; import main.persistence.DBManager; import main.persistence.DBSource; import main.persistence.dao.CorsoDiLaureaDAO; import java.sql.*; import java.util.ArrayList; import java.util.List; public class CorsoDiLaureaDAOJDBC implements main.persistence.dao.CorsoDiLaureaDAO { private final DBSource dbSource; @Override public void save(main.persistence.dao.CorsoDiLaureaDAO cdl) { } public CorsoDiLaureaDAOJDBC(DBSource dbSource) { this.dbSource = dbSource; } @Override public Studente findByPrimaryKey(String matricola) { return null; } @Override public List<CorsoDiLaurea> findAll() { List<CorsoDiLaurea> cdls = new ArrayList<>(); try { Connection conn = dbSource.getConnection(); String query = "select * from corsodilaurea"; Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while(rs.next()){ int id = rs.getInt("id"); String nome = rs.getString("nome"); CorsoDiLaurea cdl = new CorsoDiLaurea(); cdl.setID(id); cdl.setNome(nome); cdl.setStudenti(DBManager.getInstance().corsoDiLaureaDAO().findByCorsoDiLaureaID(id)); cdls.add(cdl); } } catch (SQLException throwables) { throwables.printStackTrace(); } return cdls; } @Override public void update(main.persistence.dao.CorsoDiLaureaDAO cdl) { } @Override public void delete(main.persistence.dao.CorsoDiLaureaDAO cdl) { } @Override public ArrayList<Studente> findByCorsoDiLaureaID(int clid) { ArrayList<Studente> studenti = new ArrayList<>(); try { Connection conn = dbSource.getConnection(); String query = "select * from studente where corsodilaurea=?"; PreparedStatement st = conn.prepareStatement(query); st.setInt(1,clid); ResultSet rs = st.executeQuery(); if (rs.next()){ String matr = rs.getString("matricola"); String nome = rs.getString("nome"); String cognome = rs.getString("cognome"); String dataNascita = rs.getString("datanascita"); int scuola = rs.getInt("scuola"); Studente stud = new Studente(); stud.setNome(nome); stud.setCognome(cognome); stud.setMatricola(matr); stud.setDataNascita(dataNascita); stud.setScuola(DBManager.getInstance().scuolaDAO().findByPrimaryKey(scuola)); studenti.add(stud); } } catch (SQLException throwables) { throwables.printStackTrace(); } return studenti; } }
true
7d77dff893ad78b4f71681b861c76e1df75ca771
Java
assertlab/extractviewer_project
/mapping-application-web/src/main/java/br/ufpe/cin/cloud/mapeamento/web/base/converter/BooleanConverter.java
UTF-8
1,990
2.625
3
[ "MIT" ]
permissive
/** * CloudMapping - Sistema de Extração de Dados de Mapeamento dos Experimentos em Computação em Nuvem * * Copyright (c) AssertLab. * * Este software é confidencial e propriedade da AssertLab. Não é permitida sua distribuição ou divulgação * do seu conteúdo sem expressa autorização do AssertLab. Este arquivo contém informações proprietárias. */ package br.ufpe.cin.cloud.mapeamento.web.base.converter; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; /** * Converter para os valores representativos de um campo boleano. * * @author helaine.lins * @created 17/04/2014 - 21:10:40 */ @FacesConverter(value = "boleanoConverter") public class BooleanConverter implements Converter { /** * {@inheritDoc}. * * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, * javax.faces.component.UIComponent, java.lang.String) */ @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { Boolean valor = null; if ("Sim".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value)) { valor = Boolean.TRUE; } else if ("Não".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) { valor = Boolean.FALSE; } return valor; } /** * {@inheritDoc}. * * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, * javax.faces.component.UIComponent, java.lang.Object) */ @Override public String getAsString(FacesContext context, UIComponent component, Object value) { String valor = ""; if (value != null) { if (Boolean.TRUE.equals(value)) { valor = "Sim"; } else { valor = "Não"; } } return valor; } }
true
0e9182784caac10c87f75cbaa3afe2164a77d2bf
Java
fogbow/fogbow-mono-manager
/src/main/java/org/fogbowcloud/manager/core/plugins/compute/openstack/OpenStackOCCIComputePlugin.java
UTF-8
8,496
1.648438
2
[ "Apache-2.0" ]
permissive
package org.fogbowcloud.manager.core.plugins.compute.openstack; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.http.Header; import org.apache.http.client.HttpClient; import org.apache.http.message.BasicHeader; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.compute.occi.OCCIComputePlugin; import org.fogbowcloud.manager.occi.model.Category; import org.fogbowcloud.manager.occi.model.ErrorType; import org.fogbowcloud.manager.occi.model.HeaderUtils; import org.fogbowcloud.manager.occi.model.OCCIException; import org.fogbowcloud.manager.occi.model.OCCIHeaders; import org.fogbowcloud.manager.occi.model.ResponseConstants; import org.fogbowcloud.manager.occi.model.Token; import org.fogbowcloud.manager.occi.order.OrderAttribute; import org.fogbowcloud.manager.occi.order.OrderConstants; import org.restlet.Client; import org.restlet.Request; import org.restlet.data.ClientInfo; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.util.Series; public class OpenStackOCCIComputePlugin extends OCCIComputePlugin{ private static final String PUBLIC_KEY_TERM = "public_key"; private static final String PUBLIC_KEY_SCHEME = "http://schemas.openstack.org/instance/credentials#"; private static final String NAME_PUBLIC_KEY_ATTRIBUTE = "org.openstack.credentials.publickey.name"; private static final String DATA_PUBLIC_KEY_ATTRIBUTE = "org.openstack.credentials.publickey.data"; private static final String NAME_PUBLIC_KEY_DEFAULT = "fogbow_keypair"; private OpenStackNovaV2ComputePlugin openStackNovaV2ComputePlugin; public OpenStackOCCIComputePlugin(Properties properties) { super(properties); openStackNovaV2ComputePlugin = new OpenStackNovaV2ComputePlugin(properties); super.fogTermToCategory.put(OrderConstants.PUBLIC_KEY_TERM, new Category( PUBLIC_KEY_TERM, PUBLIC_KEY_SCHEME, OrderConstants.MIXIN_CLASS)); } protected Set<Header> getExtraHeaders(List<Category> requestCategories, Map<String, String> xOCCIAtt, Token token) { List<Category> openStackCategories = new ArrayList<Category>(); for (Category category : requestCategories) { openStackCategories.add(super.fogTermToCategory.get(category.getTerm())); // adding ssh public key if (category.getTerm().equals(OrderConstants.PUBLIC_KEY_TERM)) { xOCCIAtt.put(NAME_PUBLIC_KEY_ATTRIBUTE, NAME_PUBLIC_KEY_DEFAULT); xOCCIAtt.put(DATA_PUBLIC_KEY_ATTRIBUTE, xOCCIAtt.get(OrderAttribute.DATA_PUBLIC_KEY.getValue())); xOCCIAtt.remove(OrderAttribute.DATA_PUBLIC_KEY.getValue()); } } String userdataBase64 = xOCCIAtt.remove(OrderAttribute.USER_DATA_ATT.getValue()); if (userdataBase64 != null) { xOCCIAtt.put("org.openstack.compute.user_data", userdataBase64); } Set<Header> headers = new HashSet<Header>(); for (Category category : openStackCategories) { headers.add(new BasicHeader(OCCIHeaders.CATEGORY, category.toHeader())); } for (String attName : xOCCIAtt.keySet()) { headers.add(new BasicHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, attName + "=" + "\"" + xOCCIAtt.get(attName) + "\"")); } return headers; } @SuppressWarnings("unchecked") @Override public void bypass(Request request, org.restlet.Response response) { if (computeOCCIEndpoint == null || computeOCCIEndpoint.isEmpty()) { throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.CLOUD_NOT_SUPPORT_OCCI_INTERFACE); } try { URI origRequestURI = new URI(request.getResourceRef().toString()); URI occiURI = new URI(oCCIEndpoint); URI newRequestURI = new URI(occiURI.getScheme(), occiURI.getUserInfo(), occiURI.getHost(), occiURI.getPort(), origRequestURI.getPath(), origRequestURI.getQuery(), origRequestURI.getFragment()); Client clienteForBypass = new Client(Protocol.HTTP); Request proxiedRequest = new Request(request.getMethod(), newRequestURI.toString()); // forwarding headers from cloud to response Series<org.restlet.data.Header> requestHeaders = (Series<org.restlet.data.Header>) request .getAttributes().get("org.restlet.http.headers"); boolean convertToOcci = false; for (org.restlet.data.Header header : requestHeaders) { if (header.getName().contains("Content-type") && !header.getValue().equals(OCCIHeaders.OCCI_CONTENT_TYPE) && request.getMethod().getName() .equals(org.restlet.data.Method.POST.getName())) { convertToOcci = true; } else if (header.getName().contains(OCCIHeaders.ACCEPT)) { try { String headerAccept = header.getValue(); ClientInfo clientInfo = null; if (headerAccept.contains(OCCIHeaders.TEXT_PLAIN_CONTENT_TYPE)) { clientInfo = new ClientInfo(MediaType.TEXT_PLAIN); } else if (headerAccept.contains(OCCIHeaders.TEXT_URI_LIST_CONTENT_TYPE)) { clientInfo = new ClientInfo(MediaType.TEXT_PLAIN); } else { clientInfo = new ClientInfo(new MediaType(headerAccept)); } proxiedRequest.setClientInfo(clientInfo); } catch (Exception e) {} } } if (convertToOcci) { convertRequestToOcci(request, requestHeaders); } // Removing one header if request has more than one (one normalized and other not normalized) if (requestHeaders.getValuesArray(HeaderUtils.normalize(OCCIHeaders.X_AUTH_TOKEN), true).length == 2) { requestHeaders.removeFirst(OCCIHeaders.X_AUTH_TOKEN); } proxiedRequest.getAttributes().put("org.restlet.http.headers", requestHeaders); clienteForBypass.handle(proxiedRequest, response); // Removing Body of response when POST of actions if (origRequestURI.toASCIIString().contains("?action=")) { response.setEntity("", MediaType.TEXT_PLAIN); } } catch (URISyntaxException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } } @Override public ResourcesInfo getResourcesInfo(Token token) { return openStackNovaV2ComputePlugin.getResourcesInfo(token); } protected void convertRequestToOcci(Request request, Series<org.restlet.data.Header> requestHeaders) { try { String entityAsText = request.getEntityAsText(); if (!entityAsText.contains(OCCIHeaders.CATEGORY) && !entityAsText.contains(OCCIHeaders.X_OCCI_ATTRIBUTE)) { return; } requestHeaders.removeAll(OCCIHeaders.TEXT_PLAIN_CONTENT_TYPE); requestHeaders.removeAll("Content-type"); requestHeaders.add(OCCIHeaders.ACCEPT, OCCIHeaders.OCCI_ACCEPT); requestHeaders.add("Content-type", OCCIHeaders.OCCI_CONTENT_TYPE); String category = ""; String attribute = ""; String[] linesBody = entityAsText.split("\n"); for (String line : linesBody) { if (line.contains(OCCIHeaders.CATEGORY + ":")) { category += line.replace(OCCIHeaders.CATEGORY + ":", "").trim() + "\n"; } else if (line.contains(OCCIHeaders.X_OCCI_ATTRIBUTE + ":")) { attribute += line.replace(OCCIHeaders.X_OCCI_ATTRIBUTE + ":", "") .trim() + "\n"; } } requestHeaders.add(new org.restlet.data.Header(OCCIHeaders.CATEGORY, category.trim().replace("\n", ","))); requestHeaders.add(new org.restlet.data.Header("X-occi-attribute", attribute.trim().replace("\n", ","))); request.setEntity("", MediaType.TEXT_PLAIN); } catch (Exception e) {} } @Override public void uploadImage(Token token, String imagePath, String imageName, String diskFormat) { openStackNovaV2ComputePlugin.uploadImage(token, imagePath, imageName, null); } @Override public String getImageId(Token token, String imageName) { return openStackNovaV2ComputePlugin.getImageId(token, imageName); } protected Flavor getFlavor(Token token, String requirements) { Flavor flavorFound = openStackNovaV2ComputePlugin.getFlavor(token, requirements); normalizeNameFlavorOCCI(flavorFound); return flavorFound; } protected void normalizeNameFlavorOCCI(Flavor flavor) { if (flavor != null) { flavor.setName(flavor.getName().replace(".", "-")); } } protected void setFlavorsProvided(Properties properties) { } protected void setFlavors(List<Flavor> flavors) { super.setFlavors(flavors); } protected void setClient(HttpClient client) { super.setClient(client);; } }
true
a31ce32282c166fde68fcd5e9c2123d4a123a62e
Java
recolic/ali-middleware-5
/workspace-provider/src/main/java/com/aliware/tianchi/CallbackServiceImpl.java
UTF-8
3,374
2.484375
2
[]
no_license
package com.aliware.tianchi; import org.apache.dubbo.rpc.listener.CallbackListener; import org.apache.dubbo.rpc.service.CallbackService; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * @author daofeng.xjf * <p> * 服务端回调服务 * 可选接口 * 用户可以基于此服务,实现服务端向客户端动态推送的功能 */ public class CallbackServiceImpl implements CallbackService { public CallbackServiceImpl() { timer.schedule(new TimerTask() { @Override public void run() { if (!listeners.isEmpty()) { //System.out.println("Server push " +generateStatusMessage() + " Mem="+Runtime.getRuntime().freeMemory()); for (Map.Entry<String, CallbackListener> entry : listeners.entrySet()) { try { //entry.getValue().receiveServerMsg(System.getProperty("quota") + " " + new Date().toString());Runtime.getRuntime().freeMemory() entry.getValue().receiveServerMsg(System.getProperty("quota") + "," + generateStatusMessage()); } catch (Throwable t1) { listeners.remove(entry.getKey()); } } } } }, 0, 1000); } private Timer timer = new Timer(); private String generateStatusMessage() { try { List<String> cpuLoadList = getProcessCpuLoad().stream().map(Object::toString).collect(Collectors.toList()); String cpuLoadString = String.join(",", cpuLoadList); System.out.println(cpuLoadList); return cpuLoadList.get(0); } catch(Exception ex) { return "error"; } } /** * key: listener type * value: callback listener */ private final Map<String, CallbackListener> listeners = new ConcurrentHashMap<>(); @Override public void addListener(String key, CallbackListener listener) { System.out.println("Server: add Listener " + key); listeners.put(key, listener); listener.receiveServerMsg(new Date().toString()); // send notification for change } // System status impl private static List<Double> getProcessCpuLoad() throws Exception { List<Double> result = new ArrayList<>(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem"); AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" }); for(int i = 0; i < list.size(); ++i) { Attribute att = (Attribute) list.get(i); Double value = (Double)att.getValue(); if(value == -1.0) // usually takes a couple of seconds before we get real values result.add(Double.NaN); else // returns a percentage value with 1 decimal point precision result.add(((int)(value * 1000) / 10.0)); } return result; } }
true
e7092669c0aa41585bbe4bdcf3785d1a5c86e154
Java
HectorRizzo/ChairGameSimulator
/Proyecto/src/controller/Principal.java
UTF-8
2,074
2.3125
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 controller; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * * @author Jocelyn Chicaiza */ public class Principal implements Initializable { @FXML void toExit(ActionEvent event) { Platform.exit(); } @FXML void toPlay(ActionEvent event) throws IOException { ((Node) (event.getSource())).getScene().getWindow().hide(); Parent parent = FXMLLoader.load(getClass().getResource("/View/Configurations.fxml")); Stage stage = new Stage(); Scene scene = new Scene(parent); stage.setScene(scene); stage.show(); } @FXML void showHelp(ActionEvent event) { try { ((Node) (event.getSource())).getScene().getWindow().hide(); FXMLLoader loader; loader = new FXMLLoader(getClass().getResource("/View/Help.fxml") ); Parent parent = loader.load(); Help controller = loader.getController(); Stage stage = new Stage(); Scene scene = new Scene(parent); stage.setScene(scene); stage.show(); stage.setOnCloseRequest(e->controller.closeWindows()); } catch (IOException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void initialize(URL url, ResourceBundle rb) { //Meotodo para controllar los elemetos de la vista } }
true
8f1a3b980f95258590befe928cf2ff3e80854107
Java
welmahjoub/gestionCabinet
/pfe/src/main/java/com/spring/pfe/Dao/DonneePhysiologDao.java
UTF-8
1,240
1.921875
2
[]
no_license
package com.spring.pfe.Dao; import java.util.List; import java.util.UUID; import com.spring.pfe.Entity.DonnePhysiolog; public interface DonneePhysiologDao { /*========================================================================================================================*/ /*========================================= Methodes de l'interface Données physiologiques ================================================*/ /*========================================================================================================================*/ public void Ajouter(DonnePhysiolog d); public int getCountDonnePhysiolog(); public List<DonnePhysiolog> getAllDonnePhysiolog(); public DonnePhysiolog getDonnePhysiologById(UUID id); public List<DonnePhysiolog> getAllDonnePhysiologByPatient(String cinPatient); public void TesterDonneesPhysiologique(DonnePhysiolog d); /*========================================================================================================================*/ /*========================================= ================================================*/ /*========================================================================================================================*/ }
true
37405d007db4544fe698b87357c07220326dda0f
Java
testsmith-io/training-java-unit-testing
/src/test/java/io/testsmith/exercises/DataDrivenAccountTest.java
UTF-8
1,448
3.21875
3
[]
no_license
package io.testsmith.exercises; import org.junit.Assert; import org.junit.Test; public class DataDrivenAccountTest { @Test public void withdraw500FromAccount_shouldResultInCorrectBalance() { // Arrange - create a new savings account with an initial balance of 1000 DataDrivenAccount account = new DataDrivenAccount(1000, 12345, AccountType.SAVINGS); // Act - withdraw 500 account.withdraw(500); // Assert - check that the remaining balance is 500 Assert.assertEquals(500, account.getBalance()); } @Test public void withdraw999FromAccount_shouldResultInCorrectBalance() { // Arrange - create a new savings account with an initial balance of 1000 DataDrivenAccount account = new DataDrivenAccount(1000, 12345, AccountType.SAVINGS); // Act - withdraw 999 account.withdraw(999); // Assert - check that the remaining balance is 1 Assert.assertEquals(1, account.getBalance()); } @Test public void withdraw1000FromAccount_shouldResultInCorrectBalance() { // Arrange - create a new savings account with an initial balance of 1000 DataDrivenAccount account = new DataDrivenAccount(1000, 12345, AccountType.SAVINGS); // Act - withdraw 1000 account.withdraw(1000); // Assert - check that the remaining balance is 0 Assert.assertEquals(0, account.getBalance()); } }
true
d5ddcb4fc744e2cb485688ffe653e6645800b398
Java
johnlpuc163/twitterAndroid
/MyTwt/app/src/main/java/com/mytwt/app/LoadMoreAsyncTask.java
UTF-8
2,222
2.34375
2
[]
no_license
package com.mytwt.app; import android.os.AsyncTask; import android.util.Log; import java.util.List; import twitter4j.Paging; import twitter4j.Status; import twitter4j.Twitter; public class LoadMoreAsyncTask extends AsyncTask<Void, Void, LoadMoreAsyncTask.LoadMoreStatusesResult> { private long targetId; private int loadType; private Twitter twitter; private LoadMoreStatusesResponder responder; private final int LOAD_NEWER = 1; private final int LOAD_TIMELINE = 0; private final int LOAD_OLDER = -1; public interface LoadMoreStatusesResponder { public void statusesLoaded(LoadMoreStatusesResult result); } public class LoadMoreStatusesResult { public List<twitter4j.Status> statuses; public int loadType; public LoadMoreStatusesResult(List<twitter4j.Status> statuses, int loadType) { super(); this.statuses = statuses; this.loadType = loadType; } } //constructor public LoadMoreAsyncTask(LoadMoreStatusesResponder responder, Twitter twitter, long targetId, int loadType) { super(); this.responder = responder; this.targetId = targetId; this.twitter = twitter; this.loadType = loadType; } @Override protected LoadMoreAsyncTask.LoadMoreStatusesResult doInBackground(Void...params) { List<twitter4j.Status> statii = null; try { switch (loadType){ case LOAD_TIMELINE: statii = twitter.getHomeTimeline(); break; case LOAD_NEWER: statii = twitter.getHomeTimeline(new Paging(1).sinceId(targetId)); break; case LOAD_OLDER: statii = twitter.getHomeTimeline(new Paging(1).maxId(targetId)); default: break; } } catch (Exception e) { throw new RuntimeException("Unable to load timeline", e); } return new LoadMoreStatusesResult(statii, loadType); } @Override public void onPostExecute(LoadMoreStatusesResult result) { responder.statusesLoaded(result); } }
true
ab296c73ed7187a8c60c20f06ff987bd8974693d
Java
aaabdallah/realestateproject-coreserver
/src/aaacs/coreserver/database/DatabaseWrapper.java
UTF-8
3,012
2.5
2
[]
no_license
package aaacs.coreserver.database; import java.sql.Connection; import javax.naming.Context; import javax.naming.InitialContext; import aaacs.coreserver.administration.Configurator; /** * @author Ahmed A. Abd-Allah * Created on Oct 29, 2006 * * This class should be used to isolate any database-dependent code. It also * has code that is particular to all databases (e.g. getConnection). */ public class DatabaseWrapper { // ----- Supported Databases ---------------------------------------------- public static final String DB_POSTGRESQL = "PostgreSQL"; // ----- Current database ------------------------------------------------- private static String currentDatabase = null; private static String databaseJNDIName = null; public static String getCurrentDatabase() { return currentDatabase; } public static String getDatabaseJNDIName() { return databaseJNDIName; } public static boolean setDatabaseParameters(String inCurrentDatabase, String inDatabaseJNDIName) { if (isSupported(inCurrentDatabase)) { currentDatabase = inCurrentDatabase; databaseJNDIName = inDatabaseJNDIName; return true; } return false; } public static boolean isSupported(String database) { if (database != null) { if (database.equalsIgnoreCase(DB_POSTGRESQL)) return true; } return false; } /* public static PrimaryKeyHolder getLastPrimaryKeyGenerated(Connection connection, String tableName) throws CoreServerException { Statement stmt = null; CSLogger mainLogger = Configurator.getMainLogger(); try { if (currentDatabase.equalsIgnoreCase(DB_POSTGRESQL)) { stmt = connection.createStatement(); //stmt.executeQuery("select currval('" + tableName + "_id_seq')"); stmt.executeQuery("select currval('s_global_id_seq')"); ResultSet resultSet = stmt.getResultSet(); if (resultSet.first()) { return PrimaryKeyHolder.getFromResultSet(resultSet, "currval"); } throw new CoreServerException("No primary key found in result set.", false, null); } throw new CoreServerException("Unrecognized database type.", false, null); } catch (Exception e) { mainLogger.error("database.UnableToGetLastPrimaryKeyGenerated", e); throw new CoreServerException("database.UnableToGetLastPrimaryKeyGenerated", true, e); } finally { try { if (stmt != null) stmt.close(); } catch (Exception e) {} } } */ public static Connection getConnection() throws Exception { try { Context ctx = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup(getDatabaseJNDIName()); Connection connection = ds.getConnection(); //connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); //connection.setAutoCommit(false); return connection; } catch (Exception e) { e.printStackTrace(); (Configurator.getMainLogger()).fatalError("database.UnableToEstablishConnection", e); throw e; } } /** * */ public DatabaseWrapper(String database) { } }
true
c27c53cab5d334e5b533d4b3e47966a20d2a422d
Java
qiuxirufengQAQ/gmf-colson-lianxi
/gmcf-colson-dal/src/main/java/com/colson/dataStructure/StackSingleLink.java
UTF-8
518
3.453125
3
[]
no_license
package com.colson.dataStructure; /** * 单向链表实现栈 */ public class StackSingleLink { private SingleLinkedList link; public StackSingleLink(){ link = new SingleLinkedList(); } //添加元素 public void push(Object obj){ link.addHead(obj); } //移除栈顶元素 public Object pop(){ Object obj = link.deleteHead(); return obj; } //判断是否为空 public boolean isEmpty(){ return link.isEmpty(); } //打印栈内元素信息 public void display(){ link.display(); } }
true
16b2ff13e860929e8ab1db448a98c4b84faee3c3
Java
Gauravgkp/PE1
/src/main/java/com/boeing/PE1/Iteration.java
UTF-8
1,170
3.84375
4
[]
no_license
package com.boeing.PE1;/* * Gaurav Singh, * * Stack Route, * * Boeing India Pvt Ltd. */ import java.util.Scanner; /** * The class take an integer value and generate a series upto the entered value by * by repeating the number as many times as the number itself represents. * * @version 1.10 31-Dec-2018 * * @author Gaurav Singh */ public class Iteration { /* This function repeat a number n number of times as the number represent. */ public static boolean iteration(int times){ for(int i=1; i<=times; i++){ for(int j=1; j<=i; j++){ /* Print the number as many times as the number value is. */ System.out.print(i+" "); } } return true; } /* This is main function which calls the iteration function and pass the user input. */ public static void main(String [] args){ System.out.println("Enter number of iteration"); Scanner scan = new Scanner(System.in); /* Scan the input from user for number of iteration*/ int times = scan.nextInt(); boolean pass = iteration(times); //Call the iteration function. return; } }
true
5286d9e74a913d6c9e05a5f35588fffc9f54e349
Java
JuliaBorisevska/ContactCatalog
/src/main/java/com/itechart/contactcatalog/command/MailSendingCommand.java
UTF-8
2,471
2.53125
3
[]
no_license
package com.itechart.contactcatalog.command; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itechart.contactcatalog.controller.ContactServlet; import com.itechart.contactcatalog.dao.ContactDAO; import com.itechart.contactcatalog.exception.ServiceException; import com.itechart.contactcatalog.logic.ContactService; import com.itechart.contactcatalog.logic.MailSender; import com.itechart.contactcatalog.subject.Contact; import com.itechart.contactcatalog.template.TemplateCreator; public class MailSendingCommand implements ActionCommand { private static Logger logger = LoggerFactory.getLogger(MailSendingCommand.class); private static final String TEXT_CONTACT_ID = "idContact"; private static final String TEXT_TOPIC = "topic"; private static final String TEXT_TEMPLATE = "template"; private static final String TEXT_LETTER = "letter"; @Override public boolean execute(HttpServletRequest request, HttpServletResponse response) { try{ logger.info("Start MailSendingCommand with request: {}", ContactServlet.takeRequestInformation(request)); String[] ids = request.getParameterValues(TEXT_CONTACT_ID); List<Contact> contacts = new ArrayList<>(); for (String id : ids){ Contact contact =ContactService.receiveContactById(Integer.valueOf(id)); contacts.add(contact); } String topic = request.getParameter(TEXT_TOPIC); String template = request.getParameter(TEXT_TEMPLATE); logger.debug("template {}", template); String text = request.getParameter(TEXT_LETTER); for (Contact cont : contacts){ if (!TEXT_LETTER.equals(template)){ TemplateCreator creator=new TemplateCreator(); text = creator.formMessage(cont, template); } MailSender.sendMessage(topic, text, cont.getEmail()); } request.getSession().setAttribute("contactListStatement", ContactDAO.getStatementForContactsList()); request.getSession().setAttribute("contactCountStatement", ContactDAO.getStatementForContactsCount()); ContactListCommand command = new ContactListCommand(); return command.execute(request, response); }catch(ServiceException | NumberFormatException e) { request.setAttribute("customerror", "message.customerror"); logger.error("Exception in execute: {}", e); } return false; } }
true
a3b694672535487aaf9201416a96d9a9571184b1
Java
nvkk-devops/cdktf-java-aws
/src/main/java/imports/aws/AppmeshVirtualNodeSpecServiceDiscoveryDns.java
UTF-8
5,736
1.992188
2
[]
no_license
package imports.aws; @javax.annotation.Generated(value = "jsii-pacmak/1.24.0 (build b722f66)", date = "2021-03-10T09:47:02.039Z") @software.amazon.jsii.Jsii(module = imports.aws.$Module.class, fqn = "aws.AppmeshVirtualNodeSpecServiceDiscoveryDns") @software.amazon.jsii.Jsii.Proxy(AppmeshVirtualNodeSpecServiceDiscoveryDns.Jsii$Proxy.class) public interface AppmeshVirtualNodeSpecServiceDiscoveryDns extends software.amazon.jsii.JsiiSerializable { @org.jetbrains.annotations.NotNull java.lang.String getHostname(); default @org.jetbrains.annotations.Nullable java.lang.String getServiceName() { return null; } /** * @return a {@link Builder} of {@link AppmeshVirtualNodeSpecServiceDiscoveryDns} */ static Builder builder() { return new Builder(); } /** * A builder for {@link AppmeshVirtualNodeSpecServiceDiscoveryDns} */ public static final class Builder implements software.amazon.jsii.Builder<AppmeshVirtualNodeSpecServiceDiscoveryDns> { private java.lang.String hostname; private java.lang.String serviceName; /** * Sets the value of {@link AppmeshVirtualNodeSpecServiceDiscoveryDns#getHostname} * @param hostname the value to be set. This parameter is required. * @return {@code this} */ public Builder hostname(java.lang.String hostname) { this.hostname = hostname; return this; } /** * Sets the value of {@link AppmeshVirtualNodeSpecServiceDiscoveryDns#getServiceName} * @param serviceName the value to be set. * @return {@code this} */ public Builder serviceName(java.lang.String serviceName) { this.serviceName = serviceName; return this; } /** * Builds the configured instance. * @return a new instance of {@link AppmeshVirtualNodeSpecServiceDiscoveryDns} * @throws NullPointerException if any required attribute was not provided */ @Override public AppmeshVirtualNodeSpecServiceDiscoveryDns build() { return new Jsii$Proxy(hostname, serviceName); } } /** * An implementation for {@link AppmeshVirtualNodeSpecServiceDiscoveryDns} */ @software.amazon.jsii.Internal final class Jsii$Proxy extends software.amazon.jsii.JsiiObject implements AppmeshVirtualNodeSpecServiceDiscoveryDns { private final java.lang.String hostname; private final java.lang.String serviceName; /** * Constructor that initializes the object based on values retrieved from the JsiiObject. * @param objRef Reference to the JSII managed object. */ protected Jsii$Proxy(final software.amazon.jsii.JsiiObjectRef objRef) { super(objRef); this.hostname = software.amazon.jsii.Kernel.get(this, "hostname", software.amazon.jsii.NativeType.forClass(java.lang.String.class)); this.serviceName = software.amazon.jsii.Kernel.get(this, "serviceName", software.amazon.jsii.NativeType.forClass(java.lang.String.class)); } /** * Constructor that initializes the object based on literal property values passed by the {@link Builder}. */ protected Jsii$Proxy(final java.lang.String hostname, final java.lang.String serviceName) { super(software.amazon.jsii.JsiiObject.InitializationMode.JSII); this.hostname = java.util.Objects.requireNonNull(hostname, "hostname is required"); this.serviceName = serviceName; } @Override public final java.lang.String getHostname() { return this.hostname; } @Override public final java.lang.String getServiceName() { return this.serviceName; } @Override @software.amazon.jsii.Internal public com.fasterxml.jackson.databind.JsonNode $jsii$toJson() { final com.fasterxml.jackson.databind.ObjectMapper om = software.amazon.jsii.JsiiObjectMapper.INSTANCE; final com.fasterxml.jackson.databind.node.ObjectNode data = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode(); data.set("hostname", om.valueToTree(this.getHostname())); if (this.getServiceName() != null) { data.set("serviceName", om.valueToTree(this.getServiceName())); } final com.fasterxml.jackson.databind.node.ObjectNode struct = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode(); struct.set("fqn", om.valueToTree("aws.AppmeshVirtualNodeSpecServiceDiscoveryDns")); struct.set("data", data); final com.fasterxml.jackson.databind.node.ObjectNode obj = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode(); obj.set("$jsii.struct", struct); return obj; } @Override public final boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AppmeshVirtualNodeSpecServiceDiscoveryDns.Jsii$Proxy that = (AppmeshVirtualNodeSpecServiceDiscoveryDns.Jsii$Proxy) o; if (!hostname.equals(that.hostname)) return false; return this.serviceName != null ? this.serviceName.equals(that.serviceName) : that.serviceName == null; } @Override public final int hashCode() { int result = this.hostname.hashCode(); result = 31 * result + (this.serviceName != null ? this.serviceName.hashCode() : 0); return result; } } }
true
ebc12d55444512629a70ae3a75f76cd8376dc17d
Java
ChangeVision/astah-uml2c-plugin
/src/main/java/com/change_vision/astah/extension/plugin/uml2c/Messages.java
UTF-8
2,272
2.859375
3
[ "Apache-2.0" ]
permissive
package com.change_vision.astah.extension.plugin.uml2c; import java.text.MessageFormat; import java.util.Enumeration; import java.util.Locale; import java.util.ResourceBundle; import com.change_vision.jude.api.inf.ui.IMessageProvider; /** * メッセージリソースを扱うクラスです * <p/> * * com/change_vision/astah/extension/plugin/uml2c/messages. * propertesプロパティファイルからメッセージを取得します */ public class Messages implements IMessageProvider { /** * デフォルトのプロパティファイルの配置場所 */ public static final String DEFAULT_BUNDLE = "com.change_vision.astah.extension.plugin.uml2c.messages"; /** * メッセージリソースバンドル */ private static ResourceBundle INTERNAL_MESSAGES = ResourceBundle.getBundle(DEFAULT_BUNDLE, Locale.getDefault(), Messages.class.getClassLoader()); Messages() { } /** * 別のプロパティファイルを読み込ませるテスト用のメソッド * * @param bundlePath * テスト用のプロパティファイル * @param clazz * プロパティファイルが配置されているディレクトリに存在するクラス */ static void setupForTest(String bundlePath, Class<?> clazz) { INTERNAL_MESSAGES = ResourceBundle.getBundle(bundlePath, Locale.getDefault(), clazz.getClassLoader()); } /** * メッセージを取得します。 * * @param key * プロパティファイルに記述したメッセージのキー * @param parameters * メッセージに埋め込むプレースフォルダの値 * @return メッセージ */ public static String getMessage(String key, Object... parameters) { String entry = INTERNAL_MESSAGES.getString(key); return MessageFormat.format(entry, parameters); } static Enumeration<String> getKeys() { return INTERNAL_MESSAGES.getKeys(); } static Locale getLocale() { return INTERNAL_MESSAGES.getLocale(); } @Override public String provideMessage(String key, Object... parameters) { return getMessage(key, parameters); } }
true
c5e0d22907a8c49383c4119a95b00e246e20a11a
Java
imrenagi/rojak-api
/service-auth/src/main/java/id/rojak/auth/infrastructure/service/BcryptEncryptionService.java
UTF-8
794
2.203125
2
[ "MIT" ]
permissive
package id.rojak.auth.infrastructure.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; /** * Created by inagi on 8/1/17. */ @Component public class BcryptEncryptionService implements EncryptionService { private final static Logger log = LoggerFactory.getLogger(BcryptEncryptionService.class); private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); @Override public String encryptedValue(String plainText) { return encoder.encode(plainText); } @Override public boolean matches(String plainText, String encryptedText) { return encoder.matches(plainText, encryptedText); } }
true
7338c602d623fdabedf3f028405c206eb2f5f4fd
Java
ashkmrptl/PracticeApplication
/src/main/java/com/akp/gfg/practice/mathandalgos/AddTwoFractions.java
UTF-8
993
3.5
4
[]
no_license
package com.akp.gfg.practice.mathandalgos; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class AddTwoFractions { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] arr = br.readLine().split("\\s+"); addFraction(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]), Integer.parseInt(arr[2]), Integer.parseInt(arr[3])); } br.close(); } static void addFraction(int num1, int den1, int num2, int den2) { int resd, resn; resd = lcm(den1, den2); resn = num1 * (resd / den1) + num2 * (resd / den2); int k = gcd(resn, resd); resd = resd / k; resn = resn / k; System.out.println(resn + "/" + resd); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static int lcm(int a, int b) { return (a * b) / gcd(a, b); } }
true
2c508ab236c8092444f0cc463199d944d3fb6ef8
Java
awebneck/phlogiston
/src/main/java/com/jeremypholland/phlogiston/common/entities/EntityGentledOcelot.java
UTF-8
328
2.046875
2
[]
no_license
package com.jeremypholland.phlogiston.common.entities; import net.minecraft.world.World; /** * Created by jeremy on 12/9/15. */ public class EntityGentledOcelot extends EntityGentled { public static final String UL_NAME = "gentledOcelot"; public EntityGentledOcelot(World worldIn) { super(worldIn); } }
true
a1d7eb4f54713f86c33fd5783f59283bd59307a2
Java
paolocaviedes/ArquitecturaSistemas
/Solemne1/Solemne1-ejb/src/java/Solemne1/Device.java
UTF-8
1,337
2.5625
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 Solemne1; import java.util.ArrayList; /** * * @author Paolo-Acer */ public class Device { private String idDevice=""; private int latitude; private int longitude; private ArrayList<Medicion> Medicion; public String getIdDevice() { return idDevice; } public void setIdDevice(String idDevice) { this.idDevice = idDevice; } public int getLatitude() { return latitude; } public void setLatitude(int latitude) { this.latitude = latitude; } public int getLongitude() { return longitude; } public void setLongitude(int longitude) { this.longitude = longitude; } public ArrayList<Medicion> getMedicion() { return Medicion; } public void setMedicion(ArrayList<Medicion> Medicion) { this.Medicion = Medicion; } public String devolverMediciones(){ String mediciones=""; for (int i=0;i<getMedicion().size();i++){ mediciones+=getMedicion().get(i).imprimir(); //notas+=i<getNotas().size()-1?",":""; } return mediciones; } }
true
5daa04747ba9b9cd918532e546fa5a59f4b8eccf
Java
How-Bout-No/completeconfig
/common/src/main/java/io/github/how_bout_no/completeconfig/extensions/clothbasicmath/ClothBasicMathGuiExtension.java
UTF-8
1,046
2.375
2
[ "Apache-2.0" ]
permissive
package io.github.how_bout_no.completeconfig.extensions.clothbasicmath; import io.github.how_bout_no.completeconfig.data.ColorEntry; import io.github.how_bout_no.completeconfig.extensions.GuiExtension; import io.github.how_bout_no.completeconfig.gui.cloth.Provider; import me.shedaniel.clothconfig2.api.ConfigEntryBuilder; import me.shedaniel.math.Color; import java.util.Collection; import java.util.Collections; final class ClothBasicMathGuiExtension implements GuiExtension { @Override public Collection<Provider> getProviders() { return Collections.singletonList(Provider.create(ColorEntry.class, (ColorEntry<Color> entry) -> ConfigEntryBuilder.create() .startColorField(entry.getText(), entry.getValue()) .setAlphaMode(entry.isAlphaMode()) .setDefaultValue(entry.getDefaultValue().getColor()) .setTooltip(entry.getTooltip()) .setSaveConsumer2(entry::setValue), Color.class)); } }
true
8cb8b70c03a72adee840bf87747cee652a6acf21
Java
mapstruct/mapstruct
/processor/src/test/java/org/mapstruct/ap/test/injectionstrategy/shared/CustomerRecordEntity.java
UTF-8
734
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.injectionstrategy.shared; import java.util.Date; /** * @author Sjaak Derksen */ public class CustomerRecordEntity { private Date registrationDate; private CustomerEntity customer; public Date getRegistrationDate() { return registrationDate; } public void setRegistrationDate(Date registrationDate) { this.registrationDate = registrationDate; } public CustomerEntity getCustomer() { return customer; } public void setCustomer(CustomerEntity customer) { this.customer = customer; } }
true
a85a6b51cd2241f63ab40da080fbe2059bc91780
Java
xuj1210/general
/src/unit2/forLoopPractice/Avg5.java
UTF-8
420
3.390625
3
[]
no_license
package unit2.forLoopPractice; import codehs.*; public class Avg5 extends ConsoleProgram{ public void run() { double sum = 0; for(int counter = 0; counter <= 4; counter++){ double number = readDouble("Enter a number: "); sum = sum + number; } double answer = sum / (double)5; System.out.println("The average of the 5 numbers is " + answer); } }
true
4829b6a89509ee3cd6071d0dd7dc554a02076d26
Java
anilgauda/hybrid-cloud-container-mgmt
/libraries/configurevm/src/main/java/ie/ncirl/container/manager/library/configurevm/strategy/ApplicationWeightedStrategy.java
UTF-8
7,700
2.5
2
[]
no_license
package ie.ncirl.container.manager.library.configurevm.strategy; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; import ie.ncirl.container.manager.library.configurevm.ContainerConfig; import ie.ncirl.container.manager.library.configurevm.model.ApplicationModel; import ie.ncirl.container.manager.library.configurevm.model.Container; import ie.ncirl.container.manager.library.configurevm.model.ContainersList; import ie.ncirl.container.manager.library.configurevm.model.DeploymentModel; import ie.ncirl.container.manager.library.configurevm.model.VMModel; public class ApplicationWeightedStrategy implements WeightedStrategy { public static Logger logger = Logger.getLogger(ApplicationWeightedStrategy.class.getName()); /** * Deploy Application taking number of applications to be deployed as a baseline to calculate the weight. * * @param deploymentList the deployment list * @param weightInPercent the weight in percent * @return the containers list */ @Override public ContainersList deploy(List<DeploymentModel> deploymentList, int weightInPercent) { ContainerConfig containerConfig = new ContainerConfig(); /** * Map to store number of applications to be deployed key: repoName value: * number of applicationData related to each repo **/ Map<String, Integer> appNumberMap = new HashMap<>(); /** * Map to store details of applicationData to be undeployed key : repoName value: * queue of all vms to be undeployed **/ Map<String, Queue<VMModel>> appVMMapToDeploy = new HashMap<>(); /** * Map to store details of applicationData to be deployed key : repoName value: * queue of all vms to be deployed **/ Map<String, Queue<VMModel>> appVMapToUndeploy = new HashMap<>(); /** * Map to store details of containerids to be undeployed : repoName value: * queue of all containerids to be deployed **/ Map<String, Queue<String>> appContainerMap = new HashMap<>(); Map<String,ApplicationModel> applicationMap=new HashMap<>(); ArrayList<Container> deployedContainers=new ArrayList<>(); ArrayList<Container> unDeployedContainers =new ArrayList<>(); ContainersList containerList=new ContainersList(); for (DeploymentModel model : deploymentList) { Container container = model.getContainer(); ApplicationModel app = container.getApplication(); VMModel undeployVM = container.getServer(); VMModel deployVM = model.getOptimalVM(); String imageName = app.getName(); if (appNumberMap.containsKey(imageName)) { appNumberMap.put(imageName, appNumberMap.get(imageName) + 1); } else { appNumberMap.put(imageName, 1); } if (appVMapToUndeploy.containsKey(imageName)) { Queue<VMModel> undeployList = appVMapToUndeploy.get(imageName); undeployList.add(undeployVM); appVMapToUndeploy.put(imageName, undeployList); } else { Queue<VMModel> undeployList = new LinkedList<>(); undeployList.add(undeployVM); appVMapToUndeploy.put(imageName, undeployList); } if (appVMMapToDeploy.containsKey(imageName)) { Queue<VMModel> deployList = appVMMapToDeploy.get(imageName); deployList.add(deployVM); appVMMapToDeploy.put(imageName, deployList); } else { Queue<VMModel> deployList = new LinkedList<>(); deployList.add(deployVM); appVMMapToDeploy.put(imageName, deployList); } if (appContainerMap.containsKey(imageName)) { Queue<String> containerIds = appContainerMap.get(imageName); containerIds.add(container.getId()); appContainerMap.put(imageName, containerIds); } else { Queue<String> containerIds = new LinkedList<>(); containerIds.add(container.getId()); appContainerMap.put(imageName, containerIds); } applicationMap.put(imageName, app); } /** Weighted value percent Deployment **/ appNumberMap.forEach((key, value) -> { logger.log(Level.INFO, String.format(" Weighted Application Statergy key: %s value: %s", key, value)); /** Calculate the Number of server that is to be deployed first **/ double numberOfServer = Math.ceil((float) (value.floatValue() * (weightInPercent / 100.0))); logger.log(Level.INFO, String.format(" Number of Servers %s", numberOfServer)); ApplicationModel applicationModel = applicationMap.get(key); for (int i = 0; i < numberOfServer; i++) { // Deploy Vms Container deployedContainer=new Container(); Container unDeployedContainer=new Container(); VMModel vm = appVMMapToDeploy.get(key).poll(); if (vm != null) { try { deployedContainer.setId(containerConfig.startContainers(vm.getPrivateKey(), vm.getUsername(), vm.getHost(), applicationModel.getRegistryImageUrl()).get(0)); deployedContainer.setServer(vm); deployedContainer.setApplication(applicationMap.get(key)); } catch (Exception e) { logger.log(Level.SEVERE, "Error Occured While Starting Container"); } } // Undeploy Vms vm = appVMapToUndeploy.get(key).poll(); String containerId = appContainerMap.get(key).poll(); if (vm != null) { List<String> containerIDs = new ArrayList<>(); containerIDs.add(containerId); try { containerConfig.stopContainers(vm.getPrivateKey(), vm.getUsername(), vm.getHost(), containerIDs); unDeployedContainer.setId(containerId); unDeployedContainer.setServer(vm); unDeployedContainer.setApplication(applicationMap.get(key)); } catch (Exception e) { logger.log(Level.SEVERE, "Error Occured While Stopping Container"); } } appNumberMap.put(key, appNumberMap.get(key) - 1); deployedContainers.add(deployedContainer); unDeployedContainers.add(unDeployedContainer); } }); /*** Application Sleep for health Checks **/ try { Thread.sleep(10000); } catch (InterruptedException e1) { } logger.log(Level.INFO, String.format("current map val after calc: %s", appNumberMap.toString())); /** Deploy remaining Application **/ appNumberMap.forEach((key, value) -> { for (int i = 0; i < value; i++) { // Deploy Vms Container deployedContainer=new Container(); Container unDeployedContainer=new Container(); ApplicationModel applicationModel = applicationMap.get(key); VMModel vm = appVMMapToDeploy.get(key).poll(); if (vm != null) { try { deployedContainer.setId(containerConfig.startContainers(vm.getPrivateKey(), vm.getUsername(), vm.getHost(), applicationModel.getRegistryImageUrl()).get(0)); deployedContainer.setServer(vm); deployedContainer.setApplication(applicationMap.get(key)); } catch (Exception e) { logger.log(Level.SEVERE, "Error Occured While Starting Container"); } } // Undeploy Vms vm = appVMapToUndeploy.get(key).poll(); String containerId = appContainerMap.get(key).poll(); if (vm != null) { List<String> containerIDs = new ArrayList<>(); containerIDs.add(containerId); try { containerConfig.stopContainers(vm.getPrivateKey(), vm.getUsername(), vm.getHost(), containerIDs); unDeployedContainer.setId(containerId); unDeployedContainer.setServer(vm); unDeployedContainer.setApplication(applicationMap.get(key)); } catch (Exception e) { logger.log(Level.SEVERE, "Error Occured While Stopping Container"); } } deployedContainers.add(deployedContainer); unDeployedContainers.add(unDeployedContainer); } }); containerList.setDeployedContainers(deployedContainers); containerList.setUndeployedContainers(unDeployedContainers); return containerList; } }
true
2089f992c89903836c006a4d4d0910354669d951
Java
zhangdu2000/SpringMVCmovie
/src/main/java/com/licyun/dao/UserPermissionDao.java
UTF-8
452
1.710938
2
[]
no_license
package com.licyun.dao; import com.licyun.model.User; import com.licyun.model.UserPermission; import com.licyun.model.UserRole; /** * Created by 李呈云 * Description: * 2016/10/18. */ public interface UserPermissionDao { String findPermissionsByEmail(String email); Long insertPermissions(UserPermission userPermission); Long updatePermissions(UserPermission userPermission); Long deletePermissionsByEmail(String email); }
true
883b711f572abdc5275bc5987c32bfcf79bb5c37
Java
marcondesmacaneiro/academico
/src/main/java/br/com/yanaga/samples/academico/domain/CursoRepository.java
UTF-8
164
1.53125
2
[ "Apache-2.0" ]
permissive
package br.com.yanaga.samples.academico.domain; import me.yanaga.winter.data.jpa.Repository; public interface CursoRepository extends Repository<Curso, Long> { }
true
b1d497a009a5bdb043673b6ac81a6ad6bb0d1c48
Java
Dwopplee/CS111
/PS11/src/Question2.java
UTF-8
1,149
3.46875
3
[]
no_license
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Question2 { public static void main (String[] args) throws FileNotFoundException { Scanner sysIn = new Scanner (System.in); System.out.println("Movie search by year range. Enter two years."); int y1 = sysIn.nextInt(); int y2 = sysIn.nextInt(); System.out.println("Movies with short names that were released between " + y1 + " and " + y2); Scanner fileIn = new Scanner(new File("db.txt")); int count = 0; while (fileIn.hasNextLine()) { String movie = fileIn.nextLine(); int year = fileIn.nextInt(); fileIn.nextLine(); fileIn.nextLine(); if (year >= y1 && year <= y2) { if (movie.length() < 6) { System.out.println(movie); count++; } } } if (count == 0) { System.out.println("No matching movies found!"); } else { System.out.println("Number of matches: " + count); } } }
true
83c9f7d58228b978acdc6ddf56c54711af935b03
Java
liesnychevskyi/selenium_core_full_automation
/src/main/java/selenium_core/helpers/selenium_grid/SeleniumGridTest.java
UTF-8
1,601
2.46875
2
[]
no_license
package selenium_core.helpers.selenium_grid; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.Test; import java.net.MalformedURLException; import java.net.URL; public class SeleniumGridTest { @Test public void chromeTest() throws MalformedURLException { //1. Define desire capabilities: DesiredCapabilities cap = new DesiredCapabilities(); cap.setBrowserName("chrome"); cap.setPlatform(Platform.MAC); // cap.setPlatform(Platform.WIN10); //2. Chrome option definition ChromeOptions options = new ChromeOptions(); options.merge(cap); // Just join the options + cap //3. HUB address String hubUrl = "http://192.168.1.19:4444/wd/hub"; //4. WebDriver instance WebDriver driver = new RemoteWebDriver(new URL(hubUrl),options); //------------------------------------------------//test driver.get("http://www.facebook.com"); System.out.println(driver.getTitle()); // DesiredCapabilities cap = DesiredCapabilities.chrome(); // ChromeOptions options = new ChromeOptions(); // cap.setCapability(ChromeOptions.CAPABILITY,options); // RemoteWebDriver driver= new RemoteWebDriver(new URL("http://192.168.1.19:4444/wd/hub"), cap); // driver.get("http://www.facebook.com"); // System.out.println(driver.getTitle()); } }
true
f8301575eb9e3faf99a757bf6d49a436c907c091
Java
REGnosys/rosetta-code-generators
/default-cdm-generators/src/main/java/org/isda/cdm/generators/CDMRosettaSetup.java
UTF-8
708
1.765625
2
[ "Apache-2.0" ]
permissive
package org.isda.cdm.generators; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Provider; import com.regnosys.rosetta.RosettaRuntimeModule; import com.regnosys.rosetta.RosettaStandaloneSetup; import com.regnosys.rosetta.generator.external.ExternalGenerators; public final class CDMRosettaSetup extends RosettaStandaloneSetup { public final class CDMRuntimeModule extends RosettaRuntimeModule { @Override public Class<? extends Provider<ExternalGenerators>> provideExternalGenerators() { return DefaultExternalGeneratorsProvider.class; } } @Override public Injector createInjector() { return Guice.createInjector(new CDMRuntimeModule()); } }
true
0d7abe4c87dec7dd9d44a96efeddac7b1dfe80ba
Java
rcarvalhoxavier/moviedb
/src/com/moviedb/model/Movie.java
UTF-8
7,905
2.15625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.moviedb.model; import java.io.Serializable; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Entity; import javax.persistence.Id; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author rcarvalhoxavier */ @Entity public class Movie implements Serializable { @Id private String imdbid; private String title; private String director; private String writer; private String actors; private String plot; private String posterUrl; private String runtime; private double rating; private int votes; private String genres; private int year; private String imdburl; private String tagline; private boolean watched; /** * * @return */ public String getTagline() { return tagline; } public void setTagline(String tagline) { this.tagline = tagline; } public String getActors() { return actors; } public void setActors(String actors) { this.actors = actors; } public String getDirector() { return director; } public void setDirector(String director) { this.director = director; } public String getPlot() { return plot; } public void setPlot(String plot) { this.plot = plot; } public String getPosterUrl() { return posterUrl; } public void setPosterUrl(String posterUrl) { this.posterUrl = posterUrl; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getGenres() { return genres; } public void setGenres(String genres) { this.genres = genres; } public String getImdbid() { return imdbid; } public void setImdbid(String imdbid) { this.imdbid = imdbid; } public String getImdburl() { return imdburl; } public void setImdburl(String imdburl) { this.imdburl = imdburl; } public double getRating() { return rating; } public void setRating(double rating) { this.rating = rating; } public String getRuntime() { return runtime; } public void setRuntime(String runtime) { this.runtime = runtime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getVotes() { return votes; } public void setVotes(int votes) { this.votes = votes; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public boolean isWatched() { return watched; } public void setWatched(boolean watched) { this.watched = watched; } public Movie() { } public Movie(JSONObject json, SearchAPI api) throws JSONException { if (json != null) { switch (api) { case AppIMDB: JSONObject js = null; JSONArray ja = null; json = json.getJSONObject(Imdb.data); this.imdbid = json.getString(Imdb.tconst); this.imdburl = Imdb.imdb + this.imdbid; this.rating = json.get(Imdb.rating) != null ? json.getDouble(Imdb.rating) : 0.0; this.votes = json.getInt(Imdb.numVotes); js = json.getJSONObject(Imdb.runtime); this.runtime = String.valueOf(js != null ? js.get(Imdb.time) : ""); this.title = json.getString(Imdb.title); this.year = json.getInt(Imdb.year); this.tagline = json.get(Imdb.tagline) != null ? json.getString(Imdb.tagline) : ""; this.plot = json.getJSONObject(Imdb.plot) != null ? json.getJSONObject(Imdb.plot).getString(Imdb.outline) : ""; ja = json.getJSONArray(Imdb.genres); this.genres = ja.toString().replaceAll("\\[|\\]", "").replaceAll("\\\"", ""); js = json.getJSONObject(Imdb.image); this.posterUrl = js != null ? js.getString(Imdb.url) : ""; ja = json.get(Imdb.directors) != null ? json.getJSONArray(Imdb.directors) : new JSONArray(); this.director = ja.toString(Imdb.name); ja = json.get(Imdb.writers) != null ? json.getJSONArray(Imdb.writers) : new JSONArray(); this.writer = ja.toString(Imdb.name); ja = json.get(Imdb.cast) != null ? json.getJSONArray(Imdb.cast) : new JSONArray(); this.actors = ja.toString(Imdb.name); break; case AppIMDBFind: this.imdbid = json.getString(Imdb.imdbFind_tconst); this.imdburl = Imdb.imdb + this.imdbid; this.title = json.getString(Imdb.title).replace("&#x27;", "'"); String description = json.optString(Imdb.imdbFind_description); Pattern pattern = Pattern.compile("(19|20)\\d\\d"); Matcher mYear = pattern.matcher(description); if (mYear.find()) { this.year = Integer.parseInt(mYear.group(0)); } //this.posterUrl = json.getJSONObject(Imdb.image) != null ? json.getJSONObject(Imdb.image).getString(Imdb.url) : ""; break; case mediaImdb: this.imdbid = json.getString(Imdb.mediaImdb_tconst); this.actors = json.getString(Imdb.mediaImdb_cast); this.title = json.getString(Imdb.mediaImdb_title); this.year = json.getInt(Imdb.mediaImdb_year); ja = json.get(Imdb.mediaImdb_image) != null ? json.getJSONArray(Imdb.mediaImdb_image) : new JSONArray(); this.posterUrl = ja != null ? ja.getString(0) : ""; break; } } } @Override public String toString() { return "Movie{" + "imdbid=" + imdbid + ", title=" + title + ", year=" + year + ", rating=" + rating + '}'; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Movie other = (Movie) obj; if ((this.imdbid == null) ? (other.imdbid != null) : !this.imdbid.equals(other.imdbid)) { return false; } if ((this.genres == null) ? (other.genres != null) : !this.genres.equals(other.genres)) { return false; } if ((this.imdburl == null) ? (other.imdburl != null) : !this.imdburl.equals(other.imdburl)) { return false; } if (this.votes != other.votes) { return false; } if ((this.runtime == null) ? (other.runtime != null) : !this.runtime.equals(other.runtime)) { return false; } if ((this.title == null) ? (other.title != null) : !this.title.equals(other.title)) { return false; } if (this.year != other.year) { return false; } if (Double.doubleToLongBits(this.rating) != Double.doubleToLongBits(other.rating)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + (this.imdbid != null ? this.imdbid.hashCode() : 0); return hash; } }
true
eb3f17e41db1dce50fe12b9b3d35cfd61f5209f7
Java
Mononofu/OOP
/Gruppe/Aufgabe2/oop/Infrastructure.java
UTF-8
235
2.34375
2
[]
no_license
package oop; public class Infrastructure { public Infrastructure(String description) { this.description = description; } public Boolean provides(Infrastructure i) { return false; } protected String description; }
true
239404cfa517aad678bba891b27bf48d3f562773
Java
Kopilov/multiplatformconfig
/src/main/java/com/github/kopilov/multiplatformconfig/MultiplatformConfigBuilder.java
UTF-8
4,306
2.578125
3
[ "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference", "NTP", "LLVM-exception", "CC0-1.0", "CC-BY-4.0", "Zlib", "BSD-3-Clause", "LicenseRef-scancode-protobuf", "ZPL-2.1", "OpenSSL", "JSON", "BSL-1.0", "Apache-2.0", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
package com.github.kopilov.multiplatformconfig; import java.io.File; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import net.harawata.appdirs.AppDirsFactory; import org.apache.commons.configuration2.CompositeConfiguration; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.SystemConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.Parameters; import org.apache.commons.configuration2.ex.ConfigurationException; /** * * @author Kopilov */ public class MultiplatformConfigBuilder { public static final AtomicBoolean testMode = new AtomicBoolean(false); private static PropertiesConfiguration processPropertiesFile(File configFile, boolean autoSave) throws ConfigurationException { final var paramsFactory = new Parameters(); final var configProperties = paramsFactory.properties(); configProperties.setFile(configFile); final var configBuilder = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(configProperties); if (autoSave && !configFile.exists()) { try { configFile.getParentFile().mkdirs(); configFile.createNewFile(); } catch (IOException ex) { throw new ConfigurationException("Could not create config in autosave mode", ex); } } if (!configFile.exists()) { return null; } configBuilder.setAutoSave(autoSave); return configBuilder.getConfiguration(); } public static Configuration buildConfig( boolean portableByDefault, boolean autosaveByDefault, String appName, String appVersion, String configFileName ) throws ConfigurationException { final var systemConfiguration = new SystemConfiguration(); CompositeConfiguration config;// = new CompositeConfiguration(); final var portable = systemConfiguration.getBoolean("multiplatformconfig.portable", portableByDefault); final var autosave = systemConfiguration.getBoolean("multiplatformconfig.autosave", autosaveByDefault); if (portable || testMode.get()) { //read configuration from file in current working directory, enable autosave final var portableConfig = processPropertiesFile(new File(configFileName + ".properties"), autosave); if (autosave) { config = new CompositeConfiguration(portableConfig); } else { config = new CompositeConfiguration(); if (portableConfig != null) { config.addConfiguration(portableConfig); } } config.addConfigurationFirst(systemConfiguration); } else { final var appDirs = AppDirsFactory.getInstance(); //read configuration from file in user home directory, enable autosave final var userConfigFile = new File(appDirs.getUserConfigDir(appName, appVersion, null) + File.separator + configFileName + ".properties"); final var userConfig = processPropertiesFile(userConfigFile, autosave); if (autosave) { config = new CompositeConfiguration(userConfig); } else { config = new CompositeConfiguration(); if (userConfig != null) { config.addConfiguration(userConfig); } } config.addConfigurationFirst(systemConfiguration); //read configuration from file in system distribution, do not save for (String directory: appDirs.getSiteConfigDir(appName, appVersion, null, true).split(":")) { final var systemConfigFile = new File(directory + File.separator + configFileName + ".properties"); final var systemConfig = processPropertiesFile(systemConfigFile, false); if (systemConfig != null) { config.addConfiguration(systemConfig); } } } return config; } }
true
62130d59179743c3666ffb4c4c3168c1a88f4e3a
Java
bogdan-csoregi/pos
/fifth/src/main/java/com/acme/apps/pos/PointOfSale.java
UTF-8
2,285
2.8125
3
[]
no_license
package com.acme.apps.pos; import java.util.ArrayList; import java.util.List; public class PointOfSale { public static final double FED_TAX = 0.05; public static final double COMERCIAL_TAX = 0.08; private Catalog catalog; private Display display; private Receip receip = new Receip(); private List<Receip> receipsCach = new ArrayList<Receip>(); private List<Receip> receipsCard = new ArrayList<Receip>(); public PointOfSale(Catalog catalog, Display display) { this.catalog = catalog; this.display = display; } public void scan(String code) { if ("".equals(code)) { display.printEmptyCodeMessage(); } else { printProductForCode(code); } } private void printProductForCode(String code) { Product product = catalog.getProduct(code); if (product == null) { display.printCodeNotFound(code); } else { Double fedTax = product.getPrice() * FED_TAX; Double commercialTax = 0.0; if (product.isNeedsCommercialTax()) { commercialTax = product.getPrice() * COMERCIAL_TAX; } Double finalPrice = product.getPrice() + fedTax + commercialTax; receip.addNewPrice(product.getPrice(), product.isNeedsCommercialTax(), fedTax, commercialTax); display.printPrice(finalPrice); } } public void payWithCash() { pay(receipsCach); } public void payWithCard() { pay(receipsCard); } private void pay(List<Receip> receips) { if (receip.isEmpty()) { throw new IllegalStateException("No item to pay."); } receips.add(receip); for (ReceipItem item : receip.getItems()) { String line = "$" + item.getPrice() + " G"; if (item.isHasCommercialTax()) { line += "P"; } display.write(line); } display.write("Total: $" + receip.getTotalWithoutTax()); display.write("GST: $" + receip.getGST()); display.write("PST: $" + receip.getPST()); display.write("Grand Total: $" + receip.getTotalWithTax()); receip = new Receip(); } public List<Receip> getCashReport() { List<Receip> result = new ArrayList<Receip>(receipsCach); receipsCach.clear(); return result; } public List<Receip> getCardReport() { List<Receip> result = new ArrayList<Receip>(receipsCard); receipsCard.clear(); return result; } public void setDisplay(MockDisplay display) { this.display = display; } }
true
682bc2d679850247ddf799cdb78386238a1a8397
Java
liveqmock/base_framework
/Server/xingzhen-xz/xingzhen-xz-service/src/main/java/com/hisign/xingzhen/xz/service/impl/GroupBackupServiceImpl.java
UTF-8
10,348
1.6875
2
[]
no_license
package com.hisign.xingzhen.xz.service.impl; import cn.jmessage.api.message.MessageType; import com.alibaba.fastjson.JSONObject; import com.hisign.bfun.benum.BaseEnum; import com.hisign.bfun.bexception.BusinessException; import com.hisign.bfun.bif.BaseMapper; import com.hisign.bfun.bif.BaseRest; import com.hisign.bfun.bif.BaseServiceImpl; import com.hisign.bfun.bmodel.Conditions; import com.hisign.bfun.bmodel.JsonResult; import com.hisign.bfun.bmodel.UpdateParams; import com.hisign.bfun.butils.JsonResultUtil; import com.hisign.xingzhen.common.constant.Constants; import com.hisign.xingzhen.common.util.DateUtil; import com.hisign.xingzhen.common.util.IpUtil; import com.hisign.xingzhen.common.util.StringUtils; import com.hisign.xingzhen.nt.api.model.JMBean; import com.hisign.xingzhen.nt.api.model.MsgBean; import com.hisign.xingzhen.nt.api.service.NtService; import com.hisign.xingzhen.sys.api.model.SysDict; import com.hisign.xingzhen.sys.api.model.SysUserInfo; import com.hisign.xingzhen.sys.api.service.SysDictService; import com.hisign.xingzhen.sys.api.service.SysUserService; import com.hisign.xingzhen.xz.api.entity.Group; import com.hisign.xingzhen.xz.api.entity.GroupBackup; import com.hisign.xingzhen.xz.api.entity.XzLog; import com.hisign.xingzhen.xz.api.model.GroupBackupModel; import com.hisign.xingzhen.xz.api.model.GroupModel; import com.hisign.xingzhen.xz.api.param.GroupBackupParam; import com.hisign.xingzhen.sys.api.param.SysUserInfoParam; import com.hisign.xingzhen.xz.api.service.GroupBackupService; import com.hisign.xingzhen.xz.mapper.GroupBackupMapper; import com.hisign.xingzhen.xz.mapper.GroupMapper; import com.hisign.xingzhen.xz.mapper.UsergroupMapper; import com.hisign.xingzhen.xz.mapper.XzLogMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 《专案组归档记录》 业务逻辑服务类 * * @author 何建辉 */ @Service("groupBackupService") public class GroupBackupServiceImpl extends BaseServiceImpl<GroupBackup, GroupBackupModel, String> implements GroupBackupService { private Logger log = LoggerFactory.getLogger(GroupBackupServiceImpl.class); @Autowired protected GroupBackupMapper groupBackupMapper; @Autowired private XzLogMapper xzLogMapper; @Autowired private GroupMapper groupMapper; @Autowired private SysUserService sysUserService; @Autowired private NtService ntService; @Autowired private UsergroupMapper usergroupMapper; @Autowired private SysDictService sysDictService; @Override protected BaseMapper<GroupBackup, GroupBackupModel, String> initMapper() { return groupBackupMapper; } @Override public JsonResult add(GroupBackup entity) throws BusinessException { return addNotNull(entity); } @Override public JsonResult addNotNull(GroupBackup entity) throws BusinessException { return super.addNotNull(entity); } @Override @Transactional(rollbackFor = Exception.class) public JsonResult add(List<GroupBackup> list) throws BusinessException { try { groupBackupMapper.batchInsert(list); } catch (Exception e) { throw new BusinessException(BaseEnum.BusinessExceptionEnum.INSERT, e); } return JsonResultUtil.success(); } @Override @Transactional(rollbackFor = Exception.class) public JsonResult update(UpdateParams params) throws BusinessException { try { groupBackupMapper.updateCustom(params); } catch (Exception e) { throw new BusinessException(BaseEnum.BusinessExceptionEnum.UPDATE, e); } return JsonResultUtil.success(); } @Override @Transactional(rollbackFor = Exception.class) public JsonResult delByIds(List<String> ids) throws BusinessException { try { groupBackupMapper.deleteByIds(ids); } catch (Exception e) { throw new BusinessException(BaseEnum.BusinessExceptionEnum.DELETE, e); } return JsonResultUtil.success(); } @Override @Transactional(rollbackFor = Exception.class) public JsonResult delBy(Conditions conditions) throws BusinessException { try { groupBackupMapper.deleteCustom(conditions); } catch (Exception e) { throw new BusinessException(BaseEnum.BusinessExceptionEnum.DELETE, e); } return JsonResultUtil.success(); } @Override @Transactional(rollbackFor=Exception.class) public JsonResult backup(GroupBackupParam param) throws BusinessException { Date now=new Date(); //判断是否归档 GroupBackup entity = new GroupBackup(); Group group = new Group(); String backupLogMsg = "撤销归档"; if (param.getBackupStatus().equals(Constants.YES)){ BeanUtils.copyProperties(param,entity); entity.setId(StringUtils.getUUID()); entity.setCreatetime(now); entity.setBackupTime(now); entity.setDeleteflag(Constants.DELETE_FALSE); long i = groupBackupMapper.insertNotNull(entity); if (i<1){ return error(BaseEnum.BusinessExceptionEnum.INSERT.Msg()); } backupLogMsg = "归档"; }else { param.setBackupStatus(Constants.NO); } //获取用户信息 SysUserInfo user = sysUserService.getUserInfoByUserId(param.getCreator()); if (user==null){ log.error("该用户不存在,[user=?]",user); return error("抱歉,该用户不存在,请刷新页面再试!"); } //同时更新专案组 GroupModel gm = groupMapper.findById(param.getGroupid()); if (gm==null){ return error("对不起,该专案组不存在!"); } BeanUtils.copyProperties(gm,group); group.setBackupStatu(param.getBackupStatus()); group.setLastupdatetime(now); if (param.getBackupStatus().equals(Constants.YES)) { group.setBackupTime(now); group.setBackupReason(param.getBackupReason()); } else{ group.setBackupTime(null); group.setBackupReason(""); } long num = groupMapper.update(group); //更新小组信息-子小组全部与父专案组一致 UpdateParams updateParams = new UpdateParams(Group.class); Conditions conditions = new Conditions(Group.class); Conditions.Criteria criteria = conditions.createCriteria(); criteria.add(Group.GroupEnum.pgroupid.get(), BaseEnum.ConditionEnum.EQ,gm.getId()) .add(Group.GroupEnum.deleteflag.get(), BaseEnum.ConditionEnum.EQ,Constants.DELETE_FALSE); if (param.getBackupStatus().equals(Constants.YES)) { updateParams.add(new String[]{Group.GroupEnum.backupTime.get(),Group.GroupEnum.backupStatu.get(),Group.GroupEnum.lastupdatetime.get()} ,new Object[]{group.getBackupTime(),param.getBackupStatus(),group.getLastupdatetime()}); } else{ updateParams.add(new String[]{Group.GroupEnum.backupTime.get(),Group.GroupEnum.backupStatu.get(),Group.GroupEnum.lastupdatetime.get()} ,new Object[]{"",param.getBackupStatus(),group.getLastupdatetime()}); } updateParams.setConditions(conditions); groupMapper.updateCustom(updateParams); if (num<1){ throw new BusinessException(BaseEnum.BusinessExceptionEnum.INSERT); } try { //极光推送,不需要回滚 JMBean jmBean = new JMBean(StringUtils.getUUID(), Constants.SEND_CONNECT_CASE_INFO,Constants.JM_FROM_TYPE_ADMIN, Constants.JM_TARGET_TYPE_GROUP, MessageType.CUSTOM.getValue(), param.getCreator(), gm.getJmgid()); //msgBody Map<String, Object> map = new HashMap<>(); map.put("groupId",param.getGroupid()); map.put("msgType",Constants.SEND_GROUP_BACKUP_INFO); map.put("text","专案组撤销归档"); if (param.getBackupStatus().equals(Constants.YES)){ map.put("text","专案组归档"); //获取归档理由的字典 SysDict dict = sysDictService.getDictByPKAndDK("GDYY", param.getBackupReason()); if (dict!=null){ map.put("backupReason",dict.getValue()); }else{ map.put("backupReason","空"); } } map.put("creator",param.getCreator()); map.put("createName",user.getUserName()); map.put("createTime", DateUtil.getDateTime(now)); jmBean.setMsg_body(JSONObject.toJSONString(map)); ntService.sendJM(jmBean); MsgBean bean = new MsgBean(); //发送信息提醒 String text = StringUtils.concat(backupLogMsg,":您所在专案组[", gm.getGroupname(), "]已经",backupLogMsg); bean.setMsgId(StringUtils.getUUID()); bean.setReceiverType(String.valueOf(Constants.ReceiveMessageType.TYPE_3)); bean.setMsgContent(text); bean.setPublishId(param.getCreator()); bean.setPublishName(user.getUserName()); //获取组内成员 SysUserInfoParam info = new SysUserInfoParam(); info.setGroupId(gm.getId()); info.setInGroup(true); List<SysUserInfo> userList = usergroupMapper.findGroupUserList(info); if (userList!=null && userList.size()!=0){ bean.setList(userList); } ntService.sendMsg(bean); //保存操作日志 XzLog xzLog = new XzLog(IpUtil.getRemotIpAddr(BaseRest.getRequest()),Constants.XZLogType.GROUP, "专案组"+backupLogMsg+"(ID:" + entity.getId()+")", entity.getCreator(), entity.getCreatetime(), gm.getId()); xzLogMapper.insertNotNull(xzLog); } catch (Exception e) { log.info("保存操作日志失败:",e); } return success(); } }
true
e477f68fc079e8810b2417617fcb4a1f88adf641
Java
Jacob-W21/PaintingPlace
/src/data/ColorPicker.java
UTF-8
328
3
3
[]
no_license
package data; public class ColorPicker { public enum Choices { Black, White, Red, Green, Blue; } static Choices choice = Choices.Black; public static Choices getColor() { return choice; } public static void setChoice(Choices colorChoice) { ColorPicker.choice = colorChoice; } }
true
97ccc51f6e63e3bcca60dd66f3b0496de9040446
Java
Warlordius/beast
/src/main/java/com/github/beast/parser/Parser.java
UTF-8
3,500
2.90625
3
[]
no_license
package com.github.beast.parser; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedList; import java.util.List; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.Segment; import net.htmlparser.jericho.Source; import com.github.beast.page.Link; import com.github.beast.page.Page; import com.github.beast.util.Utility; /** * A singleton class representing a parser to extract information from a HTML * document. The parsing engine provided by Jericho Parser. <code>Parser</code> * provides general <i>title</i> and <i>link</i> extracting capabilities and may * be used for any HTML document. * * @author Štefan Sabo * @version 1.0 * * @see <a href="http://jerichohtml.sourceforge.net">Jericho parser</a> */ public class Parser { /** Instance of a singleton class. */ private static Parser instance; /** * Constructor of the <code>Parser</code> class. Is private because * <code>Parser</code> is a singleton class. */ protected Parser() { } /** * Returns instance of the <code>Parser</code> singleton class. If no * instance exists, new instance is created. * * @return instance of the singleton class */ public static Parser getInstance() { if (instance == null) { instance = new Parser(); } return instance; } /** * Extracts all HTML {@link Link links} from a given {@link Page}. All * relative links are changed to absolute and protocol is prefixed in order * to obtain valid absolute URLs. * * @param page the page to be processed * @return list of outgoing links in the processed page * @see #parseLinks(Segment) */ public List<Link> parseLinks(final Page page) { Source source = new Source(page.getCode()); String hostUrl = page.getUrl().getProtocol() + "://" + page.getUrl().getHost(); List<Link> links = parseLinks(source, hostUrl); return links; } /** * Extracts a <i>title</i> attribute of the given {@link Page}. * * @param page the page to be processed * @return the title of the given page */ public String parseTitle(final Page page) { Source source = new Source(page.getCode()); Element title = source.getFirstElement("title"); return title.getContent().toString().trim(); } /** * Extracts all HTML {@link Link links} from a given {@link Segment} of a * page. All relative links are changed to absolute and protocol is prefixed * in order to obtain valid absolute URLs. * * @param segment the segment of a HTML document to be processed * @param hostUrl the URL of containing document, needed in order to handle * relative links * @return list of outgoing links in the processed segment */ protected List<Link> parseLinks(final Segment segment, final String hostUrl) { List<Link> links = new LinkedList<Link>(); String anchorText; String urlText; URL url = null; List<Element> elements; if (segment == null) { return links; } else { elements = segment.getAllElements("a "); } for (Element element : elements) { anchorText = element.getContent().toString(); urlText = element.getStartTag().getAttributeValue("href"); if (urlText != null) { if (urlText.startsWith("/")) { urlText = hostUrl + urlText; } try { url = Utility.stringToURL(urlText); Link newLink = new Link(anchorText, url); links.add(newLink); } catch (MalformedURLException e) { System.err.println("Malformed URL: " + urlText); } } } return links; } }
true
780960ffa67e765098e6eaac919264c1dc5f0cdf
Java
PavelEzhkov/otus-java-2018-08-EzhkovP
/homework5/src/main/java/GC.java
UTF-8
1,811
2.75
3
[]
no_license
import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.HashSet; import java.util.List; import java.util.Set; public class GC { static final Set<String> YOUNG_GC = new HashSet<String>(4); static final Set<String> OLD_GC = new HashSet<String>(4); static { // young generation GC names YOUNG_GC.add("Copy"); YOUNG_GC.add("PS Scavenge"); YOUNG_GC.add("ParNew"); YOUNG_GC.add("G1 Young Generation"); // old generation GC names OLD_GC.add("MarkSweepCompact"); OLD_GC.add("PS MarkSweep"); OLD_GC.add("ConcurrentMarkSweep"); OLD_GC.add("G1 Old Generation"); } public static void printGCstatic(){ long minorCount = 0; long minorTime = 0; long majorCount = 0; long majorTime = 0; List<GarbageCollectorMXBean> mxBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean gc : mxBeans){ long count = gc.getCollectionCount(); if (count >= 0){ if (YOUNG_GC.contains(gc.getName())){ minorCount += count; majorTime += gc.getCollectionTime(); } else if (OLD_GC.contains(gc.getName())){ majorCount += count; majorTime += gc.getCollectionTime(); } } } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("MinorGC -> Count: ").append(minorCount) .append(", Time (ms): ").append(minorTime) .append(", MajorGC -> Count: ").append(majorCount) .append(", Time (ms): ").append(majorTime); System.out.println(stringBuilder); } }
true
4d77f02f02078688fb7ddae66295a2ec3df151bd
Java
nik-ovchinnikov/katalog-server
/src/main/java/com/niki/katalog/DAO/IDeletedItemDAO.java
UTF-8
469
2.140625
2
[]
no_license
package com.niki.katalog.DAO; import com.niki.katalog.entity.DeletedItem; import java.util.List; public interface IDeletedItemDAO { List<DeletedItem> findAll(); void delete(String itemKey); void add(DeletedItem item); void update(DeletedItem item); int getIdByKey(String key); DeletedItem find(int id); List<DeletedItem> getDeletedItemsByStorage(String storageName); List<DeletedItem> getDeletedItemsByType(String typeName); }
true
e0f2caea56cf3d789844accb2acef3592181334d
Java
BruceDbigmowang/kpi2
/src/main/java/com/cx/kpi2/pojo/Bussiness.java
UTF-8
882
2.1875
2
[]
no_license
package com.cx.kpi2.pojo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; @Entity @Table(name="bussinessCategory") @JsonIgnoreProperties({"handler","hibernateLazyInitializer"}) public class Bussiness { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) int id; @Column(name = "bussiness") String bussiness; @Column(name = "category") String category; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBussiness() { return bussiness; } public void setBussiness(String bussiness) { this.bussiness = bussiness; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
true
0aedf53ac35a8e1b24e61d47488853930537ca38
Java
vcaldas/folsomiaCounter
/src/main/java/com/vcaldas/Folsomia_Counter/AppDev.java
UTF-8
1,316
3.328125
3
[]
no_license
package com.vcaldas.Folsomia_Counter; import java.io.File; import java.io.FilenameFilter; public class AppDev { private static File INPUTDIR = new File("/Users/caldas/Dropbox/Photos Folsomia"); private static int NFiles; private static File[] listOfFiles; public static void main(final String... args) { // Populate File array listOfFiles = getFiles(INPUTDIR,".jpg"); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { System.out.println("File " + listOfFiles[i].getName()); } else if (listOfFiles[i].isDirectory()) { System.out.println("Directory " + listOfFiles[i].getName()); } } NFiles = listOfFiles.length; System.out.println(NFiles); } /** * Returns an File array containing all files of a given directory * that meets the extension criteria. * * @param inputdir a directory (File) * @param extension the image extension to filter (e.g. ".JPG") * @return the File array */ private static File[] getFiles(File inputdir, String extension) { return inputdir.listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(extension.toLowerCase()); } }); } }
true
bd711c0f629f2695eb35e65edb23149ac7cdb4d0
Java
benjatouf/repo
/src/main/java/irepository/ICompagnieAerienneVolRepository.java
UTF-8
161
1.734375
2
[]
no_license
package irepository; import metier.CompagnieAerienneVol; public interface ICompagnieAerienneVolRepository extends IRepository<CompagnieAerienneVol, Long> { }
true
e11cba25409f72dbab32929502425f340aefdb37
Java
wesley-fly/mediaengine-app
/Android/MediaEgnineApp/app/src/main/java/com/internal/demo/android/ui/AudioTalkingActivity.java
UTF-8
6,863
2.09375
2
[]
no_license
package com.internal.demo.android.ui; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.internal.demo.R; import com.internal.demo.android.utility.CallAudioHelper; import com.internal.mediasdk.CallState; import com.internal.mediasdk.MediaEngineSDK; import com.internal.mediasdk.RecCallType; public class AudioTalkingActivity extends BaseActivity { private static final String TAG = AudioTalkingActivity.class.getSimpleName(); private String m_callId; private String m_dstId; private int is_callee = 0; private int mute = 1; private int hold = 1; private int speaker = 0; private TextView callStatusTextView; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { String status = (String) msg.obj; callStatusTextView.setText(status); } }; private AppSimpleListener appSimpleListener = new AppSimpleListener() { @Override public void onReceiveCallEvent(String callId, String callerId, String calleeId, String callerName, int media, int callType) { if (callType == RecCallType.RECEIVE_CALL_TYPE_MISSED_CALL && callId.equals(m_callId)) { MyApplication.isTalking = false; finish(); } } @Override public void onCallStateEvent(String callId, int state, int reason) { Log.d(TAG, "onCallStateEvent callId: " + callId + ",state: " + state + ",reason: " + reason); if (!callId.equals(m_callId)) { Log.e(TAG,"错误的通知事件,CALL ID不正确!"); return; } Message msg = handler.obtainMessage(); switch (state) { case CallState.CALL_STATE_HANGUP: msg.obj = "通话结束"; CallAudioHelper.stopRingback(); if (reason == 2 || reason == 3)// 被叫忙 { //Toast.makeText(AudioTalkingActivity.this,"对方正在通话中",Toast.LENGTH_SHORT).show(); // showToastMessage("对方正在通话中"); Log.e(TAG,"对方正在通话中!"); } MediaEngineSDK.getInstance().setAudioOutput(0); MyApplication.isTalking = false; finish(); break; case CallState.CALL_STATE_ANSWER: CallAudioHelper.stopRingback(); msg.obj = "音频通话中"; break; case CallState.CALL_STATE_HOLD: if (reason == 0) { msg.obj = "保持中"; } else { msg.obj = "音频通话中"; } break; case CallState.CALL_STATE_INITIATE: CallAudioHelper.startRingback(); msg.obj = "通话连接中"; break; default: break; } handler.sendMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_audio_talking); ((MyApplication) getApplication()).registerEventListener(appSimpleListener); Intent intent = getIntent(); if (intent != null) { m_callId = intent.getStringExtra("call_id"); m_dstId = intent.getStringExtra("dst_id"); is_callee = intent.getIntExtra("is_callee", 0); } callStatusTextView = (TextView) findViewById(R.id.tv_status); TextView accountTextView = (TextView) findViewById(R.id.tv_account); accountTextView.setText(m_dstId); Button hangupButton = (Button) findViewById(R.id.btn_hangup); final Button muteButton = (Button) findViewById(R.id.btn_mute); final Button holdButton = (Button) findViewById(R.id.btn_hold); final Button speakerButton = (Button) findViewById(R.id.btn_speaker); speakerButton.setText("扬声器"); MediaEngineSDK.getInstance().setAudioOutput(0); muteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaEngineSDK.getInstance().muteCall(m_callId, mute); if (mute == 1) { muteButton.setText("取消静音"); mute = 0; } else { muteButton.setText("静音"); mute = 1; } } }); holdButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaEngineSDK.getInstance().holdCall(m_callId, hold); if (hold == 1) { holdButton.setText("恢复通话"); hold = 0; } else { holdButton.setText("保持"); hold = 1; } } }); hangupButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CallAudioHelper.stopRingback(); new Thread(new Runnable() { public void run() { MediaEngineSDK.getInstance().hangupCall(m_callId); } }).start(); MyApplication.isTalking = false; finish(); } }); speakerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (speaker == 1) { speakerButton.setText("扬声器"); speaker = 0; } else { speakerButton.setText("关闭扬声器"); speaker = 1; } MediaEngineSDK.getInstance().setAudioOutput(speaker); } }); if(is_callee == 1) { int ret = MediaEngineSDK.getInstance().answerCall(m_callId); if (ret != 0) { Log.e(TAG, "接听来电失败, " + ret); MyApplication.isTalking = false; finish(); } } } @Override protected void onDestroy() { super.onDestroy(); ((MyApplication) getApplication()).unRegisterEventListener(appSimpleListener); } }
true
c6c3eec9ef8ccf73bb74b200756c72b589ed1764
Java
MichaelMyw/SSM
/src/main/java/com/mjava/ssm/controller/CategoryController.java
UTF-8
1,965
2.109375
2
[]
no_license
package com.mjava.ssm.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.mjava.ssm.po.Category; import com.mjava.ssm.service.CategoryService; import com.mjava.ssm.util.Page; @Controller public class CategoryController { @Autowired CategoryService categoryService; @RequestMapping("/listCategory") public ModelAndView listCategory(Page page) { PageHelper.offsetPage(page.getStart(), 5); List<Category> list = categoryService.listCategory(); int total = (int) new PageInfo<>(list).getTotal(); page.calculateLast(total); ModelAndView mav = new ModelAndView(); mav.addObject("list", list); mav.setViewName("listCategory"); return mav; } @RequestMapping("/addCategory") public ModelAndView addCategory(Category c) { categoryService.addCategory(c); ModelAndView mav = new ModelAndView(); mav.setViewName("redirect:listCategory"); return mav; } @RequestMapping("/deleteCategory") public ModelAndView deleteCategory(int id) { categoryService.deleteCategory(id); ModelAndView mav = new ModelAndView(); mav.setViewName("redirect:listCategory"); return mav; } @RequestMapping("/editCategory") public ModelAndView editCategory(int id) { Category c = categoryService.getCategory(id); ModelAndView mav = new ModelAndView(); mav.addObject("c", c); mav.setViewName("editCategory"); return mav; } @RequestMapping("/updateCategory") public ModelAndView updateCategory(Category c) { categoryService.updateCategory(c); ModelAndView mav = new ModelAndView(); mav.setViewName("redirect:listCategory"); return mav; } }
true
f2257a4574624b152294534cf5a3fffd95392faa
Java
kocsenc/software-project-day
/src/TeamLead.java
UTF-8
5,469
3.328125
3
[ "MIT" ]
permissive
import java.util.ArrayList; /** * Team Lead Class * <p/> * Work on: Conor */ public class TeamLead extends Thread { private static int leads = 0; private final ArrayList<Developer> developers = new ArrayList<Developer>(); private final int id; public long entered; private SoftwareProjectManager manager; private int devArrived = 0; private Firm firm; private boolean locked = false; // Waits private Condition waitForDevs = new Condition() { @SuppressWarnings("unused") private boolean isMet() { return devArrived == 3; } }; private Condition waitForUnlock = new Condition() { @SuppressWarnings("unused") private boolean isMet() { return !locked; } }; public TeamLead(String name) { this.id = TeamLead.leads; TeamLead.leads += 1; } /** * Adds a developer to the TL's team * @param dev - developer to add */ public synchronized void addDeveloper(Developer dev) { developers.add(dev); } /** * Sets the Team Lead's manager * @param man - manager to set to */ public synchronized void setManager(SoftwareProjectManager man) { this.manager = man; } /** * Sets the Team Lead's firm * @param firm - firm to set to */ public synchronized void setFirm(Firm firm) { this.firm = firm; } /** * Knocks on the PM's door for the morning meeting */ public synchronized void knock() { try { wait(); } catch (InterruptedException e) { } this.devArrived += 1; } public void run() { try { // Wait up to 30 mins Thread.sleep(Util.randomInBetween(0, FirmTime.HALF_HOUR.ms())); // Arrive & knock on manager's door this.entered = firm.getTime(); System.out.println(Util.timeToString(firm.getTime())+": TeamLead #" + this.id + " arrives."); manager.knock(); // Locks until released from meeting // Wait for the developers and start standup waitForDevs.waitUntilMet(10); firm.attemptJoin(); // Lock until we have room empty System.out.println(Util.timeToString(firm.getTime())+": TeamLead #" + this.id + " begins standup."); Thread.sleep(15 * FirmTime.MINUTE.ms()); System.out.println(Util.timeToString(firm.getTime())+": TeamLead #" + this.id + " ends standup."); // End Standup for (Developer dev : developers) { synchronized (dev) { dev.unlock(); synchronized (this) { notifyAll(); } } } // Wait until lunch while (firm.getTime() < FirmTime.HOUR.ms() * 4) { synchronized (this) { wait(10); } } // Go to lunch lock(); System.out.println(Util.timeToString(firm.getTime())+": TeamLead #" + this.id + " goes on lunch."); Thread.sleep(FirmTime.MINUTE.ms() * (30 + (int) Math.random() * 30)); System.out.println(Util.timeToString(firm.getTime())+": TeamLead #" + this.id + " ends lunch."); unlock(); // Wait until end of the day meeting while (firm.getTime() < FirmTime.HOUR.ms() * 8) { synchronized (this) { wait(10); } } // Attend Meeting lock(); System.out.println(Util.timeToString(firm.getTime())+": TeamLead #" + this.id + " goes to meeting."); firm.attemptJoin(); unlock(); // Finish up and leave while (firm.getTime() - this.entered < 8 * FirmTime.HOUR.ms()) { synchronized (this) { wait(10); } } lock(); System.out.println(Util.timeToString(firm.getTime())+": TeamLead #" + this.id + " goes home."); } catch (InterruptedException e1) { } } /** * Unlocks the teamlead */ public synchronized void unlock() { locked = false; } /** * Locks the teamlead */ public synchronized void lock() { waitForUnlock.waitUntilMet(10); locked = true; } /** * Developer calls this method when asking a question */ public synchronized void askedQuestion() { // 50% chance of coming up with the answer this.waitForUnlock.waitUntilMet(10); boolean canIAnswer = Util.randomInBetween(0, 1) == 2; // 10 minute wait only applies for the manager //Thread.sleep(FirmTime.MINUTE.ms() * 10); // See if we need to talk to the SPM incase we don't know the answer if (!canIAnswer) { this.askQuestion(); } } /** * Asks the Project Manager a question */ private synchronized void askQuestion() { this.lock(); this.manager.askQuestion(); unlock(); } /** * Gets list of developers under this team lead. * * @return list of developers under this team lead. */ public synchronized ArrayList<Developer> getDevelopers() { return developers; } }
true
def8a0f941952b6eff8c3feb21521fa66553358f
Java
probepark/intellij-community
/platform/util/src/com/intellij/util/containers/ObjectIntHashMap.java
UTF-8
452
2.515625
3
[ "Apache-2.0" ]
permissive
package com.intellij.util.containers; import gnu.trove.TObjectIntHashMap; /** * return -1 instead of 0 if no such mapping exists */ public class ObjectIntHashMap<K> extends TObjectIntHashMap<K> { public ObjectIntHashMap(int initialCapacity) { super(initialCapacity); } public ObjectIntHashMap() { super(); } @Override public final int get(K key) { int index = index(key); return index < 0 ? -1 : _values[index]; } }
true
1c4c240a35d0b4d413102a547f001d26f3095259
Java
PierrickJACQUETTE/TextDraw
/Source/Sym.java
UTF-8
424
1.75
2
[]
no_license
public enum Sym { EOF, DRAW, FORM_POLYGON, FORM_CIRCLE, FORM_ELLIPSE, OPEN_ACCOLADE, CLOSE_ACCOLADE, OPEN_POINT, CLOSE_POINT, INT, COMMA, COLOR, DEF, DEF_NAME, WRITE, PLUS, MOINS, MULT, DIV, OPEN_PARENTHESE, CLOSE_PARENTHESE, MOVE, REFLECT, ROTATE, EXTEND, AT, FROM, AROUND, OF, GROW, SPIN, POINT, SEMI, EXTENSION, RECOLOR, IN, AND; }
true
0c589aa7c2894ee3806b4addd6c39b3a56371af9
Java
raj-monty25/cozarbrepo
/cozarb/service/src/main/java/com/cozarb/paytm/response/bean/PaytmResponseBean.java
UTF-8
2,517
1.648438
2
[]
no_license
package com.cozarb.paytm.response.bean; public class PaytmResponseBean { protected String CURRENCY; protected String GATEWAYNAME; protected String RESPMSG; protected String BANKNAME; protected String PAYMENTMODE; protected String MID; protected String RESPCODE; protected String TXNID; protected String TXNAMOUNT; protected String TXNTYPE; protected String ORDERID; protected String STATUS; protected String BANKTXNID; protected String TXNDATE; protected String CHECKSUMHASH; protected String REFUNDAMT; public String getCURRENCY() { return CURRENCY; } public void setCURRENCY(String cURRENCY) { CURRENCY = cURRENCY; } public String getGATEWAYNAME() { return GATEWAYNAME; } public void setGATEWAYNAME(String gATEWAYNAME) { GATEWAYNAME = gATEWAYNAME; } public String getRESPMSG() { return RESPMSG; } public void setRESPMSG(String rESPMSG) { RESPMSG = rESPMSG; } public String getBANKNAME() { return BANKNAME; } public void setBANKNAME(String bANKNAME) { BANKNAME = bANKNAME; } public String getPAYMENTMODE() { return PAYMENTMODE; } public void setPAYMENTMODE(String pAYMENTMODE) { PAYMENTMODE = pAYMENTMODE; } public String getMID() { return MID; } public void setMID(String mID) { MID = mID; } public String getRESPCODE() { return RESPCODE; } public void setRESPCODE(String rESPCODE) { RESPCODE = rESPCODE; } public String getTXNID() { return TXNID; } public void setTXNID(String tXNID) { TXNID = tXNID; } public String getTXNAMOUNT() { return TXNAMOUNT; } public void setTXNAMOUNT(String tXNAMOUNT) { TXNAMOUNT = tXNAMOUNT; } public String getORDERID() { return ORDERID; } public void setORDERID(String oRDERID) { ORDERID = oRDERID; } public String getSTATUS() { return STATUS; } public void setSTATUS(String sTATUS) { STATUS = sTATUS; } public String getBANKTXNID() { return BANKTXNID; } public void setBANKTXNID(String bANKTXNID) { BANKTXNID = bANKTXNID; } public String getTXNDATE() { return TXNDATE; } public void setTXNDATE(String tXNDATE) { TXNDATE = tXNDATE; } public String getCHECKSUMHASH() { return CHECKSUMHASH; } public void setCHECKSUMHASH(String cHECKSUMHASH) { CHECKSUMHASH = cHECKSUMHASH; } public String getTXNTYPE() { return TXNTYPE; } public void setTXNTYPE(String tXNTYPE) { TXNTYPE = tXNTYPE; } public String getREFUNDAMT() { return REFUNDAMT; } public void setREFUNDAMT(String rEFUNDAMT) { REFUNDAMT = rEFUNDAMT; } }
true
7c3815735045d18e99270d6a27463fac3dcee433
Java
milovanovicd/Airplane-tickets-Java
/ProjectCommon/src/domain/Avion.java
UTF-8
3,950
2.515625
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 domain; import java.sql.ResultSet; import java.util.LinkedList; import java.util.Objects; /** * * @author dejanmilovanovic */ public class Avion implements DomainObject { private long avionID; private Avioprevoznik avioprevoznik; private String tipAviona; public Avion() { } public Avion(long avionID, Avioprevoznik avioprevoznik, String tipAviona) { this.avionID = avionID; this.avioprevoznik = avioprevoznik; this.tipAviona = tipAviona; } public String getTipAviona() { return tipAviona; } public void setTipAviona(String tipAviona) { this.tipAviona = tipAviona; } public long getAvionID() { return avionID; } public void setAvionID(long avionID) { this.avionID = avionID; } public Avioprevoznik getAvioprevoznik() { return avioprevoznik; } public void setAvioprevoznik(Avioprevoznik avioprevoznik) { this.avioprevoznik = avioprevoznik; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Avion other = (Avion) obj; if (this.avionID != other.avionID) { return false; } if (!Objects.equals(this.tipAviona, other.tipAviona)) { return false; } if (!Objects.equals(this.avioprevoznik, other.avioprevoznik)) { return false; } return true; } @Override public String getTableName() { return "avion"; } @Override public boolean isAutoincrement() { return true; } @Override public void setObjectId(long id) { this.avionID = id; } @Override public String getAttributeNamesForInsert() { String s = ""; s += "avioprevoznik_id"; s += ",tip_aviona"; return s; } @Override public String getAttributeValuesForInsert() { return avioprevoznik.getAvioprevoznikID() + ", '" + tipAviona +"'"; } @Override public long getId() { return this.avionID; } @Override public String getIdName() { return "avion_id"; } @Override public LinkedList<DomainObject> getListFromRs(ResultSet rs) throws Exception { LinkedList<DomainObject> list = new LinkedList<>(); while (rs.next()) { long avionId = rs.getLong("a.avion_id"); long avioprevoznikId = rs.getLong("ap.avioprevoznik_id"); String nazivAvioprevoznika = rs.getString("ap.naziv_avioprevoznika"); String avionTip = rs.getString("a.tip_aviona"); Avioprevoznik ap = new Avioprevoznik(avioprevoznikId, nazivAvioprevoznika); Avion avion = new Avion(avionId, ap, avionTip); list.add(avion); } return list; } @Override public String setQueryForUpdate() { return "UPDATE avion SET avioprevoznik_id = " + this.avioprevoznik.getAvioprevoznikID() + ", tip_aviona = '" + this.tipAviona+ "' WHERE avion_id = "+this.avionID; } @Override public String setQueryForSelect() { return "SELECT * FROM avion a\n" + "JOIN avioprevoznik ap ON (a.avioprevoznik_id = ap.avioprevoznik_id)"; } @Override public String toString() { return tipAviona; } @Override public String setQueryForDelete() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
true
ad44bad1912ec27803839a17bed647e603474545
Java
BhanukaUOM/Hackerrank-Algorithm-Solutions
/6. Graph Theory/10. Dijkstra: Shortest Reach 2.java
UTF-8
2,237
2.984375
3
[ "MIT" ]
permissive
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static int minresultance(int result[], boolean visited[], int V) { int min = 99999999; int min_index=-1; for (int v = 0; v < V; v++){ if (visited[v] == false && result[v] <= min) { min = result[v]; min_index = v; } } return min_index; } static int[] bfs(int n, int[][] edges, int s) { int[] result = new int[n]; for (int i=0; i<n; i++) result[i] = 99999999; result[s] = 0; boolean[] visited = new boolean[n]; int tmp = s; while(tmp != -1){ visited[tmp] = true; for(int i=0; i<n; i++){ if(edges[tmp][i]>0 && result[i] > result[tmp] + edges[tmp][i]){ result[i] = result[tmp] + edges[tmp][i]; } } tmp = minresultance(result, visited, n); } return result; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = in.nextInt(); for(int j = 0; j < q; j++){ int n = in.nextInt(); int m = in.nextInt(); int[][] edges = new int[n][n]; for(int i=0; i<m; i++){ int x = in.nextInt() - 1; int y = in.nextInt() - 1; int w = in.nextInt(); if (edges[x][y]==0 || edges[x][y]>w){ edges[x][y] = w; edges[y][x] = w; } } int s = in.nextInt() - 1; int[] result = bfs(n, edges, s); for (int i = 0; i < result.length; i++) { if (result[i] == 99999999) System.out.print("-1 "); else if (result[i] != 0) System.out.print(result[i] + " "); } System.out.println(""); } in.close(); } }
true
f0c357fbf0f8e1a9e27b9b064d3a966e234fd0ba
Java
reiern70/wiquery-jqplot
/src/test/java/nl/topicus/wqplot/web/pages/examples/CorePage.java
UTF-8
6,099
2.640625
3
[]
no_license
package nl.topicus.wqplot.web.pages.examples; import java.util.Arrays; import nl.topicus.wqplot.components.JQPlot; import nl.topicus.wqplot.data.NumberSeries; import nl.topicus.wqplot.data.NumberSeriesEntry; import nl.topicus.wqplot.data.SimpleNumberSeries; import nl.topicus.wqplot.options.PlotAxes; import nl.topicus.wqplot.options.PlotMarkerStyle; import nl.topicus.wqplot.options.PlotOptions; import nl.topicus.wqplot.options.PlotSeries; import nl.topicus.wqplot.options.PlotTick; import nl.topicus.wqplot.options.PlotTitle; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.model.util.ListModel; public class CorePage extends WebPage { private static final long serialVersionUID = 1L; public CorePage() { addPlot1(); addPlot2(); addPlot3(); addPlot4(); } private void addPlot1() { NumberSeries<Double, Double> l1 = new NumberSeries<Double, Double>(); for (double i = 0; i < 2 * Math.PI; i += 0.4) l1.addEntry(i, Math.cos(i)); NumberSeries<Double, Double> l2 = new NumberSeries<Double, Double>(); for (double i = 0; i < 2 * Math.PI; i += 0.4) l2.addEntry(i, 2 * Math.sin(i - 0.8)); NumberSeries<Double, Double> l3 = new NumberSeries<Double, Double>(); for (double i = 0; i < 2 * Math.PI; i += 0.4) l3.addEntry(i, 2.5 + Math.pow(i / 4, 2)); NumberSeries<Double, Double> l4 = new NumberSeries<Double, Double>(); for (double i = 0; i < 2 * Math.PI; i += 0.4) l4.addEntry(i, -2.5 - Math.pow(i / 4, 2)); @SuppressWarnings("unchecked") JQPlot chart1 = new JQPlot("chart1", new ListModel<NumberSeries<Double, Double>>(Arrays.asList(l1, l2, l3, l4))); PlotOptions chart1O = chart1.getOptions(); chart1O.setTitle("Line Style Options"); PlotSeries chart1series1 = chart1O.addNewSeries(); chart1series1.setLineWidth(2d); chart1series1.getMarkerOptions().setStyle(PlotMarkerStyle.diamond); PlotSeries chart1series2 = chart1O.addNewSeries(); chart1series2.setShowLine(false); chart1series2.getMarkerOptions().setSize(7d).setStyle(PlotMarkerStyle.diamond); PlotSeries chart1series3 = chart1O.addNewSeries(); chart1series3.getMarkerOptions().setStyle(PlotMarkerStyle.circle); PlotSeries chart1series4 = chart1O.addNewSeries(); chart1series4.setLineWidth(5d); chart1series4.getMarkerOptions().setSize(14d).setStyle(PlotMarkerStyle.filledSquare); add(chart1); } private void addPlot2() { NumberSeries<Double, Double> l1 = new NumberSeries<Double, Double>(); for (double i = 0; i < 2 * Math.PI; i += 0.1) l1.addEntry(i, Math.cos(i)); @SuppressWarnings("unchecked") JQPlot chart2 = new JQPlot("chart2", new ListModel<NumberSeries<Double, Double>>(Arrays.asList(l1))); PlotOptions chart2O = chart2.getOptions(); chart2O.setTitle(new PlotTitle("Shadow Options")); PlotSeries chart2series1 = chart2O.addNewSeries(); chart2series1.setLineWidth(5d); chart2series1.setShadowAngle(0d); chart2series1.setShadowOffset(1.5d); chart2series1.setShadowAlpha(0.08d); chart2series1.setShadowDepth(6); chart2series1.getMarkerOptions().setShow(false); add(chart2); } private void addPlot3() { NumberSeries<Double, Double> l1 = new NumberSeries<Double, Double>(); l1.addEntry(new NumberSeriesEntry<Double, Double>(1d, 1d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(1.5d, 2.25d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(2d, 4d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(2.5d, 6.25d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(3d, 9d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(3.5d, 12.25d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(4d, 16d)); SimpleNumberSeries<Double> l2 = new SimpleNumberSeries<Double>(25d, 17.5d, 12.25d, 8.6d, 6.0d, 4.2d, 2.9d); SimpleNumberSeries<Integer> l3 = new SimpleNumberSeries<Integer>(4, 25, 13, 22, 14, 17, 15); @SuppressWarnings("unchecked") JQPlot chart3 = new JQPlot("chart3", new ListModel(Arrays.asList(l1, l2, l3))); PlotOptions chart3O = chart3.getOptions(); chart3O.getLegend().setShow(true); chart3O.setTitle("Mixed Data Input Formats"); PlotSeries chart3series1 = chart3O.addNewSeries(); chart3series1.setLabel("Rising line"); chart3series1.setShowLine(false); chart3series1.getMarkerOptions().setStyle(PlotMarkerStyle.square); chart3O.addNewSeries().setLabel("Declining line"); PlotSeries chart3series3 = chart3O.addNewSeries(); chart3series3.setLabel("Zig Zag line"); chart3series3.setLineWidth(5d); chart3series3.setShowMarker(false); add(chart3); } private void addPlot4() { NumberSeries<Double, Double> l1 = new NumberSeries<Double, Double>(); l1.addEntry(new NumberSeriesEntry<Double, Double>(1d, 1d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(1.5d, 2.25d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(2d, 4d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(2.5d, 6.25d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(3d, 9d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(3.5d, 12.25d)); l1.addEntry(new NumberSeriesEntry<Double, Double>(4d, 16d)); SimpleNumberSeries<Double> l2 = new SimpleNumberSeries<Double>(25d, 12.5d, 6.25d, 3.125d); @SuppressWarnings("unchecked") JQPlot chart4 = new JQPlot("chart4", new ListModel(Arrays.asList(l1, l2))); PlotOptions chart4O = chart4.getOptions(); chart4O.getLegend().setShow(true); chart4O.setTitle("Customized Axes Ticks"); chart4O.getGrid().setBackground("#f3f3f3").setGridLineColor("#accf9b"); PlotSeries chart4series1 = chart4O.addNewSeries(); chart4series1.setLabel("Rising line"); chart4series1.getMarkerOptions().setStyle(PlotMarkerStyle.square); chart4O.addNewSeries().setLabel("Declining line"); PlotAxes chart4axes = chart4O.getAxes(); chart4axes.getXaxis().setTicks( Arrays.asList(new PlotTick(0, "zero"), new PlotTick(1, "one"), new PlotTick(2, "two"), new PlotTick(3, "three"), new PlotTick(4, "four"), new PlotTick(5, "five"))); chart4axes.getYaxis().setTicks(-5, 0, 5, 10, 15, 20, 25, 30).getTickOptions() .setFormatString("%d"); add(chart4); } }
true
dc0356a241d67b819f6faedf044d4f91fd8911d8
Java
radhakrishnan-iyer/intuit-product-service
/src/main/java/com/intuit/config/TimesheetConfig.java
UTF-8
440
1.882813
2
[]
no_license
package com.intuit.config; import com.intuit.service.IProductService; import com.intuit.service.TimesheetService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; @Profile("timesheet") public class TimesheetConfig { @Bean public IProductService validateService() { IProductService validateService = new TimesheetService(); return validateService; } }
true
a58789ae4ebf34805de71d40b497f36b877ba220
Java
MustafaYesilyurt/fabflix_full_stack
/parser_project/Movie.java
UTF-8
2,237
2.9375
3
[]
no_license
import java.util.ArrayList; public class Movie { private String xmlid; private String movieId; private String title; private String year; private String director; private String directorId; private ArrayList<String> genres; public Movie(){} public Movie(String id, String title, String year, String director, String directorId, ArrayList<String> genres) { this.xmlid = id; this.movieId = null; this.title = title; this.year = year; this.director = director; this.directorId = directorId; this.genres = genres; } public String getXmlId() { return xmlid; } public String getMovieId() { return movieId; } public String getDirector() { return director; } public String getDirectorId() { return directorId; } public String getTitle() { return title; } public String getYear() { return year; } public ArrayList<String> getGenres() {return genres;} public void setXmlId(String id) { this.xmlid = id; } public void setMovieId(String movieId) { this.movieId = movieId; } public void setDirector(String director) { this.director = director; } public void setDirectorId(String directorId) { this.directorId = directorId; } public void setTitle(String title) { this.title = title; } public void setYear(String year) { this.year = year; } public void setGenres(ArrayList<String> genres) { this.genres = genres; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Movie Details - "); sb.append("ID: " + getXmlId()); sb.append(", "); sb.append("Title: " + getTitle()); sb.append(", "); sb.append("Year: " + getYear()); sb.append(", "); for (int i = 0; i < genres.size(); i++) { if (i == 0) sb.append("Genres: "); sb.append(genres.get(i)); sb.append(", "); } sb.append("Director: " + getDirector()); sb.append(", "); sb.append("Director ID: "+ getDirectorId()); return sb.toString(); } }
true
a97591581876daf0cc6ac5f98d457ed5cbd98fdd
Java
kazyury/MementoWeaver
/MementoWeaver/src/nobugs/nolife/mw/ui/controller/MainMenuController.java
SHIFT_JIS
1,080
1.96875
2
[]
no_license
package nobugs.nolife.mw.ui.controller; import java.net.URL; import java.util.ResourceBundle; import nobugs.nolife.mw.AppMain; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.layout.AnchorPane; public class MainMenuController extends AnchorPane implements MWSceneController { private AppMain appl; // Cxgnh @FXML protected void installMaterial(ActionEvent e){appl.fwdInstallMaterial();} @FXML protected void generateMemento(ActionEvent e){appl.fwdInstalledMaterialList();} @FXML protected void modifyMemento(ActionEvent e){appl.fwdSelectMementoType();} @FXML protected void archive(ActionEvent e){appl.fwdSelectArchiveMemento();} @FXML protected void scanMaterial(ActionEvent e){appl.fwdScannedMementos();} @FXML protected void exit(ActionEvent e) {Platform.exit();} @Override public void initialize(URL arg0, ResourceBundle arg1) { // do nothing. } @Override public void setApplication(AppMain appMain, Object o) { appl = appMain; } }
true
787ef6feb12c08eeae7e6acec7bb8fb25f11a6b5
Java
ArGaLu/CursoJava
/Ejercicios/Guia1EstructuraControl/Ejercicio2WHILE.java
UTF-8
609
3.46875
3
[]
no_license
package primera_guia_variables_y_estructuras_de_control_COMPLETA; import java.util.Scanner; public class Ejercicio2WHILE { public static void main (String[]args){ Scanner scan = new Scanner(System.in); System.out.println("ingrese un numero"); int a=scan.nextInt(), cont=0, cont2=1; while(cont2<=a){ if (a%cont2==0){ cont++; } cont2++; } if (cont>2){ System.out.println("el numero no es primo"); } else{ System.out.println("el numero es primo"); } } }
true
f199360635783bab49ddc1e02206b806cf9fb1d6
Java
ErickBits/CajeroAutomaticoJava
/src/cajeroelectronico/ClaseConsulta.java
UTF-8
438
2.046875
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 cajeroelectronico; /** * * @author Mao-U */ public class ClaseConsulta extends ClaseMetodos { @Override public void Transacciones(){ System.out.println("Su Saldo actual es de:_" + getSaldo()); } }
true
45c201cc783e0120ec8268677d7405ce65615d18
Java
tnorbye/intellij-community
/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullabilityProblemKind.java
UTF-8
7,379
2.453125
2
[ "Apache-2.0" ]
permissive
package com.intellij.codeInspection.dataFlow; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.psi.*; import com.siyeh.ig.psiutils.ExpressionUtils; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.PropertyKey; import java.util.Objects; import java.util.function.Consumer; import static com.intellij.codeInspection.InspectionsBundle.BUNDLE; /** * Represents a kind of nullability problem * @param <T> a type of anchor element which could be associated with given nullability problem kind */ public class NullabilityProblemKind<T extends PsiElement> { private final String myName; private final String myNullLiteralMessage; private final String myNormalMessage; private NullabilityProblemKind(@NotNull String name) { myName = name; myNullLiteralMessage = null; myNormalMessage = null; } private NullabilityProblemKind(@NotNull String name, @NotNull @PropertyKey(resourceBundle = BUNDLE) String message) { this(name, message, message); } private NullabilityProblemKind(@NotNull String name, @NotNull @PropertyKey(resourceBundle = BUNDLE) String nullLiteralMessage, @NotNull @PropertyKey(resourceBundle = BUNDLE) String normalMessage) { myName = name; myNullLiteralMessage = InspectionsBundle.message(nullLiteralMessage); myNormalMessage = InspectionsBundle.message(normalMessage); } public static final NullabilityProblemKind<PsiMethodCallExpression> callNPE = new NullabilityProblemKind<>("callNPE"); public static final NullabilityProblemKind<PsiMethodReferenceExpression> callMethodRefNPE = new NullabilityProblemKind<>("callMethodRefNPE", "dataflow.message.npe.methodref.invocation"); public static final NullabilityProblemKind<PsiNewExpression> innerClassNPE = new NullabilityProblemKind<>("innerClassNPE", "dataflow.message.npe.inner.class.construction"); public static final NullabilityProblemKind<PsiExpression> fieldAccessNPE = new NullabilityProblemKind<>("fieldAccessNPE", "dataflow.message.npe.field.access.sure", "dataflow.message.npe.field.access"); public static final NullabilityProblemKind<PsiArrayAccessExpression> arrayAccessNPE = new NullabilityProblemKind<>("arrayAccessNPE", "dataflow.message.npe.array.access"); public static final NullabilityProblemKind<PsiElement> unboxingNullable = new NullabilityProblemKind<>("unboxingNullable", "dataflow.message.unboxing"); public static final NullabilityProblemKind<PsiExpression> assigningToNotNull = new NullabilityProblemKind<>("assigningToNotNull", "dataflow.message.assigning.null", "dataflow.message.assigning.nullable"); public static final NullabilityProblemKind<PsiExpression> storingToNotNullArray = new NullabilityProblemKind<>("storingToNotNullArray", "dataflow.message.storing.array.null", "dataflow.message.storing.array.nullable"); public static final NullabilityProblemKind<PsiExpression> nullableReturn = new NullabilityProblemKind<>("nullableReturn"); public static final NullabilityProblemKind<PsiExpression> nullableFunctionReturn = new NullabilityProblemKind<>("nullableFunctionReturn", "dataflow.message.return.nullable.from.notnull.function", "dataflow.message.return.nullable.from.notnull.function"); public static final NullabilityProblemKind<PsiElement> passingNullableToNotNullParameter = new NullabilityProblemKind<>("passingNullableToNotNullParameter"); public static final NullabilityProblemKind<PsiElement> passingNullableArgumentToNonAnnotatedParameter = new NullabilityProblemKind<>("passingNullableArgumentToNonAnnotatedParameter"); public static final NullabilityProblemKind<PsiElement> assigningNullableValueToNonAnnotatedField = new NullabilityProblemKind<>("assigningNullableValueToNonAnnotatedField"); // assumeNotNull problem is not reported, just used to force the argument to be not null public static final NullabilityProblemKind<PsiExpression> assumeNotNull = new NullabilityProblemKind<>("assumeNotNull"); /** * Creates a new {@link NullabilityProblem} of this kind using given anchor * @param anchor anchor to bind the problem to * @return newly created problem or null if anchor is null */ @Contract("null -> null; !null -> !null") public final NullabilityProblem<T> problem(@Nullable T anchor) { return anchor == null ? null : new NullabilityProblem<>(this, anchor); } /** * Returns the supplied problem with adjusted type parameter or null if supplied problem kind is not this kind * * @param problem problem to check * @return the supplied problem or null */ @SuppressWarnings("unchecked") @Nullable public final NullabilityProblem<T> asMyProblem(NullabilityProblem<?> problem) { return problem != null && problem.myKind == this ? (NullabilityProblem<T>)problem : null; } /** * Returns true if the kind of supplied problem is the same as this kind * * @param problem problem to check * @return true if the kind of supplied problem is the same as this kind */ public final boolean isMyProblem(@Nullable NullabilityProblem<?> problem) { return problem != null && problem.myKind == this; } /** * Executes given consumer if the supplied problem has the same kind as this kind * * @param problem a problem to check * @param consumer a consumer to execute. A problem anchor is supplied as the consumer argument. */ public void ifMyProblem(NullabilityProblem<?> problem, Consumer<T> consumer) { NullabilityProblem<T> myProblem = asMyProblem(problem); if (myProblem != null) { consumer.accept(myProblem.getAnchor()); } } @Override public String toString() { return myName; } /** * Represents a concrete nullability problem on PSI which consists of PSI element (anchor) and {@link NullabilityProblemKind}. * @param <T> a type of anchor element */ public static final class NullabilityProblem<T extends PsiElement> { private final @NotNull NullabilityProblemKind<T> myKind; private final @NotNull T myAnchor; NullabilityProblem(@NotNull NullabilityProblemKind<T> kind, @NotNull T anchor) { myKind = kind; myAnchor = anchor; } @NotNull public T getAnchor() { return myAnchor; } @NotNull public String getMessage() { if (myKind.myNullLiteralMessage == null || myKind.myNormalMessage == null) { throw new IllegalStateException("This problem kind has no message associated: " + myKind); } return myAnchor instanceof PsiExpression && ExpressionUtils.isNullLiteral((PsiExpression)myAnchor) ? myKind.myNullLiteralMessage : myKind.myNormalMessage; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof NullabilityProblem)) return false; NullabilityProblem<?> problem = (NullabilityProblem<?>)o; return myKind.equals(problem.myKind) && myAnchor.equals(problem.myAnchor); } @Override public int hashCode() { return Objects.hash(myKind, myAnchor); } @Override public String toString() { return "[" + myKind + "] " + myAnchor.getText(); } } }
true
82ce03a1710b6d19fc9d11a59a5d1ddd625e1ba3
Java
sandeshdahake/GameOfThronesOnSteroids
/src/test/java/com/sandeshdahake/game/saveGame/SaveGameServiceTest.java
UTF-8
1,461
2.40625
2
[]
no_license
package com.sandeshdahake.game.saveGame; import com.sandeshdahake.game.util.FileDeserializationException; import com.sandeshdahake.game.util.FileIOService; import com.sandeshdahake.game.util.FileSerializationException; import com.sandeshdahake.game.util.IFileIOService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; /** * @author sandeshDahake */ public class SaveGameServiceTest { private IFileIOService fileIOService; private ISaveGameService saveGameService; @Before public void setUp() { fileIOService = mock(FileIOService.class); saveGameService = new SaveGameService() .setFileIOService(fileIOService); } @Test public void saveGame() { try { saveGameService.saveGame(); verify(fileIOService).write(GameState.getInstance(), "game.got"); } catch (FileSerializationException e) { e.printStackTrace(); } } @Test public void loadGame() { try { saveGameService.loadGame(); verify(fileIOService).read(GameState.class, "game.got"); } catch (FileDeserializationException e) { e.printStackTrace(); } } @Test public void fileExists() { when(fileIOService.fileExists("game.got")).thenReturn(true); Assert.assertEquals(saveGameService.fileExists("game.got"), true); } }
true
4efe46e781f61c536ce3018bbdac823fd34f9051
Java
CSC422-Group-1/Repo
/ZombieWar/src/main/java/com/csc422/zombiewar/weapons/SubmachineGun.java
UTF-8
160
2.046875
2
[]
no_license
package com.csc422.zombiewar.weapons; //accuracy & damage of weapon public class SubmachineGun extends Weapon { public SubmachineGun() { super(15, 6); } }
true
189ec95978d48a96614098f91ee95391d66c050b
Java
lotockijj/fx
/src/main/java/coursera/DiceRolling.java
UTF-8
1,340
3.734375
4
[]
no_license
package coursera; import java.util.Random; /** * Created by Роман Лотоцький on 13.12.2016. */ public class DiceRolling { public void simpleSimulate(int rolls){ Random rand = new Random(); int twos = 0; int twelves = 0; for (int i = 0; i < rolls; i++) { int d1 = rand.nextInt(6) + 1; int d2 = rand.nextInt(6) + 1; if(d1 + d2 == 2){ twos += 1; } else if(d1 + d2 == 12){ twelves += 1; } } System.out.println("2's=\t" + twos + "\t" + 100*twos/rolls); System.out.println("12's=\t" + twelves + "\t" + 100*twelves/rolls); } public void simulate(int rolls){ Random rand = new Random(); int[] counts = new int[13]; for (int i = 0; i < rolls; i++) { int d1 = rand.nextInt(6) + 1; int d2 = rand.nextInt(6) + 1; //System.out.println(d1 + " " + d2); counts[d1 + d2] += 1; } for (int k = 2; k < counts.length; k++) { System.out.println(k + "'s=" + "\t" + counts[k] + "\t" + 100*counts[k]/rolls); } } public static void main(String[] args) { DiceRolling dice = new DiceRolling(); //dice.simpleSimulate(10); dice.simulate(1000); } }
true
db1316a5999bc7064beca2143ccfbf6b1c753f95
Java
MiaoDX/bp_java
/src/main/java/com/handANN/AreaLineChartWithXChart.java
UTF-8
3,503
2.765625
3
[]
no_license
package com.handANN; import org.knowm.xchart.*; import org.knowm.xchart.style.markers.SeriesMarkers; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Exchanger; import java.util.function.DoubleBinaryOperator; import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; /** * Created by miao on 2016/10/26. */ public class AreaLineChartWithXChart { public static void main(String[] args) throws InterruptedException, IOException { IRanGen ranGen = new RanGen(0); int num = 10; Function sinf = MatchingFunctions.sinF; Function same = ActivationFuntions.sameLambda; Function OnePlusSinPiX = MatchingFunctions.OnePlusSinPiX; FunctionFaux functionFaux = new FunctionFaux(ranGen, same, -2.0, 2.0, num); List<Double> x = functionFaux.getDomainValues(); List<Double> y1 = functionFaux.getFunctionValues(); functionFaux = new FunctionFaux(ranGen, sinf, -2.0, 2.0, num); List<Double> y2 = functionFaux.getFunctionValues(); show(x, y1, y2); } public static void show(List<List<Double>> xAndYs, String picName, List<String> lineNames) throws InterruptedException, IOException { assertThat(xAndYs.size()).isEqualTo(lineNames.size()+1); // Create Chart XYChart chart = new XYChartBuilder().width(800).height(600).title(picName).xAxisTitle("x").yAxisTitle("f").build(); for(int i = 0;i < lineNames.size(); i ++){ chart.addSeries(lineNames.get(i), xAndYs.get(0), xAndYs.get(i+1)).setMarker(SeriesMarkers.NONE);; } new SwingWrapper<XYChart>(chart).displayChart(); BitmapEncoder.saveBitmap(chart, "./" + picName, BitmapEncoder.BitmapFormat.PNG); Thread.sleep(5000); } public static void show(List<Double> x, List<Double> y1, String picName, String firstLineName) throws InterruptedException, IOException { // Create Chart XYChart chart = new XYChartBuilder().width(800).height(600).title("Check").xAxisTitle("x").yAxisTitle("f").build(); XYSeries seriesLiability = chart.addSeries(firstLineName, x, y1); seriesLiability.setMarker(SeriesMarkers.NONE); new SwingWrapper<XYChart>(chart).displayChart(); BitmapEncoder.saveBitmap(chart, "./" + picName, BitmapEncoder.BitmapFormat.PNG); Thread.sleep(5000); } public static void show(List<Double> x, List<Double> y1, List<Double> y2, String picName, String firstLineName, String secondLineName) throws InterruptedException, IOException { // Create Chart XYChart chart = new XYChartBuilder().width(800).height(600).title("Check").xAxisTitle("x").yAxisTitle("f").build(); XYSeries seriesLiability = chart.addSeries(firstLineName, x, y1); seriesLiability.setMarker(SeriesMarkers.NONE); chart.addSeries(secondLineName, x, y2); new SwingWrapper<XYChart>(chart).displayChart(); BitmapEncoder.saveBitmap(chart, "./" + picName, BitmapEncoder.BitmapFormat.PNG); Thread.sleep(5000); } public static void show(List<Double> x, List<Double> y1, List<Double> y2, String picName) throws InterruptedException, IOException { show(x, y1, y2, picName, "Should be", "We got"); } public static void show(List<Double> x, List<Double> y1, List<Double> y2) throws InterruptedException, IOException { show(x, y1, y2, "Our_answer", "Should be", "We got"); } }
true
dc77a42ff0f61f5f2ec00047771b5b0d444818f8
Java
osgee/goods
/src/cn/nudt/goods/service/impl/AdminServiceBean.java
UTF-8
2,165
2.296875
2
[]
no_license
package cn.nudt.goods.service.impl; import java.sql.SQLException; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.itcast.commons.CommonUtils; import cn.nudt.goods.bean.Admin; import cn.nudt.goods.dao.AdminDao; import cn.nudt.goods.dao.BookDao; import cn.nudt.goods.service.AdminService; @Service @Transactional public class AdminServiceBean implements AdminService { @Resource AdminDao adminDao; @Resource BookDao bookDao; final int managerLevel=1; public void updatePassword(String adminId, String newPass, String oldPass) { Admin admin = adminDao.findByAdminidAndPassword(adminId, oldPass); if (admin != null) { admin.setAdminpwd(newPass); adminDao.update(admin); } else { System.out.println("用户不存在!"); } } public Admin login(Admin admin) { if (admin==null) { return null; }else return adminDao.find(admin.getAdminname(), admin.getAdminpwd()); } public void activatioin(String code) { try { Admin admin = adminDao.findBy("activationCode",code); if (admin == null) throw new SQLException("无效的激活码!"); if (admin.isStatus()) throw new SQLException("您已经激活过了,不要二次激活!"); admin.setStatus(true); adminDao.add(admin); } catch (SQLException e) { throw new RuntimeException(e); } } public boolean ajaxValidateAdminname(String adminname) { Admin admin = adminDao.findBy("adminname", adminname); return admin == null; } public boolean ajaxValidateEmail(String email) { Admin admin =adminDao.findBy("email", email); return admin == null; } public void regist(Admin admin) { admin.setAdminId(CommonUtils.uuid()); //测试环境下设为真,生产环境中设为假 admin.setStatus(true); admin.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid()); adminDao.add(admin); } public Admin findByAdminId(String adminId) { return adminDao.findBy("adminId", adminId); } public boolean isManager(String adminId) { return adminDao.findBy("adminId", adminId).getAuthority()>=managerLevel; } }
true
0c520ff972504ce846459f7bd91df29c885c3cf1
Java
ivasandom/DP2-1920-G2-14
/src/main/java/org/springframework/samples/petclinic/repository/SpecialtyRepository.java
UTF-8
276
1.726563
2
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
package org.springframework.samples.petclinic.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.samples.petclinic.model.Specialty; public interface SpecialtyRepository extends CrudRepository<Specialty, Integer> { }
true
5f30ed3a59847a60f652aa7770fb1d0a8f67f0ed
Java
Axanndar/progettoEsame
/progetto-1-2014/src/it/uniroma3/model/Prodotto.java
UTF-8
1,539
2.671875
3
[]
no_license
package it.uniroma3.model; import java.util.List; import javax.persistence.*; @Entity @NamedQuery(name = "findAllProdotti", query = "SELECT p FROM Prodotto p") public class Prodotto { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false) private String nome; private Float prezzo; @Column(length = 2000) private String descrizione; @Column(nullable = false) private String codice; @ManyToMany(mappedBy = "prodotti") private List<Fornitore> fornitori; public Prodotto() { } public Prodotto(String nome, Float prezzo, String descrizione, String codice) { this.nome = nome; this.prezzo = prezzo; this.descrizione = descrizione; this.codice = codice; } // Getters & Setters public Long getId() { return id; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public String getCodice() { return this.codice; } public void setCodice(String codice) { this.codice = codice; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public Float getPrezzo() { return prezzo; } public void setPrezzo(Float prezzo) { this.prezzo = prezzo; } public boolean equals(Object obj) { Prodotto prodotto = (Prodotto) obj; return this.getCodice().equals(prodotto.getCodice()); } public int hashCode() { return this.codice.hashCode(); } public void setId(Long id) { this.id = id; } }
true
e78e5c77c407c187ae737cc34157c9ae8c347591
Java
mohangowda/JsonTest
/src/main/java/com/mohan/core/User.java
UTF-8
562
2.65625
3
[]
no_license
package com.mohan.core; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.io.*; public class User implements Serializable { private static final long serialVersionUID = 1L; public int age = 29; public String name = "mohan"; public List<String> messages = new ArrayList<String>() { { add("msg 1"); add("msg 2"); add("msg 3"); } }; //getter and setter methods @Override public String toString() { return "User [age=" + age + ", name=" + name + ", " + "messages=" + messages + "]"; } }
true
14321098909f92033e6803b9b55a7a784289769e
Java
zmldlut/Lab-dao
/src/com/zml/dao/impl/NodeTypeDaoImpl.java
UTF-8
1,109
2.53125
3
[]
no_license
package com.zml.dao.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.zml.dao.NodeTypeDao; import com.zml.model.NodeType; public class NodeTypeDaoImpl extends BaseDaoImpl implements NodeTypeDao{ @Override public boolean doCreate(NodeType obj) { // TODO Auto-generated method stub return false; } @Override public NodeType findDao(NodeType obj) { // TODO Auto-generated method stub return null; } @Override public ArrayList<NodeType> getTypes() { ArrayList<NodeType> result = new ArrayList<NodeType>(); String sql = "select * from node_type"; try { this.pstmt = this.conn.prepareStatement(sql); ResultSet rs = this.pstmt.executeQuery(); while(rs.next()){ NodeType type = new NodeType(); type.setId(rs.getInt(1)); type.setType(rs.getString(2)); result.add(type); } } catch (SQLException e) { e.printStackTrace(); } finally{ try{ this.pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } return result; } }
true
232999e6e4984b8ee7dbbaa174c4f0c22790f619
Java
Nikkey-Liu/owl
/src/main/java/cn/wan/owl/config/DataSourceConfig.java
UTF-8
426
1.65625
2
[]
no_license
package cn.wan.owl.config; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.context.annotation.Configuration; @Data @NoArgsConstructor @AllArgsConstructor @Configuration public class DataSourceConfig { private String url = "jdbc:mysql://localhost:3306/myowldatabase"; private String username = "root"; private String password = "123456"; }
true
5cc8117a3dbfcfcd7c51d47c90e11ebf902facec
Java
HiagoW/SIJOGA
/src/java/dao/FaseProcessoDAO.java
UTF-8
1,253
2.21875
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 dao; import beans.Processo; import beans.FaseProcesso; import beans.Usuario; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import util.HibernateUtil; /** * * @author hiago */ public class FaseProcessoDAO { public FaseProcessoDAO() { } public FaseProcesso buscarFase(String descricao) { Session session = HibernateUtil.getSessionFactory().openSession(); Query query = session.createQuery("from FaseProcesso where descricao = :descricao"); query.setParameter("descricao", descricao); FaseProcesso fase = (FaseProcesso) query.uniqueResult(); session.close(); return fase; } public List<FaseProcesso> buscarFasesAdv() { Session session = HibernateUtil.getSessionFactory().openSession(); Query query = session.createQuery("from FaseProcesso where id = 1 or id = 2"); List<FaseProcesso> fases = query.list(); session.close(); return fases; } }
true
0626ac594be89d63ee13aa30650332291c1c9692
Java
hcsoft/lijiang-xinnonghe
/src/com/szgr/util/TaxPayerService.java
GB18030
2,944
2.09375
2
[]
no_license
package com.szgr.util; import org.apache.log4j.Logger; import org.springframework.util.Assert; import com.szgr.commonbus.IDeptManagerInfo; import com.szgr.commonbus.TempTaxpayerDeptManagerInfo; import com.szgr.framework.authority.datarights.SystemUserAccessor; import com.szgr.framework.core.ApplicationContextUtils; import com.szgr.framework.core.ApplicationException; import com.szgr.framework.core.database.proc.ProcSingleValue; import com.tdgs.vo.RegTaxregistmainVO; public class TaxPayerService { private static final Logger log = Logger.getLogger(TaxPayerService.class); private static IDeptManagerInfo deptManagerInfo = new TempTaxpayerDeptManagerInfo(); public static OrgInfo getOrgInfo(final String taxpayerid){ OrgInfo result = null; if(isTempTaxpayer(taxpayerid)){ String userorgcode = SystemUserAccessor.getInstance().getTaxorgcode(); String taxorgcode = userorgcode.substring(0,6)+"0000"; String taxorgsupcode = taxorgcode.substring(0,4)+"000000"; String taxdeptcode = deptManagerInfo.getTaxdeptcode(); String taxmanagercode = deptManagerInfo.getTaxmanagercode(); result = new OrgInfo(taxorgsupcode,taxorgcode,taxdeptcode,taxmanagercode); }else{ RegTaxregistmainVO regTaxVo = ApplicationContextUtils.getHibernateTemplate().get(RegTaxregistmainVO.class,taxpayerid); if(regTaxVo == null){ throw new ApplicationException("taxpayerid=["+taxpayerid+"]ȡעϢʧܣ"); } result = new OrgInfo(regTaxVo.getTaxorgsupcode(), regTaxVo.getTaxorgcode(), regTaxVo.getTaxdeptcode(), regTaxVo.getTaxmanagercode()); } String optorgcode = null; String optempcode = null; try{ optorgcode = SystemUserAccessor.getInstance().getTaxorgcode(); optempcode = SystemUserAccessor.getInstance().getTaxempcode(); }catch(NullPointerException ex){ } result.setOptorgcode(optorgcode); result.setOptempcode(optempcode); return result; } public static boolean isTempTaxpayer(String taxpayerid){ Assert.notNull(taxpayerid, "taxpayerid is not null!"); return taxpayerid.startsWith("T"); } public static String getTemporaryTaxpayerid(){ String orgcode = null; try{ orgcode = SystemUserAccessor.getInstance().getTaxorgcode(); }catch(NullPointerException ex){ throw new ApplicationException("ǰǷ޵½û", ex); } orgcode = orgcode.substring(0,6)+"0000"; return getTemporaryTaxpayerid(orgcode); } public static String getTemporaryTaxpayerid(final String taxorgcode) { log.info("taxorgcode =========== "+taxorgcode); ProcSingleValue proc = new ProcSingleValue(ProcConstants.SP_TEMPTAXPAYER,new Object[]{taxorgcode},true); Object result = proc.getSingleValue(); if(result == null){ throw new ApplicationException("ݻش["+taxorgcode+"]ȡʱʧܣ"); } log.info("ȡʱΪ=========="+result); return result.toString(); } }
true
fe3e179a1838ba3c802c31a4dc9c5973e33a589a
Java
fardhanardhi/rumahsakit
/src/rumahsakit/dao/ICrudTransaksi.java
UTF-8
635
1.929688
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 rumahsakit.dao; import java.util.ArrayList; import rumahsakit.entity.Transaksi; /** * * @author adan */ public interface ICrudTransaksi { public abstract void insert(Transaksi transaksi); public abstract void delete(int id); public abstract void update(Transaksi transaksi); public abstract ArrayList<Transaksi> ambilSemuaData(); public abstract ArrayList<Transaksi> selectWhere(String where); }
true
4ee48cbc9c9cc09473a0f84227c74de89189154a
Java
maymay7621/RongChat
/app/src/main/java/com/rongchat/activity/MyInfoActivity.java
UTF-8
2,007
2
2
[ "Apache-2.0" ]
permissive
package com.rongchat.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import com.rongchat.R; /** * Created by AMing on 16/3/25. * Company RongCloud */ public class MyInfoActivity extends BaseActivity implements View.OnClickListener { private RelativeLayout portraitRL, nameRL, numberRL, scannerCodeRL, sexRL, regionRL, myAddressRL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rc_ac_myinfo); initViews(); } private void initViews() { portraitRL = (RelativeLayout) findViewById(R.id.re_avatar); nameRL = (RelativeLayout) findViewById(R.id.re_name); numberRL = (RelativeLayout) findViewById(R.id.re_rcid); scannerCodeRL = (RelativeLayout) findViewById(R.id.re_scanner_code); sexRL = (RelativeLayout) findViewById(R.id.re_sex); regionRL = (RelativeLayout) findViewById(R.id.re_region); myAddressRL = (RelativeLayout) findViewById(R.id.re_address); portraitRL.setOnClickListener(this); nameRL.setOnClickListener(this); numberRL.setOnClickListener(this); scannerCodeRL.setOnClickListener(this); sexRL.setOnClickListener(this); regionRL.setOnClickListener(this); myAddressRL.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.re_avatar: break; case R.id.re_name: break; case R.id.re_rcid: break; case R.id.re_scanner_code: startActivity(new Intent(MyInfoActivity.this,GenerateCodeActivity.class)); break; case R.id.re_sex: break; case R.id.re_region: break; case R.id.re_address: break; } } }
true
42e5d46abd4f4dc81c1898c60779031bdcb500e7
Java
vsingh258/TradingExercise
/src/test/java/com/trading/days/DefaultWorkingDaysTest.java
UTF-8
1,391
2.671875
3
[]
no_license
package com.trading.days; import static org.junit.Assert.assertEquals; import java.time.LocalDate; import org.junit.Before; import org.junit.Test; import com.trading.utils.date.DefaultWorkingDays; import com.trading.utils.date.WorkingDays; /** * @author vikramjitsingh * */ public class DefaultWorkingDaysTest { private WorkingDays workingDays; @Before public void setUp() throws Exception { workingDays = DefaultWorkingDays.getInstance(); } @Test public void testFindFirstWorkingDate_Monday() throws Exception { final LocalDate monday = LocalDate.of(2017, 8, 21); assertEquals(monday, workingDays.getFirstWorkingDate(monday)); } @Test public void testFindFirstWorkingDate_Friday() throws Exception { final LocalDate friday = LocalDate.of(2017, 8, 25); assertEquals(friday, workingDays.getFirstWorkingDate(friday)); } @Test public void testFindFirstWorkingDate_Saturday() throws Exception { final LocalDate saturday = LocalDate.of(2017, 8, 26); assertEquals(LocalDate.of(2017, 8, 28), workingDays.getFirstWorkingDate(saturday)); } @Test public void testFindFirstWorkingDate_Sunday() throws Exception { final LocalDate sunday = LocalDate.of(2017, 8, 27); assertEquals(LocalDate.of(2017, 8, 28), workingDays.getFirstWorkingDate(sunday)); } }
true
3fc9f9b26d998effaa58100714a35d5dbdccaa62
Java
shalvisinha/carboless_VIT_HACK_Team-Tem
/app/src/main/java/com/example/carbonfootprint/login.java
UTF-8
5,074
2.21875
2
[]
no_license
package com.example.carbonfootprint; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class login extends AppCompatActivity { Dbmanager db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); db= new Dbmanager(this); final Button log = (Button)findViewById(R.id.log); CheckBox remember = findViewById(R.id.cb); SharedPreferences preferences = getSharedPreferences("checkbox",MODE_PRIVATE); String checkbox = preferences.getString("remember",""); if(checkbox.equals("true")){ Intent intent = new Intent(login.this,chat.class); startActivity(intent); }else if(checkbox.equals("fasle")){ Toast.makeText(this,"please sign", Toast.LENGTH_SHORT).show(); } log.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editText = (EditText)findViewById(R.id.editText); EditText editText2 = (EditText)findViewById(R.id.editText2); String name = editText.getText().toString(); String s2 = editText2.getText().toString(); new Dbmanager(login.this); if(TextUtils.isEmpty(editText.getText().toString())) { editText.setError("Cannot be empty"); Intent start = new Intent(getApplicationContext(),MainActivity.class); } else if (TextUtils.isEmpty(editText2.getText().toString()) | editText2.length()!=10) { editText2.setError("please enter a valid phone number"); Intent start = new Intent(getApplicationContext(),MainActivity.class); } else { Boolean check = db.check(s2); if(check==true) { Toast.makeText(login.this,"Sorry, you are not registered!please signUp first!!", Toast.LENGTH_SHORT).show(); } else { Intent start = new Intent(getApplicationContext(), chat.class); start.putExtra("com.example.myapplication.some", name); start.putExtra("com.example.myapplication.ph", s2); startActivity(start); } } } }); Button sign= (Button)findViewById(R.id.sign); sign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editText = (EditText)findViewById(R.id.editText); EditText editText2 = (EditText)findViewById(R.id.editText2); String s1 = editText.getText().toString(); String s2 = editText2.getText().toString(); Boolean check = db.check(s2); if(check== true) { Boolean insert = db.insert(s1, s2); if (insert == true) { Toast.makeText(login.this, "Congratulations!!your account has been created.Please login", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(login.this, "failed", Toast.LENGTH_SHORT).show(); } } else{ Toast.makeText(login.this, "Account already exist!!", Toast.LENGTH_SHORT).show(); } } }); remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(buttonView.isChecked()){ SharedPreferences preferences = getSharedPreferences("checkbox",MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("remember","true"); editor.apply(); Toast.makeText(login.this,"checked", Toast.LENGTH_SHORT).show(); } else if(!buttonView.isChecked()){ SharedPreferences preferences = getSharedPreferences("checkbox",MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("remember","false"); editor.apply(); Toast.makeText(login.this,"unchecked", Toast.LENGTH_SHORT).show(); } } }); } }
true
25ebb435831275c13cdaf2411c2ed389370aa5ba
Java
moutainhigh/sefonsoft-crm
/crm-search/src/main/java/com.sefonsoft.oa.search/config/MySearchConfiguration.java
UTF-8
1,238
1.90625
2
[]
no_license
package com.sefonsoft.oa.search.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; /** * @ClassName: MySearchConfiguration * @author: Peng YiWen * @date: 2020/5/2 16:36 */ @SpringBootConfiguration public class MySearchConfiguration { public static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); COMMON_OPTIONS = builder.build(); } @Bean public RestHighLevelClient getConnection() { RestClientBuilder builder = null; builder = RestClient.builder(new HttpHost("192.168.56.10", 9200, "http")); RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder); // RestHighLevelClient client = new RestHighLevelClient( // RestClient.builder( // new HttpHost("localhost", 9200, "http"))); return restHighLevelClient; } }
true
7f4976c5d930a348c918b4f77a05a54f77b1f807
Java
Deepalin71/Clarion-Promise-Qa
/src/main/java/com/promise_qa/utils/TestUtils.java
UTF-8
881
2.421875
2
[]
no_license
package com.promise_qa.utils; import java.io.File; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.promise_qa.config.Constants; public class TestUtils { WebDriverWait wait; File file; public void waitElementUntilClickable(WebDriver driver, WebElement element) { wait = new WebDriverWait(driver, Constants.EXPLICIT_WAIT); wait.until(ExpectedConditions.elementToBeClickable(element)); } public void waitElementUntilVisible(WebDriver driver, WebElement element) { wait = new WebDriverWait(driver, Constants.EXPLICIT_WAIT); wait.until(ExpectedConditions.visibilityOf(element)); } public String getAbsoluteFilePath(String relativePath) { file = new File(relativePath); return file.getAbsolutePath(); } }
true
279304539c3ce72ec7f2c9d67125b3c6fe7e04fb
Java
deus-ex-silicium/Cyber_Life
/src/rules/eState.java
UTF-8
114
1.648438
2
[]
no_license
package rules; /** * Created by Nibiru on 2016-04-27. */ public enum eState { ALIVE, DEAD, EMPTY }
true
f51366b8b80d5a1b8a777ece1e02bc073034ebff
Java
dowsam/rebirth-commons
/src/main/java/cn/com/rebirth/commons/settings/loader/SettingsLoaderFactory.java
UTF-8
850
2.109375
2
[]
no_license
/* * Copyright (c) 2005-2012 www.china-cti.com All rights reserved * Info:rebirth-search-commons SettingsLoaderFactory.java 2012-7-6 10:23:47 l.xue.nong$$ */ package cn.com.rebirth.commons.settings.loader; /** * A factory for creating SettingsLoader objects. */ public final class SettingsLoaderFactory { /** * Instantiates a new settings loader factory. */ private SettingsLoaderFactory() { } /** * Loader from resource. * * @param resourceName the resource name * @return the settings loader */ public static SettingsLoader loaderFromResource(String resourceName) { return new PropertiesSettingsLoader(); } /** * Loader from source. * * @param source the source * @return the settings loader */ public static SettingsLoader loaderFromSource(String source) { return new PropertiesSettingsLoader(); } }
true
c5013e419b49ad427884b4142ad9d4c81c8eeb92
Java
zhaokuankuan/open-note
/src/main/java/com/github/note/common/ReturnModel.java
UTF-8
539
1.90625
2
[]
no_license
package com.github.note.common; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author :Mr.kk * @date: 2018/8/16-18:07 */ @Data @AllArgsConstructor @NoArgsConstructor public class ReturnModel implements Serializable{ //成功 public static final int Success = 200; //失败 public static final int Error = 500; public static final long serialVersionUID = 1L; private int code; private String msg; private Object data; }
true
7c66ca35cb787877c2e1d1a1eb78b7c14ab7878a
Java
EricRybarczyk/spring-di-demo
/src/test/java/dev/ericrybarczyk/springdidemo/controllers/PropertyInjectedControllerTest.java
UTF-8
858
2.8125
3
[ "Apache-2.0" ]
permissive
package dev.ericrybarczyk.springdidemo.controllers; import dev.ericrybarczyk.springdidemo.services.ConstructorInjectedGreetingService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PropertyInjectedControllerTest { PropertyInjectedController controller; @BeforeEach void setUp() { // generally mimic what Spring Framework does for us - provide needed dependencies controller = new PropertyInjectedController(); controller.greetingService = new ConstructorInjectedGreetingService(); } @Test void getGreeting() { // trivial test, but it shows the controller code works final String EXPECTED = "Hello World"; String actual = controller.getGreeting(); assertEquals(EXPECTED, actual); } }
true
12916ab6ceecbb89123c20c2218d703da7fe4a8d
Java
jolindse/QuizServer
/src/logic/NetworkListner.java
ISO-8859-1
990
3.21875
3
[]
no_license
package logic; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * Serversocket listener. * * @author Johan Lindstrm (jolindse@hotmail.com) * */ public class NetworkListner extends Thread { private int PORT = 55500; private ServerSocket server = null; private Controller controller; public NetworkListner(Controller controller) { this.controller = controller; } @Override public void run() { try { server = new ServerSocket(PORT); controller.outputInfo("Server up and listening to port " + server.getLocalPort()); while (true) { Socket connection = server.accept(); // When connection is detected send socket to controller. controller.userConnected(connection); } } catch (IOException e) { controller.errorDialog("Communication error", "Problem establishing network connection", "Server was unable to establish a network connection. Make sure port "+PORT+" isn't in use."); } } }
true
3da43a2c954b104c8145e14b036322c416a4502c
Java
einkebil/play2-maven-plugin
/play2-maven-plugin/src/main/java/com/google/code/play2/plugin/AbstractPlay2SourceGeneratorMojo.java
UTF-8
4,232
1.820313
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013-2020 Grzegorz Slowikowski (gslowikowski at gmail dot 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.google.code.play2.plugin; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.sonatype.plexus.build.incremental.BuildContext; import com.google.code.play2.provider.api.SourceGenerationException; /** * Source generator base class for Play! mojos. * * @author <a href="mailto:gslowikowski@gmail.com">Grzegorz Slowikowski</a> */ public abstract class AbstractPlay2SourceGeneratorMojo extends AbstractPlay2Mojo { /** * Source files encoding. * <br> * <br> * If not specified, the encoding value will be the value of the {@code file.encoding} system property. * * @since 1.0.0 */ @Parameter( property = "project.build.sourceEncoding" ) protected String sourceEncoding; /** * For M2E integration. */ @Component protected BuildContext buildContext; protected static final String DEFAULT_TARGET_DIRECTORY_NAME = "src_managed"; protected void addSourceRoot( File generatedDirectory ) { if ( !project.getCompileSourceRoots().contains( generatedDirectory.getAbsolutePath() ) ) { project.addCompileSourceRoot( generatedDirectory.getAbsolutePath() ); getLog().debug( "Added source directory: " + generatedDirectory.getAbsolutePath() ); } } protected void configureSourcePositionMappers() { String sourcePositionMappersGAV = String.format( "%s:%s:%s", pluginGroupId, "play2-source-position-mappers", pluginVersion ); project.getProperties().setProperty( "sbt._sourcePositionMappers", sourcePositionMappersGAV ); } protected void reportCompilationProblems( File source, SourceGenerationException e ) { if ( e.line() > 0 ) { getLog().error( String.format( "%s:%d: %s", source.getAbsolutePath(), Integer.valueOf( e.line() ), e.getMessage() ) ); String lineContent = readFileNthLine( source, e.line() - 1, "unknown" ); if ( lineContent != null ) { getLog().error( lineContent ); if ( e.position() > 0 ) { int pointerSpaceLength = Math.min( e.position() - 1, lineContent.length() ); char[] pointerLine = new char[ pointerSpaceLength + 1 ]; for ( int i = 0; i < pointerSpaceLength; i++ ) { pointerLine[ i ] = lineContent.charAt( i ) == '\t' ? '\t' : ' '; } pointerLine[ pointerSpaceLength ] = '^'; getLog().error( String.valueOf( pointerLine ) ); } } } else { getLog().error( String.format( "%s: %s", source.getAbsolutePath(), e.getMessage() /* message */ ) ); } } private String readFileNthLine( File file, int lineNo, String defaultValue ) { String result = null; try { BufferedReader is = createBufferedFileReader( file, sourceEncoding ); try { int i = 0; while ( i <= lineNo ) { result = is.readLine(); i++; } } finally { is.close(); } } catch ( IOException e ) { result = defaultValue; } return result; } }
true
1391a15ccadded2f2bc68d1898e77d3b54aa2f53
Java
forFire/customer
/src/main/java/com/service/cache/RedisTestCache.java
UTF-8
1,792
2.390625
2
[]
no_license
package com.service.cache; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import com.model.Orders; import com.util.JsonUtil; /** * */ @Component public class RedisTestCache { @Autowired private RedisTemplate<String, Object> redisTemplate; private static final String ORDER = "order_"; private static final String SET = "set_"; /** *set 无序去重 */ public void addControlRoomByOrgId(String orderId, Orders orders) { redisTemplate.opsForSet().add(SET+orderId,JsonUtil.toJson(orders)); } public Set<Object> getControlRoomByOrgId(String orderId) { return redisTemplate.opsForSet().members(SET+orderId); } public void removeControlRoomByOrgId(String orderId,Orders orders) { redisTemplate.opsForSet().remove(SET+orderId,JsonUtil.toJson(orders)); } /** *hashMap */ private static final String HASH_MAP = "hash_map"; //放入map 先组装《key,value》 public void setMap(Map<String, String> map){ redisTemplate.opsForHash().putAll(HASH_MAP , map); } //加减1 对map里的key操作 public void incrementValue( String key, int num){ redisTemplate.opsForHash().increment(HASH_MAP, key, num); } //取出 id 为 key 可以是map 里的key 也可以是 加减1的那个key public Integer getValue(String id){ Object num = redisTemplate.opsForHash().get(HASH_MAP, id); if(num == null) return 0; return Integer.parseInt(num.toString()); } //删除 public void delMap(){ redisTemplate.delete(HASH_MAP);; } /** *list */ public void listTest(String key,String value){ redisTemplate.opsForList().leftPush(key, value); } }
true
419bbf230790b8e13d391f0fcd0f7fc8673c72bb
Java
olivergeith/android_wallpaperDesigner
/src/de/geithonline/wallpaperdesigner/shapes/SimpleTrianglePath.java
UTF-8
795
2.90625
3
[]
no_license
package de.geithonline.wallpaperdesigner.shapes; import android.graphics.Path; import android.graphics.PointF; import android.graphics.RectF; public class SimpleTrianglePath extends Path { public SimpleTrianglePath(final PointF center, final float radiusW, final float radiusH) { draw(center, radiusW, radiusH); } private void draw(final PointF center, final float radiusW, final float radiusH) { final RectF oval = new RectF(); oval.left = center.x - radiusW; oval.right = center.x + radiusW; oval.top = center.y - radiusH; oval.bottom = center.y + radiusH; moveTo(oval.left, oval.bottom); lineTo(center.x, oval.top); lineTo(oval.right, oval.bottom); close(); } }
true
39f17dd85a0af6fd677d8811b9a3edf5c53390dc
Java
mrlonelyjtr/Multithread
/Active Object/2/1/activeobject/Servant.java
UTF-8
532
2.71875
3
[]
no_license
package activeobject; import java.math.BigInteger; class Servant implements ActiveObject { @Override public Result<String> add(String x, String y) { String retvalue = null; try { BigInteger bigX = new BigInteger(x); BigInteger bigY = new BigInteger(y); BigInteger bigZ = bigX.add(bigY); retvalue = bigZ.toString(); } catch (NumberFormatException e) { retvalue = null; } return new RealResult<String>(retvalue); } }
true
be4bb81272f7b5517dc396745c0a96b9d0ae8dc6
Java
sohamghosh28/sea-manifesto
/src/seamanifesto/FileManager.java
UTF-8
2,325
2.515625
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 seamanifesto; import java.io.File; import java.io.FileWriter; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * * @author alex */ public class FileManager { // String jsondata = "{\"name\": \"Sam Smith\", \"technology\": \"Python\"}"; // String messagetype = "MESSAGE TYPE", messageid = "MESSAGE ID", reportingevent = "REPORTING EVENT", senderid = "SENDERID", jobid = "JOBID", date = "DATE", declaration = "DECLARATION"; // Form samobj = new Form(jsondata, messagetype, messageid, reportingevent, senderid, jobid, date, declaration); public static void main(String[] args) { FileManager fm = new FileManager(); fm.init(); } public void init() { // System.out.println(samobj.getFileName()); // System.out.println(samobj.getData()); // System.out.println("\n============================================\n"); // this.exportfile(samobj, null); } public void exportfile(Form obj, String path) { String jsonstring = obj.getData(); //String jsonstring=""; JSONObject jsonObject = new JSONObject(); JSONParser jsonParser = new JSONParser(); if ((jsonstring != null) && !(jsonstring.isEmpty())) { try { jsonObject = (JSONObject) jsonParser.parse(jsonstring); } catch (org.json.simple.parser.ParseException e) { e.printStackTrace(); } } try { if (path == null) { path = "jsonfiles"; } System.out.println("./" + path + "/" + obj.getFileName() + ".json"); File file = new File("./" + path + "/" + obj.getFileName() + ".json"); FileWriter writer = new FileWriter(file); writer.write(jsonObject.toJSONString()); writer.flush(); writer.close(); System.out.println("File Written"); } catch (Exception e) { System.out.println("Error Occurred"); } // System.out.println(jsonObject.toJSONString()); } }
true
1923c38708b18f097130b390904cd6b8580a1e0c
Java
chibiqilin/taylor_series_java
/src/main/java/trigLib/ACotTest.java
UTF-8
1,142
2.484375
2
[]
no_license
package trigLib; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; import static trigLib.TrigLib.*; @RunWith(Parameterized.class) public class ACotTest { private Double input; private Double expected; public ACotTest(Double input, Double expected) { super(); this.input = input; this.expected = expected; } @Parameterized.Parameters public static Collection data() { return Arrays.asList(new Object[][]{ {0.0, 1.57079632}, {0.577350, 1.04719775}, {1.0, 0.785398163}, {1.732050, 0.52359897}, {-1.732050, -0.52359897}, {-0.577350, -1.04719775}, {-6.313751,-0.15707964}, {0.466307,1.13446455} }); } @Test public void testACotTest() { System.out.println("ACot(" + input + ") = " + expected); // test accuracy assertEquals(expected, arccot(input), 0.000001); } }
true
5bac9858c452d9b95ccb9571d2ef5415b0010552
Java
jbeecham/ovirt-engine
/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/adbroker/LdapGetAdUserByUserIdCommand.java
UTF-8
1,467
1.992188
2
[ "Apache-2.0" ]
permissive
package org.ovirt.engine.core.bll.adbroker; import java.util.List; import org.ovirt.engine.core.common.businessentities.AdUser; import org.ovirt.engine.core.compat.Guid; // // JTODO - this needs testing -- Livnat // public class LdapGetAdUserByUserIdCommand extends LdapWithConfiguredCredentialsCommandBase { private Guid getUserId() { return ((LdapSearchByIdParameters) getParameters()).getId(); } public LdapGetAdUserByUserIdCommand(LdapSearchByIdParameters parameters) { super(parameters); } @Override protected void executeQuery(DirectorySearcher directorySearcher) { AdUser user; LdapQueryData queryData = new LdapQueryDataImpl(); queryData.setFilterParameters(new Object[] { getUserId() }); queryData.setLdapQueryType(LdapQueryType.getUserByGuid); queryData.setDomain(getDomain()); Object searchResult = directorySearcher.FindOne(queryData); user = populateUserData((AdUser) searchResult, getDomain()); if (user != null) { GroupsDNQueryGenerator generator = createGroupsGeneratorForUser(user); List<LdapQueryData> partialQueries = generator.getLdapQueriesData(); for (LdapQueryData partialQuery : partialQueries) { PopulateGroup(partialQuery, getDomain(), user.getGroups(), getLoginName(), getPassword()); } } setReturnValue(user); setSucceeded(true); } }
true
aed53f46ed0cec100e2c0f75c4da93b8b9358f10
Java
jasmemu/jasPro
/jas/src/main/java/com/zyg/jas/managerport/controller/ClassesController.java
UTF-8
7,522
2.203125
2
[]
no_license
package com.zyg.jas.managerport.controller; import com.github.pagehelper.PageInfo; import com.zyg.jas.common.pojo.Classes; import com.zyg.jas.common.pojo.Student; import com.zyg.jas.common.tool.constant.JasConstant; import com.zyg.jas.common.tool.util.ResultEntity; import com.zyg.jas.common.tool.vo.ClassVO; import com.zyg.jas.managerport.service.StudentService; import com.zyg.jas.managerport.service.impl.ClassesServiceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/mport/classes") @CrossOrigin public class ClassesController { private Logger logger = LoggerFactory.getLogger(ClassesController.class); @Autowired private ClassesServiceImpl classessService; @Autowired private StudentService studentService; // 根据专业id、年级获取班级(numClasses) @RequestMapping(value = "/get/numclass/{speId}/{grade}",method = RequestMethod.GET) @ResponseBody public ResultEntity<List<Integer>> getNumClassesBySpeIdAndGradeHandler(@PathVariable("speId") Integer speId,@PathVariable("grade") String grade){ List<Integer> numClasssList = classessService.getNumClassesBySpeIdAndGrade(speId,grade); return ResultEntity.successWithData(numClasssList); } // 根据classes的专业id、年级、班级获取学生 @RequestMapping(value = "/get/students/by/classes",method = RequestMethod.POST) @ResponseBody public ResultEntity<List<Student>> getStudentByClassesHandler(@RequestBody Classes classes){ List<Student> studentList = studentService.getStudentByClasses(classes); return ResultEntity.successWithData(studentList); } //根据专业id或年级或班级(classes)的id搜索班级信息 @RequestMapping(value = "/get/for/search",method = RequestMethod.POST) @ResponseBody public ResultEntity<List<Classes>> getClassesForSerach(@RequestParam(value = "speId",required = false) Integer speId, @RequestParam(value = "cGrade",required = false) String cGrade,@RequestParam(value = "cClass",required = false) Integer cClass){ logger.info("搜索内容: "+ speId+"-"+cGrade+"-"+cClass); List<Classes> list = classessService.getClassesForSearch(speId,cGrade,cClass); List<ClassVO> classVOList = classessService.getCountBySpecialtyGradeClass(); for (int i=0;i<list.size();i++){ boolean flag= false; for (int j=0;j<classVOList.size();j++){ if (list.get(i).getSpeId().equals(classVOList.get(j).getSpeId())&& list.get(i).getGrade().equals(classVOList.get(j).getsGrade())&& list.get(i).getNumClass().equals(classVOList.get(j).getsClass())){ list.get(i).setStuNum(classVOList.get(j).getNum()); flag = true; break; } } if(!flag){ list.get(i).setStuNum(0); } } return ResultEntity.successWithData(list); } //获取所有的班级编号(numClass) @RequestMapping(value = "/get/grades",method = RequestMethod.GET) @ResponseBody public ResultEntity<String[]> getGrades(){ return ResultEntity.successWithData(JasConstant.GRADE_LIST); } //获取所有的班级编号(numClass) @RequestMapping(value = "/get/no/repetition",method = RequestMethod.GET) @ResponseBody public ResultEntity<List<Integer>> getClassNumNoRepetition(){ Integer maxNumClass = classessService.getClassesNoRepetition(); List<Integer> numClassList = new ArrayList<>(); for (int i=0;i<maxNumClass;i++){ numClassList.add(i+1); } return ResultEntity.successWithData(numClassList); } //批量删除班级信息,接收是一个数组存放的是班级(classes)的id @RequestMapping(value = "/delete/batch",method = RequestMethod.POST) @ResponseBody public ResultEntity deleteBatch(@RequestBody int[] idList){ classessService.removeClassesBatchById(idList); return ResultEntity.successWithoutData(); } // 接收的是班级(classes)中的id,根据id删除班级 @RequestMapping(value = "/remove/class/by/id/{id}",method = RequestMethod.GET) @ResponseBody public ResultEntity removeClassHandler(@PathVariable("id") Integer id){ classessService.removeClassesById(id); return ResultEntity.successWithoutData(); } // 添加一个班级,或者修改班级的班主任编号, @RequestMapping(value = "/save/class",method = RequestMethod.POST) @ResponseBody public ResultEntity saveClass(@RequestBody Classes classes){ System.out.println("接收到的class"+classes); if (classessService.saveClasses(classes).equals("success")){ return ResultEntity.successWithoutData(); }else { return ResultEntity.failed(""); } } //获取course表所有记录,分页 @RequestMapping(value = "/getAllClasses/{pageNo}/{pageSize}",method = RequestMethod.GET) @ResponseBody public List<Classes> getAllCourse(@PathVariable("pageNo") Integer pageNo, @PathVariable("pageSize") Integer pageSize){ PageInfo<Classes> pageInfo = classessService.getAllClasses(pageNo,pageSize); List<Classes> list = new ArrayList<>(); for (Classes info : pageInfo.getList()) { list.add(info); } System.out.println("所有班级:"); for (int i=0;i<list.size();i++){ System.out.println(list.get(i)); } List<ClassVO> classVOList = classessService.getCountBySpecialtyGradeClass(); System.out.println("数人数:"); for (int i=0;i<classVOList.size();i++){ System.out.println(classVOList.get(i)); } for (int i=0;i<list.size();i++){ boolean flag= false; for (int j=0;j<classVOList.size();j++){ if (list.get(i).getSpeId().equals(classVOList.get(j).getSpeId())&& list.get(i).getGrade().equals(classVOList.get(j).getsGrade())&& list.get(i).getNumClass().equals(classVOList.get(j).getsClass())){ list.get(i).setStuNum(classVOList.get(j).getNum()); flag = true; break; } } if(!flag){ list.get(i).setStuNum(0); } } return list; } //获取course表记录数量 @RequestMapping(value = "/getClassesTotal",method = RequestMethod.GET) @ResponseBody public String getCourseTotal(){ Integer classesCount = classessService.getClassTotal(); if (classesCount!=null){ return String.valueOf(classesCount); }else { return ""; } } //获取course表记录数量 @RequestMapping(value = "/getCountBySpecialtyGradeClass",method = RequestMethod.GET) @ResponseBody public List<ClassVO> getCountBySpecialtyGradeClassHandler(){ List<ClassVO> stuCountByClass = classessService.getCountBySpecialtyGradeClass(); if (stuCountByClass!=null){ return stuCountByClass; }else { return null; } } }
true
e90be1816c54c49e6df695cca330e53c917859ff
Java
SalimZ04/Smart-Ambulance
/SmartAmbulanceApp/src/main/java/Controllers/DeleteConfirmationController.java
ISO-8859-1
5,061
2.34375
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 Controllers; import Include.Notification; import MainConrollers.AmbulanceMainController; import MainConrollers.AmbulanceTravelMainController; import MainConrollers.PatientMainController; import Models.Ambulance; import Models.AmbulanceTravel; import Models.Patient; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXTextField; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.stage.Stage; /** * FXML Controller class * * @author rachid dev */ public class DeleteConfirmationController implements Initializable { @FXML private JFXButton yesDeleteBtn; @FXML private JFXButton cancelBtn; @FXML private JFXTextField matriculetxt; @FXML private JFXTextField idPatienttxt; @FXML private JFXTextField ambulanceTravelTxt; AmbulanceMainController amc; PatientMainController pa; AmbulanceTravelMainController amcT; Notification nt = new Notification(); /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { yesDeleteBtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent Action) { if (matriculetxt.getText()!="") { try { deleteAmbulance(matriculetxt.getText()); } catch (SQLException ex) { System.out.println("Error de suppression"); } } if (idPatienttxt.getText()!="") { try { int idP = Integer.parseInt(idPatienttxt.getText()); deletePatient(idP); } catch (SQLException ex) { Logger.getLogger(DeleteConfirmationController.class.getName()).log(Level.SEVERE, null, ex); } } if (ambulanceTravelTxt.getText()!="") { try { int idT = Integer.parseInt(ambulanceTravelTxt.getText()); deleteAmbulanceTravel(idT); } catch (SQLException ex) { Logger.getLogger(DeleteConfirmationController.class.getName()).log(Level.SEVERE, null, ex); } } CloseView(); } }); //System.out.println("heyyy"); } @FXML private void leaveView(ActionEvent event) { Stage stage = (Stage) cancelBtn.getScene().getWindow(); stage.close(); } private void CloseView() { Stage stage = (Stage) cancelBtn.getScene().getWindow(); stage.close(); } public void deleteAmbulance(String matricule) throws SQLException{ AmbulanceMainController amc = new AmbulanceMainController(); boolean result = amc.DeleteAmbulance(matricule); if (result) { nt.SuccessNotification("ambulance est supprim avec succes", "ambulance deleted successfully"); }else{ nt.Failednotification("ambulance Non supprim ", "ambulance NOT deleted"); } } public void deletePatient(int id) throws SQLException{ boolean etat ; PatientMainController pa = new PatientMainController(); etat = pa.DeletePatient(id); if (etat) { nt.SuccessNotification("Patient est supprim avec succes", "patient deleted successfully"); }else{ nt.Failednotification("Patient Non supprim ", "patient NOT deleted"); } } public void deleteAmbulanceTravel(int id) throws SQLException{ boolean etat = false; AmbulanceTravelMainController amcT = new AmbulanceTravelMainController(); etat = amcT.deleteAmbulanceTravel(id); if (etat) { nt.SuccessNotification("ambulance Voyage est supprim avec succes", "ambulance Travel deleted successfully"); }else{ nt.Failednotification("ambulance Voyage Non supprim ", "ambulance Travel NOT deleted"); } } public void SetMatricule(Ambulance am){ matriculetxt.setText(am.getMatricule()); } public void SetIdPatient(Patient p){ idPatienttxt.setText(Integer.toString(p.getIdPatient())); } public void SetIdTravel(AmbulanceTravel am){ ambulanceTravelTxt.setText(Integer.toString(am.getIdTravel())); } }
true
bc1e3cf3b3e982e4d918f9b03076ac041f8ef32a
Java
mbizhani/Samples
/src/main/java/org/devocative/samples/xml/vo/XPart2.java
UTF-8
621
2.046875
2
[ "Apache-2.0" ]
permissive
package org.devocative.samples.xml.vo; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; @XStreamAlias("part2") public class XPart2 { @XStreamAsAttribute private String p2y; @XStreamAsAttribute private String p2z; public String getP2y() { return p2y; } public void setP2y(String p2y) { this.p2y = p2y; } public String getP2z() { return p2z; } public void setP2z(String p2z) { this.p2z = p2z; } @Override public String toString() { return "XPart2{" + "p2z='" + p2z + '\'' + ", p2y='" + p2y + '\'' + '}'; } }
true
3355182b0beb4bfeea43ed0c0e7c7337dce626f5
Java
pxson001/facebook-app
/classes5.dex_source_from_JADX/com/facebook/graphql/enums/GraphQLEventTicketOrderStatus.java
UTF-8
893
2.03125
2
[]
no_license
package com.facebook.graphql.enums; /* compiled from: map_style */ public enum GraphQLEventTicketOrderStatus { UNSET_OR_UNRECOGNIZED_ENUM_VALUE, RESERVED, PURCHASED, REFUNDED, FAILED, TIMED_OUT; public static GraphQLEventTicketOrderStatus fromString(String str) { if (str == null || str.isEmpty()) { return UNSET_OR_UNRECOGNIZED_ENUM_VALUE; } if (str.equalsIgnoreCase("RESERVED")) { return RESERVED; } if (str.equalsIgnoreCase("PURCHASED")) { return PURCHASED; } if (str.equalsIgnoreCase("REFUNDED")) { return REFUNDED; } if (str.equalsIgnoreCase("FAILED")) { return FAILED; } if (str.equalsIgnoreCase("TIMED_OUT")) { return TIMED_OUT; } return UNSET_OR_UNRECOGNIZED_ENUM_VALUE; } }
true
2c31f35420bd72ecfdc8e37fb2273cadec84e758
Java
zhongxingyu/Seer
/Diff-Raw-Data/21/21_f134bbd3c331e78f91430505149ed808a5efb8c4/JSLint/21_f134bbd3c331e78f91430505149ed808a5efb8c4_JSLint_s.java
UTF-8
11,342
2.375
2
[]
no_license
package com.googlecode.jslint4java; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.UniqueTag; import com.googlecode.jslint4java.Issue.IssueBuilder; import com.googlecode.jslint4java.JSFunction.Builder; import com.googlecode.jslint4java.JSLintResult.ResultBuilder; /** * A utility class to check JavaScript source code for potential problems. * * @author dom */ public class JSLint { // Uncomment to enable the rhino debugger. // static { // org.mozilla.javascript.tools.debugger.Main.mainEmbedded(null); // } /** * A helper class for interpreting the output of {@code JSLINT.data()}. */ private static final class IdentifierConverter implements Util.Converter<JSIdentifier> { public JSIdentifier convert(Object obj) { Scriptable identifier = (Scriptable) obj; String name = Util.stringValue("name", identifier); int line = Util.intValue("line", identifier); return new JSIdentifier(name, line); } } /** * A helper class for interpreting the output of {@code JSLINT.data()}. */ private static final class JSFunctionConverter implements Util.Converter<JSFunction> { public JSFunction convert(Object obj) { Scriptable scope = (Scriptable) obj; String name = Util.stringValue("name", scope); int line = Util.intValue("line", scope); Builder b = new JSFunction.Builder(name, line); b.last(Util.intValue("last", scope)); for (String param : Util.listValueOfType("param", String.class, scope)) { b.addParam(param); } for (String closure : Util.listValueOfType("closure", String.class, scope)) { b.addClosure(closure); } for (String var : Util.listValueOfType("var", String.class, scope)) { b.addVar(var); } for (String exception : Util.listValueOfType("exception", String.class, scope)) { b.addException(exception); } for (String outer : Util.listValueOfType("outer", String.class, scope)) { b.addOuter(outer); } for (String unused : Util.listValueOfType("unused", String.class, scope)) { b.addUnused(unused); } for (String global : Util.listValueOfType("global", String.class, scope)) { b.addGlobal(global); } for (String label : Util.listValueOfType("label", String.class, scope)) { b.addLabel(label); } return b.build(); } } private final Map<Option, Object> options = new EnumMap<Option, Object>(Option.class); private final Scriptable scope; /** * Create a new {@link JSLint} object. You must pass in a {@link Scriptable} * which already has the {@code JSLINT} function defined. */ public JSLint(Scriptable scope) { this.scope = scope; } /** * Add an option to change the behaviour of the lint. This will be passed in * with a value of "true". * * @param o * Any {@link Option}. */ public void addOption(Option o) { options.put(o, Boolean.TRUE); } /** * Add an option to change the behaviour of the lint. The option will be * parsed as appropriate using an {@link OptionParser}. * * @param o * Any {@link Option}. * @param arg * The value to associate with <i>o</i>. */ public void addOption(Option o, String arg) { OptionParser optionParser = new OptionParser(); options.put(o, optionParser.parse(o.getType(), arg)); } /** * Assemble the {@link JSLintResult} object. */ private JSLintResult buildResults(String systemId, long startNanos, long endNanos) { ResultBuilder b = new JSLintResult.ResultBuilder(systemId); b.duration(TimeUnit.NANOSECONDS.toMillis(endNanos - startNanos)); for (Issue issue : readErrors(systemId)) { b.addIssue(issue); } // Collect a report on what we've just linted. b.report(callReport(false)); // Extract JSLINT.data() output and set it on the result. Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope); Object o = lintScope.get("data", lintScope); // Real JSLINT will always have this, but some of my test stubs don't. if (o != UniqueTag.NOT_FOUND) { Function reportFunc = (Function) o; Scriptable data = (Scriptable) reportFunc.call(Context.getCurrentContext(), scope, scope, new Object[] {}); for (String global : Util.listValueOfType("globals", String.class, data)) { b.addGlobal(global); } for (String url : Util.listValueOfType("urls", String.class, data)) { b.addUrl(url); } for (Entry<String, Integer> member : getDataMembers(data).entrySet()) { b.addMember(member.getKey(), member.getValue()); } for (JSIdentifier id : Util.listValue("unused", data, new IdentifierConverter())) { b.addUnused(id); } for (JSIdentifier id : Util.listValue("implieds", data, new IdentifierConverter())) { b.addImplied(id); } b.json(Util.booleanValue("json", data)); for (JSFunction f : Util.listValue("functions", data, new JSFunctionConverter())) { b.addFunction(f); } } return b.build(); } private String callReport(boolean errorsOnly) { Object[] args = new Object[] { Boolean.valueOf(errorsOnly) }; Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope); Object report = lintScope.get("report", lintScope); // Shouldn't happen ordinarily, but some of my tests don't have it. if (report == UniqueTag.NOT_FOUND) { return ""; } Function reportFunc = (Function) report; return (String) reportFunc.call(Context.getCurrentContext(), scope, scope, args); } private void doLint(String javaScript) { String src = javaScript == null ? "" : javaScript; Object[] args = new Object[] { src, optionsAsJavaScriptObject() }; Function lintFunc = (Function) scope.get("JSLINT", scope); // JSLINT actually returns a boolean, but we ignore it as we always go // and look at the errors in more detail. lintFunc.call(Context.getCurrentContext(), scope, scope, args); } /** * Set the "member" field of the {@link JSLintResult}. */ private Map<String,Integer> getDataMembers(Scriptable data) { Object o1 = data.get("member", data); if (o1 == UniqueTag.NOT_FOUND) { return new HashMap<String, Integer>(); } Scriptable member = (Scriptable) o1; Object[] propertyIds = ScriptableObject.getPropertyIds(member); Map<String, Integer> members = new HashMap<String, Integer>(propertyIds.length); for (Object id : propertyIds) { String k = id.toString(); members.put(k, Util.intValue(k, member)); } return members; } /** * Return the version of jslint in use. */ public String getEdition() { Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope); return (String) lintScope.get("edition", lintScope); } /** * Check for problems in a {@link Reader} which contains JavaScript source. * * @param systemId * a filename * @param reader * a {@link Reader} over JavaScript source code. * * @return a {@link JSLintResult}. */ public JSLintResult lint(String systemId, Reader reader) throws IOException { return lint(systemId, Util.readerToString(reader)); } /** * Check for problems in JavaScript source. * * @param systemId * a filename * @param javaScript * a String of JavaScript source code. * * @return a {@link JSLintResult}. */ public JSLintResult lint(String systemId, String javaScript) { long before = System.nanoTime(); doLint(javaScript); long after = System.nanoTime(); return buildResults(systemId, before, after); } /** * Turn the set of options into a JavaScript object, where the key is the * name of the option and the value is true. */ private Scriptable optionsAsJavaScriptObject() { Scriptable opts = Context.getCurrentContext().newObject(scope); for (Entry<Option, Object> entry : options.entrySet()) { String key = entry.getKey().getLowerName(); Object value = Context.javaToJS(entry.getValue(), opts); opts.put(key, opts, value); } return opts; } private List<Issue> readErrors(String systemId) { ArrayList<Issue> issues = new ArrayList<Issue>(); Scriptable JSLINT = (Scriptable) scope.get("JSLINT", scope); Scriptable errors = (Scriptable) JSLINT.get("errors", JSLINT); int count = Util.intValue("length", errors); for (int i = 0; i < count; i++) { Scriptable err = (Scriptable) errors.get(i, errors); // JSLINT spits out a null when it cannot proceed. // TODO Should probably turn i-1th issue into a "fatal". if (err != null) { issues.add(IssueBuilder.fromJavaScript(systemId, err)); } } return issues; } /** * Report on what variables / functions are in use by this code. * * @param javaScript * @return an HTML report. */ public String report(String javaScript) { return report(javaScript, false); } /** * Report on what variables / functions are in use by this code. * * @param javaScript * @param errorsOnly * If a report consisting solely of the problems is desired. * @return an HTML report. */ public String report(String javaScript, boolean errorsOnly) { // Run the lint function itself as prep. doLint(javaScript); // The run the reporter. return callReport(errorsOnly); } /** * Clear out all options that have been set with {@link #addOption(Option)}. */ public void resetOptions() { options.clear(); } }
true
bbf9e3669aa59f7267cc4232b33a357e6f3811cc
Java
opennetworkinglab/onos
/drivers/server/src/main/java/org/onosproject/drivers/server/impl/stats/DefaultMemoryStatistics.java
UTF-8
5,560
2.125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.drivers.server.impl.stats; import org.onosproject.drivers.server.stats.MemoryStatistics; import org.onosproject.drivers.server.stats.MonitoringUnit; import org.onosproject.net.DeviceId; import com.google.common.base.MoreObjects; import com.google.common.base.Strings; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.drivers.server.Constants.MSG_STATS_MEMORY_FREE_NEGATIVE; import static org.onosproject.drivers.server.Constants.MSG_STATS_MEMORY_TOTAL_NEGATIVE; import static org.onosproject.drivers.server.Constants.MSG_STATS_MEMORY_USED_NEGATIVE; import static org.onosproject.drivers.server.Constants.MSG_STATS_UNIT_NULL; import static org.onosproject.drivers.server.stats.MonitoringUnit.CapacityUnit; /** * Default implementation for main memory statistics. */ public final class DefaultMemoryStatistics implements MemoryStatistics { private static final CapacityUnit DEF_MEM_UNIT = CapacityUnit.KILOBYTES; private final DeviceId deviceId; private final MonitoringUnit unit; private long used; private long free; private long total; private DefaultMemoryStatistics(DeviceId deviceId, MonitoringUnit unit, long used, long free, long total) { checkNotNull(unit, MSG_STATS_UNIT_NULL); checkArgument(used >= 0, MSG_STATS_MEMORY_USED_NEGATIVE); checkArgument(free >= 0, MSG_STATS_MEMORY_FREE_NEGATIVE); checkArgument((total >= 0) && (used + free == total), MSG_STATS_MEMORY_TOTAL_NEGATIVE); this.deviceId = deviceId; this.unit = unit; this.used = used; this.free = free; this.total = total; } // Constructor for serializer private DefaultMemoryStatistics() { this.deviceId = null; this.unit = null; this.used = 0; this.free = 0; this.total = 0; } /** * Creates a builder for DefaultMemoryStatistics object. * * @return builder object for DefaultMemoryStatistics object */ public static DefaultMemoryStatistics.Builder builder() { return new Builder(); } @Override public MonitoringUnit unit() { return this.unit; } @Override public long used() { return this.used; } @Override public long free() { return this.free; } @Override public long total() { return this.total; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("device", deviceId) .add("unit", this.unit()) .add("used", this.used()) .add("free", this.free()) .add("total", this.total()) .toString(); } public static final class Builder { DeviceId deviceId; MonitoringUnit unit = DEF_MEM_UNIT; long used; long free; long total; private Builder() { } /** * Sets the device identifier. * * @param deviceId device identifier * @return builder object */ public Builder setDeviceId(DeviceId deviceId) { this.deviceId = deviceId; return this; } /** * Sets memory statistics unit. * * @param unitStr memory statistics unit as a string * @return builder object */ public Builder setUnit(String unitStr) { if (!Strings.isNullOrEmpty(unitStr)) { this.unit = CapacityUnit.getByName(unitStr); } return this; } /** * Sets the amount of used main memory. * * @param used used main memory * @return builder object */ public Builder setMemoryUsed(long used) { this.used = used; return this; } /** * Sets the amount of free main memory. * * @param free free main memory * @return builder object */ public Builder setMemoryFree(long free) { this.free = free; return this; } /** * Sets the total amount of main memory. * * @param total total main memory * @return builder object */ public Builder setMemoryTotal(long total) { this.total = total; return this; } /** * Creates a DefaultMemoryStatistics object. * * @return DefaultMemoryStatistics object */ public DefaultMemoryStatistics build() { return new DefaultMemoryStatistics( deviceId, unit, used, free, total); } } }
true
bd65745afb4f83296206dce8e7e75817c68e851f
Java
xinkong/GRass
/app/src/main/java/com/grass/grass/entity/Commend.java
UTF-8
822
1.859375
2
[]
no_license
package com.grass.grass.entity; /** * Created by huchao on 2016/1/4. */ public class Commend { private int id; private int userId; private String commendTime; private String commendContent; public String getCommendContent() { return commendContent; } public void setCommendContent(String commendContent) { this.commendContent = commendContent; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getCommendTime() { return commendTime; } public void setCommendTime(String commendTime) { this.commendTime = commendTime; } }
true
9e55916994e881f4d5ba3996b525751c1bc2ea20
Java
qqgirllianxin/hell
/hell-ml/src/main/java/ps/hell/ml/nlp/tool/hanlp/hankcs/test/seg/TestPersonRecognition.java
UTF-8
3,015
2.265625
2
[]
no_license
/* * <summary></summary> * <author>He Han</author> * <email>hankcs.cn@gmail.com</email> * <create-date>2014/05/2014/5/29 15:23</create-date> * * <copyright file="TestPersonRecognition.java" company="上海林原信息科技有限公司"> * Copyright (c) 2003-2014, 上海林原信息科技有限公司. All Right Reserved, http://www.linrunsoft.com/ * This source is subject to the LinrunSpace License. Please contact 上海林原信息科技有限公司 to get more information. * </copyright> */ package ps.hell.ml.nlp.tool.hanlp.hankcs.test.seg; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.HanLP; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.corpus.io.FolderWalker; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.corpus.io.IOUtil; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.corpus.tag.Nature; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.seg.Dijkstra.DijkstraSegment; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.seg.NShort.NShortSegment; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.seg.Segment; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.seg.common.Term; import ps.hell.ml.nlp.tool.hanlp.hankcs.hanlp.utility.SentencesUtil; import junit.framework.TestCase; import java.io.File; import java.util.List; /** * @author hankcs */ public class TestPersonRecognition extends TestCase { static final String FOLDER = "D:\\Doc\\语料库\\上海静安\\"; public void testBatch() throws Exception { List<File> fileList = FolderWalker.open(FOLDER); int i = 0; for (File file : fileList) { System.out.println(++i + " / " + fileList.size() + " " + file.getName() + " "); String path = file.getAbsolutePath(); String content = IOUtil.readTxt(path); DijkstraSegment segment = new DijkstraSegment(); List<List<Term>> sentenceList = segment.seg2sentence(content); for (List<Term> sentence : sentenceList) { if (SentencesUtil.hasNature(sentence, Nature.nr)) { System.out.println(sentence); } } } } public void testNameRecognition() throws Exception { HanLP.Config.enableDebug(); NShortSegment segment = new NShortSegment(); System.out.println(segment.seg("世界上最长的姓名是简森·乔伊·亚历山大·比基·卡利斯勒·达夫·埃利奥特·福克斯·伊维鲁莫·马尔尼·梅尔斯·帕特森·汤普森·华莱士·普雷斯顿。")); } public void testJPName() throws Exception { HanLP.Config.enableDebug(); Segment segment = new DijkstraSegment().enableJapaneseNameRecognize(true); System.out.println(segment.seg("北川景子参演了林诣彬导演")); } public void testChineseNameRecognition() throws Exception { HanLP.Config.enableDebug(); Segment segment = new DijkstraSegment(); System.out.println(segment.seg("编剧邵钧林和稽道青说")); } }
true
66fc42b988a5a63e3a895fc31b7b31a35fef9387
Java
puneetkhanal/finance
/src/com/finance/framework/entities/AbstractCustomerManager.java
UTF-8
823
2.328125
2
[]
no_license
package com.finance.framework.entities; import java.util.Observable; import com.finance.framework.controllers.FrameworkController; import com.finance.framework.intefaces.ICustomer; import com.finance.framework.intefaces.ICustomerManager; public abstract class AbstractCustomerManager extends Observable implements ICustomerManager { private FrameworkController frameworkController; @Override public final void setFrameworkController(FrameworkController frameworkController) { this.frameworkController = frameworkController; addObserver(frameworkController); } @Override public final boolean submitCustomer(ICustomer customer) { addCustomer(customer); setChanged(); notifyObservers(); return true; } // public final void setChanged(){ // //frameworkController.dataSetChanged(); // } // }
true
3561a298f14869bcc1d6130d71772498b13cf14f
Java
naveen8801/java-tutorial
/src/npower/company/FirstandLastOcuurance.java
UTF-8
1,266
4
4
[]
no_license
package npower.company; // Find first occurance and last occurance of a number in a array // With help of occuarances we can also cout no. of times target is occuring import java.util.Arrays; public class FirstandLastOcuurance { public static void main(String[] args) { int[] arr = {5,7,7,7,7,8,8,10}; int[] rangeOfOccurance = occurance(arr , 8); System.out.println(Arrays.toString(rangeOfOccurance)); } static int[] occurance(int[] arr , int target){ int s = 0; int e = arr.length; int first = -1; int last = -1; while(s <= e){ int m = (s+e)/2; if(arr[m]==target){ first = m; e = m -1; } else if(arr[m]<target){ s = m + 1; } else{ e = m -1; } } s = 0; e = arr.length - 1; while(s <= e){ int m = (s+e)/2; if(arr[m]==target){ last = m; s = m + 1; } else if(arr[m]<target){ s = m + 1; } else{ e = m -1; } } return new int[]{first,last}; } }
true
ba981b60b1251fdda1eaf2f53bba9307a37d1ebd
Java
zbs4ms/doraemon
/doraemon-base/src/main/java/com/doraemon/base/redis/RedisOperation.java
UTF-8
6,278
2.515625
3
[]
no_license
package com.doraemon.base.redis; import com.doraemon.base.guava.DPreconditions; import lombok.Data; import lombok.extern.log4j.Log4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.List; import java.util.Map; /** * Created by zbs on 2017/6/23. */ @Configuration @Data @Log4j public class RedisOperation { @Autowired private RedisConfiguration redisConfiguration; @Autowired private JedisPool jedisPool; private boolean usePool = false; private boolean usePassword = false; public RedisOperation usePool() { usePool = true; return this; } public RedisOperation usePassword() { usePassword = true; return this; } private Jedis getJedis() throws Exception { if(jedisPool == null) throw new Exception("redis连接为空."); Jedis jedis; if (usePool) { jedis = jedisPool.getResource(); }else { jedis = new Jedis(redisConfiguration.getHost(), redisConfiguration.getPort()); } log.debug("redis的连接为: ip:" + redisConfiguration.getHost() + " host:" + redisConfiguration.getPort() ); if (usePassword || redisConfiguration.getPassword()!=null) { jedis.auth(redisConfiguration.getPassword()); log.debug(" redis的密码是:password:" + redisConfiguration.getPassword()); } return jedis; } private void close(Jedis jedis) { if (jedis != null) jedis.close(); } /** * redis 的 get 方法 * * @param key * @return */ public String get(String key) throws Exception { Jedis jedis = null; try { jedis = getJedis(); log.info("redis查询 key:"+key); DPreconditions.checkNotNullAndEmpty(key,"传入redis查询的值不能为空,或者为''"); return jedis.get(key); } finally { this.close(jedis); } } /** * redis 的 set 方法 * @param key * @return */ public String set(String key,String value) throws Exception { Jedis jedis = null; try { jedis = getJedis(); log.info("redis插入值 key:"+key+" value:"+value); return jedis.set(key,value); }finally { this.close(jedis); } } /** * redis 的 delete 方法 * @param key * @return */ public Long del(String key) throws Exception { Jedis jedis = null; try{ jedis = getJedis(); return jedis.del(key); }finally { this.close(jedis); } } /** * redis 设置key 过期时间方法 * @param key * @return */ public void expire(String key,int time) throws Exception { Jedis jedis = null; try { jedis = getJedis(); jedis.expire(key,time); }finally { this.close(jedis); } } /** * redis 自增 * @param key * @return */ public Long incrBy(String key,long value) throws Exception { Jedis jedis = null; try { jedis = getJedis(); return jedis.incrBy(key,value); }finally { this.close(jedis); } } /** * redis 自减 * @param key * @return */ public Long decrBy(String key,long value) throws Exception { Jedis jedis = null; try { jedis = getJedis(); return jedis.decrBy(key,value); }finally { this.close(jedis); } } /** * redis 的 执行 lua 脚本 * @param script * @param keys * @param args * @return */ public Object eval(String script, List<String> keys, List<String> args) throws Exception { Jedis jedis = null; try { jedis = getJedis(); return jedis.eval(script,keys,args); }finally { this.close(jedis); } } /** * redis 入队列 * @param key * @param value */ public void push(String key,String ... value) throws Exception { Jedis jedis = null; try { jedis = getJedis(); jedis.lpush(key,value); }finally { this.close(jedis); } } /** * redis 出队列 * @param key * @return */ public String pop(String key) throws Exception { Jedis jedis = null; try { jedis = getJedis(); return jedis.rpop(key); }finally { this.close(jedis); } } /** * redis 退回一条数据到队列中 * @param key * @return */ public void backToQueue(String key,String valus) throws Exception { Jedis jedis = null; try { jedis = getJedis(); jedis.rpush(key,valus); }finally { this.close(jedis); } } /** * 查询队列 (start = 0 & end = -1 代表查询全部) * @param key * @param start * @param end * @return */ public List<String> lrange(String key, long start, long end) throws Exception { Jedis jedis = null; try { jedis = getJedis(); return jedis.lrange(key,start,end); }finally { this.close(jedis); } } /** * 封装redis 的hmset方法 * @param key */ public Map hget(String key ) throws Exception { Jedis jedis = null; Map<String,String> map; try { jedis = getJedis(); return jedis.hgetAll(key); } finally { this.close(jedis); } } /** * 封装redis 的hmset方法 * @param key * @param map */ public void hset(String key ,Map map) throws Exception { Jedis jedis = null; try { jedis = getJedis(); jedis.hmset(key,map); } finally { this.close(jedis); } } }
true
7658804ffd3119288a136bdffdffbad9ee1b3560
Java
HackFmiNpe/TheForceMediaCenter
/MediaControllerApp/mobile/src/main/java/npe/hackfmi/mediacontrollerapp/tasks/InitialiseAsyncTask.java
UTF-8
2,368
2.421875
2
[ "MIT" ]
permissive
package npe.hackfmi.mediacontrollerapp.tasks; import android.os.AsyncTask; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.Timer; /** * By Antoan Angelov on 19-Dec-15. */ public class InitialiseAsyncTask extends AsyncTask<Void, Void, Void> { private static final String DST_ADDRESS = "192.168.0.105"; private static final int DST_PORT = 49155; public static final int TIMEOUT = 30 * 1000; // half a minute private static final long PERIOD_MILLIS = 33; private final LinkedList<JSONObject> mQueue = new LinkedList<>(); private Timer mTimer; private Socket mSocket; @Override protected Void doInBackground(Void... params) { try { mSocket = new Socket(DST_ADDRESS, DST_PORT); mTimer = new Timer(); mTimer.schedule(new SendMessageAsyncTask(mSocket, mQueue), 0, PERIOD_MILLIS); } catch (IOException e) { e.printStackTrace(); try { if (mSocket != null) { mSocket.close(); } } catch (IOException e1) { e1.printStackTrace(); } } return null; } public void stop() { if (mTimer != null) { mTimer.cancel(); } if (mSocket != null) { try { mSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } public void addRequest(String gesture, String file_name) { try { mQueue.add(new JSONObject() .put("gesture", gesture) .put("file_name", file_name)); } catch (JSONException e) { e.printStackTrace(); } } public void addRequest(String gesture) { try { mQueue.add(new JSONObject() .put("gesture", gesture)); } catch (JSONException e) { e.printStackTrace(); } } }
true
063c4caa3726efb218b4d550539f72248cde1f6c
Java
cedar997/Leetcode
/src/com/cedar/leetcode/tmp/t_29/Solution.java
UTF-8
1,288
3.296875
3
[]
no_license
package com.cedar.leetcode.tmp.t_29; public class Solution { public int divide(int dividend, int divisor) { //q为最后返回的商 int q=0; int sign=1; if(divisor==Integer.MIN_VALUE){ if(dividend==Integer.MIN_VALUE) //两最小负数相除,结果为1 return 1; //除数是最小负数,则返回0 return 0; } //除0返回最大值 if(divisor==0)return Integer.MAX_VALUE; //除1返回被除数 if(divisor==1) return dividend; //将除数转化为正数,并记录符号 if(divisor<0){ divisor=-divisor; sign=-sign; } if(dividend==Integer.MIN_VALUE){ if(divisor==1) //结果溢出,返回指定值 return Integer.MAX_VALUE; q++; dividend+=divisor; } //将被除数转换为正数,并调整符号 if(dividend<0){ dividend=-dividend; sign=-sign; } //用减法模拟除法 while(dividend>=divisor){ dividend-=divisor; q++; } //结果加上符号 if(sign<0) return -q; return q; } }
true
d22aaa239f4504b973323fea92a8c5013007c938
Java
vogtn/Learn-Java
/Loops/src/Application.java
UTF-8
723
4.03125
4
[]
no_license
/** * Created by nicv on 5/5/17. */ public class Application { public static void main(String[] args){ /* boolean loop = 4 < 5; System.out.println(loop) => returns true */ //while loop int value = 0; while(value < 10) { System.out.println("Hello " + value); //store value + 1 value = value + 1; } //for loop System.out.println("While loop"); for(int i=0; i<5; i++) { //%d print this string, but using the value of the integer //\n is a new line escape character System.out.printf("The value of i is: %d\n", i); } } }
true