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
fbfa3393db4c1a0c9ada2cda405b5dc4517224a1
Java
dhis2/dhis2-core
/dhis-2/dhis-web-api/src/main/java/org/hisp/dhis/webapi/filter/AppCacheFilter.java
UTF-8
4,588
1.726563
2
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.webapi.filter; import java.io.CharArrayWriter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import lombok.extern.slf4j.Slf4j; import org.hisp.dhis.i18n.ui.locale.UserSettingLocaleManager; import org.hisp.dhis.system.SystemInfo; import org.hisp.dhis.system.SystemService; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.UserSettingKey; import org.hisp.dhis.user.UserSettingService; import org.springframework.beans.factory.annotation.Autowired; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ @Slf4j @WebFilter(urlPatterns = {"*.appcache"}) public class AppCacheFilter implements Filter { @Autowired private CurrentUserService currentUserService; @Autowired private SystemService systemService; @Autowired private UserSettingLocaleManager localeManager; @Autowired private UserSettingService userSettingService; @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; PrintWriter writer = response.getWriter(); CharResponseWrapper responseWrapper = new CharResponseWrapper(response); chain.doFilter(request, responseWrapper); responseWrapper.setContentType("text/cache-manifest"); SystemInfo systemInfo = systemService.getSystemInfo(); writer.print(responseWrapper.toString()); writer.println("# DHIS2 " + systemInfo.getVersion() + " r" + systemInfo.getRevision()); writer.println("# User: " + currentUserService.getCurrentUsername()); writer.println("# User UI Language: " + localeManager.getCurrentLocale()); writer.println( "# User DB Language: " + userSettingService.getUserSetting(UserSettingKey.DB_LOCALE)); writer.println("# Calendar: " + systemInfo.getCalendar()); } } @Override public void init(FilterConfig filterConfig) throws ServletException { log.debug("Init AppCacheFilter called!"); } @Override public void destroy() { log.debug("Destroy AppCacheFilter called!"); } } class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; @Override public String toString() { return output.toString(); } public CharResponseWrapper(HttpServletResponse response) { super(response); output = new CharArrayWriter(); } @Override public PrintWriter getWriter() { return new PrintWriter(output); } }
true
b4768f42f5a68480b0c00d9c8933178623ca4473
Java
dubenju/javay
/src/java/com/tulskiy/musique/gui/menu/LibraryMenu.java
UTF-8
2,584
2.046875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2008, 2009, 2010, 2011 Denis Tulskiy * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * version 3 along with this work. If not, see <http://www.gnu.org/licenses/>. */ package com.tulskiy.musique.gui.menu; import com.tulskiy.musique.gui.library.LibraryTree; import com.tulskiy.musique.gui.playlist.PlaylistColumn; import com.tulskiy.musique.gui.playlist.PlaylistTable; import com.tulskiy.musique.images.Images; import com.tulskiy.musique.playlist.Playlist; import com.tulskiy.musique.playlist.Track; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import static com.tulskiy.musique.gui.library.LibraryAction.*; /** * Author: Denis Tulskiy * Date: 2/5/11 */ public class LibraryMenu extends Menu { private PlaylistTable fakeTable; public JPopupMenu create(LibraryTree parent, Playlist playlist, ArrayList<Track> tracks) { if (fakeTable == null) { fakeTable = new PlaylistTable(playlist, new ArrayList<PlaylistColumn>()); fakeTable.dispose(); } ActionMap aMap = parent.getActionMap(); JPopupMenu popup = new JPopupMenu(); JMenuItem sendToCurrent = new JMenuItem(aMap.get(SEND_TO_CURRENT)); sendToCurrent.setIcon(Images.getEmptyIcon()); sendToCurrent.setAccelerator(SEND_TO_CURRENT.getKeyStroke()); popup.add(sendToCurrent); JMenuItem sendToNew = new JMenuItem(aMap.get(SEND_TO_NEW)); sendToNew.setAccelerator(SEND_TO_NEW.getKeyStroke()); popup.add(sendToNew); JMenuItem addToCurrent = new JMenuItem(aMap.get(ADD_TO_CURRENT)); addToCurrent.setAccelerator(ADD_TO_CURRENT.getKeyStroke()); popup.add(addToCurrent); popup.addSeparator(); TracksMenu tracksMenu = new TracksMenu(); JPopupMenu menu = tracksMenu.create(fakeTable, playlist, tracks); for (Component component : menu.getComponents()) { popup.add(component); } return popup; } public static void addMenu(JMenu menu) { } }
true
8e50e6d2bb91b5abe0237afcce1eb5f38b3f8b67
Java
SergioCarvalho/SocialSports
/SocialSportsPlatform/src/indexacao/Evento.java
ISO-8859-2
2,637
2.90625
3
[]
no_license
package indexacao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Vector; public class Evento { public static Vector<String> devolveEventosBD() { // TODO Auto-generated method stub Vector<String> vector_eventos = new Vector<String>(); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/socialsports", "root", "mysqlsergio"); String sql = "select nome_evento from evento"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ vector_eventos.add(rs.getString(1)); } conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return vector_eventos; } public static void insereEventoBD(String evento, String modalidade) { // TODO Auto-generated method stub int id_modalidade = devolveEventoIdModalidade(modalidade); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/socialsports", "root", "mysqlsergio"); String sql_insert = "insert into evento (id_evento, nome_evento, id_modalidade)" + "values (null,'" + evento + "','" + id_modalidade + "')"; Statement stmt_insert = conn.createStatement(); stmt_insert.executeUpdate(sql_insert); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //mtodo que devolve o id_modalidade associado a cada modalidade protected static int devolveEventoIdModalidade(String modalidade) { // TODO Auto-generated method stub if(modalidade.equals("Futebol")){ return 1; } else if(modalidade.equals("Tnis")){ return 2; } else if(modalidade.equals("Basquetebol")){ return 3; } else return 1; } //devolve o id do evento baseado no nome do evento public static int devolveEventoIdEvento(String evento) { // TODO Auto-generated method stub int id_evento = 0; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/socialsports", "root", "mysqlsergio"); String sql = "select id_evento from evento where nome_evento = '" + evento + "'"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ id_evento = rs.getInt(1); } conn.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return id_evento; } }
true
2f2914cf9b4c50619a3c9975299d16e82959defa
Java
vijayks25/Java
/Polygon.java
UTF-8
448
3.09375
3
[]
no_license
public class Polygon { Point [] vertices; Polygon(int n) { vertices = new Point[n]; } Polygon() { vertices = new Point[4]; } float perimeter() { float per=0; for (int i = 0;i < vertices.length-1; i+=1) { per += vertices[i].distance(vertices[i+1]); } per = per + vertices[vertices.length-1].distance(vertices[0]) ; return per; } }
true
7d6dc8ae5e01b0d2cc0fe5338fcfdb126e355134
Java
lufei1992/coderising
/coreJava/src/main/java/java36/c1/s02/Demo02.java
UTF-8
2,860
3.84375
4
[]
no_license
package java36.c1.s02; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Objects; /** * Exception 实践选择 */ public class Demo02 { public static void main(String[] args) { readPreferences1(null); readPreferences2(null); } /** * 1. 尽量不要捕获类似Exception这样的通用异常,而是应该捕获特定异常。 * Thread.sleep() 抛出 InterruptedException * 2. 不要生吞(swallow)异常 */ public static void demo1(){ try { // 业务代码 // ... Thread.sleep(1000); } catch (Exception e) { // ignore it } } /** * 产品代码中,通常都不允许这样处理。 * 在稍微复杂一点的生产系统中,标准出错不是个合适的输出选项,因为你很难判断到底输出到哪里去了。 * 尤其是对于分布式系统,如果发生异常,但是无法找到堆栈轨迹(stacktrace),这纯属为诊断设置障碍。 * 所以,最好使用产品日志,详细地输出到日志系统里。 */ public static void demo2(){ try { // 业务代码 // ... }catch(Exception e){ e.printStackTrace(); } } /** * Throw early, catch late 原则 * 如果fileName 是null,那么程序就会抛出 NullPointerException,但是由于没有第一时间暴露 * 出问题,堆栈信息可能非常令人费解,往往需要相对复杂的定位。 * 实际产品代码中,可能是各种情况,比如获取配置失败之类的。在发现问题的时候, * 第一时间抛出去,能够更加清晰地反映问题。 * @param fileName fileName */ private static void readPreferences1(String fileName){ try { InputStream in = new FileInputStream(fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * 修改一下,让问题“throw early” * @param fileName */ private static void readPreferences2(String fileName){ Objects.requireNonNull(fileName); try { InputStream in = new FileInputStream(fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * “catch late ” * 捕获异常后,需要怎么处理? * 最差的方式:生吞异常 * 如果实在不知道如何处理,可以选择保留原有异常的cause信息,直接再抛出或者构建新的异常抛出去。 * 在更高层面,因为有了清晰的业务逻辑,往往会更清楚合适的处理方式是什么。 */ /** * */ }
true
d298e8cc5c764a35a3c67122f773193786ac2ea6
Java
CyranoChen/HAK-AMS
/fqdb/fqdb/src/main/java/com/nlia/fqdb/service/impl/CheckInDeskResolve.java
UTF-8
5,484
1.984375
2
[]
no_license
package com.nlia.fqdb.service.impl; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Node; import org.springframework.stereotype.Service; import com.nlia.fqdb.dao.CheckInDeskDao; import com.nlia.fqdb.entity.base.CheckInDesk; import com.nlia.fqdb.service.ICheckInDeskResolve; import com.nlia.fqdb.util.CommonData; import com.nlia.fqdb.util.ParseXmlUtil; import com.wonders.aiis.core.dao.GenericDao; import com.wonders.aiis.core.service.AbstractCrudService; @Service public class CheckInDeskResolve extends AbstractCrudService<CheckInDesk, Long> implements ICheckInDeskResolve { ParseXmlUtil parseXmlUtil = new ParseXmlUtil(); @Resource private CheckInDeskDao checkInDeskDao; @Resource private CheckInDeskManager checkInDeskManager; @Override protected GenericDao<CheckInDesk, Long> getDao() { return checkInDeskDao; } public String parseCheckInDeskDataOfXmlString(String xmlString) { Document doc; boolean isExist = false; String operationMode = ""; CheckInDesk checkInDesk = new CheckInDesk(); try { doc = DocumentHelper.parseText(xmlString); Node root = doc.selectSingleNode("/IMFRoot/SysInfo/OperationMode"); if(parseXmlUtil.isExistNode(root)) operationMode = root.getText(); isExist = isExist(doc); if("NEW".equals(operationMode)) { if(!isExist) { parseXmlString(checkInDesk, doc, operationMode); checkInDesk.setCreateUser(ParseXmlUtil.createUser); checkInDesk.setCreateTime(parseXmlUtil.getSysDate()); checkInDesk.setRemoveFlag("1"); return "success:" + checkInDeskManager.save(checkInDesk).getId().toString() + ":new"; } else { checkInDesk = findByKey(doc); operationMode = "MOD"; parseXmlString(checkInDesk, doc, operationMode); checkInDesk.setModifyUser(ParseXmlUtil.createUser); checkInDesk.setModifyTime(parseXmlUtil.getSysDate()); return "success:" + checkInDeskManager.save(checkInDesk).getId().toString() + ":mod"; } } if("MOD".equals(operationMode)) { if(isExist) { checkInDesk = findByKey(doc); parseXmlString(checkInDesk, doc, operationMode); checkInDesk.setModifyUser(ParseXmlUtil.createUser); checkInDesk.setModifyTime(parseXmlUtil.getSysDate()); return "success:" + checkInDeskManager.save(checkInDesk).getId().toString() + ":mod"; } else { operationMode = "NEW"; parseXmlString(checkInDesk, doc, operationMode); checkInDesk.setCreateUser(ParseXmlUtil.createUser); checkInDesk.setCreateTime(parseXmlUtil.getSysDate()); checkInDesk.setRemoveFlag("1"); return "success:" + checkInDeskManager.save(checkInDesk).getId().toString() + ":new"; } } if("DEL".equals(operationMode)) { if (isExist) { checkInDesk = findByKey(doc); checkInDesk.setRemoveFlag("0"); return "success:" + checkInDeskManager.save(checkInDesk).getId().toString() + ":del"; } else { return "failure:0:no"; } } } catch (DocumentException e) { e.printStackTrace(); } return "failure:2:no"; } public boolean isExist(Document doc) { Map<String, Object> filters = new HashMap<String, Object>(); Node root = doc.selectSingleNode("/IMFRoot/Data/PrimaryKey/BasicDataKey/BasicDataID"); if(parseXmlUtil.isExistNode(root)) filters.put("basicDataID_equal", root.getText()); filters.put("removeFlag_equal", CommonData.REMOVEFLAG.NOT_REMOVED.getValue()); if((checkInDeskManager.findBy(filters, null, -1, -1)).size() > 0) return true; else return false; } public CheckInDesk findByKey(Document doc) { Map<String, Object> filters = new HashMap<String, Object>(); Node root; root = doc.selectSingleNode("/IMFRoot/Data/PrimaryKey/BasicDataKey/BasicDataID"); if(parseXmlUtil.isExistNode(root)) { filters.put("basicDataID_equal", root.getText()); } filters.put("removeFlag_equal", CommonData.REMOVEFLAG.NOT_REMOVED.getValue()); return checkInDeskManager.findBy(filters, null, -1, -1).get(0); } public void parseXmlString(CheckInDesk checkInDesk, Document doc, String operationMode) { Node root; root = doc.selectSingleNode("/IMFRoot/Data/PrimaryKey/BasicDataKey/BasicDataID"); if(parseXmlUtil.isInsertOrUpdateNode(root, operationMode)) { checkInDesk.setBasicDataID(root.getText()); } root = doc.selectSingleNode("/IMFRoot/Data/BasicData/CheckInDesk/CheckInDeskCode"); if(parseXmlUtil.isInsertOrUpdateNode(root, operationMode)) { checkInDesk.setCheckInDeskCode(root.getText()); } root = doc.selectSingleNode("/IMFRoot/Data/BasicData/CheckInDesk/CheckInDeskTerminal"); if(parseXmlUtil.isInsertOrUpdateNode(root, operationMode)) { checkInDesk.setCheckInDeskTerminal(root.getText()); } root = doc.selectSingleNode("/IMFRoot/Data/BasicData/CheckInDesk/CheckInDeskType"); if(parseXmlUtil.isInsertOrUpdateNode(root, operationMode)) { checkInDesk.setCheckInDeskType(root.getText()); } root = doc.selectSingleNode("/IMFRoot/Data/BasicData/CheckInDesk/CheckInDeskDescription"); if(parseXmlUtil.isInsertOrUpdateNode(root, operationMode)) { checkInDesk.setCheckInDeskDescription(root.getText()); } } }
true
4d64e08625e4161ea83fffa0aa88dae2ea4bbb0f
Java
Dowat/main
/src/main/java/seedu/task/logic/commands/DeleteTaskCommand.java
UTF-8
2,278
2.984375
3
[ "MIT" ]
permissive
package seedu.task.logic.commands; import java.util.logging.Logger; import seedu.task.model.item.ReadOnlyTask; import seedu.task.model.item.Task; import seedu.task.model.item.UniqueTaskList.TaskNotFoundException; import seedu.task.commons.core.LogsCenter; import seedu.task.commons.core.Messages; import seedu.task.commons.core.UnmodifiableObservableList; /** * @@author A0121608N * Deletes a Task identified using it's last displayed index from the taskbook. * */ public class DeleteTaskCommand extends DeleteCommand { public static final String MESSAGE_DELETE_TASK_SUCCESS = "Deleted Task: %1$s"; private ReadOnlyTask taskToDelete; private final Logger logger = LogsCenter.getLogger(DeleteTaskCommand.class); public DeleteTaskCommand(int targetIndex) { this.lastShownListIndex = targetIndex; } public DeleteTaskCommand(Task taskToDelete) { this.taskToDelete = taskToDelete; } @Override public CommandResult execute() { assert model != null; if(taskToDelete == null){ UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (outOfBounds(lastShownList.size())) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } taskToDelete = lastShownList.get(lastShownListIndex - 1); } logger.info("-------[Executing DeleteTaskCommand] " + this.toString() ); try { model.deleteTask(taskToDelete); } catch (TaskNotFoundException tnfe) { assert false : "The target task cannot be missing"; } return new CommandResult(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToDelete)); } private boolean outOfBounds(int listSize){ return listSize < lastShownListIndex || lastShownListIndex < 1; } @Override public CommandResult undo() { AddTaskCommand reverseCommand = new AddTaskCommand(taskToDelete); reverseCommand.setData(model); return reverseCommand.execute(); } @Override public String toString() { return COMMAND_WORD +" "+ this.taskToDelete.getAsText(); } }
true
4548b288c1219f3b5787c0b83c7800162658c295
Java
RainmanJin/ZhejiangMicroEnt
/.svn/pristine/a4/a42143260b009dcb1b162c79570734df431fbb64.svn-base
UTF-8
7,544
2.3125
2
[]
no_license
package gscloud; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.commons.lang.StringUtils; import cn.gov.zj.gsj.v1.api.GsjClient; import cn.gov.zj.gsj.v1.obj.entity.DeleteRequest; import cn.gov.zj.gsj.v1.obj.entity.DeleteResponse; import cn.gov.zj.gsj.v1.obj.entity.InputData; import cn.gov.zj.gsj.v1.obj.entity.InputRequest; import cn.gov.zj.gsj.v1.obj.entity.InputResponse; import cn.gov.zj.gsj.v1.obj.entity.ModifyRequest; import cn.gov.zj.gsj.v1.obj.entity.ModifyResponse; import cn.gov.zj.gsj.v1.obj.entity.QueryRequest; import cn.gov.zj.gsj.v1.obj.entity.QueryResponse; import cn.gov.zj.gsj.v1.sys.ApiException; /** * 工商云平台数据库相关方法操作 * * @author zhuyong */ public class CrudClould { public void crudClould() { } /** * 数据查询 * * @param client * @param ip * @param db * @param table */ @SuppressWarnings("unchecked") public HashMap<String, String> queryInstance(GsjClient client, String ip, String db, String sql) { QueryRequest queryRequest = new QueryRequest(); @SuppressWarnings("rawtypes") HashMap hmr = new HashMap(); queryRequest.setIp(ip);// 数据库 IP queryRequest.setDb(db);// 数据库名 queryRequest.setQuery(sql);// select // select // * queryRequest.setPageNum(0);// 查询起始,注意不是页数 queryRequest.setPageSize(20);// 查询数量 try { QueryResponse queryResponse = client.excute(queryRequest); System.out.println(queryResponse.getErrorCode()); if (StringUtils.isEmpty(queryResponse.getErrorCode())) { // 执行成功 String result = queryResponse.getResult(); // 获取结果信息 System.out.println("result:" + result); hmr.put("result", "success"); hmr.put("data", result); return hmr; } else { String errorCode = queryResponse.getErrorCode(); // 获取错误码 String message = queryResponse.getMessage(); // 获取错误 System.out.println("errorCode:" + errorCode); System.out.println("message:" + message); hmr.put("result", "error"); hmr.put("errorCode", errorCode); hmr.put("message", message); return hmr; } } catch (ApiException e) { e.printStackTrace(); } finally { // client. } hmr.put("result", "error"); hmr.put("errorCode", "111"); hmr.put("message", "连接异常"); return hmr; } /** * 单条数据插入 * * @param client * @param ip * @param db * @param table */ public void InputInstance(GsjClient client, String ip, String db, String table) { InputRequest inputRequest = new InputRequest(); inputRequest.setIp(ip);// 数据库 IP inputRequest.setDb(db);// 数据库名 inputRequest.setTable(table);// 表名 InputData data = new InputData(); data.putData("field", "test");// 字段名和字段值,字段值如果是日期格式则需使用"YYYY-MM-DD // hh:mm:ss"(长短按字段格式定)格式的字符串作为字段值填入 data.putData("field2", "test2"); data.putData("field3", "test3"); inputRequest.setData(data); try { InputResponse inputResponse = client.excute(inputRequest); if (StringUtils.isEmpty(inputResponse.getErrorCode())) { // 执行成功 String result = inputResponse.getResult(); // 获取结果信息 System.out.println("result:" + result); } else { String errorCode = inputResponse.getErrorCode(); // 获取错误码 String message = inputResponse.getMessage(); // 获取错误信息 System.out.println("errorCode:" + errorCode); System.out.println("message:" + message); } } catch (ApiException e) { // TODO: handle exception } } /** * 多条数据 */ public void InputManyInstance(GsjClient client, String ip, String db, String table) { InputRequest inputRequest = new InputRequest(); inputRequest.setIp("59.202.28.95");// 数据库 IP inputRequest.setDb("TESTDB");// 数据库名 inputRequest.setTable("testab");// 表名 List<InputData> dataList = new ArrayList<InputData>(); InputData data1 = new InputData(); data1.putData("field", "test");// 字段名和字段值,字段值如果是日期格式则需使用"YYYY-MM-DD // hh:mm:ss"(长短按字段格式定)格式的字符串作为字段值填入 data1.putData("field2", "test2"); data1.putData("field3", "test3"); dataList.add(data1); InputData data2 = new InputData(); data2.putData("field", "test4"); data2.putData("field2", "test5"); data2.putData("field3", "test6"); dataList.add(data2); inputRequest.setDatas(dataList); try { InputResponse inputResponse = client.excute(inputRequest); if (StringUtils.isEmpty(inputResponse.getErrorCode())) { // 执行成功 String result = inputResponse.getResult(); // 获取结果信息 System.out.println("result:" + result); } else { String errorCode = inputResponse.getErrorCode(); // 获取错误码 String message = inputResponse.getMessage(); // 获取错误信息 System.out.println("errorCode:" + errorCode); System.out.println("message:" + message); } } catch (ApiException e) { // TODO: handle exception } } /** * 更新操作 */ public void ModifyInstance(GsjClient client, String ip, String db, String table) { ModifyRequest modifyRequest = new ModifyRequest(); modifyRequest.setIp("59.202.28.95");// 数据库 IP modifyRequest.setDb("TESTDB");// 数据库名 modifyRequest.setTable("testab");// 表名 InputData data = new InputData(); data.putData("field", "test8");// 字段名和字段值,字段值如果是日期格式则需使用"YYYY-MM-DD // hh:mm:ss"(长短按字段格式定)格式的字符串作为字段值填入 data.putData("field2", "test88"); data.putData("field3", "test888"); modifyRequest.setWhere("id=1 and field=test");// where 条件,用于 updatesql modifyRequest.setData(data); try { ModifyResponse modifyResponse = client.excute(modifyRequest); if (StringUtils.isEmpty(modifyResponse.getErrorCode())) { // 执行成功 String result = modifyResponse.getResult(); // 获取结果信息 System.out.println("result:" + result); } else { String errorCode = modifyResponse.getErrorCode(); // 获取错误码 String message = modifyResponse.getMessage(); // 获取错误信息 System.out.println("errorCode:" + errorCode); System.out.println("message:" + message); } } catch (ApiException e) { // TODO: handle exception } } /** * 删除操作 若删除成功则返回值 result 为“success , 删除数据数量:n”,n 为删除的数据条数。 */ public void deleteInstance(GsjClient client, String ip, String dbName, String tableName,String whereSql) { DeleteRequest deleteRequest = new DeleteRequest(); deleteRequest.setIp("59.202.28.95");// 数据库 IP deleteRequest.setDb(dbName);// 数据库名 deleteRequest.setTable(tableName);// 表名 deleteRequest.setWhere(whereSql);// where 条件,用于 delete sql try { DeleteResponse deleteResponse = client.excute(deleteRequest); if (StringUtils.isEmpty(deleteResponse.getErrorCode())) { // 执行成功 String result = deleteResponse.getResult(); // 获取结果信息 System.out.println("result:" + result); } else { String errorCode = deleteResponse.getErrorCode(); // 获取错误码 String message = deleteResponse.getMessage(); // 获取错误信息 System.out.println("errorCode:" + errorCode); System.out.println("message:" + message); } } catch (ApiException e) { e.printStackTrace(); } } }
true
2b094fdecb16696663dabdc01124c888c92595ec
Java
floodboad/IBM-Resilience4J-June
/functional-Programm/src/main/java/com/example/demo/LambdaArgsParameters.java
UTF-8
2,303
3.921875
4
[]
no_license
package com.example.demo; @FunctionalInterface interface Single { void setName(String name); } //Two or more parameters @FunctionalInterface interface Concatation { void concat(String firstName, String lastName); } //ReturnValues @FunctionalInterface interface Producer { String produce(); } @FunctionalInterface interface SupplyAndProduce { String accept(String something); } @FunctionalInterface interface Calculator { int calculate(int a, int b); } public class LambdaArgsParameters { public static void main(String[] args) { //Pass single parameter Single single = null; //pass single Variable single = (String name) -> { System.out.println(name); System.out.println("Single Interface"); }; single.setName("Subramanian"); //code Refactoring 1: if function body has one line of code: remove {} single = (String name) -> System.out.println(name); single.setName("Subramanian"); //code Refactoring 2: if function arg has variable with type // Type inference : the type is implicitly understood. single = (name) -> System.out.println(name); single.setName("Subramanian"); //code Refactoring 3: if function single arg has variable with type :drop () single = name -> System.out.println(name); single.setName("Subramanian"); //Two parameters Concatation concatation = (firstName, lastName) -> System.out.println(firstName + lastName); concatation.concat("Subramanian", "Murugan"); Producer producer = null; producer = () -> { return "SOmething has produced"; }; System.out.println(producer.produce()); //code Refactoring 1: if function body has only return statement, no more code: remove {} and return statement producer = () -> "SOmething has produced"; System.out.println(producer.produce()); //take and return the same SupplyAndProduce sp = something -> something; System.out.println(sp.accept("something is taken and returned")); Calculator calc = (a, b) -> { int c = a + b; return c; }; System.out.println(calc.calculate(10, 20)); } }
true
8b2894dc1b895f19eca12f5d68d13ba72e1d4665
Java
littleredcap/Douyu
/my_player/src/main/java/liang/zhou/lane8/no5/my_player/common/Loader.java
UTF-8
182
1.6875
2
[]
no_license
package liang.zhou.lane8.no5.my_player.common; import java.util.Map; public interface Loader<T> { void load(Map<String,String> header,String url,ServerResponse<T> listener); }
true
ef8e36b369303aa59f5ce708a4a71c244e98c21c
Java
webroboteu/sdk
/src/webrobotapi/model/transform/Delete_bot_from_idRequestProtocolMarshaller.java
UTF-8
2,103
1.992188
2
[]
no_license
/** * null */ package webrobotapi.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import webrobotapi.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * Delete_bot_from_idRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class Delete_bot_from_idRequestProtocolMarshaller implements Marshaller<Request<Delete_bot_from_idRequest>, Delete_bot_from_idRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.API_GATEWAY) .requestUri("/bots/{projectId}/id/{botId}").httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false) .hasPayloadMembers(false).serviceName("webrobotapi").build(); private final com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory; public Delete_bot_from_idRequestProtocolMarshaller(com.amazonaws.opensdk.protect.protocol.ApiGatewayProtocolFactoryImpl protocolFactory) { this.protocolFactory = protocolFactory; } public Request<Delete_bot_from_idRequest> marshall(Delete_bot_from_idRequest delete_bot_from_idRequest) { if (delete_bot_from_idRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<Delete_bot_from_idRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, delete_bot_from_idRequest); protocolMarshaller.startMarshalling(); Delete_bot_from_idRequestMarshaller.getInstance().marshall(delete_bot_from_idRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
true
4686cde3e82a20dc7c88429aa58561fa4169870c
Java
logzio/logzio-java-sender
/logzio-sender-test/src/main/java/io/logz/test/MockLogzioBulkListener.java
UTF-8
10,992
2.125
2
[ "Apache-2.0" ]
permissive
package io.logz.test; import com.google.common.base.Splitter; import com.google.common.base.Throwables; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.eclipse.jetty.io.RuntimeIOException; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.BindException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; import static org.assertj.core.api.Assertions.assertThat; public class MockLogzioBulkListener implements Closeable { private final static Logger logger = LoggerFactory.getLogger(MockLogzioBulkListener.class); private static final String LISTENER_ADDRESS = "localhost"; private Server server; private Queue<LogRequest> logRequests = new ConcurrentLinkedQueue<>(); private final String host; private final int port; private int malformedLogs = 0; private boolean isServerTimeoutMode = false; private boolean raiseExceptionOnLog = false; private int timeoutMillis = 10000; public void setFailWithServerError(boolean raiseExceptionOnLog) { this.raiseExceptionOnLog = raiseExceptionOnLog; } public void setServerTimeoutMode(boolean serverTimeoutMode) { this.isServerTimeoutMode = serverTimeoutMode; } public void setTimeoutMillis(int timeoutMillis) { this.timeoutMillis = timeoutMillis; } public MockLogzioBulkListener() throws IOException { this.host = LISTENER_ADDRESS; this.port = findFreePort(); server = new Server(new InetSocketAddress(host, port)); server.setHandler(new AbstractHandler() { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException{ logger.debug("got request with query string: {} ({})", request.getQueryString(), this); if (isServerTimeoutMode) { try { Thread.sleep(timeoutMillis); baseRequest.setHandled(true); return; } catch (InterruptedException e) { // swallow } } // Bulks are \n delimited, so handling each log separately try (Stream<String> logStream = getLogsStream(request)) { logStream.forEach(line -> { if (raiseExceptionOnLog) { throw new RuntimeException(); } String queryString = request.getQueryString(); LogRequest tmpRequest = new LogRequest(queryString, line); logRequests.add(tmpRequest); logger.debug("got log: {} ", line); }); logger.debug("Total number of logRequests {} ({})", logRequests.size(), logRequests); } catch (IllegalArgumentException e) { malformedLogs++; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } finally { baseRequest.setHandled(true); } } }); logger.info("Created a mock listener ("+this+")"); } private Stream<String> getLogsStream(HttpServletRequest request) throws IOException { String contentEncoding = request.getHeader("Content-Encoding"); if (contentEncoding != null && request.getHeader("Content-Encoding").equals("gzip")) { GZIPInputStream gzipInputStream = new GZIPInputStream(request.getInputStream()); Reader decoder = new InputStreamReader(gzipInputStream, "UTF-8"); BufferedReader br = new BufferedReader(decoder); return br.lines(); } else { return request.getReader().lines(); } } private int findFreePort() throws IOException { int attempts = 1; int port = -1; while (attempts <= 3) { int availablePort = -1; try { ServerSocket serverSocket = new ServerSocket(0); serverSocket.close(); availablePort = serverSocket.getLocalPort(); port = availablePort; break; } catch (BindException e) { if (attempts++ == 3) { throw new RuntimeException("Failed to get a non busy port: "+availablePort, e); } else { logger.info("Failed to start mock listener on port {}", availablePort); } } } return port; } public void start() throws Exception { logger.info("Starting MockLogzioBulkListener"); server.start(); int attempts = 1; while (!server.isRunning()) { logger.info("Server has not started yet"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw Throwables.propagate(e); } attempts++; if (attempts > 10) { throw new RuntimeIOException("Failed to start after multiple attempts"); } } logger.info("Started listening on {}:{} ({})", host, port, this); } public void stop() { logger.info("Stopping MockLogzioBulkListener"); try { server.stop(); } catch (Exception e) { e.printStackTrace(); } int attempts = 1; while (server.isRunning()) { logger.info("Server has not stopped yet"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw Throwables.propagate(e); } attempts++; if (attempts > 10) { throw new RuntimeIOException("Failed to stop after multiple attempts"); } } logger.info("Stopped listening on {}:{} ({})", host, port, this); } @Override public void close() throws IOException { stop(); } public Collection<LogRequest> getReceivedMsgs() { return Collections.unmodifiableCollection(logRequests); } public int getPort() { return port; } public String getHost() { return host; } public static class LogRequest { private final String token; private final String type; private final JsonObject jsonObject; public LogRequest(String queryString, String logLine) { Map<String, String> paramToValueMap = Splitter.on('&').withKeyValueSeparator('=').split(queryString); if (paramToValueMap.containsKey("token")) { token = paramToValueMap.get("token"); } else { throw new IllegalArgumentException("Token not found in query string: "+queryString); } if (paramToValueMap.containsKey("type")) { type = paramToValueMap.get("type"); } else { throw new IllegalArgumentException("Token not found in query string: "+queryString); } try { jsonObject = new JsonParser().parse(logLine).getAsJsonObject(); } catch (Exception e) { throw new IllegalArgumentException("Not a valid json received in body of request. logLine = " + logLine, e); } } public String getToken() { return token; } public String getType() { return type; } public JsonObject getJsonObject() { return jsonObject; } public String getMessage() { return getStringFieldOrNull("message"); } public String getLogger() { return getStringFieldOrNull("logger"); } public String getLogLevel() { return getStringFieldOrNull("loglevel"); } public String getHost() { return getStringFieldOrNull("hostname"); } public String getStringFieldOrNull(String fieldName) { if (jsonObject.get(fieldName) == null) return null; return jsonObject.get(fieldName).getAsString(); } @Override public String toString() { return "[Token = "+token +", type = "+type+"]: " + jsonObject.toString(); } } public Optional<LogRequest> getLogByMessageField(String msg) { return logRequests.stream() .filter(r -> r.getMessage() != null && r.getMessage().equals(msg)) .findFirst(); } public int getNumberOfReceivedLogs() { return logRequests.size(); } public int getNumberOfReceivedMalformedLogs() { return malformedLogs; } public MockLogzioBulkListener.LogRequest assertLogReceivedByMessage(String message) { Optional<MockLogzioBulkListener.LogRequest> logRequest = getLogByMessageField(message); assertThat(logRequest.isPresent()).describedAs("Log with message '"+message+"' received").isTrue(); return logRequest.get(); } public void assertNumberOfReceivedMsgs(int count) { assertThat(getNumberOfReceivedLogs()) .describedAs("Messages on mock listener: {}", getReceivedMsgs()) .isEqualTo(count); } public void assertNumberOfReceivedMalformedMsgs(int count) { assertThat(getNumberOfReceivedMalformedLogs()) .describedAs("Malformed messages on mock listener: {}", malformedLogs) .isEqualTo(count); } public void assertLogReceivedIs(String message, String token, String type, String loggerName, String level) { MockLogzioBulkListener.LogRequest log = assertLogReceivedByMessage(message); assertLogReceivedIs(log, token, type, loggerName, level); } public void assertLogReceivedIs(MockLogzioBulkListener.LogRequest log, String token, String type, String loggerName, String level) { assertThat(log.getToken()).isEqualTo(token); assertThat(log.getType()).isEqualTo(type); assertThat(log.getLogger()).isEqualTo(loggerName); assertThat(log.getLogLevel()).isEqualTo(level); } }
true
bc84d19797cef1b95906835a68a088cfc4c9f5de
Java
zzhujing/JavaDataStructureAndAlgorithm
/src/test/java/com/concurrent/juc/AtomicIntegerTest.java
UTF-8
845
3.125
3
[]
no_license
package com.concurrent.juc; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; /** * AtomicInteger 之类的原子类型主要是通过{@link sun.misc.Unsafe#compareAndSwapInt(Object, long, int, int)} * 来进行CPU指令级别的比较和赋值 */ public class AtomicIntegerTest { @Test public void testAtomic() { final AtomicInteger value = new AtomicInteger(); // IntStream.rangeClosed(1, 2) // .forEach(i -> new Thread(() -> { // while (value.getAndIncrement() < 50) { // System.out.println(Thread.currentThread().getName() +"->"+value.get()); // } // }, String.valueOf(i)).start()); System.out.println(value.accumulateAndGet(1, Integer::sum)); } }
true
5695bd1c018aab1c0a8ccdf5a87d15744de903dc
Java
GLTron3000/PacmanProject
/src/main/java/entity/Pacgum.java
UTF-8
787
2.890625
3
[]
no_license
package entity; import game.Kernel; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; public class Pacgum extends Pickable{ public Pacgum(double x, double y) { super(x, y); type="Pacgum"; } @Override public void onPick(Kernel k) { k.pickables.remove(this); k.score+=value; } @Override public void draw(Canvas canvas) { GraphicsContext gc = canvas.getGraphicsContext2D(); if(texture == null){ gc.setFill(Color.WHITE); gc.fillRect(x, y, size, size); }else{ gc.setFill(Color.BLACK); gc.fillRect(x, y, size, size); gc.drawImage(texture, x, y, size, size); } } }
true
bb5e271a798b15e32532b5e3acf394289806f924
Java
jainaks2010/SpringBootDemoActuator
/src/main/java/com/demo/spring/boot/actuator/authentication/UserServiceHealth.java
UTF-8
820
1.867188
2
[]
no_license
package com.demo.spring.boot.actuator.authentication; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import com.demo.spring.boot.services.user.UserService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; @Component @RestControllerEndpoint(id="user-service") public class UserServiceHealth { @Autowired private UserService userService; @GetMapping("/health") public Map<String,String> checkUserServiceHealth() throws JsonMappingException, JsonProcessingException { return userService.getUser(1); } }
true
44b2afd2f6948999b781bd0c93fae7b0505225dc
Java
jsonx-org/java
/generator/src/main/java/org/jsonx/Spec.java
UTF-8
1,477
2.59375
3
[ "MIT" ]
permissive
/* Copyright (c) 2020 JSONx * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.jsonx; class Spec<T> { /** * Creates a new {@link Spec} with the specified {@code set} and {@code get} values. * * @param <T> The type parameter of the arguments. * @param set The raw value set from the specification. * @param get The calculated value to be gotten from this {@link Spec}. * @return A new {@link Spec} with the specified {@code set} and {@code get} values. */ static <T>Spec<T> from(final T set, final T get) { return new Spec<>(set, get); } final T set; final T get; private Spec(final T set, final T get) { this.set = set; this.get = get; } @Override public String toString() { return "set: " + set + "\nget: " + get; } }
true
a34ab33635257a9667a649b9b57ced375cb5f8de
Java
piupiuhwt/codenote
/src/main/java/com/hwt/notes/basic/RadixExample.java
UTF-8
1,493
2.96875
3
[]
no_license
package com.hwt.notes.basic; import java.lang.management.ManagementFactory; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; //进制问题 //java中默认没有无符号数 //所以记得 int类型 二进制表示时 最高位为1 表示负数 //所以下方得最后一个输出为false //改正方法时在进制数据后方加个L使他变为long类型 public class RadixExample { public static void main(String[] args) { System.out.println(0xf0000000); System.out.println(0b11110000000000000000000000000000L); //上面输出是f0000000 System.out.println(4026531840L == 0b11110000000000000000000000000000); //这个输出啥 System.out.println("".equals(new String(new char[]{'a','c'}, 0, 0))); Map<String,Boolean> c = new HashMap(); Boolean taskStatus = true; System.out.println(taskStatus == null); System.out.println(ManagementFactory.getOperatingSystemMXBean().getName()); String useString = "/test/task_0/rule_234542/adfasdf12313fdgdg.pcap"; Pattern pattern = Pattern.compile("/task_\\d+/"); Matcher matcher = pattern.matcher(useString); if (matcher.find()) { int start = matcher.start(); int end = matcher.end(); System.out.println(useString.substring(start+1, end-1)); System.out.println("start : " + start + " end : " + end); } } }
true
caeaf1c52115c7a3cd1bf7c94410f19e823e4f08
Java
damithsenanayake/openaz-pep-implementation
/src/main/java/org/wso2/identity/entitlement/proxy/pep/PepResponseImpl.java
UTF-8
15,377
1.96875
2
[]
no_license
package org.wso2.identity.entitlement.proxy.pep; import java.util.HashMap; import org.openliberty.openaz.azapi.AzResponseContext; import org.openliberty.openaz.azapi.AzResult; import org.openliberty.openaz.azapi.AzEntity; import org.openliberty.openaz.azapi.AzObligations; import org.openliberty.openaz.azapi.constants.AzCategoryIdObligation; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openliberty.openaz.azapi.pep.PepRequestFactory; import org.openliberty.openaz.azapi.pep.PepResponse; import org.openliberty.openaz.azapi.pep.PepRequest; import org.openliberty.openaz.azapi.pep.PepResponseFactory; import org.openliberty.openaz.azapi.pep.Obligation; import org.openliberty.openaz.azapi.pep.PepException; import org.openliberty.openaz.azapi.constants.PepRequestOperation; import org.openliberty.openaz.azapi.constants.PepRequestQueryType; import org.openliberty.openaz.azapi.constants.PepResponseBehavior; import org.openliberty.openaz.azapi.constants.PepResponseType; import org.openliberty.openaz.azapi.AzResourceActionAssociation; /** * PepResponse is the main entry point for processing the results * of a {@link PepRequestImpl#decide()} call. * <br> * It enables processing one result at a time for an AzResponseContext, * which may contain multiple decisions from one of the * <ul> * <li> * {@link PepRequestFactoryImpl#newBulkPepRequest(Object, java.util.List, Object)} * calls, * </ul> * or a * <ul> * <li> * {@link PepRequestFactory#newQueryPepRequest(Object, Object, String, PepRequestQueryType)} * call. * </ul> * It also provides a wrapper around the <code>AzResponseContext</code> * which enables access to the underlying low level AzApi funtions. * <p> * Please refer to {@link PepRequestFactoryImpl} for code example containing * processing of a PepResponse. */ public class PepResponseImpl implements PepResponse { private Log log = LogFactory.getLog(this.getClass()); private AzResponseContext responseContext; private PepResponseFactory responseFactory; private PepRequestOperation operation; private PepRequest pepRequest; private Iterator resultIterator; private Object currentResult; private boolean queryAllowed; /** * Create an instance of the PepResponse using an AzResponseContext, * which is returned by an AzService.decide() or queryVerbose() * * @param responseContext the actual <code>AzResponseContext</code> from * the underlying AzService * @param pepRequest the pepRequest associated with this pepResponse * @param responseFactory the pepResponseFactory used to * create this pepResponse. * This handle is used to get access to the <code>ObligationFactory</code> * to create <code>Obligation</code> instances and access the * <code>Behavior</code> for each indeterminate response type * @see ObligationFactoryImpl * @see ObligationImpl * @see PepResponseFactoryImpl * @param operation the operation that this pepResponse is responding to */ PepResponseImpl(AzResponseContext responseContext, PepRequest pepRequest, PepResponseFactory responseFactory, PepRequestOperation operation) { super(); this.responseContext = responseContext; this.responseFactory = responseFactory; this.pepRequest = pepRequest; this.resultIterator = responseContext.getResults().iterator(); this.operation = operation; //Move the iterator to the first entry if it's a decide if (operation==PepRequestOperation.DECIDE && this.resultIterator.hasNext()) { if (log.isTraceEnabled()) log.trace( "Setting currentResult. Operation = " + operation); currentResult = this.resultIterator.next(); } } /** * Create a PepResponse from a Set<AzResourceActionAssociation> * which has been returned by an AzService.query(). * @param actionResourceAssociations * @param pepRequest * @param responseFactory * @param queryAllowed */ PepResponseImpl( Set<AzResourceActionAssociation> actionResourceAssociations, PepRequest pepRequest, PepResponseFactory responseFactory, boolean queryAllowed ) { this.operation = PepRequestOperation.QUERY; this.responseFactory = responseFactory; this.pepRequest = pepRequest; this.resultIterator = actionResourceAssociations.iterator(); this.queryAllowed = queryAllowed; if (log.isTraceEnabled()) log.trace( "Query ResponseImpl: " + "\n\tresultIterator.hasNext() = " + resultIterator.hasNext() + "\n\tqueryAllowed() = " + queryAllowed); } /** * For bulk requests and query requests, move the iterator to * the next result. * <b> * For bulk requests and query requests, the iterator initially * points prior to the first result. * <b> * For single newPepRequest, the iterator always points to the * first and only result and next() always returns false. * @return true if there is another result for bulk requests * and query requests, false otherwise. */ public boolean next() throws PepException { if (this.operation == PepRequestOperation.DECIDE) { this.log.warn( "The DECIDE operation only has a single result. " + "Don't call PepResponse.next()"); return false; } if (this.resultIterator.hasNext()) { this.currentResult = this.resultIterator.next(); return true; } else { this.currentResult = null; return false; } } /** * Returns the decision associated with the current result. * @return true if the user was granted access to the resource, * otherwise false * @throws PepException if the <code>Behavior</code> configured * in the <code>PepResponseFactory</code> * indicates that for the specific AzDecision and AzStatus * that an exception should be thrown */ public boolean allowed() throws PepException { if (!(this.currentResult instanceof AzResult)) { return this.queryAllowed; } AzResult azResult = (AzResult)this.currentResult; switch (azResult.getAzDecision()){ case AZ_PERMIT: return true; case AZ_DENY: return false; case AZ_NOTAPPLICABLE: return enforceBehavior(this.getResponseFactory(). getNotApplicableBehavior()); case AZ_INDETERMINATE: switch (azResult.getAzStatusCode()) { case AZ_SYNTAX_ERROR: return enforceBehavior(this.getResponseFactory(). getSyntaxErrorBehavior()); case AZ_PROCESSING_ERROR: return enforceBehavior(this.getResponseFactory(). getProcessingErrorBehavior()); case AZ_MISSING_ATTRIBUTE: return enforceBehavior(this.getResponseFactory(). getMissingAttributeBehavior()); } } // end switch throw new PepException( "AzResult.getAzDecision did not match any of the known values"); } /** * Return the action object associated with the current * result. The action object is the same object that was * used to create the PepRequest and may be used to * correlate the PepResponse results with the action-resource * pairs that were used to create the PepRequest. * @return an object that was used as an action in the PepRequest * @throws PepException */ public Object getAction() throws PepException { return getPepRequest().getActionObject( this.getAzResourceActionAssociation()); } /** * Return the resource object associated with the current * result. The resource object is the same object that was * used to create the PepRequest and may be used to * correlate the PepResponse results with the action-resource * pairs that were used to create the PepRequest. * @return an object that was used as a resource in the PepRequest * @throws PepException */ public Object getResource() throws PepException { return getPepRequest().getResourceObject( this.getAzResourceActionAssociation()); } /** * Return the set of Obligations associated with the current result * indexed by ObligationId. * @return a Map of String, Obligation pairs * @throws PepException */ public Map<String,Obligation> getObligations() throws PepException { assertValidResult(); HashMap<String,Obligation> obligations = new HashMap<String,Obligation>(); if (!(this.currentResult instanceof AzResult)) { this.log.warn( "getObligations() method not supported on " + "PepRequest.OPERATION.QUERY"); return obligations; } AzResult azResult = (AzResult)this.currentResult; AzObligations azObligations = azResult.getAzObligations(); if (azObligations!=null) { if (log.isTraceEnabled()) log.trace( "process azObligations"); Iterator<AzEntity<AzCategoryIdObligation>> obligationsIt = azObligations.iterator(); while (obligationsIt.hasNext()) { AzEntity<AzCategoryIdObligation> azObligation = obligationsIt.next(); if (log.isTraceEnabled()) log.trace( "read and wrap next azObligation"); Obligation obligation = this.getResponseFactory().getObligationFactory(). createObject(azObligation); String name = obligation.getAzEntity(). getAzEntityId(); if (log.isTraceEnabled()) log.trace( "\n\tput wrapped Obligation: ObligationId = " + name); obligations.put(name,obligation); } } else { if (log.isTraceEnabled()) log.trace( "No Obligations returned in PepResponse"); } return obligations; } /** * The handle to the actual <code>AzResponseContext</code>. * @return the AzResponseContext returned by AzApi */ public AzResponseContext getAzResponseContext() throws PepException { return this.responseContext; } /** * Return the PepRequest object associated with this * PepResponse. * @return the PepRequest object that was issued in * association with this PepResponse. */ public PepRequest getPepRequest(){ return pepRequest; } protected PepResponseFactory getResponseFactory() { return this.responseFactory; } AzResourceActionAssociation getAzResourceActionAssociation() throws PepException{ assertValidResult(); if (this.currentResult instanceof AzResult) { return ((AzResult)this.currentResult). getAzResourceActionAssociation(); } else { return ((AzResourceActionAssociation)this.currentResult); } } /** * Return true, false, or throw an Exception based on the * configured PepResponseBehavior that is passed here to enforce * @param behavior * @return * @throws PepException */ private boolean enforceBehavior(PepResponseBehavior behavior) throws PepException{ if (behavior==PepResponseBehavior.RETURN_YES) { return true; } else if (behavior==PepResponseBehavior.RETURN_NO) { return false; } else { this.log.error( "Enforce behavior is throwing an exception: " + "behavior = " + behavior.toString()); // rich: not sure why the following message was here // so I commented it out. It may have made sense for // an earlier version but no longer appears relevant: // + "This means that the allowed() method was called " + //"on an instance of the PepResponse that was not " + //"created by the PepRequest."); throw new PepException( "This Excecption is being thrown based on configured " + "PepResponseBehavior for AzResult containing AzDecision " + "with value of NotApplicable or Indeterminate"); } } private void assertValidResult() throws PepException { if (this.currentResult==null) { throw new PepException( "The current AzResult in this PepResponse is null."); } } public PepResponseType getPepResponseType() { // TODO Auto-generated method stub return null; } @Override public boolean getResourceActionOnly() { // TODO Auto-generated method stub return false; } } /** * Returns the information contained in the Obligations of this PepResponse * @return the key to the map is the <code>ObligationId</code>. The value is another map that contains the * name of the attribute and the value of the attribute contained in that <code>Obligation</code> * @throws PepException */ /* public Map<String,Map<String,String>> getObligations() throws PepException { assertValidResult(); HashMap<String,Map<String,String>> obligations = new HashMap<String,Map<String,String>>(); if (!(this.currentResult instanceof AzResult)) { this.log.warn("getObligations() method not supported on PepRequest.OPERATION.QUERY"); return obligations; } AzResult azResult = (AzResult)this.currentResult; AzObligations azObligations = azResult.getAzObligations(); if (azObligations!=null) { log.info("process obligations"); Iterator<AzEntity<AzCategoryIdObligation>> obligationsIt = azObligations.iterator(); while (obligationsIt.hasNext()) { AzEntity<AzCategoryIdObligation> azObligation = obligationsIt.next(); log.info("read next obligation"); Obligation obligation = this.getResponseFactory().getObligationFactory(). createObject(azObligation); String name = obligation.getWrappedObject(). getAzEntityId(); log.info("ObligationId = " + name); Map<String,String> values = obligation.getStringValues(); obligations.put(name,values); } } else { log.info("No Obligations returned in PepResponse"); } return obligations; } */
true
b3825b29e94147e1c2bfde61538dc6ddfa8b928e
Java
AlexMaskovyak/hardware-varying-network-simulator
/src/network/IData.java
UTF-8
365
2.734375
3
[]
no_license
package network; /** * Describes an abstract unit of data. * @author Alex Maskovyak * */ public interface IData { /** * Obtains the unique identifier for this piece. * @return the ID; */ public int getID(); /** * Obtains the actual content stored in this data wrapper. * @return Data's content; */ public byte[] getContent(); }
true
987d0ff3d2eed0de1043b3d17807c060a9aab682
Java
ZackZhouc/springboot-mybatis-base
/web/src/main/java/com/yzj/cep/web/config/BadRequestHandler.java
UTF-8
1,486
2.171875
2
[]
no_license
package com.yzj.cep.web.config; import com.yzj.cep.common.pojo.vo.ResponseVO; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice public class BadRequestHandler { @ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class) public ResponseVO badParamHandler(HttpServletRequest request, Exception e) throws Exception { e.printStackTrace(); return ResponseVO.genBadRequestResponse(); } @ExceptionHandler(org.springframework.web.HttpRequestMethodNotSupportedException.class) public ResponseVO methodNotAllowdHandler(HttpServletRequest request, Exception e) throws Exception { e.printStackTrace(); return ResponseVO.genMethodNotAllowedResponse(); } @ExceptionHandler(org.springframework.web.bind.MissingServletRequestParameterException.class) public ResponseVO missingRequireParameter(HttpServletRequest request, Exception e) throws Exception { e.printStackTrace(); return ResponseVO.genBadRequestResponse(); } @ExceptionHandler(org.springframework.web.HttpMediaTypeNotSupportedException.class) public ResponseVO httpMediaTypeNotSupportedException(HttpServletRequest request, Exception e) throws Exception { e.printStackTrace(); return ResponseVO.genHttpMediaTypeNotSupportedResponse(); } }
true
1f90ed2327ced9acb52ebf2eb918e19bad1ccbf5
Java
alsysew/workspace_java_VM
/VeiculosAbstratos/src/model/Moto.java
ISO-8859-1
491
2.875
3
[]
no_license
package model; public class Moto extends Veiculo{ private String estilo; public Moto(String marca, String placa, String estilo) { super(marca, placa); this.estilo = estilo; } @Override public void acelerar() { System.out.println("Moto "+super.marca+"/"+super.placa+"/"+this.estilo+" acelerando na mo! PROPROPROPRO"); } @Override public void freiar() { System.out.println("Moto "+super.marca+"/"+super.placa+"/"+this.estilo+" freiando no p! ROOOOOOOCCCCC"); } }
true
8b331aa535067dfa6dc068acd9bd93de9cb0d28f
Java
pointdisarr/flyinna
/src/main/java/DAO/DAOflight.java
UTF-8
2,992
2.953125
3
[]
no_license
package DAO; import console.Console; import console.SystemConsole; import entity.City; import entity.Flight; import java.io.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Random; public class DAOflight implements DAO { private final String rPath = "src/main/destCities.txt"; private final String pRath = "src/main/srcCities.txt"; private final String wPath = "src/main/flightboard.txt"; Random rnd = new Random(); int flightDstId = 0; int flightSrcId = 0; Console console = new SystemConsole(); ArrayList<Flight> flights = new ArrayList<>(); private String readDestination; private String readSource; private int flightId = 0; public DAOflight() { if (flights.size() == 0) { load(); } } public void load() { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(rPath)); BufferedReader bufferedReader2 = new BufferedReader(new FileReader(pRath)); readDestination = bufferedReader.readLine(); readSource = bufferedReader2.readLine(); while (readDestination != null || readSource != null) { LocalDateTime flightDate = LocalDateTime.of(LocalDate.now(), LocalTime.of(rnd.nextInt(24), rnd.nextInt(60))); readDestination = bufferedReader.readLine(); flightDstId++; readSource = bufferedReader2.readLine(); flightSrcId++; City cityDest = new City(flightDstId, readDestination); City citySrc = new City(flightSrcId, readSource); flightId++; Flight flight = new Flight(flightId, citySrc, cityDest, flightDate); flights.add(flight); } bufferedReader.close(); bufferedReader2.close(); create(); } catch (IOException ex) { console.printLn("Couldn't read from cities"); } } public void create() { try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(wPath))) { for (Flight c : flights) { try { bufferedWriter.write(String.valueOf(c)); bufferedWriter.newLine(); } catch (IOException e) { console.printLn("Couldn't update the board"); } } } catch (IOException e) { System.out.println("Couldn't to write to the board file"); } } @Override public Object get(int id) { return flights.get(id); } @Override public ArrayList getAll() { return flights; } @Override public void put(Object o) { flights.add((Flight) o); } @Override public void delete(int id) { flights.remove(id); } }
true
cfb803afd02fc2d4e8654764a53d8896db0a989b
Java
StutiSri/twu-biblioteca-stutisrivastava
/src/main/java/com/twu/io/outputwriter/ConsoleOutputWriter.java
UTF-8
610
2.84375
3
[ "Apache-2.0" ]
permissive
package com.twu.io.outputwriter; import com.twu.io.output.ConsoleOutput; import java.io.BufferedWriter; import java.io.IOException; public class ConsoleOutputWriter implements OutputWriter { private final BufferedWriter bufferedWriter; public ConsoleOutputWriter(BufferedWriter bufferedWriter) { this.bufferedWriter = bufferedWriter; } @Override public void write(ConsoleOutput output) { try { bufferedWriter.write(output.toString()); bufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } }
true
671598d4a6a3c9caec8a3a475c9c51cb42e78fe5
Java
GabeOchieng/ggnn.tensorflow
/data/libgdx/AndroidOnscreenKeyboard_subSequence.java
UTF-8
121
1.835938
2
[]
no_license
@Override public CharSequence subSequence(int start, int end) { Log.d("Editable", "subSequence"); return null; }
true
29057f210abd976794e331eaf913920ebdd182dd
Java
anantkshirsagar/FingerPrintRecognition
/src/com/mantra/service/BiometricService.java
UTF-8
1,423
2.75
3
[]
no_license
package com.mantra.service; import java.util.logging.Logger; import com.mantra.manager.FingerPrintEventManager; import MFS100.FingerData; import MFS100.MFS100; public class BiometricService { private static final Logger LOG = Logger.getLogger(BiometricService.class.getName()); private final MFS100 mfs100; public BiometricService(FingerPrintEventManager fingerPrintEventManager) { mfs100 = new MFS100(fingerPrintEventManager); getMfs100().Init(); LOG.info("Scanner initialized!"); } /** * This method is used to capture finger print data. <strong>if</strong> * showPreview is true then it first calls OnPreview() method & after * OnCaptureCompleted() method, <strong>else</strong> OnCaptureCompleted() * method is called. * * @param quality * @param timeOut * @param showPreview * @return * @throws InterruptedException */ public int startCapture(int quality, int timeOut, boolean showPreview) { LOG.info("In startCapture"); int status = getMfs100().StartCapture(quality, timeOut, showPreview); LOG.info("Status: " +status); return status; } public int autoCapture(FingerData fingerData, int timeOut, boolean showPreview, boolean isDetectFinger) { LOG.info("In autoCapture"); return getMfs100().AutoCapture(fingerData, timeOut, showPreview, isDetectFinger); } public MFS100 getMfs100() { return mfs100; } }
true
df41359ac72c68e14cdbb21539a279630132a0f8
Java
Cantara/Whydah-SecurityTokenService
/src/main/java/net/whydah/sts/errorhandling/AppExceptionMapper.java
UTF-8
560
2.109375
2
[ "Apache-2.0" ]
permissive
package net.whydah.sts.errorhandling; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider @Produces(MediaType.APPLICATION_XML) public class AppExceptionMapper implements ExceptionMapper<AppException> { public Response toResponse(AppException ex) { return Response.status(ex.getStatus()) .entity(ExceptionConfig.handleSecurity(new ErrorMessage(ex)).toString()) .type(MediaType.APPLICATION_JSON). build(); } }
true
e2ef0ea4bb746a0a417da4ebc1f8238655937c4b
Java
sebaudracco/bubble
/com/inmobi/rendering/a$4.java
UTF-8
2,217
1.8125
2
[]
no_license
package com.inmobi.rendering; import com.inmobi.commons.core.utilities.Logger; import com.inmobi.commons.core.utilities.Logger.InternalLogLevel; import com.inmobi.rendering.InMobiAdActivity.C3179b; /* compiled from: JavaScriptBridge */ class a$4 implements C3179b { final /* synthetic */ String f7970a; final /* synthetic */ String f7971b; final /* synthetic */ String f7972c; final /* synthetic */ String f7973d; final /* synthetic */ String f7974e; final /* synthetic */ String f7975f; final /* synthetic */ String f7976g; final /* synthetic */ String f7977h; final /* synthetic */ String f7978i; final /* synthetic */ String f7979j; final /* synthetic */ String f7980k; final /* synthetic */ a f7981l; a$4(a aVar, String str, String str2, String str3, String str4, String str5, String str6, String str7, String str8, String str9, String str10, String str11) { this.f7981l = aVar; this.f7970a = str; this.f7971b = str2; this.f7972c = str3; this.f7973d = str4; this.f7974e = str5; this.f7975f = str6; this.f7976g = str7; this.f7977h = str8; this.f7978i = str9; this.f7979j = str10; this.f7980k = str11; } public void mo6262a(int i, String[] strArr, int[] iArr) { if (iArr.length == 2 && iArr[0] == 0 && iArr[1] == 0) { try { a.a(this.f7981l).m10633a(this.f7970a, this.f7971b, this.f7972c, this.f7973d, this.f7974e, this.f7975f, this.f7976g, this.f7977h, this.f7978i, this.f7979j, this.f7980k); return; } catch (Exception e) { a.a(this.f7981l).m10631a(this.f7970a, "Unexpected error", "createCalendarEvent"); Logger.m10359a(InternalLogLevel.ERROR, "InMobi", "Could not create calendar event; SDK encountered unexpected error"); Logger.m10359a(InternalLogLevel.INTERNAL, a.a(), "SDK encountered unexpected error in handling createCalendarEvent() request from creative; " + e.getMessage()); return; } } a.a(this.f7981l).m10631a(this.f7970a, "Permission denied by user.", "createCalendarEvent"); } }
true
70c44be7ff14eb40cdbd420f0754bb254e831044
Java
flywind2/joeis
/src/irvine/oeis/a015/A015939.java
UTF-8
484
2.765625
3
[]
no_license
package irvine.oeis.a015; import irvine.math.z.Z; import irvine.oeis.Sequence; /** * A015939 <code>A015938(n)-2^n</code>. * @author Sean A. Irvine */ public class A015939 implements Sequence { private int mN = 0; @Override public Z next() { Z k = Z.ONE.shiftLeft(++mN); long j = 0; final Z n = Z.valueOf(mN); while (true) { k = k.add(1); ++j; if (Z.TWO.modPow(k, k).equals(Z.TWO.modPow(n, k))) { return Z.valueOf(j); } } } }
true
53d02b82b0756be40116bbc7df0871ade3b66ab1
Java
yamiko/cv_service
/src/main/java/org/cvs/application/services/CandidateServiceImpl.java
UTF-8
6,036
2.5625
3
[ "MIT" ]
permissive
package org.cvs.application.services; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Validator; import org.cvs.application.exceptions.EntryNotActiveException; import org.cvs.application.exceptions.EntryNotFoundException; import org.cvs.data.entities.Candidate; import org.cvs.data.entities.Portfolio; import org.cvs.data.repositories.CandidateRepository; import org.cvs.data.repositories.PortfolioRepository; import org.cvs.utils.Lookup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class CandidateServiceImpl implements CandidateService { @Autowired private PortfolioRepository portfolioRepository; @Autowired private CandidateRepository candidateRepository; @Autowired private Validator validator; @Override public Candidate addCandidate(Candidate candidate) { Candidate greenCandidate = new Candidate(); // Extract all fields to safely add to DB greenCandidate.setAddressLine1(candidate.getAddressLine1()); greenCandidate.setAddressLine2(candidate.getAddressLine2()); greenCandidate.setAddressLine3(candidate.getAddressLine3()); greenCandidate.setCountry(candidate.getCountry()); greenCandidate.setPostcode(candidate.getPostcode()); greenCandidate.setGender(candidate.getGender()); greenCandidate.setDateOfBirth(candidate.getDateOfBirth()); greenCandidate.setEmail(candidate.getEmail()); greenCandidate.setPreferredContactNumber(candidate.getPreferredContactNumber()); greenCandidate.setAlternativeContactNumber(candidate.getAlternativeContactNumber()); greenCandidate.setFirstName(candidate.getFirstName()); greenCandidate.setMiddleName(candidate.getMiddleName()); greenCandidate.setLastName(candidate.getLastName()); greenCandidate.setTitle(candidate.getTitle()); greenCandidate.setVoided(Lookup.NOT_VOIDED); greenCandidate.setRetired(Lookup.NOT_RETIRED); // Validate using Bean constraints Set<ConstraintViolation<Candidate>> violations = validator.validate(greenCandidate); if (!violations.isEmpty()) { StringBuilder sb = new StringBuilder(); for (ConstraintViolation<Candidate> constraintViolation : violations) { sb.append(" -> " + constraintViolation.getMessage()); } throw new ConstraintViolationException("Validation error: " + sb.toString(), violations); } List<Portfolio> portfolios = candidate.getPortfolio().stream().collect(Collectors.toList()); Candidate newCandidate = new Candidate(); newCandidate = candidateRepository.save(greenCandidate); // Safely add relationships with (an) existing portfolio(s) for (Portfolio portfolio : portfolios) { Portfolio existingPortfolio = portfolioRepository.findById(portfolio.getId()).orElse(null); if (existingPortfolio == null) { log.info("Skipping invalid portfolio entry for Portfolio ID " + portfolio.getId()); } else { log.info("Found portfolio : " + existingPortfolio.getId() + ", created on : " + existingPortfolio.getCreatedDate()); newCandidate.getPortfolio().add(existingPortfolio); newCandidate = candidateRepository.save(newCandidate); log.info("added portfolio to user"); } } return newCandidate; } @Override public List<Candidate> getCandidates() { List<Candidate> candidates = candidateRepository.findAll().stream() .filter(p -> p.getVoided() != Lookup.VOIDED && p.getRetired() != Lookup.RETIRED) .collect(Collectors.toList()); candidates.sort(Comparator.comparing(Candidate::getId)); return candidates; } @Override public List<Candidate> getCandidates(Long portfolioId) { List<Candidate> candidates = candidateRepository.findAll().stream() .filter(p -> p.getVoided() != Lookup.VOIDED && p.getRetired() != Lookup.RETIRED && (p.getPortfolio().stream().filter(q -> q.getId().longValue() == portfolioId).findFirst() .orElse(new Portfolio()).getId().longValue() == portfolioId)) .collect(Collectors.toList()); candidates.sort(Comparator.comparing(Candidate::getId)); return candidates; } @Override public Candidate getActiveCandidate(Long candidateId) throws EntryNotActiveException, EntryNotFoundException { Candidate candidate = candidateRepository.findById(candidateId).orElse(null); if (candidate != null && candidate.getVoided() != Lookup.VOIDED && candidate.getRetired() != Lookup.RETIRED) { return candidate; } else { if (candidate == null || candidate.getVoided() == Lookup.VOIDED) { throw new EntryNotFoundException("Invalid operation for [CANDIDATE]." + candidateId); } else { throw new EntryNotActiveException("Invalid operation for [CANDIDATE]." + candidateId); } } } @Override public void deleteCandidate(Long candidateId) throws EntryNotFoundException { Candidate candidate = candidateRepository.findById(candidateId).orElse(null); if (candidate != null && candidate.getVoided() != Lookup.VOIDED) { candidate.setVoided(Lookup.VOIDED); candidate.setVoidedReason("System operation - voided"); candidateRepository.save(candidate); log.info("Deleted candidate with ID: " + candidateId); } else { throw new EntryNotFoundException("Invalid operation for [CANDIDATE]." + candidateId); } } @Override public void retireCandidate(Long candidateId) throws EntryNotFoundException { Candidate candidate = candidateRepository.findById(candidateId).orElse(null); if (candidate != null && candidate.getRetired() != Lookup.RETIRED) { candidate.setRetired(Lookup.RETIRED); candidate.setRetiredReason("System operation - retired"); candidateRepository.save(candidate); log.info("Retired candidate with ID: " + candidateId); } else { throw new EntryNotFoundException("Invalid operation for [CANDIDATE]." + candidateId); } } }
true
c30b5ec82def4f4374938a7583024686d4712531
Java
lfystyle/YiXianUser
/app/src/main/java/com/example/lfy/myapplication/SubmitOrder/PayType.java
UTF-8
2,803
1.945313
2
[]
no_license
package com.example.lfy.myapplication.SubmitOrder; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.lfy.myapplication.Bean.AddressBean; import com.example.lfy.myapplication.MainActivity; import com.example.lfy.myapplication.R; import com.example.lfy.myapplication.Variables; /** * Created by lfy on 2016/6/29. */ public class PayType extends AppCompatActivity { TextView payType; TextView user; TextView address; TextView money; Button look_order; String type; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Variables.setTranslucentStatus(this); setContentView(R.layout.submit_paytype); initView(); Intent intent = getIntent(); AddressBean list = (AddressBean) intent.getSerializableExtra("address"); String price = intent.getStringExtra("money"); type = intent.getStringExtra("payType"); payType.setText(type); user.setText("收件人:" + list.getName() + " " + list.getPhone()); address.setText(list.getDistrict() + list.getAddress()); money.setText("实付款:¥" + price); } private void initView() { payType = (TextView) findViewById(R.id.payType); user = (TextView) findViewById(R.id.user); address = (TextView) findViewById(R.id.address); money = (TextView) findViewById(R.id.money); imageView = (ImageView) findViewById(R.id.left); look_order = (Button) findViewById(R.id.look_order); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(PayType.this, MainActivity.class); startActivity(intent); finish(); } }); look_order.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (type.equals("支付成功")) { MainActivity.jump(0); } else { MainActivity.jump(1); } Intent intent = new Intent(PayType.this, MainActivity.class); startActivity(intent); finish(); } }); } @Override public void onBackPressed() { super.onBackPressed(); MainActivity.classify.performClick(); Intent intent = new Intent(PayType.this, MainActivity.class); startActivity(intent); finish(); } }
true
f4bd706c2bb2f8db1c9c3bbd6f90b6123a776b10
Java
Jcondori/Template_PFUltima
/src/java/Controller/Controller.java
UTF-8
498
1.84375
2
[]
no_license
package Controller; import java.io.IOException; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import java.io.Serializable; import javax.faces.context.FacesContext; @Named(value = "controller") @SessionScoped public class Controller implements Serializable { public void template() throws IOException{ FacesContext.getCurrentInstance().getExternalContext().redirect("/Template_PFUltima/faces/Vistas/Template/Template.xhtml"); } }
true
7596086c60893d24dca7a8e26d9490852db1c649
Java
jojo8775/leet-code
/src/main/java/interview/leetcode/prob/MinimizeDeviationInArray.java
UTF-8
2,048
4.1875
4
[]
no_license
package interview.leetcode.prob; import java.util.PriorityQueue; /** * You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2]. If the element is odd, multiply it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4]. The deviation of the array is the maximum difference between any two elements in the array. Return the minimum deviation the array can have after performing some number of operations. Example 1: Input: nums = [1,2,3,4] Output: 1 Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. Example 2: Input: nums = [4,1,5,20,3] Output: 3 Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. Example 3: Input: nums = [2,10,8] Output: 3 Constraints: n == nums.length 2 <= n <= 5 * 104 1 <= nums[i] <= 109 Accepted 53,406 Submissions 101,020 * @author jojo * Feb 23, 2023 11:28:10 PM */ public class MinimizeDeviationInArray { public int minimumDeviation(int[] nums) { PriorityQueue<Integer> evens = new PriorityQueue<>((a, b) -> b - a); int minimum = Integer.MAX_VALUE; for (int num : nums) { if (num % 2 == 0) { evens.offer(num); minimum = Math.min(minimum, num); } else { evens.offer(num * 2); minimum = Math.min(minimum, num * 2); } } int minDeviation = Integer.MAX_VALUE; while (!evens.isEmpty()) { int currentValue = evens.poll(); minDeviation = Math.min(minDeviation, currentValue - minimum); if (currentValue % 2 == 0) { evens.offer(currentValue / 2); minimum = Math.min(minimum, currentValue / 2); } else { // if the maximum is odd, break and return break; } } return minDeviation; } }
true
34a9a9fb0f60428cae1342f8085565cbda23b51c
Java
nmerris/StockUp
/src/main/java/com/stockup/group/repository/TransactionRepo.java
UTF-8
221
1.632813
2
[]
no_license
package com.stockup.group.repository; import com.stockup.group.model.Transaction; import org.springframework.data.repository.CrudRepository; public interface TransactionRepo extends CrudRepository<Transaction, Long>{ }
true
aa757d3be34fbd769ecfc02ffa034de80fb0f963
Java
jacobthewest/340_Twitter_Clone
/app/src/main/java/edu/byu/cs/tweeter/client/model/service/UpdateFollowServiceProxy.java
UTF-8
1,246
2.5
2
[]
no_license
package edu.byu.cs.tweeter.client.model.service; import java.io.IOException; import edu.byu.cs.tweeter.client.model.net.ServerFacade; import edu.byu.cs.tweeter.shared.net.TweeterRemoteException; import edu.byu.cs.tweeter.shared.service.UpdateFollowService; import edu.byu.cs.tweeter.shared.service.request.UpdateFollowRequest; import edu.byu.cs.tweeter.shared.service.response.UpdateFollowResponse; public class UpdateFollowServiceProxy implements UpdateFollowService { private static final String URL_PATH = "/updatefollow"; @Override public UpdateFollowResponse updateFollow(UpdateFollowRequest request) throws IOException, TweeterRemoteException { ServerFacade serverFacade = getServerFacade(); UpdateFollowResponse updateFollowResponse = serverFacade.updateFollow(request, URL_PATH); return updateFollowResponse; } /** * Returns an instance of {@link ServerFacade}. Allows mocking of the ServerFacade class for * testing purposes. All usages of ServerFacade should get their ServerFacade instance from this * method to allow for proper mocking. * * @return the instance. */ public ServerFacade getServerFacade() { return new ServerFacade(); } }
true
f072ea738513d4ebc480ddf13c14344abbaa8349
Java
Yongki40/belajar-MDP
/fragment-v3/app/src/main/java/com/belajar/fragment_v3/Pengeluaran.java
UTF-8
2,437
2.28125
2
[]
no_license
package com.belajar.fragment_v3; import android.graphics.Color; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. * Use the {@link Pengeluaran#newInstance} factory method to * create an instance of this fragment. */ public class Pengeluaran extends Fragment { ArrayList<DataTrans> dataTrans = new ArrayList<>(); public Pengeluaran() { // Required empty public constructor } public static Pengeluaran newInstance(ArrayList<DataTrans> dataTrans) { Pengeluaran fragment = new Pengeluaran(); Bundle args = new Bundle(); args.putParcelableArrayList("dataTrans",dataTrans); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { this.dataTrans = getArguments().getParcelableArrayList("dataTrans"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_pengeluaran, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ListView lv = view.findViewById(R.id.lv); ArrayList<DataTrans> lPengeluaran = new ArrayList<>(); for (DataTrans data: dataTrans) { if(data.jenis.equals("Pengeluaran")){ lPengeluaran.add(data); } } ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,lPengeluaran); lv.setAdapter(adapter); TextView tvSaldo = view.findViewById(R.id.tvSaldo); int saldo = 0; for (DataTrans data: lPengeluaran) { saldo += data.nilai; } tvSaldo.setText(saldo+""); tvSaldo.setTextColor(Color.RED); } }
true
8ab6f7d04d8c9fa1e87e1194369f5dab699972de
Java
karino2/sk-livejournal-offline
/lj/src/com/googlecode/karino/ProfileManager.java
UTF-8
3,231
2.203125
2
[]
no_license
package com.googlecode.karino; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import com.googlecode.karino.R; import com.googlecode.karino.db.BlogDBAdapter; import android.app.Activity; import android.database.Cursor; import android.util.Log; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ProfileManager extends Activity { public static final int CONFIG_ROW = 1; public static final int POST_ROW = 3; public static final int TEMP_CONFIG_ROW = 2; private EditText mLogin; private EditText mPassword; private final String TAG = "BlogConfigEditor"; private Button button; private BlogDBAdapter mDbHelper; private String oldLogin; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.editdialog); mDbHelper = new BlogDBAdapter(this); try { mDbHelper.open(); } catch (Exception e) { } mLogin = (EditText) findViewById(R.id.ed_et_login); mPassword = (EditText) findViewById(R.id.ed_et_password); button = (Button) findViewById(R.id.ed_bt_confirm); TextView tv; tv = (TextView) findViewById(R.id.ed_tv_login); tv.setText(R.string.login); tv = (TextView) findViewById(R.id.ed_tv_password); tv.setText(R.string.password); button.setText(R.string.save); // populateFields(); oldLogin = mLogin.getText().toString(); button.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { saveState(); setResult(RESULT_OK); finish(); } }); button = (Button) findViewById(R.id.ed_bt_fetch); button.setText(R.string.verify); final LiveJournalAPI lj = new LiveJournalAPI(); button.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { lj.getUserBlogs(ProfileManager.this); } }); } private void populateFields() { try { Cursor bc = mDbHelper.fetchConfig(TEMP_CONFIG_ROW); startManagingCursor(bc); String str = bc.getString(bc .getColumnIndexOrThrow(BlogDBAdapter.KEY_LOGIN)); mLogin.setText(str); if (oldLogin == null) { oldLogin = str; } mPassword.setText(bc.getString(bc .getColumnIndexOrThrow(BlogDBAdapter.KEY_PASSWORD))); } catch (Exception e) { oldLogin = ""; } } protected void onResume() { super.onResume(); populateFields(); } protected void onPause() { super.onPause(); String login = mLogin.getText().toString(); String password = mPassword.getText().toString(); if (!mDbHelper.updateConfig(TEMP_CONFIG_ROW, login, password)) { mDbHelper.createConfig(login, password); } } private void saveState() { String login = mLogin.getText().toString(); if (!oldLogin.equals(login)) { if (!mDbHelper.updateConfig(POST_ROW, " ", " ")) { mDbHelper.createConfig(" ", " "); } } String password = mPassword.getText().toString(); if (!mDbHelper.updateConfig(CONFIG_ROW, login, password)) { mDbHelper.createConfig(login, password); } } }
true
ffbd13d6ce61db937517eecdff42f54fe11b6f5f
Java
chenrushui/SpringBootProject
/src/main/java/com/demo/www/springbootdemo/controller/DoctorEducationController.java
UTF-8
2,116
2.203125
2
[]
no_license
package com.demo.www.springbootdemo.controller; import com.demo.www.springbootdemo.module.anno.loginpermission.LoginPermission; import com.demo.www.springbootdemo.pojo.BaseResult; import com.demo.www.springbootdemo.pojo.DoctorEducation; import com.demo.www.springbootdemo.service.DoctorEducationService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; /** * Created on 2019/3/29. * author:crs * Description:医生的教育信息 */ @Api(description = "用户教育信息") @Slf4j @RestController @RequestMapping(value = "/education") public class DoctorEducationController { @Autowired private DoctorEducationService doctorEducationService; /** * 查询教育信息 * * @param doctorId * @return */ @ApiOperation(value = "获取医生教育信息") @GetMapping(value = "/", produces = "application/json;charset=UTF-8") public BaseResult getDoctorEducationByDoctorId(@RequestParam("doctorId") Long doctorId) { ArrayList<DoctorEducation> list = new ArrayList<>(); DoctorEducation doctorEducation = doctorEducationService.getDoctorEducationByDoctorId(doctorId); if (doctorEducation != null) { list.add(doctorEducation); } return BaseResult.buildSuccess(list); } @ApiOperation(value = "编辑医生教育信息") @PostMapping(value = "/edit", produces = "application/json;charset=UTF-8") public BaseResult editDoctorEducation(@RequestBody DoctorEducation doctorEducation) { int row = doctorEducationService.putDoctorEducation(doctorEducation); log.info("保存教育信息成功,医生id是:" + doctorEducation.getDoctorId()); return BaseResult.buildSuccess(row); } @LoginPermission(value = "是否可以登陆?") @GetMapping("/anno") public BaseResult<String> getTestAnno() { return BaseResult.buildSuccess("登陆权限"); } }
true
74f809e914ad667545f88749e8e8daf8bceb7cbd
Java
Siddhartha1193/Just-ParkIt
/app/src/main/java/com/parkingapp/sample/MainActivity.java
UTF-8
58,348
1.742188
2
[]
no_license
package com.parkingapp.sample; /* * File history * 1. Raymond Thai * changes: added onlocationchangelistener to setupmaps method which changes map camera to user's current location * changed information snippet to parking spot snippet * added personal icons * implemented pooja's fix to delete previous marker when new marker is selected * implemented Clear Marker button so user can clear all markers on map * Fixed radio buttons on layers and help menu in action overflow so that checked tab corresponds to current state * * 2. Pooja K * changes: Added a code to handle add to favorites and iew favorites part. * Added a code to check whether street cleaning is currently going on or not and display message accordingly. * * 3. Pooja K * changes: merged the codes of street cleaning and SFPark APIs. * added a code to display markers for parking locations returned by SFParkAPI. */ //import android.app.AlertDialog; import android.app.SearchManager; import android.content.Context; import android.location.LocationManager; import android.provider.Settings; import android.support.v7.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteException; import android.graphics.Color; import android.location.Address; import android.content.ContextWrapper; import android.location.Geocoder; import android.location.Location; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.text.Spannable; import android.text.style.ForegroundColorSpan; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.pooja.sfparksample.R; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationListener; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.parkingapp.connection.SFParkHandler; import com.parkingapp.database.DBConnectionHandler; import com.parkingapp.database.FavoritesConnectionHandler; import com.parkingapp.exception.ParkingAppException; import com.parkingapp.parser.OperationHoursBean; import com.parkingapp.parser.RatesBean; import com.parkingapp.parser.SFParkBean; import com.parkingapp.database.StreetCleaningDataBean; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.zip.GZIPInputStream; import android.util.Log; public class MainActivity extends AppCompatActivity implements LocationListener, ConnectionCallbacks, OnConnectionFailedListener { private static final String TAG = "LocationActivity"; private static GoogleMap mMap; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000; private String information; private String streetCleaningInformation; private GoogleApiClient mGoogleApiClient; private boolean mRequestingLocationUpdates = false; private LocationRequest mLocationRequest; private Location mLastLocation; MarkerOptions marker; List<SFParkBean> SfParkBeanList = null; DBConnectionHandler dbConnectionHandler; String radius = "0.25"; List<Marker> markers = new ArrayList<>(); FavoritesConnectionHandler fdb; /** * * @param savedInstanceState */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); fdb = new FavoritesConnectionHandler(this); if (checkPlayServices()) { buildGoogleApiClient(); createLocationRequest(); } checkGPSStatus(); SfParkBeanList = new ArrayList<SFParkBean>(); setContentView(R.layout.activity_map); ContextWrapper contextWrapper = new ContextWrapper(getBaseContext()); dbConnectionHandler = DBConnectionHandler.getDBHandler(contextWrapper); setUpMapIfNeeded(); mMap.setMyLocationEnabled(true); mMap.getMyLocation(); // changed default location from sfsu to sf CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(37.721897, -122.47820939999997)); CameraUpdate zoom = CameraUpdateFactory.zoomTo(13); mMap.moveCamera(center); mMap.animateCamera(zoom); } /** * Creates LocationRequest object. We also set the update interval in milliseconds and we also * set the minimum displacement between location updates in meters. */ protected void createLocationRequest() { int UPDATE_INTERVAL = 10000; int FASTEST_INTERVAL = 5000; int DISPLACEMENT = 10; mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL); mLocationRequest.setFastestInterval(FASTEST_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setSmallestDisplacement(DISPLACEMENT); // set to 10 meters. } /* This method checks if the user has GPS and Network Services enabled. If the locations services aren't enabled, this method redirects the user to the phone's settings */ private void checkGPSStatus() { LocationManager locationManager = null; boolean gps_enabled = false; boolean network_enabled = false; if ( locationManager == null ) { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); } try { gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex){ ex.printStackTrace(); } try { network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex){ ex.printStackTrace(); } if ( !gps_enabled && !network_enabled ){ AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this,R.style.DialogTheme); //Pops up a dialog box if location services are not enabled dialog.setTitle("GPS Not Enabled"); dialog.setMessage("Please turn on GPS for proper functionality. \nGo to Settings -> Location -> Turn Location ON or press OK to take you there"); dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //this will navigate user to the device location settings screen Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); AlertDialog alert = dialog.create(); alert.show(); } } /** * Build a GoogleApiClient. Uses addApi() to request the LocationServices API */ protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Verifies that Google Play services are enabled on the user's device * @return */ private boolean checkPlayServices() { int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (result != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(result)) { GooglePlayServicesUtil.getErrorDialog(result, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Toast.makeText(getApplicationContext(), "Google Play services are not available", Toast.LENGTH_LONG).show(); finish(); } return false; } return true; } @Override protected void onStart() { super.onStart(); if (mGoogleApiClient != null) { mGoogleApiClient.connect(); } } @Override protected void onResume() { super.onResume(); checkPlayServices(); if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); setUpMapIfNeeded(); } } @Override protected void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } @Override protected void onPause() { super.onPause(); stopLocationUpdates(); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { mMap.getUiSettings().setZoomControlsEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(false); mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { markers.add(marker); if (marker.isInfoWindowShown()) { marker.hideInfoWindow(); } else { marker.showInfoWindow(); } return true; } }); mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { private Location mLocation = null; @Override public void onMyLocationChange(Location myLocation) { if (mLocation == null) { mLocation = myLocation; mMap.clear(); mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); CameraUpdate update = CameraUpdateFactory.newLatLngZoom(new LatLng(myLocation.getLatitude(), myLocation.getLongitude()), 16); mMap.animateCamera(update); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.721897, -122.47820939999997), 14.0f)); } } }); mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { // empty parking location list SfParkBeanList.clear(); // retrieve and display street cleaning and parking information setStreetCleaningAndParkingInformation(latLng); } } ); mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker marker) { } @Override public void onMarkerDrag(Marker marker) { } @Override public void onMarkerDragEnd(Marker marker) { // send the latlng to updateMarkerPosition(). updateMarkerPosition(marker.getPosition()); } }); } private void setStreetCleaningAndParkingInformation(LatLng latLng) { //note: parking API is called inside addMarker method. Geocoder geocoder = new Geocoder(getApplicationContext()); Geocoder.isPresent(); List<Address> matches = null; try { matches = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); } catch (IOException e) { e.printStackTrace(); } boolean found = true; List<StreetCleaningDataBean> streetCleanAddress = new ArrayList<StreetCleaningDataBean>(); String[] text = new String[8]; String[] text_address = new String[8]; String[] text_day = new String[8]; String[] side = new String[8]; StringBuilder rightFrom = new StringBuilder(); StringBuilder rightTo = new StringBuilder(); StringBuilder leftFrom = new StringBuilder(); StringBuilder leftTo = new StringBuilder(); text[0] = ("Street cleaning data not available"); if (matches != null && matches.size() > 0) { Address address = matches.get(0); if (address.getSubThoroughfare() != null && address.getThoroughfare() != null && address.getPostalCode() != null) { String sub[] = address.getSubThoroughfare().split("-"); int substreetParm = 0; String streetParm = null; int postalCode = 0; if (sub[0] != null) { try { substreetParm = Integer.valueOf(sub[0]); streetParm = address.getThoroughfare().toUpperCase(); postalCode = Integer.valueOf(address.getPostalCode()); Log.d("substreetParm: ", address.getSubThoroughfare()); Log.d("substreetParm[0]: ", sub[0]); Log.d("addressParm: ", streetParm); Log.d("Pincode: ", address.getPostalCode()); } catch (NumberFormatException ne) { found = false; } if (found) { streetCleanAddress = dbConnectionHandler.getRequiredAddress(substreetParm, streetParm, postalCode); if (streetCleanAddress != null && streetCleanAddress.size() > 0) { int count = 1; Calendar calendar = Calendar.getInstance(); int currDay = calendar.get(Calendar.DAY_OF_WEEK); calendar.setMinimalDaysInFirstWeek(7); int currWeek = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH); String currDayOfWeek = getDayOfWeek(currDay); for (StreetCleaningDataBean bean : streetCleanAddress) { StringBuilder sc = new StringBuilder(); StringBuilder sc_day = new StringBuilder(); if (bean.getRightLeft()!= null && bean.getRightLeft().equals("R")) { sc.append(String.valueOf(bean.getRT_FADD())).append("-") .append(String.valueOf(bean.getRT_TOADD())).append(" ") .append(bean.getSTREETNAME()).append("\n"); side[count - 1] = ("R"); rightFrom.append(String.valueOf(bean.getRT_FADD())).append(" ") .append(bean.getSTREETNAME()).append(" ") .append("San Francisco ") .append(bean.getZIP_CODE()); rightTo.append(String.valueOf(bean.getRT_TOADD())).append(" ") .append(bean.getSTREETNAME()).append(" ") .append("San Francisco ") .append(bean.getZIP_CODE()); } if (bean.getRightLeft() != null && bean.getRightLeft().equals("L")) { sc.append(String.valueOf(bean.getLF_FADD())).append("-") .append(String.valueOf(bean.getLF_TOADD())) .append(" ").append(bean.getSTREETNAME()).append("\n"); side[count - 1] = ("L"); leftFrom.append(String.valueOf(bean.getLF_FADD())).append(" ") .append(bean.getSTREETNAME()).append(" ") .append("San Francisco ") .append(bean.getZIP_CODE()); leftTo.append(String.valueOf(bean.getLF_TOADD())).append(" ") .append(bean.getSTREETNAME()).append(" ") .append("San Francisco ") .append(bean.getZIP_CODE()); } text_address[count - 1] = sc.toString(); List<Integer> weekList = new ArrayList<Integer>(); // to check if street cleaning is going on currently String currentInfo = "Street cleaning is not going on currently \n"; if (weekList.contains(currWeek) && currDayOfWeek != null && currDayOfWeek.equalsIgnoreCase(bean.getWeekDay())) { String fromString = calendar.get(Calendar.DATE) + ":" + (calendar.get(Calendar.MONTH) + 1) + ":" + calendar.get(Calendar.YEAR) + ":" + bean.getFromHour(); String toString = calendar.get(Calendar.DATE) + ":" + (calendar.get(Calendar.MONTH) + 1) + ":" + calendar.get(Calendar.YEAR) + ":" + bean.getToHour(); if (weekList.contains(currWeek) && currDayOfWeek != null && currDayOfWeek.equalsIgnoreCase("Mon")) { SimpleDateFormat parser = new SimpleDateFormat("dd:MM:yyyy:HH:mm"); try { Date fromDate = parser.parse(fromString); Date toDate = parser.parse(toString); if (calendar.getTime().after(fromDate) && calendar.getTime().before(toDate)) { currentInfo = "Street cleaning is going on currently \n"; } } catch (ParseException e) { e.printStackTrace(); } } } sc.append(currentInfo); sc.append(bean.getWeekDay() + " Weeks:"); sc_day.append(bean.getWeekDay() + " Weeks:"); if ("Y".equals(bean.getWeek1OfMonth())) { weekList.add(1); sc.append(" 1"); sc_day.append(" 1"); } if ("Y".equals(bean.getWeek2OfMonth())) { weekList.add(2); sc.append(" 2"); sc_day.append(" 2"); } if ("Y".equals(bean.getWeek3OfMonth())) { weekList.add(3); sc.append(" 3"); sc_day.append(" 3"); } if ("Y".equals(bean.getWeek4OfMonth())) { weekList.add(4); sc.append(" 4"); sc_day.append(" 4"); } if ("Y".equals(bean.getWeek5OfMonth())) { weekList.add(5); sc.append(" 5"); sc_day.append(" 5"); } sc.append(" \n"); sc_day.append(" \n"); sc.append(bean.getFromHour() + "-" + bean.getToHour() + "\n"); sc_day.append(bean.getFromHour() + "-" + bean.getToHour() + "\n"); if ("N".equals(bean.getHolidays())) { sc.append("No cleaning on holidays \n"); sc_day.append("No cleaning on holidays \n"); } text[count - 1] = sc.toString(); text_day[count - 1] = sc_day.toString(); Log.d("Data:text[count-1] ", text[count - 1]); Log.d("Data:text_address ", text_address[count - 1]); Log.d("Data:text_day[count-1] ", text_day[count - 1]); Log.d("Data:side[count-1] ", side[count - 1]); //check if address was already stored earlier in text[] array int check ; int match_found = 0; for(check = 0; check <= count-2; check++){ if(text_address[count-1].equals(text_address[check]) && (match_found == 0)){ Log.d("Data:count-1 ", String.valueOf(count - 1)); Log.d("Data:check", String.valueOf(check)); Log.d("Data:text_address[cnt] ", text_address[count - 1]); Log.d("Data:text_address[chk] ", text_address[check]); Log.d("Data:text_day[count-1] ", text_day[count - 1]); Log.d("Data:text[check] ", text[check]); text[check] = text[check] + text_day[count-1]; text[count-1] = ""; match_found = 1; } } count++; if (count == 9) { break; } } } } } String title = getString(R.string.street_cleaning_info); Log.d("Right from ", rightFrom.toString()); Log.d("Right to ", rightTo.toString()); Log.d("Left from ", leftFrom.toString()); Log.d("Left to ", leftTo.toString()); // adds markers at the clicked location and parking locations addMarker(latLng, title, rightFrom.toString(), rightTo.toString(), leftFrom.toString(), leftTo.toString(), text, side); } } } private List<Address> getGeoCoder(LatLng latLng) { Geocoder geocoder = new Geocoder(getApplicationContext()); Geocoder.isPresent(); List<Address> matches = null; try { matches = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); } catch (IOException e) { e.printStackTrace(); } return matches; } private void drawLine(String rightFrom, String rightTo, String leftFrom, String leftTo) { Log.d("method:", "Drawline method called"); Geocoder geocoder = new Geocoder(getApplicationContext()); Geocoder.isPresent(); try { List<Address> rightFromLatLngList = geocoder.getFromLocationName(rightFrom, 1); List<Address> rightToLatLngList = geocoder.getFromLocationName(rightTo, 1); List<Address> leftFromLatLngList = geocoder.getFromLocationName(leftFrom, 1); List<Address> leftToLatLngList = geocoder.getFromLocationName(leftTo, 1); if (rightFromLatLngList != null && leftToLatLngList.size() > 0 && rightToLatLngList != null && rightToLatLngList.size() > 0 && leftFromLatLngList != null && leftFromLatLngList.size() > 0 && leftToLatLngList != null && leftToLatLngList.size() > 0) { Address rightFromLatLng = rightFromLatLngList.get(0); Address rightToLatLng = rightToLatLngList.get(0); Address leftFromLatLng = leftFromLatLngList.get(0); Address leftToLatLng = leftToLatLngList.get(0); Log.d("Right from lat ", String.valueOf(rightFromLatLng.getLatitude())); Log.d("Right from long ", String.valueOf(rightFromLatLng.getLongitude())); Log.d("Right to lat ", String.valueOf(rightToLatLng.getLatitude())); Log.d("Right to long ", String.valueOf(rightToLatLng.getLongitude())); Log.d("Left from lat ", String.valueOf(leftFromLatLng.getLatitude())); Log.d("Left from long ", String.valueOf(leftFromLatLng.getLongitude())); Log.d("Left to lat ", String.valueOf(leftToLatLng.getLatitude())); Log.d("Left to long ", String.valueOf(leftToLatLng.getLongitude())); mMap.addPolyline(new PolylineOptions() .add(new LatLng(rightFromLatLng.getLatitude(), rightFromLatLng.getLongitude()), new LatLng(rightToLatLng.getLatitude(), rightToLatLng.getLongitude())) .width(10) .color(Color.MAGENTA)); mMap.addPolyline(new PolylineOptions() .add(new LatLng(leftFromLatLng.getLatitude(), leftFromLatLng.getLongitude()), new LatLng(leftToLatLng.getLatitude(), leftToLatLng.getLongitude())) .width(10) .color(Color.BLUE)); } } catch (IOException e) { e.printStackTrace(); } } private void updateMarkerPosition(LatLng latLng) { //Log.d("DEMO=====>", latLng.toString()); SFParkHandler sfParkHandler = new SFParkHandler(); String latitude = String.valueOf(latLng.latitude); String longitude = String.valueOf(latLng.longitude); //String radius = "0.25"; //List<SFParkBean> response = null; mMap.clear(); try { SfParkBeanList = sfParkHandler.callAvailabilityService(latitude, longitude, radius); } catch (ParkingAppException e) { e.printStackTrace(); Log.d("Caught Exception", e.getMessage()); } if (SfParkBeanList != null) { StringBuilder sf = new StringBuilder(); int count = 1; for (SFParkBean bean : SfParkBeanList) { sf.append(" " + count + " : " + bean.getName() + "\n"); //Log.d("DEMO=====>", sf.toString()); count++; // set the Marker options. marker = new MarkerOptions() .position(new LatLng(bean.getLatitude(),bean.getLongitude())) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)) .draggable(true).visible(true).title("Spot " + count); mMap.addMarker(marker); Log.d("added marker at " , bean.getName() + " " + bean.getLatitude() + " " + bean.getLongitude()); /* if (count == Constants.LIMIT_FOR_PARKING_DISPLAY + 1) { break; }*/ } // set the information using Setter. setInformation(sf.toString()); if (count == 1) { sf.append("Parking not found"); setInformation(sf.toString()); } // set the Marker options. marker = new MarkerOptions() .position(latLng) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)) .draggable(true); // add marker to Map mMap.addMarker(marker); marker.isDraggable(); /* // update the WindowAdapter in order to inflate the TextView with custom Text View Adapter mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker marker) { return null; } @Override public View getInfoContents(Marker marker) { // Define a customView to attach it onClick of marker. View customView = getLayoutInflater().inflate(R.layout.marker, null); // inflate the customView layout with TextView. TextView tvInformation = (TextView) customView.findViewById(R.id.information); // get the information. tvInformation.setText(getInformation()); return customView; } }); */ } } private void addMarker(LatLng latLng, final String title, String rightFrom, String rightTo, String leftFrom, String leftTo, final String[] text, final String[] side) { // update the WindowAdapter in order to inflate the TextView with custom Text View Adapter mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker marker) { return null; } @Override public View getInfoContents(Marker marker) { // Define a customView to attach it onClick of marker. View customView = getLayoutInflater().inflate(R.layout.marker, null); // inflate the customView layout with TextView. TextView tvInformation = (TextView) customView.findViewById(R.id.information); // get the information. tvInformation.setText(""); int length = 0; if(marker.getTitle().equals(title)) { for (int i = 0; i < 5; i++) { if (text[i] != null && !text[i].equals("")) { tvInformation.append(text[i]+"\n"); Spannable spannableText = (Spannable) tvInformation.getText(); if (side[i]!= null && side[i].equalsIgnoreCase("R")) { spannableText.setSpan(new ForegroundColorSpan(Color.MAGENTA), length, length + text[i].length(), 0); } if (side[i] != null && side[i].equalsIgnoreCase("L")) { spannableText.setSpan(new ForegroundColorSpan(Color.BLUE), length, length + text[i].length(), 0); } length = length + text[i].length(); } } if(SfParkBeanList.size() ==0) { tvInformation.append("\nParking data not available"); } } else { tvInformation.setText(getLocationText(marker)); } return customView; } }); Log.d("Right from ", rightFrom); Log.d("Right to ", rightTo); Log.d("Left from ", leftFrom); Log.d("Left to ", leftTo); mMap.clear(); drawLine(rightFrom, rightTo, leftFrom,leftTo); // set the Marker options. setParkingLocations(latLng); mMap.addMarker(new MarkerOptions() .position(latLng) .title(title) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))).showInfoWindow(); } private String getLocationText(Marker marker) { StringBuilder info = new StringBuilder(); for(int i=0; i < SfParkBeanList.size() ; i++) { SFParkBean bean = SfParkBeanList.get(i); if (bean.getName().equals(marker.getTitle())) { marker.setTitle(bean.getName()); info.append(bean.getName() + "\n"); if(bean.getType() != null) { info.append("Type : "); if(bean.getType().equalsIgnoreCase("on")) { info.append("Street Parking \n"); } else { info.append("Garage Parking \n"); } } // To display status of parking location /* if (bean.getType() != null) { info.append("Status: " + bean.getType() + "\n"); }*/ if (bean.getAddress() != null) { info.append("Address: " + bean.getAddress() + "\n"); } if (bean.getContactNumber() != null) { info.append("Contact Number : " + bean.getContactNumber() + "\n"); } if (bean.getOperationHours() != null) { List<OperationHoursBean> opHours = bean.getOperationHours(); if (opHours.size() > 0) { info.append("Operation Hours: \n"); for (OperationHoursBean opBean : opHours) { if (opBean.getFromDay() != null) { info.append(opBean.getFromDay()); } if (opBean.getToDay() != null) { info.append("-" + opBean.getToDay()); } info.append(":"); if (opBean.getStartTime() != null) { info.append(opBean.getStartTime()); } if (opBean.getEndTime() != null) { info.append("-" + opBean.getEndTime()); } info.append("\n"); } } } if (bean.getRatesBeanList() != null) { List<RatesBean> ratesList = bean.getRatesBeanList(); if (ratesList != null && ratesList.size() > 0) { info.append("Parking Rates: \n"); for (RatesBean ratesBean : ratesList) { if(ratesBean.getBegTime() != null) { info.append(ratesBean.getBegTime()); } if (ratesBean.getEndTime() != null) { info.append("-" + ratesBean.getEndTime()); } if(ratesBean.getDesc() != null) { info.append(ratesBean.getDesc()); } info.append(" : "); if(ratesBean.getRate() != 0.0) { info.append("$" + ratesBean.getRate() + " "); } if(ratesBean.getRateQuantifier() != null) { info.append(ratesBean.getRateQuantifier()); } if(ratesBean.getRateRestriction() != null) { info.append("\n " + ratesBean.getRateRestriction()); } info.append("\n"); } } } if(bean.getOper() != 0) { info.append("Number of spaces currently operational: " + bean.getOper() + "\n"); } if(bean.getOcc() != 0) { info.append("Number of spaces currently occupied: " + bean.getOcc() + "\n"); } } } return info.toString(); } private void setParkingLocations(LatLng latLng) { SFParkHandler sfParkHandler = new SFParkHandler(); String latitude = String.valueOf(latLng.latitude); String longitude = String.valueOf(latLng.longitude); //String radius = "0.25"; //mMap.clear(); // List<SFParkBean> response = null; try { SfParkBeanList = sfParkHandler.callAvailabilityService(latitude, longitude, radius); } catch (ParkingAppException e) { e.printStackTrace(); Log.d("Exception occurred at ", e.getMessage()); } Log.d("current position ", latLng.latitude + " " + latLng.longitude); if (SfParkBeanList != null) { int count = 1; for (SFParkBean bean : SfParkBeanList) { count++; Log.d("Marker added at ", bean.getName() + " " + bean.getLongitude() + " " + bean.getLatitude()); mMap.addMarker(new MarkerOptions() .position(new LatLng(bean.getLongitude(), bean.getLatitude())) .title(bean.getName()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.parking_marker)) .draggable(true).visible(true)); /*if (count == 9) { break; }*/ } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search_icon).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); // using geocode to find user entered addresses searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { MarkerOptions markerOptions = null; public boolean onQueryTextChange(String text) { return false; } public boolean onQueryTextSubmit(String text) { Geocoder geo = new Geocoder(getApplicationContext()); try { List<Address> add = geo.getFromLocationName(text, 1); for (Address adds : add) { if (add.size() > 0) {//Controls to ensure it is right address such as country etc. double longitude = adds.getLongitude(); double latitude = adds.getLatitude(); LatLng searched = new LatLng(latitude, longitude); //markerOptions.position(searched); //markerOptions.title("Your destination"); //mMap.addMarker(markerOptions); if (searched != null) { CameraUpdate center = CameraUpdateFactory.newLatLng(searched); CameraUpdate zoom = CameraUpdateFactory.zoomTo(16); mMap.moveCamera(center); mMap.animateCamera(zoom); } } } } catch (IOException e) { e.printStackTrace(); } return false; } } ); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement //when user clicks layers-> Normal, Map type will changed to normal if (id == R.id.menu_2_choice_1) { mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); Toast.makeText(getApplicationContext(), "Normal View", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //when user clicks layers-> Satellite, Map type will changed to satellite else if (id == R.id.menu_2_choice_2) { mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); Toast.makeText(getApplicationContext(), "Satellite View", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //when user clicks layers-> Terrain, Map type will changed to Terrain else if (id == R.id.menu_2_choice_3) { mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); Toast.makeText(getApplicationContext(), "Terrain View", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //when user clicks layers-> Terrain, Map type will changed to Terrain else if (id == R.id.menu_2_choice_4) { mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); Toast.makeText(getApplicationContext(), "Hybrid View", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //when user clicks Settings-> Display parking within tenth of a mile, radius sent to SFPark will be 0.1 mi if (id == R.id.menu_5_choice_1) { radius = "0.1"; Toast.makeText(getApplicationContext(), "Shall display parking within tenth of a mile", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //when user clicks Settings-> Display parking within quarter mile, radius sent to SFPark will be 0.25 mi else if (id == R.id.menu_5_choice_2) { radius = "0.25"; Toast.makeText(getApplicationContext(), "Shall display parking within quarter of a mile", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //when user clicks Settings-> Display parking within half a mile, radius sent to SFPark will be 0.5 mi else if (id == R.id.menu_5_choice_3) { radius = "0.5"; Toast.makeText(getApplicationContext(), "Shall display parking within half a mile", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //when user clicks Settings-> Display parking within a mile, radius sent to SFPark will be 1 mi else if (id == R.id.menu_5_choice_4) { radius = "1"; Toast.makeText(getApplicationContext(), "Shall display parking within 1 mile", Toast.LENGTH_LONG).show(); item.setChecked(true); return true; } //dialog fragment will appear when user clicks on Clear Markers tab in action overflow if (id == R.id.action_clearMarkers) { //calls a dialog box DialogFragment myFragment = new ClearMarkerDialog(); myFragment.show(getFragmentManager(), "theDialog"); SfParkBeanList.clear(); return true; } // getLastKnownLocation wasn't giving me accurate coordinates. // The "new" way to get accurate coordinates is by using the FusedLocationApi. if (id == R.id.action_gps) { mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { CameraUpdate currentLocation = CameraUpdateFactory.newLatLng( new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude())); mMap.animateCamera(currentLocation, 800, null); } else { Toast.makeText(getApplicationContext(), "Current location not available", Toast.LENGTH_SHORT).show(); } } //when user clicks Help-> Street Cleaning Help, help information for Street Cleaning Data will be displayed if (id == R.id.help_choice_1) { DialogFragment myFragment = new StreetCleaningHelp(); myFragment.show(getFragmentManager(), "helpDialog_1"); item.setChecked(true); return true; } //when user clicks Help-> Parking Information Help, help information for Parking Information Data will be displayed if (id == R.id.help_choice_2) { DialogFragment myFragment = new ParkingInfoHelp(); myFragment.show(getFragmentManager(), "helpDialog_2"); item.setChecked(true); return true; } if (id == R.id.help_choice_3) { DialogFragment myFragment = new AddToFavoritesHelp(); myFragment.show(getFragmentManager(), "helpDialog_3"); item.setChecked(true); return true; } //when user clicks Favorites button, the current parking info will be stored in database if (id == R.id.action_favorites) { if (markers != null & !markers.isEmpty()) { String test_string; Marker currentMarker = markers.get(markers.size()-1); test_string = currentMarker.getTitle(); DialogFragment myFragment = new AddToFavoritesDialog(); myFragment.show(getFragmentManager(), "testDialog"); try { fdb.insertFavorite(test_string); } catch (NullPointerException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Failed to add favorite spot.", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), "Please tap the marker you'd like to save", Toast.LENGTH_SHORT).show(); } } // when user clicks View Favorites, the favorite parking information will be displayed in a separate activity if (id == R.id.action_view_favorites) { Intent intent = new Intent(this, RecyclerViewActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override public void onLocationChanged(Location location) { mLastLocation = location; Toast.makeText(getApplicationContext(), "Location changed!", Toast.LENGTH_SHORT).show(); } /** * Begins location updates using the FusedLocationApi */ protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } /** * Stops location updates using the FusedLocationApi */ protected void stopLocationUpdates() { // commenting this out for now. causes force close since we are still relying on the old LocationListener LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this); } /** * Runs when a GoogleApiClient object successfully connects. * * @param connectionHint */ @Override public void onConnected(Bundle connectionHint) { if(mRequestingLocationUpdates) { startLocationUpdates(); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode()); } @Override public void onConnectionSuspended(int i) { mGoogleApiClient.connect(); } /** * Used to create a dialog fragment when a user attempts to add a location to their favorites. */ public static class AddToFavoritesDialog extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder testDialog = new AlertDialog.Builder(getActivity(), R.style.DialogTheme); testDialog.setTitle("Add to favorites?"); testDialog.setMessage("Would you like to add the current marker to favorites?"); testDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "Added to favorites!", Toast.LENGTH_SHORT).show(); } }); testDialog.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_SHORT).show(); } }); return testDialog.create(); } } /** * This is an inner class used to created a dialog fragment when users * click the Clear Markers Tab in the action overflow */ public static class ClearMarkerDialog extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder theDialog = new AlertDialog.Builder(getActivity(),R.style.DialogTheme); theDialog.setTitle("Clear Markers"); theDialog.setMessage("Are you sure you would like to clear all markers on map?"); // Markers will be cleared if user clicks YES and a toast will appear notifying //the the user theDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { mMap.clear(); Toast.makeText(getActivity(), "Markers Cleared", Toast.LENGTH_SHORT).show(); } }); //if user clicks NO, a toast will appear telling user that the clear //function has been canceled theDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "Clear Canceled", Toast.LENGTH_SHORT).show(); } }); return theDialog.create(); } } /** * This is an inner class used to created a dialog fragment when users * click the Street Cleaning Help item under the Help menu in the action overflow */ public static class StreetCleaningHelp extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder helpDialog_1 = new AlertDialog.Builder(getActivity(),R.style.DialogTheme); helpDialog_1.setTitle("Street Cleaning Help"); helpDialog_1.setMessage("-Tap anywhere on the map to place Marker\n" + "-Tap on the yellow marker to view Street Cleaning Information\n"); helpDialog_1.setNegativeButton("CLOSE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); return helpDialog_1.create(); } } /** * This is an inner class used to created a dialog fragment when users * click the Parking Information Help item under the Help menu in the action overflow */ public static class ParkingInfoHelp extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder helpDialog_2 = new AlertDialog.Builder(getActivity(),R.style.DialogTheme); helpDialog_2.setTitle("Parking Information Help"); helpDialog_2.setMessage("-Tap anywhere on the map to place Marker\n" + "-Tap on the markers with a P icon to view Parking Information"); helpDialog_2.setNegativeButton("CLOSE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); return helpDialog_2.create(); } } /** * This is an inner class used to created a dialog fragment when users * click the Add to Favorites help item under the Help menu in the action overflow */ public static class AddToFavoritesHelp extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder helpDialog_3 = new AlertDialog.Builder(getActivity(),R.style.DialogTheme); helpDialog_3.setTitle("Add to Favorites Help"); helpDialog_3.setMessage( "-Tap on the screen to create a marker\n" + "-If you would like to add to favorites,\n" + "tap the star icon in the action bar and parking data will be saved once you select the yes option\n" + "on the dialog alert message\n"+ "-To view your favorite parking spots go to View Favorites tab in the action overflow\n" ); helpDialog_3.setNegativeButton("CLOSE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); return helpDialog_3.create(); } } // getter and setter for Information. In order to access it globally. public void setInformation(String information) { this.information = information; } public String getInformation() { return information; } public void setStreetCleaningInformation(String streetCleaningInformation) { this.streetCleaningInformation = streetCleaningInformation; } public String getStreetCleaningInformation() { return streetCleaningInformation; } private String getDayOfWeek(int value) { String day = null; switch (value) { case 1: day = "Sun"; break; case 2: day = "Mon"; break; case 3: day = "Tues"; break; case 4: day = "Wed"; break; case 5: day = "Thurs"; break; case 6: day = "Fri"; break; case 7: day = "Sat"; break; } return day; } private static class InflatingEntity extends HttpEntityWrapper { public InflatingEntity(HttpEntity wrapped) { super(wrapped); } @Override public InputStream getContent() throws IOException { return new GZIPInputStream(wrappedEntity.getContent()); } @Override public long getContentLength() { return -1; } } }
true
3dc54a8fa70e88cee3285ff008792f6d8229d6f5
Java
Phuriwut/Worker
/src/Database/DBInstance.java
UTF-8
969
2.765625
3
[]
no_license
package Database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBInstance { Connection con; Statement stmt; DBInstance() throws SQLException, ClassNotFoundException { String urls = "jdbc:mysql://localhost:3306/ksch?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; Class.forName("com.mysql.jdbc.Driver"); this.con = DriverManager.getConnection(urls,"root","root"); this.stmt = con.createStatement(); } public ResultSet query(String sql) throws SQLException { return this.stmt.executeQuery(sql); } void close() throws SQLException { this.con.close(); } public PreparedStatement preparedQuery(String sql) throws SQLException { return this.con.prepareStatement(sql); } }
true
603dcef64031f262a496a84f3bdefe1da0685772
Java
jimyeongKo/study_cafe
/src/main/java/com/study/cafe/studycafe/global/error/ErrorCode.java
UTF-8
2,060
2.28125
2
[]
no_license
package com.study.cafe.studycafe.global.error; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Getter; @Getter @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum ErrorCode { //common INVALID_INPUT_VALUE(400, "C001", "올바르지 않은 형식입니다"), METHOD_NOT_ALLOWED(405, "C002", "지원하지 않는 메소드입니다."), ENTITY_NOT_FOUND(400, "C003", "해당 엔티티를 찾을 수가 없습니다."), INTERNAL_SERVER_ERROR(500, "c004", "알 수 없는 에러 발생(서버에러)"), INVALID_TYPE_VALUE(400, "C005", "타입이 올바르지 않습니다."), HANDLE_ACCESS_DENIED(403, "C006", "권한이 없습니다"), HANDLE_INVALID__TOKEN(401, "C007", "토큰이 없거나 올바르지 않습니다"), NOT_MY_ENTITY(400, "C008", "내 작성물이 아닙니다"), OVER_TIME(400, "C009", "수정 및 삭제는 등록 후 1시간 이내에만 가능합니다."), //AUTH NOT_MATCH_UID(400, "A001", "올바르지 않은 아이디 입니다."), //Member USERID_DUPLICATION(400, "M001", "존재하는 아이디 입니다."), PHONENUM_DUPLICATION(400, "M002", "이 번호로 이미 가입 되었습니다"), PASSWORD_INPUT_INVALID(400, "M003", "비밀번호를 확인 해주세요"), CHECK_USER_INVALID(400, "M004", "해당 정보에 맞는 유저가 없습니다."), USER_NOT_MATCH(400, "M005", "유저 정보가 맞지 않습니다"), //FILE FILE_NOT_FOUND(400, "R001", "해당 파일을 찾을 수가 없습니다."), FILE_SAVE_ERROR(400, "R001", "파일 저장에 실패하였습니다."), //Board BOARD_NOT_FOUND(400, "B001", "해당 게시글을 찾을 수 없습니다."), //Coupon COUPON_NOT_FOUND(400, "F001", "해당 쿠폰을 찾을 수 없습니다.") ; private final int status; private final String code; private final String message; ErrorCode(int status, String code, String message) { this.status = status; this.code = code; this.message = message; } }
true
07720860ba15413d06c3596e6a14e65303528be6
Java
zhongxingyu/Seer
/Diff-Raw-Data/27/27_16dfbf19876c2652fab66ad8c1cf39274e9d4e7c/ClipOptionsPane/27_16dfbf19876c2652fab66ad8c1cf39274e9d4e7c_ClipOptionsPane_s.java
UTF-8
8,883
2.375
2
[]
no_license
package gui; import static gui.GuiConstants.LARGE_BUTTON; import static gui.GuiConstants.LARGE_BUTTON_RADIUS; import static gui.GuiConstants.SMALL_BUTTON; import static gui.GuiConstants.STANDARD_GROWTH_FACTOR; import static sound.MusicConstants.REVERSE_MAJOR_CHORD; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiUnavailableException; import javax.swing.JPanel; import javax.swing.Timer; import sound.Clip; import sound.MidiPlayer; import sound.NotePlayerChannel; @SuppressWarnings("serial") public class ClipOptionsPane extends JPanel { private ArrayList<ClipOption> _options = new ArrayList<ClipOption>(); private ArrayList<Component> _deleteConfirmation = new ArrayList<Component>(); private PlayPauseButton _playPause; private ClipOption _deleteForReals; public ClipOption _justKidding; private boolean _showDeleteConfirmation = false; private Timer _playTimer; private double _percentPlayed = 0; private LibraryScreen _library; private MidiPlayer _player; private LabelElement _clipName; public ClipOptionsPane(LibraryScreen library, NotePlayerChannel noteChannel) { super(); this.setSize(library.getSize()); this.setBackground(new Color(0, 0, 0, 0)); this.setLocation(0, 0); _clipName = new LabelElement("", 32, library.getWidth()*4/5, 32); _clipName.setLocation(library.getWidth()/10, library.getHeight()/5); add(_clipName); _library = library; try { _player = new MidiPlayer(); } catch (MidiUnavailableException e1) { System.out.println("ERROR: problem making midi player"); } // PLAY/PAUSE BUTTON _playPause = new PlayPauseButton(_library); _options.add(_playPause); // DELETE BUTTON _options.add(new ClipOption(_library, LARGE_BUTTON, "img/greenbutton.png", "img/deletetext.png", noteChannel) { @Override public void performAction() { _player.stop(); _playTimer.stop(); changePlayPercentage(0); _playPause.setImageText("img/playcliptext.png"); showDeleteConfirmation(); } }); int columnWidth = 50 + LARGE_BUTTON; // position clip options int startX = library.getWidth() / 2 - LARGE_BUTTON - 25; for (int i = 0; i < _options.size(); i++) { _options.get(i).setDefaultLocation(startX + i * columnWidth, library.getHeight()/2 - LARGE_BUTTON_RADIUS); this.add(_options.get(i)); } // CANCEL BUTTON ('X' in upper right) ClipOption cancel = new ClipOption(_library, SMALL_BUTTON, "img/redbutton.png", "img/exittext.png", noteChannel) { @Override public void performAction() { _player.stop(); _playTimer.stop(); changePlayPercentage(0); _playPause.setImageText("img/playcliptext.png"); _library.hideOptions(); } }; this.add(cancel); int distFromBorder = 17; cancel.setDefaultLocation(getWidth()*9/10 - SMALL_BUTTON - distFromBorder, getHeight()/10 + distFromBorder); // DELETE? NO _justKidding = new ClipOption(_library, LARGE_BUTTON, "img/redbutton.png", "img/backtext.png", noteChannel) { @Override public void performAction() { hideDeleteConfirmation(); } }; _deleteConfirmation.add(_justKidding); // DELETE? YES _deleteForReals = new ClipOption(_library, LARGE_BUTTON, "img/greenbutton.png", "img/deletetext.png", noteChannel) { @Override public void performAction() { _player.stop(); _playTimer.stop(); changePlayPercentage(0); _playPause.setImageText("img/playcliptext.png"); if (_clip != null) _library.deleteClip(_clip); _library.hideOptions(); hideDeleteConfirmation(); } }; _deleteConfirmation.add(_deleteForReals); LabelElement label = new LabelElement("Delete for reals?", 32, library.getWidth()*4/5, 32); label.setLocation(library.getWidth()/10, library.getHeight()/5 + _clipName.getHeight() + 32); label.setForeground(Color.RED); _deleteConfirmation.add(label); } public void startPlaying() { _playPause.performAction(); } public void setClip(Clip clip) { _clipName.setText(clip.getFilename().replace("files/", "")); int tickLength = 50; _playTimer = new Timer(tickLength, new PlayTimerListener((int)clip.getLength()/tickLength)); _deleteForReals.setClip(clip); for (ClipOption option : _options) option.setClip(clip); hideDeleteConfirmation(); } private void showDeleteConfirmation() { _showDeleteConfirmation = true; for (ClipOption option : _options) this.remove(option); for (Component c : _deleteConfirmation) this.add(c); _deleteForReals.setLocation(_library.getWidth()/2 - LARGE_BUTTON - 25, _library.getHeight()/2 - LARGE_BUTTON_RADIUS); _justKidding.setLocation(_library.getWidth()/2 + 25, _library.getHeight()/2 - LARGE_BUTTON_RADIUS); _library.repaint(); } private void hideDeleteConfirmation() { _showDeleteConfirmation = false; for (Component c : _deleteConfirmation) this.remove(c); for (ClipOption option : _options) this.add(option); _options.get(0).setLocation(_library.getWidth()/2 - LARGE_BUTTON - 25, _library.getHeight()/2 - LARGE_BUTTON_RADIUS); _options.get(1).setLocation(_library.getWidth()/2 + 25, _library.getHeight()/2 - LARGE_BUTTON_RADIUS); _library.repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int rectX = getWidth()/10; int rectY = getHeight()/10; int rectWidth = getWidth() * 4/5; int rectHeight = getHeight() * 4/5; int arcWidth = 50; // white rectangle g2.setColor(Color.WHITE); g2.fillRoundRect(rectX, rectY, rectWidth, rectHeight, arcWidth, arcWidth); // white rectangle outline g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(5)); g2.drawRoundRect(rectX, rectY, rectWidth, rectHeight, arcWidth, arcWidth); if (!_showDeleteConfirmation) { // play-time bar g2.setColor(Color.RED); g2.fillRoundRect(rectX + 50, rectY + rectHeight * 4/5, (int)(_percentPlayed * (rectWidth - 100)), 15, 2, 2); // play-time bar outline g2.setColor(Color.GRAY); g2.drawRoundRect(rectX + 50, rectY + rectHeight * 4/5, rectWidth - 100, 15, 2, 2); } } private void changePlayPercentage(double percent) { _percentPlayed = percent; _library.repaint(); } private abstract class ClipOption extends HoverButton { protected Clip _clip; public ClipOption(Container pane, int size, String imageBase, String imageText, NotePlayerChannel noteChannel) { super(pane, imageBase, imageText, size, STANDARD_GROWTH_FACTOR, noteChannel); _chord = REVERSE_MAJOR_CHORD; } public void setClip(Clip clip) { _clip = clip; } } private class PlayPauseButton extends ClipOption { public PlayPauseButton(LibraryScreen library) { super(library, LARGE_BUTTON, "img/cyanbutton.png", "img/playcliptext.png", null); } @Override public void performAction() { if (_clip != null) { if (!_playTimer.isRunning() && _percentPlayed == 0 || _percentPlayed == 1) { setImageText("img/pausecliptext.png"); setImageBase("img/bluebutton.png"); _player.stop(); PlayTimerListener listener = (PlayTimerListener)_playTimer.getActionListeners()[0]; listener.restart(); _playTimer.start(); try { _clip.play(_player); } catch (MidiUnavailableException | InvalidMidiDataException e) { System.out.println("ERROR: problem playing clip"); } } else if (!_playTimer.isRunning()) { setImageText("img/pausecliptext.png"); setImageBase("img/bluebutton.png"); _playTimer.start(); _player.continuePlaying(); } else { setImageText("img/playcliptext.png"); setImageBase("img/cyanbutton.png"); _playTimer.stop(); _player.pause(); } } } } private class PlayTimerListener implements ActionListener { private int _maxTicks, _ticks; public PlayTimerListener(int maxTicks) { _ticks = 0; _maxTicks = maxTicks; } public void restart() { _ticks = 0; } @Override public void actionPerformed(ActionEvent e) { _ticks++; changePlayPercentage((double)_ticks/_maxTicks); if (_ticks == _maxTicks) { _playPause.setImageText("img/playcliptext.png"); _playTimer.stop(); _ticks = 0; } } } }
true
ab4f569a9c61e81e9a05c527526ae8b4f24378d3
Java
sh-zeynalli/todoList
/src/main/java/com/example/todolist/util/constant/ErrorCodes.java
UTF-8
460
2.578125
3
[]
no_license
package com.example.todolist.util.constant; public enum ErrorCodes { GENERAL_ERROR(5001,"General Error"), DATA_NOT_FOUND(5002,"Empty Field"), SUCCESS(0,"Success"); private int code; private String message; ErrorCodes(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } }
true
b5abf6638b122f8b40db5e511c2f3e4acd57b645
Java
cstdiohao/xiaogao
/leetcode/src/main/java/com/leetcode/Leetcode85.java
UTF-8
1,696
3.125
3
[]
no_license
package com.leetcode; public class Leetcode85 { public static void main(String[] args) { Leetcode85 leetcode85 = new Leetcode85(); char[][] m = {{'1', '0', '1', '0', '0'}, {'1', '0', '1', '1', '1'}, {'1', '1', '1', '1', '1'}, {'1', '0', '0', '1', '0'} }; System.out.println(leetcode85.maximalRectangle(m)); } public int maximalRectangle(char[][] matrix) { int n = matrix.length; if(n == 0){ return 0; } int m = matrix[0].length; if(m == 0){ return 0; } int[][] max = new int[n][m]; for(int i = 0; i < n; ++i){ if(matrix[i][m-1] == '0'){ max[i][m-1] = -1; }else{ max[i][m-1] = m-1; } for(int j = m-2; j >=0; --j){ if(matrix[i][j] == '0'){ max[i][j] = -1; }else{ max[i][j] = Math.max(max[i][j+1], j); } } } int ans = 0; for(int i = 0; i < n; ++i){ for(int j = 0; j < m; ++j){ if(matrix[i][j] == '0'){ continue; } int minValue = Integer.MAX_VALUE; for(int k = i; k < n; ++k){ if(matrix[k][j] == '0'){ break; } minValue = Math.min(minValue, max[k][j]); ans = Math.max(ans, (k-i+1) * (minValue-j+1)); } } } return ans; } }
true
b8f63701342d0f27ba7b84c3f929958d880bbe4d
Java
mmuellersoppart/MathematicianInTime
/src/main/java/org/openjfx/HomeController.java
UTF-8
1,408
2.53125
3
[]
no_license
package org.openjfx; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class HomeController implements Initializable{ @FXML private ImageView homeImageView; @FXML private HBox hBox; @FXML private BorderPane borderPane; public boolean homeImageViewActive; @FXML @Override public void initialize(URL url, ResourceBundle resourceBundle) { homeImageViewActive = true; } /** * @param mouseEvent * @throws IOException */ public void handleOnMouseClicked(MouseEvent mouseEvent) throws IOException { //System.out.print(mouseEvent); //System.out.println(mouseEvent.getPickResult().getIntersectedNode().getId()); //eventID //String current = new java.io.File( "." ).getCanonicalPath(); if(mouseEvent.getPickResult().getIntersectedNode().getId().equals("homeImageView") && homeImageViewActive){ Image image = new Image(getClass().getResource("Home.png").toExternalForm()); homeImageView.setImage(image); homeImageViewActive = false; } } }
true
88ccc640a59dbfc7c1233f6137c05fe00dcf6486
Java
thyferny/indwa-work
/AlpineMinerWeb/src/com/alpine/miner/impls/flowHistory/FlowHistoryInfo.java
UTF-8
2,559
2.265625
2
[]
no_license
package com.alpine.miner.impls.flowHistory; import java.io.File; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import com.alpine.miner.impls.web.resource.FlowInfo; public class FlowHistoryInfo implements Serializable { private static final long serialVersionUID = 6299222173403565451L; private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private String id, type, key, version, comments, createUser, modifiedUser, groupName, opendTime, displayText; private String[] categories; private long createTime, modifiedTime; public FlowHistoryInfo(FlowInfo flow) { this.id = flow.getId(); this.type = flow.getResourceType().name(); this.key = flow.getKey(); this.version = flow.getVersion(); this.comments = flow.getComments(); this.createUser = flow.getCreateUser(); this.modifiedUser = flow.getModifiedUser(); this.groupName = flow.getGroupName(); this.createTime = flow.getCreateTime(); this.modifiedTime = flow.getModifiedTime(); this.categories = flow.getCategories(); this.displayText = buildDisplayText(flow); this.opendTime = SDF.format(new Date()); } private String buildDisplayText(FlowInfo flow){ String text = flow.getCategories() == null || flow.getCategories().length == 0 ? flow.getModifiedUser() : flow.getCategories()[0]; text += File.separator; text += flow.getId(); return text; } public String getKey() { return key; } public String getOpendTime() { return opendTime; } public String getId() { return id; } public String getType() { return type; } public String getVersion() { return version; } public String getComments() { return comments; } public String getCreateUser() { return createUser; } public String getModifiedUser() { return modifiedUser; } public String getGroupName() { return groupName; } public long getCreateTime() { return createTime; } public long getModifiedTime() { return modifiedTime; } /** * @return the displayText */ public String getDisplayText() { return displayText; } /** * @param displayText the displayText to set */ public void setDisplayText(String displayText) { this.displayText = displayText; } /** * @return the categories */ public String[] getCategories() { return categories; } /** * @param categories the categories to set */ public void setCategories(String[] categories) { this.categories = categories; } }
true
b93de225e5ff8fed387fb0d72b643bbb76858cde
Java
VidhyaMadhavan/code_kata6
/leapyear.java
UTF-8
442
3.140625
3
[]
no_license
import java.io.*; import java.lang.*; class leapyear { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int year; System.out.println("Enter year:"); year=Integer.parseInt(br.readLine()); if(year>0&&year%4==0) { System.out.println(year+" is leapyear"); } else if(year<0) System.out.println("Invalid data"); else System.out.println(year+" is not leapyear"); } }
true
7e0f9b81b9254d7361a145d6e9fa1e6d864578c4
Java
ljukip/ISA
/application/src/main/java/com/booking/application/model/korisnici/AdminKompanije.java
UTF-8
3,903
2.328125
2
[]
no_license
package com.booking.application.model.korisnici; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.Pattern; import com.booking.application.dto.korisnici.KorisnikDTO; import com.booking.application.model.avionskakompanija.AvionskaKompanija; import com.booking.application.model.hotel.Hotel; import com.booking.application.model.vozila.KompanijaVozila; @Entity public class AdminKompanije { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 32, nullable = false) @Pattern(regexp = "^[A-Za-z]*$") private String ime; @Column(length = 32, nullable = false) @Pattern(regexp = "^[A-Za-z]*$") private String prezime; @Column(length = 32, nullable = false, unique = true, updatable = false) @Pattern(regexp = "^[A-Za-z0-9+_.-]+@(.+)$") private String email; @Column(length = 32, nullable = false) @Pattern(regexp = "^[A-Za-z0-9]*$") private String lozinka; @Column(length = 32, nullable = false) @Pattern(regexp = "^[A-Za-z ]*$") private String grad; @Column(length = 32, nullable = true, unique = true) @Pattern(regexp = "^[0-9]{9,10}$") private String telefon; @Enumerated(EnumType.STRING) private TipAdmina tip; @Column(nullable = false) private boolean aktiviran; @ManyToOne private AvionskaKompanija avionskaKompanija; @ManyToOne private Hotel hotel; @ManyToOne private KompanijaVozila kompanijaVozila; public AdminKompanije() { } public AdminKompanije(KorisnikDTO adminDTO) { this.id = adminDTO.getId(); this.ime = adminDTO.getIme(); this.prezime = adminDTO.getPrezime(); this.email = adminDTO.getEmail(); this.lozinka = adminDTO.getLozinka(); this.grad = adminDTO.getGrad(); this.telefon = adminDTO.getTelefon(); this.tip = adminDTO.getTipAdmina(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getIme() { return ime; } public void setIme(String ime) { this.ime = ime; } public String getPrezime() { return prezime; } public void setPrezime(String prezime) { this.prezime = prezime; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLozinka() { return lozinka; } public void setLozinka(String lozinka) { this.lozinka = lozinka; } public String getGrad() { return grad; } public void setGrad(String grad) { this.grad = grad; } public String getTelefon() { return telefon; } public void setTelefon(String telefon) { this.telefon = telefon; } public TipAdmina getTip() { return tip; } public void setTip(TipAdmina tip) { this.tip = tip; } public AvionskaKompanija getAvionskaKompanija() { return avionskaKompanija; } public void setAvionskaKompanija(AvionskaKompanija avionskaKompanija) { this.avionskaKompanija = avionskaKompanija; } public Hotel getHotel() { return hotel; } public void setHotel(Hotel hotel) { this.hotel = hotel; } public KompanijaVozila getKompanijaVozila() { return kompanijaVozila; } public void setKompanijaVozila(KompanijaVozila kompanijaVozila) { this.kompanijaVozila = kompanijaVozila; } public void prekopiraj(AdminKompanije adminKompanije) { this.id = adminKompanije.getId(); this.ime = adminKompanije.getIme(); this.prezime = adminKompanije.getPrezime(); this.lozinka = adminKompanije.getLozinka(); this.grad = adminKompanije.getGrad(); this.telefon = adminKompanije.getTelefon(); this.aktiviran = true; } public boolean isAktiviran() { return aktiviran; } public void setAktiviran(boolean aktiviran) { this.aktiviran = aktiviran; } }
true
82a660749edd6a14105a7c01706eaa2770b3a07a
Java
dengkang/springboot-laboratory
/rabbitmq/src/main/java/com/nged/rabbitmq/Consumer.java
UTF-8
1,122
2.0625
2
[]
no_license
package com.nged.rabbitmq; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; /** * @author: dengk * @Date: 2019/4/30 12:04 * @Description: */ @Component public class Consumer { @RabbitListener(queues = RabbitConfig.topicQueue) public void consumer(String message){ System.out.println("testQueue处理:"+ "[" + message); } @RabbitListener(queues = RabbitConfig.topicQueue2) public void consumerTopicQueue2(String message){ System.out.println("testQueue2处理:" +"[" + message); } @RabbitListener(queues = RabbitConfig.direct_queue) public void consumerDirect(String message){ System.out.println("direct 处理:"+"[" + message); } @RabbitListener(queues = RabbitConfig.queue_fanout_1) public void consumerFanout1(String message){ System.out.println("fanout1 处理:" +"[" + message); } @RabbitListener(queues = RabbitConfig.queue_fanout_2) public void consumerFanout2(String message){ System.out.println("fanout2 处理:" +"[" + message); } }
true
b5b3ae61f05780141464672209cd168ac9b38c29
Java
ojsanglovememe/mylive
/domain/src/main/java/com/src/isec/domain/interactor/ExitRoomUseCase.java
UTF-8
1,524
2.15625
2
[]
no_license
package com.src.isec.domain.interactor; import com.src.isec.domain.BaseParams; import com.src.isec.domain.entity.BaseResponse; import com.src.isec.domain.repository.IUserRepository; import javax.inject.Inject; import io.reactivex.Observable; /** * @author wj * @name IsecLive * @class name:com.src.isec.domain.interactor * @class describe * @time 2018/4/25 10:05 * @change * @chang time * @class describe 主播端退出房间 */ public class ExitRoomUseCase extends UseCase<BaseResponse, ExitRoomUseCase.Params> { private final IUserRepository mIUserRepository; @Inject public ExitRoomUseCase(IUserRepository mIUserRepository) { this.mIUserRepository = mIUserRepository; } public static ExitRoomUseCase.Params builderParams() { return new ExitRoomUseCase.Params(); } @Override protected Observable<BaseResponse> buildUseCaseObservable(Params params) { return mIUserRepository.exitRoom(params.params); } public static final class Params extends BaseParams { public Params onTxToken(String txToken) { params.put("token", txToken); return this; } public Params onLive() { params.put("type", "live"); return this; } public Params onRoomNum(String roomNum) { params.put("roomnum", roomNum); return this; } public Params onRole() { params.put("role", "1"); return this; } } }
true
7826d2cb76249c64d0df544c9dbd433a25e92038
Java
nijesung/Javafirst
/nije0801/src/DBex/DeptnoEx.java
UTF-8
2,066
3.234375
3
[]
no_license
package DBex; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.Scanner; public class DeptnoEx { public static void main(String[] args) { Connection con = null; PreparedStatement ppsm = null; Scanner sc = new Scanner(System.in); System.out.print("deptno 번호 입력: "); // 삭제할 deptno 번호를 입력 int deptno = sc.nextInt(); System.out.println("부서번호: " + deptno); sc.close(); // 여기까지가 입력받는 부분 try { Class.forName("oracle.jdbc.driver.OracleDriver"); // 드라이버 클래스 로드 con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", // 데이터베이스 연결 "scott", "tiger"); System.out.println("접속 성공"); // 연결 되었나 확인 con.setAutoCommit(false); // autocommit 해제 ppsm = con.prepareStatement("delete from dept where deptno = ?"); // SQL 실행객체 생성 ppsm.setInt(1, deptno); // ? 가 있으면 데이터를 바인딩 int r = ppsm.executeUpdate(); // SQL 실행 if(r > 0) { // 실행하고 나면 영향받은 행의 개수를 리턴한다. 조건에 맞는 데이터가 없으면 실패하는 것이 아니라 삭제하는 행의 // 개수가 0개이다. 실패하면 예외가 발생하므로 catch 로 간다. System.out.println("삭제 성공"); con.commit(); // 오토커밋 해제 시 } else System.out.println("조건에 맞는 데이터가 없음"); }catch(Exception e) { try { // 오토커밋 해제 시 작업도중 예외가 발생한 경우 rollback 을 호출 // con.rollback(); {} // 오토커밋 해제 시 System.out.println(e.getMessage()); // 예외의 내용을 출력 e.printStackTrace(); // 예외가 발생한 지점을 역추적 }finally { try { if(ppsm != null)ppsm.close(); if(con != null)con.close(); }catch(Exception e2) {} } } } }
true
1874b79cab3dc37d289271d51e7bf829708d82a6
Java
songc/MyPlant
/src/main/java/com/songc/core/ap/detect/wave/FindAPPositionIndex.java
UTF-8
11,554
2.40625
2
[]
no_license
package com.songc.core.ap.detect.wave; import java.util.Arrays; /** * Created by songc on 2/14/2017. */ class FindAPPositionIndex { private Wave lowFilterWave; private Wave centralDiffWave; private Peaks peaksNoThreshold; private Peaks peaksWithThreshold; private int sampleFrequency; private double signalThreshold; private double noiseThreshold; FindAPPositionIndex(Augument augument) { this.lowFilterWave = augument.lowFilterWave; this.centralDiffWave = augument.centralDiffWave; this.peaksNoThreshold = augument.peaksNoThreshold; this.peaksWithThreshold = augument.peaksWithThreshold; this.sampleFrequency = augument.sampleFrequency; this.signalThreshold = augument.signalThreshold; this.noiseThreshold = augument.noiseThreshold; } APWavePositionIndex getAPWavePositionIndex() { int index1 = -1, index2; //注意数组越界问题 //查找不设置阈值的波峰中第一个与设置阈值的波峰位置相等的位置,该位置之前的所有波峰都为噪声信号。 int firstSignalPeaks = this.peaksWithThreshold.getLocs()[0]; for (int i = 0; i < this.peaksNoThreshold.locs.length; i++) { if (this.peaksNoThreshold.locs[i] == firstSignalPeaks) { index1 = i; break; } } //注意数组下标问题原先 index1>3 if (index1 > 2) { index2 = this.peaksNoThreshold.locs[index1 - 3]; index1 = index1 / 2; index1 = this.peaksNoThreshold.locs[index1]; //注意数组下标问题,原先 index1>1; } else if (index1 > 0) { index2 = this.peaksNoThreshold.locs[index1 - 1]; index1 = this.peaksNoThreshold.locs[index1 / 2]; } else { index2 = 2 * this.sampleFrequency; index1 = index1 / 2; } double baseline = 0, bias = 0, sum = 0; for (int i = index1 + 2; i < index2 - 3; i++) { sum += this.lowFilterWave.data[i]; } baseline = sum / (index2 - 3 - index1 - 2); int len = this.peaksNoThreshold.locs.length; //k的初始化,原先为k=1,改为k=0 int k = 0, leftPotion = -1, rightPotion = -1, leftPeak = -1, rightPeak = -1; int[] peaks = new int[len]; int[] peaksLeft = new int[len]; int[] peaksRight = new int[len]; double[] rawPeaks = new double[len]; double[] rawPeaksLeft = new double[len]; double[] rawPeaksRight = new double[len]; int j = 0; //注意数组下标 k<=augument,peaksWithThreshold.locs.length while (k < this.peaksWithThreshold.locs.length && this.peaksWithThreshold.locs.length > 1) { //注意数组下标 原始k==1 if (k == 0) { leftPotion = leftSearch(this.centralDiffWave.data, this.peaksWithThreshold.locs[0]); rightPotion = rightSearch(this.centralDiffWave.data, this.peaksWithThreshold.locs[0]); leftPeak = leftSearch(this.centralDiffWave.data, this.peaksWithThreshold.locs[1]); rightPeak = rightSearch(this.centralDiffWave.data, this.peaksWithThreshold.locs[1]); //注意数组下标 原始k=2 k = 1; } else { leftPeak = leftSearch(this.centralDiffWave.data, this.peaksWithThreshold.locs[k]); rightPeak = rightSearch(this.centralDiffWave.data, this.peaksWithThreshold.locs[k]); } if (this.centralDiffWave.data[this.peaksWithThreshold.locs[k - 1]] * this.centralDiffWave.data[this.peaksWithThreshold.locs[k]] < 0) { if (rightPotion == leftPeak || rightPotion + 1 == leftPeak) { //写错了忘记+1了;这里好像有点问题&&两边是一样的 if (Math.abs(this.lowFilterWave.data[rightPotion + 1]) >= Math.abs(this.lowFilterWave.data[rightPotion]) && Math.abs(this.lowFilterWave.data[rightPotion + 1]) >= Math.abs(this.lowFilterWave.data[rightPotion])) { peaks[j] = rightPotion + 1; } else { peaks[j] = rightPotion; } rawPeaks[j] = this.lowFilterWave.data[rightPotion]; peaksLeft[j] = leftPotion; rawPeaksLeft[j] = this.lowFilterWave.data[leftPotion]; peaksRight[j] = rightPeak; rawPeaksRight[j] = this.lowFilterWave.data[rightPeak]; j++; } } else { //这里修改了下 int index = -1; for (int tmp : this.peaksNoThreshold.locs) { if (tmp > this.peaksWithThreshold.locs[k - 1] & tmp < this.peaksWithThreshold.locs[k]) { index++; } } if (index != -1 && (this.peaksWithThreshold.locs[k] - this.peaksWithThreshold.locs[k - 1]) <= 1 * this.sampleFrequency) { leftPotion = leftPeak; rightPotion = rightPeak; } } k++; // j++; leftPotion = leftPeak; rightPotion = rightPeak; } peaks = Arrays.copyOfRange(peaks, 0, j); peaksLeft = Arrays.copyOfRange(peaksLeft, 0, j); peaksRight = Arrays.copyOfRange(peaksRight, 0, j); rawPeaks = Arrays.copyOfRange(rawPeaks, 0, j); rawPeaksLeft = Arrays.copyOfRange(rawPeaksLeft, 0, j); rawPeaksRight = Arrays.copyOfRange(rawPeaksRight, 0, j); //需要考虑下peaksleft几个数组的长度,初始初始化是设置的是最大的长度。 int jj = 0; //注意数组越界问题 原先jj<peaksLeft.length-1; // int/2 = floor(int/2)matlab, int/2+1 = ceil(int/2) while (peaksLeft.length > 0 && jj < (peaksLeft.length - 1)) { if (peaksRight[jj] > peaksLeft[jj + 1]) { int num = (peaksRight[jj] - peaksLeft[jj + 1]) / 2; peaksRight[jj] = peaksRight[jj] - (num + 1); rawPeaksRight[jj] = this.lowFilterWave.data[peaksRight[jj]]; peaksLeft[jj + 1] = peaksLeft[jj + 1] + num; rawPeaksLeft[jj + 1] = this.lowFilterWave.data[peaksLeft[jj + 1]]; } jj++; } double[] peaksValue = new double[len]; double[] peaksLeftValue = new double[len]; double[] peaksRightValue = new double[len]; int[] peaksLoc = new int[len]; int[] peaksLeftLoc = new int[len]; int[] peaksRightLoc = new int[len]; int ci, len3 = peaksLeft.length; int index3 = 0; double camplitude; int pi; int numpeak = 0; //数组的下标问题 while (len3 > 1 && index3 < (len3 - 1)) { camplitude = Math.abs(rawPeaksLeft[index3] - rawPeaks[index3]); pi = index3; ci = index3; while (index3 < (len3 - 1) && (peaksRight[index3] + 1 == peaksLeft[index3 + 1] || peaksRight[index3] == peaksLeft[index3 + 1])) { if (camplitude < Math.abs(rawPeaksLeft[ci] - rawPeaks[index3 + 1])) { pi = index3 + 1; camplitude = rawPeaksLeft[ci] - rawPeaks[index3 + 1]; } index3++; } if (ci < index3 && camplitude > 5) { peaksLeftLoc[numpeak] = peaksLeft[ci]; peaksLeftValue[numpeak] = rawPeaksLeft[ci]; peaksRightLoc[numpeak] = peaksRight[index3]; peaksRightValue[numpeak] = rawPeaks[index3]; peaksLoc[numpeak] = peaks[pi]; peaksValue[numpeak] = rawPeaks[pi]; numpeak++; } else if (ci == index3 && camplitude > 5) { peaksLeftLoc[numpeak] = peaksLeft[index3]; peaksLeftValue[numpeak] = rawPeaksLeft[index3]; peaksRightLoc[numpeak] = peaksRight[index3]; peaksRightValue[numpeak] = rawPeaks[index3]; peaksLoc[numpeak] = peaks[index3]; peaksValue[numpeak] = rawPeaks[index3]; numpeak++; } index3++; } //注意数组下标问题, 原先index3==len3; if (len3 == 1 || index3 == len3 - 1) { camplitude = Math.abs(rawPeaksLeft[len3 - 1] - rawPeaks[len3 - 1]); if (camplitude > 5) { //原先都是len3改为len3-1 peaksLeftLoc[numpeak] = peaksLeft[len3 - 1]; peaksLeftValue[numpeak] = rawPeaksLeft[len3 - 1]; peaksRightLoc[numpeak] = peaksRight[len3 - 1]; peaksRightValue[numpeak] = rawPeaks[len3 - 1]; peaksLoc[numpeak] = peaks[len3 - 1]; peaksValue[numpeak] = rawPeaks[len3 - 1]; numpeak++; } } int[] actionPotentialLeft = Arrays.copyOfRange(peaksLeftLoc, 0, numpeak); int[] actionPotentialRight = Arrays.copyOfRange(peaksRightLoc, 0, numpeak); int[] actionPotentialPeaks = Arrays.copyOfRange(peaksLoc, 0, numpeak); return new APWavePositionIndex(actionPotentialLeft, actionPotentialPeaks, actionPotentialRight); } public int leftSearch(double[] signal, int peakLoc) { int left; while (peakLoc > 0) { if (Math.abs(signal[peakLoc]) == 0 || signal[peakLoc] * signal[peakLoc - 1] <= 0) { break; } else { peakLoc--; } } //注意数组下标问题 原先 peakLoc>1; if (peakLoc > 0 && Math.abs(signal[peakLoc]) > 0 && signal[peakLoc - 1] == 0) { peakLoc--; } left = peakLoc; return left; } public int rightSearch(double[] signal, int peakLoc) { int right; //注意数组越界问题 while (peakLoc < (signal.length - 1)) { if (Math.abs(signal[peakLoc]) == 0 || signal[peakLoc] * signal[peakLoc + 1] <= 0) { break; } else { peakLoc++; } } //注意数组越界问题,MATLAB的数组是从1开始的 if (peakLoc > 0 && peakLoc < (signal.length - 1) && Math.abs(signal[peakLoc]) > 0 && signal[peakLoc + 1] == 0) { peakLoc++; } right = peakLoc; return right; } public static class Augument { Peaks peaksNoThreshold; Peaks peaksWithThreshold; Wave lowFilterWave; Wave centralDiffWave; int sampleFrequency; double signalThreshold; double noiseThreshold; public Augument(Peaks allPeaks, Peaks signalPeaks, Wave lowFilterWave, Wave centralDiffWave, int sampleFrequency, double signalThreshold, double noiseThreshold) { this.peaksNoThreshold = allPeaks; this.peaksWithThreshold = signalPeaks; this.centralDiffWave = centralDiffWave; this.sampleFrequency = sampleFrequency; this.signalThreshold = signalThreshold; this.noiseThreshold = noiseThreshold; this.lowFilterWave = lowFilterWave; } } }
true
a8344b8ab7ae6c6af15d2544a93b00054ef7a44b
Java
alenafdr/gamelexicon
/src/main/java/ru/study/gamelexicon/service/WordServiceImpl.java
UTF-8
1,800
2.28125
2
[]
no_license
package ru.study.gamelexicon.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.study.gamelexicon.dao.WordDao; import ru.study.gamelexicon.model.Word; import java.util.List; @Service public class WordServiceImpl implements WordService { private static final Logger logger = LoggerFactory.getLogger(WordServiceImpl.class); @Autowired WordDao wordDao; @Override public List<Word> list() { return wordDao.findAll(); } @Override @Transactional public void save(Word word) { wordDao.save(word); logger.info("Word created", word); } @Override @Transactional public void update(Word word) { wordDao.save(word); logger.info("Word updated", word); } @Override @Transactional public void remove(Long id) { wordDao.deleteById(id); } @Override @Transactional public Word getById(Long id) { return wordDao.getOne(id); } @Override @Transactional public Word getByName(String name) { return wordDao.getByName(name); } @Override @Transactional public List<Word> getWordsGuessedAboveThresholdByUserId(Long id, int limit) { return wordDao.getWordsGuessedAboveThresholdByUserId(id, limit); } @Override @Transactional public List<Word> getMostHitsByUserId(Long id, int limit) { return wordDao.getMostHitsByUserId(id, limit); } @Override @Transactional public List<Word> getMostMissesByUserId(Long id, int limit) { return wordDao.getMostMissesByUserId(id, limit); } }
true
effd11761ef230085e3704ac2c2a46b0449b17d9
Java
ericignite/lusaapp
/app/src/main/java/com/example/android/sunshine/app/routing/models/CrewMember.java
UTF-8
358
2.09375
2
[]
no_license
package com.example.android.sunshine.app.routing.models; /** * Created by lancehughes on 9/17/14. */ public class CrewMember { public String id; public String name; public String leader; public CrewMember(String id, String name, String leader) { this.id = id; this.name = name; this.leader = leader; } }
true
32d0afc010295b5b036e714a69c2eed0ce1d0a7f
Java
sgros/activity_flow_plugin
/TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/JADX/src/main/java/org/telegram/messenger/C0770-$$Lambda$MessagesStorage$ANII5DCxsANA4ox20RDROdwMfjc.java
UTF-8
592
1.773438
2
[]
no_license
package org.telegram.messenger; /* compiled from: lambda */ /* renamed from: org.telegram.messenger.-$$Lambda$MessagesStorage$ANII5DCxsANA4ox20RDROdwMfjc */ public final /* synthetic */ class C0770-$$Lambda$MessagesStorage$ANII5DCxsANA4ox20RDROdwMfjc implements Runnable { private final /* synthetic */ MessagesStorage f$0; public /* synthetic */ C0770-$$Lambda$MessagesStorage$ANII5DCxsANA4ox20RDROdwMfjc(MessagesStorage messagesStorage) { this.f$0 = messagesStorage; } public final void run() { this.f$0.lambda$getWallpapers$32$MessagesStorage(); } }
true
07ef532d926991b4dfc9a2f126a5e2b1b626a4da
Java
herojing/JokeTask
/app/src/main/java/com/example/wangjing/joketask/adapter/JokeAdapter.java
UTF-8
2,186
2.40625
2
[]
no_license
package com.example.wangjing.joketask.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.wangjing.joketask.R; import com.example.wangjing.joketask.entities.JokeInfo; import java.util.ArrayList; /** * @author wangjing * @since 2016/5/20 17:28 * @version 1.0 * <p> * <strong>Features draft description.主要功能介绍</strong> * </p> */ public class JokeAdapter extends BaseAdapter { private Context mContext; private ArrayList<JokeInfo> mJokeInfoArrayList; public JokeAdapter(Context context, ArrayList<JokeInfo> jokeInfoArrayList) { mContext = context; mJokeInfoArrayList = jokeInfoArrayList; } @Override public int getCount() { return mJokeInfoArrayList == null ? 0 : mJokeInfoArrayList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View ret = null; if (convertView == null) { ret = LayoutInflater.from(mContext).inflate(R.layout.main_page_list_item, parent, false); }else { ret=convertView; } ViewHolder holder = (ViewHolder) ret.getTag(); if(holder==null){ holder=new ViewHolder(ret); ret.setTag(holder); } holder.setUI(mJokeInfoArrayList.get(position)); return ret; } public static class ViewHolder { private TextView mJokeContent; private TextView mAddTime; public ViewHolder(View pView) { mJokeContent = (TextView) pView.findViewById(R.id.joke_content); mAddTime = (TextView) pView.findViewById(R.id.add_time); } public void setUI(JokeInfo pJokeInfo) { mJokeContent.setText(pJokeInfo.getContent()); mAddTime.setText(pJokeInfo.getAddTime()); } } }
true
5f67443708cd6678768c63bb999c74e9c53a7e61
Java
LuizFernandesOliveira/lpp-java-learning-solid
/src/main/java/solid/srp/App.java
UTF-8
260
2.34375
2
[]
no_license
package solid.srp; public class App { public static void main(String[] args) { Calculator calculator = new Calculator(); calculator.sum(10, 10); calculator.subtract(10, 10); calculator.multiply(10, 10); calculator.divide(10, 10); } }
true
6f699fa08b59cde10bc0e7ca50f2a811170ba81e
Java
daniela-becheanu/POO--tema1
/src/compare/CompareActors.java
UTF-8
490
2.828125
3
[]
no_license
package compare; import convert.Actor; import java.util.Comparator; public final class CompareActors implements Comparator<Actor> { @Override public int compare(final Actor actor1, final Actor actor2) { if (actor1.getFirstCriterion() > actor2.getFirstCriterion()) { return 1; } if (actor1.getFirstCriterion() < actor2.getFirstCriterion()) { return -1; } return actor1.getName().compareTo(actor2.getName()); } }
true
5c86daf4c2d528a31f12351b6ec3ca1fcf256729
Java
princesingh00/Java-Functional
/twoD.java
UTF-8
891
3.234375
3
[]
no_license
import java.util.Scanner; import java.io.*; import java.util.ArrayList; public class twoD { public static void main(String[] args) { Scanner obj = new Scanner(System.in); // PrintWriter x = new PrintWriter(System.out); System.out.println("Enter the Number of rows : "); int row = obj.nextInt(); System.out.println("Enter the Number of columns : "); int col = obj.nextInt(); System.out.println("Enter the array elements : "); int i=0; int j=0; int[][] arr = new int[row][col]; for(i=0; i<row; i++){ for(j=0; j<col; j++) { arr[i][j] = obj.nextInt(); } } System.out.println("your array "); // x.println(arr); //x.flush(); for(i=0; i<row; i++){ for(j=0; j<col; j++) { System.out.print( arr[i][j] + "\t" ); } System.out.println(); } }}
true
8520a8c7d5e3fc5b4ce7d1ce4a43dfef0a8851c5
Java
tusharmahamuni/Ladder
/src/main/java/com/snl/model/Square.java
UTF-8
1,547
3.359375
3
[]
no_license
package com.snl.model; public class Square { protected int position; protected Board board; private Player player; public Square(Board board, int position) { this.position = position; this.board = board; validate(); } protected void validate() { if(board == null) { throw new IllegalArgumentException("board should not be null"); } } public int position() { return this.position; } public Square getToOccupy(int moves) { final Square square = board.findBoardSquare(position, moves); return square.occupyOrBackToStart(); } public Square occupyOrBackToStart() { return this.alreadyOccupied() ? this.board.firstBoardSquare() : this; } public boolean isFirstSquare() { return false; } public boolean isLastSquare() { return false; } public void enter(Player player) { if(player == null) { throw new UnsupportedOperationException("Player should not be null"); } this.player = player; } public void leave(Player player) { if(this.player == player) { this.player = null; }else { throw new UnsupportedOperationException("Player " + player + " is not occupying current square"); } } public boolean isOccupied() { return this.player != null; } public boolean alreadyOccupied() { return isOccupied(); } protected String player() { return this.isOccupied() ? ("<" + this.player + ">") : ""; } protected String squareContent() { return Integer.toString(position); } public String toString() { return "[" + this.squareContent() + this.player() + "]"; } }
true
ee9a6f847a9d4d7551982a22542f4ec88c6bfe96
Java
Ans123/ReadyBid
/rb-server-master/rb-server-api-aggregator/rb-server-api-main/src/main/java/net/readybid/api/main/access/PermissionsCheck.java
UTF-8
321
1.570313
2
[]
no_license
package net.readybid.api.main.access; import net.readybid.app.entities.authorization.dirty.InvolvedAccounts; import net.readybid.auth.user.AuthenticatedUser; /** * Created by DejanK on 4/7/2017. * */ public interface PermissionsCheck { boolean check(AuthenticatedUser user, InvolvedAccounts involvedAccounts); }
true
1e05918f99ea52440cb11d0c50dc6aac1dead07e
Java
kazak-358/Caloric
/src/main/java/net/caloric/controller/ControllerConstants.java
UTF-8
464
1.789063
2
[]
no_license
package net.caloric.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public class ControllerConstants { public static final ResponseEntity<?> CREATED_RESPONSE = new ResponseEntity<>(HttpStatus.CREATED); public static final ResponseEntity<?> OK_RESPONSE = new ResponseEntity<>(HttpStatus.OK); public static final ResponseEntity<?> NOT_MODIFIED_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_MODIFIED); }
true
281f44aa13340b1860d3a39b06fc1d4946f38e37
Java
JMartinez7477/Util
/src/util/classes/RacingCondition.java
UTF-8
1,811
3.21875
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 util.classes; import java.util.ArrayList; /** * * @author S531749 */ public class RacingCondition { String name1; String condition; String name2; int position; public RacingCondition(String name1, String condition, String second) { this.name1 = name1; this.condition = condition; if(condition.equalsIgnoreCase("BEAT")){ this.name2 = second; } if (condition.equalsIgnoreCase("WAS")) { secondToPosition(second); } } public boolean secondToPosition(String second) { if (second.equalsIgnoreCase("FIRST")) { position = 1; } else if (second.equalsIgnoreCase("SECOND")) { position = 2; } else if (second.equalsIgnoreCase("THIRD")) { position = 3; } else if (second.equalsIgnoreCase("LAST")) { position = 4; } if (position > 0) { return true; } else { return false; } } public boolean meetsCondition(ArrayList<String> people) { boolean met = false; if (condition.equalsIgnoreCase("BEAT")) { int index1 = people.indexOf(name1); int index2 = people.indexOf(name2); if (index1 < index2) { met = true; } } else if (condition.equalsIgnoreCase("WAS")) { int index = people.indexOf(name1); if (index == (position - 1)) { met = true; } } return met; } }
true
823c05b15b802805f55b1dd67d1ff9f0a6c26975
Java
otaviohenrique1/Vecx-System-Java-Desktop
/Vecx System180/Sistema/moduloFinanceiroCompraTabelas/TabelaModeloHistoricoCompra.java
IBM852
1,847
2.765625
3
[]
no_license
package moduloFinanceiroCompraTabelas; import java.util.ArrayList; import javax.swing.table.AbstractTableModel; public class TabelaModeloHistoricoCompra extends AbstractTableModel{ /** * */ private static final long serialVersionUID = 1L; private ArrayList<HistoricoCompraTabela> listaHistoricoCompra; private String[] colunas = {"Codigo da compra","Nome do funcionario", "Data e hora da venda","Preo total"}; public TabelaModeloHistoricoCompra() { this.listaHistoricoCompra = new ArrayList<>(); } public void addHistoricoCompra(HistoricoCompraTabela HistoricoCompraTabelaDados){ this.listaHistoricoCompra.add(HistoricoCompraTabelaDados); fireTableDataChanged(); } public HistoricoCompraTabela getCompra(int rowIndex){ return this.listaHistoricoCompra.get(rowIndex); } @Override public int getRowCount() { return this.listaHistoricoCompra.size(); } @Override public int getColumnCount() { return colunas.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { switch(columnIndex){ case 0: return this.listaHistoricoCompra.get(rowIndex).getCodigoCompra(); case 1: return this.listaHistoricoCompra.get(rowIndex).getNomeFuncionario(); case 2: return this.listaHistoricoCompra.get(rowIndex).getDataHoraCompra(); case 3: return this.listaHistoricoCompra.get(rowIndex).getPrecoTotal(); default: return this.listaHistoricoCompra.get(rowIndex); } } @Override public String getColumnName(int columnIndex){ return this.colunas[columnIndex]; } }
true
6cf919a0808d6fcbbc9f97d89d49813cc9c08dc0
Java
wangchao550586585/nio
/src/main/java/nio/regex/A_Regex.java
UTF-8
638
3
3
[]
no_license
package nio.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class A_Regex { public static void main(String[] args) { String input = "str"; Pattern pattern = Pattern.compile("ABC|XYZ"); Matcher matcher = pattern.matcher(input); String match0 = input.subSequence(matcher.start(), matcher.end()).toString(); String match2 = input.subSequence(matcher.start(2), matcher.end(2)).toString(); //上述代码与下列代码等效: match0 = matcher.group(); match2 = matcher.group(2); //$1表示匹配的第一个 //192 } }
true
10bbd4cf585c483b899b29d1dfc456da3085037d
Java
dancarvie/material-da-aula
/aula03/Exercicios/exercicio05.java
UTF-8
1,007
3.671875
4
[]
no_license
package Exercicios; import java.util.Scanner; public class exercicio05 { public static void main(String[] args) { Scanner entrada = new Scanner(System.in); double mediaAluno, mediaTurma, mediaGeral; final int NUM_ALUNO = 3; final int NUM_TURMA = 2; mediaGeral = 0; for (int turma = 1; turma <= NUM_TURMA; turma++){ mediaTurma = 0; for (int aluno = 1; aluno <= NUM_ALUNO; aluno++) { System.out.printf("Digite a média do " +aluno+ "º aluno: "); mediaAluno = entrada.nextDouble(); mediaTurma = mediaTurma + mediaAluno; } mediaTurma = mediaTurma / NUM_ALUNO; System.out.println("Média da turma: " + mediaTurma); mediaGeral = mediaGeral + mediaTurma; System.out.println("Média da turma " + turma+ ": " + mediaTurma); } mediaGeral = mediaGeral / NUM_TURMA; System.out.println("\nMédia Geral: " + mediaGeral); entrada.close(); } }
true
24811ed16e331b5d4f417d427b1143c35f0c212e
Java
thanh23091991/FirstProjectGroup1
/StudentManagerGroup1/src/main/java/com/studentmanager/entity/Diem.java
UTF-8
1,782
2.265625
2
[]
no_license
package com.studentmanager.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; @Entity @IdClass(Diem.class) @Table(name = "Diem") public class Diem implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @Column(name = "MaSV", columnDefinition = "char(15)", nullable = false) private String maSV; @Id @Column(name = "MaMH", columnDefinition = "char(5)", nullable = false) private String maMH; @Column(name = "HocKy", columnDefinition = "int", nullable = false) private int hocKy; @Column(name = "DiemLan1", columnDefinition = "int", nullable = false) private int diemLan1; @Column(name = "DiemLan2", columnDefinition = "int", nullable = false) private int diemLan2; public Diem() { super(); } public Diem(String maSV, String maMH, int hocKy, int diemLan1, int diemLan2) { super(); this.maSV = maSV; this.maMH = maMH; this.hocKy = hocKy; this.diemLan1 = diemLan1; this.diemLan2 = diemLan2; } public String getMaSV() { return maSV; } public void setMaSV(String maSV) { this.maSV = maSV; } public String getMaMH() { return maMH; } public void setMaMH(String maMH) { this.maMH = maMH; } public int getHocKy() { return hocKy; } public void setHocKy(int hocKy) { this.hocKy = hocKy; } public int getDiemLan1() { return diemLan1; } public void setDiemLan1(int diemLan1) { this.diemLan1 = diemLan1; } public int getDiemLan2() { return diemLan2; } public void setDiemLan2(int diemLan2) { this.diemLan2 = diemLan2; } }
true
a234e0f80b02840e8c11eaf7145b1979eb940818
Java
liulei6696/A1Restaurant
/RestaurantClient/app/src/main/java/edu/neu/a1/restaurantclient/item/Chickens.java
UTF-8
248
2.515625
3
[]
no_license
package edu.neu.a1.restaurantclient.item; public class Chickens implements Item{ private final String name = "chickens"; private final static double price = 7.0; @Override public double getPrice() { return price; } }
true
3c2dc463a096a15c14ea510f23409cfbe3dc136f
Java
xckNull/Algorithms-introduction
/src/test/java/algorithms/introduction/sort/test/RadixSortTest.java
UTF-8
361
2.5625
3
[]
no_license
package algorithms.introduction.sort.test; import java.util.Arrays; import org.junit.Test; import algorithms.introduction.sort.RadixSort; public class RadixSortTest { @Test public void testRadixSort() { int[] arr = new int[] { 1100, 192, 221, 12, 23 }; RadixSort.radixSort(arr, 10, 4); System.out.print(Arrays.toString(arr)); } }
true
45c948b4ac8a26560fd14aae428e6c23ab4deb2e
Java
gjhutchison/pixelhorrorjam2016
/core/src/com/kowaisugoi/game/rooms/RoomBathroomEntrance.java
UTF-8
8,526
2.109375
2
[ "Apache-2.0" ]
permissive
package com.kowaisugoi.game.rooms; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Timer; import com.kowaisugoi.game.audio.AudioManager; import com.kowaisugoi.game.audio.MusicId; import com.kowaisugoi.game.audio.SoundId; import com.kowaisugoi.game.control.flags.FlagId; import com.kowaisugoi.game.interactables.objects.ItemId; import com.kowaisugoi.game.interactables.passages.DirectionalPassage; import com.kowaisugoi.game.interactables.passages.Passage; import com.kowaisugoi.game.interactables.scenic.Describable; import com.kowaisugoi.game.interactables.scenic.GeneralDescribable; import com.kowaisugoi.game.messages.Messages; import com.kowaisugoi.game.player.Player; import com.kowaisugoi.game.screens.PlayGame; import com.kowaisugoi.game.system.GameUtil; import java.util.LinkedList; import java.util.List; import static com.kowaisugoi.game.control.flags.FlagId.FLAG_BOARDS_REMOVED; public class RoomBathroomEntrance extends StandardRoom { private static final String ROOM_URL = "rooms/bathroom/bathroom_entrance_boards.png"; private static final String ROOM_URL2 = "rooms/bathroom/bathroom_entrance.png"; private static final String ROOM_URL3 = "rooms/bathroom/bathroom_entrance_2.png"; private static final String ROOM_URL4 = "rooms/bathroom/bathroom_entrance_empty.png"; private final Sprite _roomSprite1 = new Sprite(new Texture(ROOM_URL)); private final Sprite _roomSprite2 = new Sprite(new Texture(ROOM_URL2)); private final Sprite _roomSprite3 = new Sprite(new Texture(ROOM_URL3)); private final Sprite _roomSprite4 = new Sprite(new Texture(ROOM_URL4)); private Describable _uncle; private List<Describable> _descriptionList1; private List<Describable> _descriptionList2; private List<Passage> _passageList2; public RoomBathroomEntrance() { super(new Sprite(new Texture(ROOM_URL))); _passageList2 = new LinkedList<Passage>(); Passage passageBack = new DirectionalPassage(RoomId.BATHROOM, RoomId.BEDROOM, new Rectangle(50, 0, 50, 15), GameUtil.Direction.DOWN); Passage passageForward = new DirectionalPassage(RoomId.BATHROOM, RoomId.BATHROOM_CABINET, new Rectangle(100, 16, 22, 61), GameUtil.Direction.UP); Describable mirror = new GeneralDescribable(Messages.getText("bathroom.cabinet.thought"), new Rectangle(99, 52, 20, 25)); passageBack.setSoundEffect(SoundId.CLICK); addPassage(passageBack); _descriptionList1 = new LinkedList<Describable>(); _descriptionList2 = new LinkedList<Describable>(); _uncle = new GeneralDescribable(Messages.getText("bathroom.uncle.thought.1"), new Rectangle(68, 25, 27, 58)); _uncle.addDescription(Messages.getText("bathroom.uncle.thought.2")); _uncle.setItemInteractionMessage(ItemId.STICK, Messages.getText("bathroom.interaction.stick.uncle")); _descriptionList1.add(_uncle); addDescribable(mirror); addDescribable(_uncle); _passageList2.add(passageForward); _passageList2.add(passageBack); } @Override public boolean click(float curX, float curY) { return super.click(curX, curY); } @Override public void flagUpdate() { if (PlayGame.getFlagManager().getFlag(FLAG_BOARDS_REMOVED).getState()) { setSprite(_roomSprite2); setPassageList(_passageList2); setDescriptionList(_descriptionList1); } if (PlayGame.getFlagManager().getFlag(FlagId.FLAG_KEYS_MISSING).getState()) { setSprite(_roomSprite4); setDescriptionList(_descriptionList2); } } @Override public void enter() { super.enter(); AudioManager.playMusic(MusicId.DRONE, false); if (PlayGame.getFlagManager().getFlag(FlagId.FLAG_KEYS_MISSING).getState()) { // Disable mouse for a *little* bit longer the first time if (!PlayGame.getFlagManager().getFlag(FlagId.FLAG_KEYS_APPEARED).getState()) { PlayGame.getRoomManager().getRoomFromId(RoomId.ROAD).pushEnterRemark("forestpath.flee.thought"); PlayGame.getFlagManager().setFlag(FlagId.FLAG_KEYS_APPEARED, true); Timer.schedule(new Timer.Task() { @Override public void run() { PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NORMAL); } } , 2.8f // Initial delay , 0 // Fire every X seconds , 1 // Number of times to fire ); } else { Timer.schedule(new Timer.Task() { @Override public void run() { PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NORMAL); } } , 0.8f // Initial delay TODO: Should make global, or shouldn't set this here , 0 // Fire every X seconds , 1 // Number of times to fire ); } PlayGame.getFlagManager().setFlag(FlagId.FLAG_KEYS_APPEARED, true); return; } PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NONE); if (!PlayGame.getFlagManager().getFlag(FlagId.FLAG_BODY_FOUND).getState()) { PlayGame.getPlayer().think(Messages.getText("bathroom.uncle.clickhimdammit")); // Big reveal timer Timer.schedule(new Timer.Task() { @Override public void run() { PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NONE); AudioManager.playSound(SoundId.CLICK); setSprite(_roomSprite3); } } , 3.5f // Initial delay , 0 // Fire every X seconds , 1 // Number of times to fire ); // Un-reveal Timer.schedule(new Timer.Task() { @Override public void run() { PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NONE); AudioManager.playSound(SoundId.CLICK); setSprite(_roomSprite1); } } , 5.5f // Initial delay , 0 // Fire every X seconds , 1 // Number of times to fire ); // Re-allow interaction Timer.schedule(new Timer.Task() { @Override public void run() { PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NORMAL); } } , 6.5f // Initial delay , 0 // Fire every X seconds , 1 // Number of times to fire ); PlayGame.getFlagManager().setFlag(FlagId.FLAG_BODY_FOUND, true); PlayGame.getRoomManager().getRoomFromId(RoomId.PARKING_AREA).pushEnterRemark("carpark.enter.snowcovered"); } else { // Re-allow interaction in normal cases Timer.schedule(new Timer.Task() { @Override public void run() { PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NORMAL); } } , 0.4f // Initial delay TODO: Should make global, or shouldn't set this here , 0 // Fire every X seconds , 1 // Number of times to fire ); PlayGame.getFlagManager().setFlag(FlagId.FLAG_BODY_FOUND, true); } } }
true
35dc62bb8602b73df2c951d62d0b119835a346fc
Java
mariadiana0914/HearMe
/app/src/main/java/com/girlesc/enguard/data/source/local/UserLocalDataSource.java
UTF-8
1,269
2.3125
2
[]
no_license
package com.girlesc.enguard.data.source.local; import com.girlesc.enguard.data.source.UserDataSource; import com.girlesc.enguard.utils.AppExecutors; import com.google.firebase.auth.AuthCredential; public class UserLocalDataSource implements UserDataSource { private static volatile UserLocalDataSource INSTANCE; private AppExecutors mAppExecutors; public UserLocalDataSource(AppExecutors mAppExecutors) { this.mAppExecutors = mAppExecutors; } public static UserLocalDataSource getInstance(AppExecutors mAppExecutors) { if (INSTANCE == null) { synchronized (UserLocalDataSource.class) { if(INSTANCE == null) { INSTANCE = new UserLocalDataSource(mAppExecutors); } } } return INSTANCE; } @Override public void logInUser(String email, String password, OnLogInCallback callback) { } @Override public void signUpUser(String email, String password, OnSignUpCallback callback) { } @Override public void sendPasswordRecoveryEmail(String email, OnPasswordRecoveryEmailCallback callback) { } @Override public void linkCredentials(AuthCredential credential, BaseCallback callback) { } }
true
8b9caf6a8c8e91e45f1880fb830ac4642051ac50
Java
Udaydeep/Test-Repository
/String_Functions/src/main/java/com/excel/ReadDataExcel.java
UTF-8
1,038
2.765625
3
[]
no_license
package com.excel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadDataExcel { static int rowCount=0; public static Object[][] ReadDataFromExcel(String FilePath, String SheetName) { Object[][] result=null; Cell firstCellInRow=null; Cell secondCellInRow=null; try { FileInputStream fis=new FileInputStream(FilePath); XSSFWorkbook workbook=new XSSFWorkbook(fis); XSSFSheet sheet=workbook.getSheet(SheetName); Row row=sheet.getRow(1); firstCellInRow=row.getCell(0); secondCellInRow=row.getCell(1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result=new Object[][]{{firstCellInRow.getStringCellValue(),secondCellInRow.getStringCellValue()}}; return result; } }
true
93f5fd8cc62449bd25692283a2b0e5b766f414b6
Java
masud-technope/EMSE-2019-Replication-Package
/Extra-DS/Corpus/class/aspectj/716.java
UTF-8
9,138
1.640625
2
[]
no_license
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.aspectj.ajdt.internal.compiler; import java.util.ArrayList; import java.util.List; import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceLocation; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.SourceLocation; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.org.eclipse.jdt.core.compiler.IProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult; import org.aspectj.org.eclipse.jdt.internal.compiler.Compiler; import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblem; import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemSeverities; /** * @author colyer * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class WeaverMessageHandler implements IMessageHandler { private IMessageHandler sink; private CompilationResult currentlyWeaving; private Compiler compiler; public WeaverMessageHandler(IMessageHandler handler, Compiler compiler) { this.sink = handler; this.compiler = compiler; } public void resetCompiler(Compiler c) { this.compiler = c; currentlyWeaving = null; } public void setCurrentResult(CompilationResult result) { currentlyWeaving = result; } public boolean handleMessage(IMessage message) throws AbortException { if (!(message.isError() || message.isWarning())) return sink.handleMessage(message); // we only care about warnings and errors here... ISourceLocation sLoc = message.getSourceLocation(); // case (By calling sink.handleMessage()) - this ensures we don't put out bogus source context info. if (sLoc instanceof EclipseSourceLocation) { EclipseSourceLocation esLoc = (EclipseSourceLocation) sLoc; if (currentlyWeaving != null && esLoc.getCompilationResult() != null) { if (!currentlyWeaving.equals(((EclipseSourceLocation) sLoc).getCompilationResult())) return sink.handleMessage(message); // throw new RuntimeException("Primary source location must match the file we are currently processing!"); } } // we're not an EclipseSourceLocation we're a SourceLocation. if (sLoc instanceof SourceLocation) { SourceLocation sl = (SourceLocation) sLoc; if (currentlyWeaving != null && sl.getSourceFile() != null) { if (!String.valueOf(currentlyWeaving.getFileName()).equals(sl.getSourceFile().getAbsolutePath())) { return sink.handleMessage(message); //throw new RuntimeException("Primary source location must match the file we are currently processing!"); } } } CompilationResult problemSource = currentlyWeaving; if (problemSource == null) { // must be a problem found during completeTypeBindings phase of begin to compile if (sLoc instanceof EclipseSourceLocation) { problemSource = ((EclipseSourceLocation) sLoc).getCompilationResult(); } if (problemSource == null) { // XXX this is ok for ajc, will have to do better for AJDT in time... return sink.handleMessage(message); } } int startPos = getStartPos(sLoc, problemSource); int endPos = getEndPos(sLoc, problemSource); int severity = message.isError() ? ProblemSeverities.Error : ProblemSeverities.Warning; char[] filename = problemSource.fileName; boolean usedBinarySourceFileName = false; if (problemSource.isFromBinarySource()) { if (sLoc != null) { filename = sLoc.getSourceFile().getPath().toCharArray(); usedBinarySourceFileName = true; } } ReferenceContext referenceContext = findReferenceContextFor(problemSource); IProblem problem = compiler.problemReporter.createProblem(filename, IProblem.Unclassified, new String[0], new String[] { message.getMessage() }, severity, startPos, endPos, sLoc != null ? sLoc.getLine() : 0); IProblem[] seeAlso = buildSeeAlsoProblems(problem, message.getExtraSourceLocations(), problemSource, usedBinarySourceFileName); problem.setSeeAlsoProblems(seeAlso); StringBuffer details = new StringBuffer(); // Stick more info in supplementary message info if (message.getDetails() != null) { details.append(message.getDetails()); } // Remember if this message was due to a deow if (message.getDeclared()) { details.append("[deow=true]"); } if (details.length() != 0) { problem.setSupplementaryMessageInfo(details.toString()); } compiler.problemReporter.record(problem, problemSource, referenceContext); return true; } public boolean isIgnoring(Kind kind) { return sink.isIgnoring(kind); } /** * No-op * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind) * @param kind */ public void dontIgnore(IMessage.Kind kind) { ; } private int getStartPos(ISourceLocation sLoc, CompilationResult result) { int pos = 0; if (sLoc == null) return 0; int line = sLoc.getLine(); if (sLoc instanceof EclipseSourceLocation) { pos = ((EclipseSourceLocation) sLoc).getStartPos(); } else { if (line <= 1) return 0; if (result != null) { if ((result.lineSeparatorPositions != null) && (result.lineSeparatorPositions.length >= (line - 1))) { pos = result.lineSeparatorPositions[line - 2] + 1; } } } return pos; } private int getEndPos(ISourceLocation sLoc, CompilationResult result) { int pos = 0; if (sLoc == null) return 0; int line = sLoc.getLine(); if (line <= 0) line = 1; if (sLoc instanceof EclipseSourceLocation) { pos = ((EclipseSourceLocation) sLoc).getEndPos(); } else { if (result != null) { if ((result.lineSeparatorPositions != null) && (result.lineSeparatorPositions.length >= line)) { pos = result.lineSeparatorPositions[line - 1] - 1; } } } return pos; } private ReferenceContext findReferenceContextFor(CompilationResult result) { ReferenceContext context = null; if (compiler.unitsToProcess == null) return null; for (int i = 0; i < compiler.unitsToProcess.length; i++) { if ((compiler.unitsToProcess[i] != null) && (compiler.unitsToProcess[i].compilationResult == result)) { context = compiler.unitsToProcess[i]; break; } } return context; } private IProblem[] buildSeeAlsoProblems(IProblem originalProblem, List sourceLocations, CompilationResult problemSource, boolean usedBinarySourceFileName) { List ret = new ArrayList(); for (int i = 0; i < sourceLocations.size(); i++) { ISourceLocation loc = (ISourceLocation) sourceLocations.get(i); if (loc != null) { DefaultProblem dp = new DefaultProblem(loc.getSourceFile().getPath().toCharArray(), "see also", 0, new String[] {}, ProblemSeverities.Ignore, getStartPos(loc, null), getEndPos(loc, null), loc.getLine()); ret.add(dp); } else { System.err.println("About to abort due to null location, dumping state:"); System.err.println("> Original Problem=" + problemSource.toString()); throw new RuntimeException("Internal Compiler Error: Unexpected null source location passed as 'see also' location."); } } if (usedBinarySourceFileName) { DefaultProblem dp = new DefaultProblem(problemSource.fileName, "see also", 0, new String[] {}, ProblemSeverities.Ignore, 0, 0, 0); ret.add(dp); } IProblem[] retValue = (IProblem[]) ret.toArray(new IProblem[] {}); return retValue; } }
true
398f1a42f38042c9a7d971c63d9d2fa7705e2a05
Java
Arnaud-PIGNEROL/Hadoop-MapReduce
/hadoop-examples-mapreduce/src/main/java/com/opstty/job/SumTrees.java
UTF-8
2,614
2.421875
2
[]
no_license
package com.opstty.job; import com.opstty.mapper.SumTreesMapper1; import com.opstty.reducer.SumTreesReducer1; import com.opstty.mapper.SumTreesMapper2; import com.opstty.reducer.SumTreesReducer2; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; public class SumTrees { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); Path path = new Path("out/"); if(otherArgs.length < 2) { System.err.println("Usage: sum <in> [<in>...] <out>"); System.exit(2); } // 1st job : count how many trees each district contains Job job1 = Job.getInstance(conf, "sum"); job1.setJarByClass(SumTrees.class); job1.setMapperClass(SumTreesMapper1.class); job1.setReducerClass(SumTreesReducer1.class); job1.setMapOutputKeyClass(IntWritable.class); job1.setMapOutputValueClass(IntWritable.class); job1.setOutputKeyClass(IntWritable.class); job1.setOutputValueClass(IntWritable.class); for (int i = 0; i < otherArgs.length - 1; ++i) { FileInputFormat.addInputPath(job1, new Path(otherArgs[i])); } FileOutputFormat.setOutputPath(job1, path); job1.waitForCompletion(true); // 2nd job : find the maximum number of trees Configuration conf2 = new Configuration(); Job job2 = Job.getInstance(conf2); job2.setJarByClass(SumTrees.class); job2.setMapperClass(SumTreesMapper2.class); job2.setReducerClass(SumTreesReducer2.class); job2.setMapOutputKeyClass(IntWritable.class); job2.setMapOutputValueClass(PairSumTrees.class); job2.setOutputKeyClass(IntWritable.class); job2.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job2, path); FileOutputFormat.setOutputPath(job2, new Path(otherArgs[otherArgs.length - 1])); System.exit(job2.waitForCompletion(true) ? 0 : 1); } }
true
1ace183720225a9148d2dae6d0b76731012b07c5
Java
ribeirowill/Teste
/src/main/java/com/pc/cofipa/session/TabelaItensSaida.java
UTF-8
2,370
2.625
3
[]
no_license
package com.pc.cofipa.session; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.IntStream; import com.pc.cofipa.model.Produto; import com.pc.cofipa.model.ItemSaida; class TabelaItensSaida { private String uuid; private List<ItemSaida> itens = new ArrayList<>(); public TabelaItensSaida(String uuid) { this.uuid = uuid; } public BigDecimal getValorTotal() { return itens.stream() .map(ItemSaida::getValorTotal) .reduce(BigDecimal::add) .orElse(BigDecimal.ZERO); } public void adicionarItem(Produto produto, Integer quantidade) { Optional<ItemSaida> itemSaidaOptional = buscarItemPorProduto(produto); ItemSaida itemSaida = null; if(itemSaidaOptional.isPresent()) { itemSaida = itemSaidaOptional.get(); itemSaida.setQuantidade(itemSaida.getQuantidade() + quantidade); }else { itemSaida = new ItemSaida(); itemSaida.setProduto(produto); itemSaida.setQuantidade(quantidade); itemSaida.setValorUnitario(produto.getValorUnitario()); itens.add(0, itemSaida); } } public void alterarQuantidadeItens(Produto produto, Integer quantidade){ ItemSaida itemSaida = buscarItemPorProduto(produto).get(); itemSaida.setQuantidade(quantidade); } public void excluirItem(Produto produto) { int indice = IntStream.range(0, itens.size()) .filter(i -> itens.get(i).getProduto().equals(produto)) .findAny().getAsInt(); itens.remove(indice); } public int total(){ return itens.size(); } public List<ItemSaida> getItens() { return itens; } private Optional<ItemSaida> buscarItemPorProduto(Produto produto) { return itens.stream() .filter(i -> i.getProduto().equals(produto)) .findAny(); } public String getUuid() { return uuid; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TabelaItensSaida other = (TabelaItensSaida) obj; if (uuid == null) { if (other.uuid != null) return false; } else if (!uuid.equals(other.uuid)) return false; return true; } }
true
2f9276996d7036065553cdc97765b9b197a3e3a7
Java
emrekirman/kiemTracking
/src/main/java/com/tasinirdepo/dao/jpa/IslemCesidiRepositoryImpl.java
UTF-8
1,189
2.25
2
[]
no_license
package com.tasinirdepo.dao.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import com.tasinirdepo.dao.IIslemCesidiRepository; import com.tasinirdepo.model.IslemCesidi; @Repository("islemCesidiRepository") @Qualifier("islemCesidiRepository") public class IslemCesidiRepositoryImpl implements IIslemCesidiRepository{ @PersistenceContext private EntityManager manager; @Override public List<IslemCesidi> findAll() { return manager.createQuery("from IslemCesidi",IslemCesidi.class).getResultList(); } @Override public int create(IslemCesidi model) { try { manager.persist(model); return 1; } catch (Exception e) { throw e; } } @Override public IslemCesidi update(IslemCesidi model) { try { return manager.merge(model); } catch (Exception e) { throw e; } } @Override public void delete(int id) { manager.remove(manager.getReference(IslemCesidi.class, id)); } @Override public IslemCesidi getById(int id) { return manager.find(IslemCesidi.class, id); } }
true
206c9bca37817a56911b9d4673b54a144ea67636
Java
TaliosFactoryTech/QA-Testing-Automatization
/src/test/java/com/ea/SpringBasic/pages/GuideSelfOnboardingPages/Step11Page.java
UTF-8
1,460
2.09375
2
[]
no_license
package com.ea.SpringBasic.pages.GuideSelfOnboardingPages; import com.ea.SpringBasic.models.GuideDetails; import com.ea.SpringBasic.pages.BasePage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class Step11Page extends BasePage { @Autowired WebDriver driver; @Value("${Step11TypeAFriendlyText}") private String typeAFriendlyMessageText; @Value("${Step11TextArea}") private String introTextArea; @Value("${Step11iLikeItButton}") private String iLikeItButton; @Value("${SelfOnboardingNextButton}") private String nextButton; public boolean validateNavigation() { return driver.findElement(By.xpath(typeAFriendlyMessageText)).isDisplayed(); } public void enterIntroMessage(GuideDetails guideDetails){ driver.findElement(By.xpath(introTextArea)).sendKeys(guideDetails.getGuide().getIntroText()); } public void clickILikeIt(){ driver.findElement(By.xpath(iLikeItButton)).click(); } public void clickNext() { driver.findElement(By.xpath(nextButton)).click(); } }
true
1316a03b2d24163bc8dacca1e6d5026b82ea76b1
Java
Eant99/effective-octo-eureka
/CWYTH/src/com/googosoft/controller/base/ProvincesController.java
UTF-8
1,053
1.867188
2
[]
no_license
package com.googosoft.controller.base; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import com.googosoft.service.base.ProvincesService; import com.googosoft.util.PageData; @Controller @RequestMapping("/provinces") public class ProvincesController extends BaseController{ @Resource(name="provincesService") private ProvincesService provincesService;//单例 /** * */ @RequestMapping("/getProvicesList") @ResponseBody public String getProvicesList(){ List list = provincesService.getProvicesList(); return new Gson().toJson(list); } @RequestMapping("/getCitiesByProvince") @ResponseBody public String getCitiesByProvince(){ PageData pd = this.getPageData(); String provinceid = pd.getString("provinceid"); List list = provincesService.getCitiesByProvince(provinceid); return new Gson().toJson(list); } }
true
504676012d404e7b2295c9882f296bacc27d10cd
Java
pynacl/amazon-mock
/app/src/main/java/com/pynacl/amazonmock/MainActivity.java
UTF-8
1,427
2.21875
2
[]
no_license
package com.pynacl.amazonmock; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import com.pynacl.amazonmock.databinding.ActivityMainBinding; import com.pynacl.amazonmock.models.Product; public class MainActivity extends AppCompatActivity implements IMainActivity { // data binding ActivityMainBinding mBinding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); init(); } private void init() { MainFragment fragment = new MainFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.main_container, fragment, "Main"); transaction.commit(); } @Override public void inflateViewProductFragment(Product product) { ViewProductFragment fragment = new ViewProductFragment(); Bundle bundle = new Bundle(); bundle.putParcelable(getString(R.string.intent_product), product); fragment.setArguments(bundle); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.main_container, fragment, getString(R.string.fragment_view_product)); transaction.addToBackStack(getString(R.string.fragment_view_product)); transaction.commit(); } }
true
635df09b019414addad73bba0eabd4728bdd4eea
Java
JetBrains/intellij-community
/java/java-tests/testData/refactoring/methodDuplicates/ReturnField.java
UTF-8
614
2.828125
3
[ "Apache-2.0" ]
permissive
class Return { private Return myReturn; private int myInt; public Return <caret>method() { myReturn = new Return(); myReturn.myInt++; return myReturn; } public void contextLValue() { myReturn = new Return(); myReturn.myInt++; myReturn = null; } public void contextNoUsage() { myReturn = new Return(); myReturn.myInt++; } public void contextRValue() { myReturn = new Return(); myReturn.myInt++; Return r = myReturn; } public void contextRValueQualified() { myReturn = new Return(); myReturn.myInt++; Return r = this.myReturn; } }
true
81326561d2bcad17e39198510532f22b3e8922c2
Java
Camibaza/turma37gen
/java/ECOMMERCE/src/entities/Carrinho.java
ISO-8859-2
2,922
3.359375
3
[]
no_license
package entities; import java.util.ArrayList; import java.util.List; public class Carrinho { List<Carrinho> carrinho = new ArrayList<>(); //ATRIBUTOS private String Produto; private String codigo; private double valor; private int quantidade; private double valorTotal; int atualizaQuantidade; public double getValorTotal() { return valorTotal; } public void setValorTotal(double valorTotal) { this.valorTotal = valorTotal; } //CONSTRUTORES public Carrinho() { super(); } public Carrinho(String produto, String codigo, double valor, int quantidade) { super(); Produto = produto; this.codigo = codigo; this.valor = valor; this.quantidade = quantidade; } //ENCAPSULAMENTO public String getProduto() { return Produto; } public void setProduto(String produto) { Produto = produto; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public int getQuantidade() { return quantidade; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } public Boolean verificaCarrinho(String codigo, int quantidade) { for (Carrinho x : carrinho) { if(x.getCodigo().equals(codigo)) { atualizaQuantidade =+ x.getQuantidade() + quantidade; x.setQuantidade(atualizaQuantidade); setValorTotal(atualizaQuantidade * x.getValor()); atualizaQuantidade = 0; return true; } } return false; } public void entraCarrinho(String produto, String codigo, double valor, int quantidade) { if (quantidade == 0) { System.out.println("QUANTIDADE INVLIDA"); }else { carrinho.add(new Carrinho(produto, codigo, valor, quantidade)); if(atualizaQuantidade != 0) { double valorTotalCompra =+ getValorTotal() + (valor * atualizaQuantidade); setValorTotal(valorTotalCompra); } else { double valorTotalCompra =+ getValorTotal() + (valor * quantidade); setValorTotal(valorTotalCompra); } } } public void mostraCarrinho() { System.out.println(); System.out.println(" *** CARRINHO *** "); System.out.println(); if (carrinho.isEmpty()) { System.out.println("O CARRINHO EST VAZIO"); } else { for (Carrinho x: carrinho) { System.out.printf("" + x.getQuantidade() + " x " + x.getProduto() + "\t Valor Unitario: " + x.getValor() + "\t Valor Total: " + (x.getQuantidade() * x.getValor()) + "\n"); } } } public void mostraCarrinhoNF() { System.out.println(); for (Carrinho x: carrinho) { System.out.printf("%d x %s - %2.f\n", x.getQuantidade(),x.getProduto(),x.getValor()); } } public void limparCarrinho() { carrinho.clear(); } }
true
f22e3cf63722f60332f3c433c653ce54fceb6145
Java
dudebf7/ADS2N14_1B
/Pessoa/Pessoa/src/com/senac/mvc/view/Visao.java
UTF-8
278
1.898438
2
[]
no_license
package com.senac.mvc.view; import com.senac.mvc.controller.Controlador; public class Visao{ public static void main(String[] args) { Controlador controlador=new Controlador(); controlador.obtemAgenda(); controlador.toString(); System.out.println(controlador); } }
true
6f55de6e9918251359ae788fd4b65f311acb29b6
Java
bafomdad/zenscape
/com/bafomdad/zenscape/util/Rainbow.java
UTF-8
1,781
2.78125
3
[]
no_license
package com.bafomdad.zenscape.util; import net.minecraft.util.MathHelper; public class Rainbow { public static float r(float phase) { phase = (float) (phase * 6.283185307179586D); float r = (MathHelper.sin(phase + 0.0F) + 1.0F) * 0.5F; float g = (MathHelper.sin(phase + 2.094395F) + 1.0F) * 0.5F; float b = (MathHelper.sin(phase + 4.18879F) + 1.0F) * 0.5F; float resat = Math.min(r, Math.min(g, b)); r -= resat; g -= resat; b -= resat; float scaler = 1.0F / Math.max(r, Math.max(g, b)); r = Math.min(scaler * r, 1.0F); g = Math.min(scaler * g, 1.0F); b = Math.min(scaler * b, 1.0F); return r; } public static float g(float phase) { phase = (float) (phase * 6.283185307179586D); float r = (MathHelper.sin(phase + 0.0F) + 1.0F) * 0.5F; float g = (MathHelper.sin(phase + 2.094395F) + 1.0F) * 0.5F; float b = (MathHelper.sin(phase + 4.18879F) + 1.0F) * 0.5F; float resat = Math.min(r, Math.min(g, b)); r -= resat; g -= resat; b -= resat; float scaler = 1.0F / Math.max(r, Math.max(g, b)); r = Math.min(scaler * r * 0.5F + 0.5F, 1.0F); g = Math.min(scaler * g * 0.5F + 0.5F, 1.0F); b = Math.min(scaler * b * 0.5F + 0.5F, 1.0F); return g; } public static float b(float phase) { phase = (float) (phase * 6.283185307179586D); float r = (MathHelper.sin(phase + 0.0F) + 1.0F) * 0.5F; float g = (MathHelper.sin(phase + 2.094395F) + 1.0F) * 0.5F; float b = (MathHelper.sin(phase + 4.18879F) + 1.0F) * 0.5F; float resat = Math.min(r, Math.min(g, b)); r -= resat; g -= resat; b -= resat; float scaler = 1.0F / Math.max(r, Math.max(g, b)); r = Math.min(scaler * r * 0.5F + 0.5F, 1.0F); g = Math.min(scaler * g * 0.5F + 0.5F, 1.0F); b = Math.min(scaler * b * 0.5F + 0.5F, 1.0F); return b; } }
true
e51c4aaef101d610eb5f063bf9871682bae3738a
Java
wilfredkim/BankingSolution
/src/main/Java/Pojo/Account.java
UTF-8
808
2.453125
2
[]
no_license
package Pojo; public class Account { private String customerId; private String accNumber; AccountType accountType; double balance; public String getAccNumber() { return accNumber; } public void setAccNumber(String accNumber) { this.accNumber = accNumber; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public AccountType getAccountType() { return accountType; } public void setAccountType(AccountType accountType) { this.accountType = accountType; } }
true
a2203d23a049ed6dd96bc407602ba57c9f1eb14f
Java
BugBang/EShop
/app/src/main/java/com/edianjucai/eshop/model/impl/ResetPasswordModelmpl1.java
UTF-8
2,455
2.09375
2
[]
no_license
package com.edianjucai.eshop.model.impl; import com.alibaba.fastjson.JSON; import com.edianjucai.eshop.model.entity.BaseActModel; import com.edianjucai.eshop.model.entity.RequestModel; import com.edianjucai.eshop.model.mode.ResetPasswordMode1; import com.edianjucai.eshop.presenter.usb.OnResetPasswordListener1; import com.edianjucai.eshop.server.InterfaceServer; import com.edianjucai.eshop.util.ModelUtil; import com.ta.sunday.http.impl.SDAsyncHttpResponseHandler; import org.apache.http.Header; import java.util.HashMap; import java.util.Map; /** * Created by user on 2016-09-20. */ public class ResetPasswordModelmpl1 implements ResetPasswordMode1 { @Override public void requestResePasswordCode(String userPhone, final OnResetPasswordListener1 onResetPasswordListener1) { Map<String, Object> mapData = new HashMap<String, Object>(); mapData.put("act", "send_reset_pwd_code"); mapData.put("mobile", userPhone); RequestModel model = new RequestModel(mapData); SDAsyncHttpResponseHandler handler = new SDAsyncHttpResponseHandler() { @Override public Object onSuccessInRequestThread(int statusCode, Header[] headers, String content) { try { BaseActModel actModel = JSON.parseObject(content, BaseActModel.class); return actModel; } catch (Exception e) { return null; } } @Override public void onStartInMainThread(Object result) { onResetPasswordListener1.startResetPassword(); } @Override public void onFinishInMainThread(Object result) { onResetPasswordListener1.finishResetPassword(); } @Override public void onSuccessInMainThread(int statusCode, Header[] headers, String content, Object result) { BaseActModel actModel = (BaseActModel) result; if (!ModelUtil.isActModelNull(actModel)) { if (actModel.getResponse_code() == 1) { onResetPasswordListener1.successResetPassword(); }else { onResetPasswordListener1.failResetPassword(actModel.getShow_err()); } } } }; InterfaceServer.getInstance().requestInterface(model, handler, true); } }
true
20fcb32e20fee10d37672234c6ec97e3011e86a0
Java
mindstorms6/OAConstants
/src/main/java/org/bdawg/open_audio/interfaces/IPlayable.java
UTF-8
1,304
2.625
3
[]
no_license
package org.bdawg.open_audio.interfaces; import java.io.File; import java.util.List; import java.util.Map; public interface IPlayable { /** * Used to get the next {@code}ISinglePlayable that {@code}SlaveManager will start playing. * Ideally, the slaves will have already downloaded this file. * @return The next SinglePlayable in the playlist */ public ISinglePlayable getNextSinglePlayable(); /** * The master that is responsible for this {@code}IPlayable. * @return The masterId for this Playable */ public String getMasterClientId(); /** * The ID of this playable. * @return The id of this playable */ public String getId(); /** * Used to find out if the master needs to download and distribute the file, or is a slave can do so on it's own. * We use things for things like pandora, 8tracks, etc where we need only fetch once and distribute on our own. * @return boolean indicating if it's safe to let all slaves download on their own, or if we should only download from source once. */ public boolean needsDistribute(); /** * Returns a list of the client IDs we care about for this playable. * @return List<String> clients */ public List<String> getClients(); public String getDownloadType(); public Map<String,String> getMeta(); }
true
a8b3cfa03cfa627c984afe2b8081a49748a843a2
Java
LeeDane/app
/app/src/main/java/com/leedane/cn/handler/SearchHandler.java
UTF-8
3,155
2.328125
2
[]
no_license
package com.leedane.cn.handler; import com.leedane.cn.application.BaseApplication; import com.leedane.cn.bean.HttpRequestBean; import com.leedane.cn.task.TaskListener; import com.leedane.cn.task.TaskLoader; import com.leedane.cn.task.TaskType; import com.leedane.cn.util.ConstantsUtil; import java.util.HashMap; import java.util.Map; /** * 搜索相关的处理 * Created by LeeDane on 2016/5/22. */ public class SearchHandler { /** * 获取搜索用户列表 * @param listener * @param key */ public static void getSearchUserRequest(TaskListener listener, String key){ HttpRequestBean requestBean = new HttpRequestBean(); Map<String, Object> params = new HashMap<>(); params.put("keyword", key); params.put("platformApp", true); //标记是app平台 params.put("type", ConstantsUtil.SEARCH_TYPE_USER);//type=3表示只搜索用户 params.putAll(BaseApplication.newInstance().getBaseRequestParams()); requestBean.setParams(params); requestBean.setRequestTimeOut(60000); requestBean.setResponseTimeOut(60000); requestBean.setServerMethod("s/s"); requestBean.setRequestMethod(ConstantsUtil.REQUEST_METHOD_GET); TaskLoader.getInstance().startTaskForResult(TaskType.LOAD_SEARCH_USER, listener, requestBean); } /** * 获取搜索博客列表 * @param listener * @param key */ public static void getSearchBlogRequest(TaskListener listener, String key){ HttpRequestBean requestBean = new HttpRequestBean(); Map<String, Object> params = new HashMap<>(); params.put("keyword", key); params.put("platformApp", true); //标记是app平台 params.put("type", ConstantsUtil.SEARCH_TYPE_BLOG);//type=1表示只搜索博客 params.putAll(BaseApplication.newInstance().getBaseRequestParams()); requestBean.setParams(params); requestBean.setRequestTimeOut(60000); requestBean.setResponseTimeOut(60000); requestBean.setServerMethod("s/s"); requestBean.setRequestMethod(ConstantsUtil.REQUEST_METHOD_GET); TaskLoader.getInstance().startTaskForResult(TaskType.LOAD_SEARCH_BLOG, listener, requestBean); } /** * 获取搜索心情列表 * @param listener * @param key */ public static void getSearchMoodRequest(TaskListener listener, String key){ HttpRequestBean requestBean = new HttpRequestBean(); Map<String, Object> params = new HashMap<>(); params.put("keyword", key); params.put("platformApp", true); //标记是app平台 params.put("type", ConstantsUtil.SEARCH_TYPE_MOOD);//type=2表示只搜索心情 params.putAll(BaseApplication.newInstance().getBaseRequestParams()); requestBean.setParams(params); requestBean.setRequestTimeOut(60000); requestBean.setResponseTimeOut(60000); requestBean.setServerMethod("s/s"); requestBean.setRequestMethod(ConstantsUtil.REQUEST_METHOD_GET); TaskLoader.getInstance().startTaskForResult(TaskType.LOAD_SEARCH_MOOD, listener, requestBean); } }
true
56fae4a46f32434dd930f584e3ecf423c85c4c6d
Java
sorianom/groupGo
/userClient/Vegos/src/com/ideanest/vegos/game/SemiPrimitiveGame.java
UTF-8
1,654
3.375
3
[]
no_license
package com.ideanest.vegos.game; import com.ideanest.vegos.gtp.*; /** * Doesn't allow playing in eyes or passing. Game is over when there are no more legal moves. * @author Piotr Kaminski */ public class SemiPrimitiveGame extends TrompTaylorGame { private boolean gameOver; public SemiPrimitiveGame(int sideSize) { super(sideSize, true); } public void recordMove(int z) { super.recordMove(z); calculateGameOver(); } public boolean isOver() { return gameOver; } protected void calculateGameOver() { gameOver = true; for (int z=0; gameOver && z<getNumPoints(); z++) { if (getPoint(z) != Point.EMPTY) continue; Board backupBoard = board.duplicate(); board.setPoint(z, nextToPlay); gameOver = !validateBoard(z, backupBoard); board = backupBoard; } } protected boolean validateBoard(int z, Board oldBoard) { // check if z is playing into what looks like an eye // (eye: neighbours same color, no more than 1 diagonal other color, except at edges) CHECK_EYE: { temp1.clear(); temp1.addNeighbors(z); for (int i=0; i<temp1.size(); i++) if (getPoint(temp1.get(i)) != nextToPlay) break CHECK_EYE; temp1.clear(); temp1.addDiagonalNeighbors(z); Color other = nextToPlay.inverse(); int numOther = 0; for (int i=0; i<temp1.size(); i++) if (getPoint(temp1.get(i)) == other) numOther++; if (numOther == 0 || numOther == 1 && temp1.size() == 4) return false; } return super.validateBoard(z, oldBoard); } public String getName() { return "Semi-Primitive"; } public boolean isPassingAllowed() { return false; } }
true
a6398869b91b4d21d4bb35674d1e05b5f21c461c
Java
krishnakc239/Blogging-Application
/src/main/java/com/edu/mum/controller/SearchController.java
UTF-8
2,624
2.015625
2
[]
no_license
package com.edu.mum.controller; import com.edu.mum.domain.Comment; import com.edu.mum.domain.Post; import com.edu.mum.domain.User; import com.edu.mum.service.PostService; import com.edu.mum.service.UserService; import com.edu.mum.util.ArithmeticUtils; import com.edu.mum.util.Pager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller public class SearchController { @Autowired private PostService postService; @Autowired private UserService userService; @GetMapping("/fullSearch") public String fullSearch(@RequestParam(defaultValue = "0") int page, @RequestParam("searchParameter") String searchParameter, Model model){ List<Post> latest5Posts = this.postService.findLatest5(); model.addAttribute("latest5Posts", latest5Posts); Page<Post> posts = postService.findAllByTitleContainingIgnoreCaseOrUser_FirstNameContainingIgnoreCase(searchParameter,searchParameter,page); Pager pager = new Pager(posts); model.addAttribute("avgRatingMap", ArithmeticUtils.getAvgRatingMap(postService.findAll())); model.addAttribute("pager", pager); model.addAttribute("comment", new Comment()); return "views/home/index"; } @GetMapping("/searchPost") public String searchPost(@RequestParam(defaultValue = "0") int page, @RequestParam("searchParameter") String searchParameter, Model model){ Page<Post> posts = postService.findAllByTitleContainingIgnoreCaseOrUser_FirstNameContainingIgnoreCase(searchParameter,searchParameter,page); Pager pager = new Pager(posts); model.addAttribute("pager", pager); model.addAttribute("avgRatingMap", ArithmeticUtils.getAvgRatingMap(postService.findAll())); return "views/posts/postList"; } @GetMapping("/searchUser") public String searchUser(@RequestParam(defaultValue = "0") int page, @RequestParam("searchParameter") String searchParameter, Model model){ Page<User> users = userService.findAllByFirstNameContainingIgnoreCaseOrUsernameContainingIgnoreCaseOrEmail(searchParameter,searchParameter,searchParameter,page); Pager pager = new Pager(users); model.addAttribute("pager", pager); return "views/users/userList"; } }
true
58ada32f1c30da9b154c806729d852e69e8166b1
Java
heshanjse/Lineme
/LIne/src/extrogene/gamedev/linegame/view/Main.java
UTF-8
3,957
1.890625
2
[]
no_license
package extrogene.gamedev.linegame.view; import com.example.line.R; import com.example.line.R.id; import com.example.line.R.layout; import com.example.line.R.menu; import extrogene.gamedev.linegame.view.level.levels; import extrogene.gamedev.linegame.view.multiplayer.listclass; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // this.requestWindowFeature(Window.FEATURE_NO_TITLE); //Remove notification bar // this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //set content view AFTER ABOVE sequence (to avoid crash) // this.setContentView(R.layout.main); final Button Singal=(Button)findViewById(R.id.singalplayer); final Button multy=(Button)findViewById(R.id.multiplayer); final Button setting=(Button)findViewById(R.id.setting); final Button about=(Button)findViewById(R.id.about); final Button help=(Button)findViewById(R.id.help); final Button frofile=(Button)findViewById(R.id.profile); Singal.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), levels.class); startActivityForResult(myIntent, 0); } }); multy.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(getBaseContext(), listclass.class); startActivityForResult(myIntent, 0); } }); about.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), about.class); startActivityForResult(myIntent, 0); } }); Animation b1=AnimationUtils.loadAnimation(Main.this, R.anim.animation); Animation b2=AnimationUtils.loadAnimation(Main.this, R.anim.animation2); Animation b3=AnimationUtils.loadAnimation(Main.this, R.anim.animation3); Animation b4=AnimationUtils.loadAnimation(Main.this, R.anim.animation4); final Animation bound=AnimationUtils.loadAnimation(Main.this, R.anim.bouns); final Animation b22=AnimationUtils.loadAnimation(Main.this, R.anim.bnn); Singal.startAnimation(b1); multy.startAnimation(b1); setting.startAnimation(b4); about.startAnimation(b1); frofile.startAnimation(b4); help.startAnimation(b1); help.setOnClickListener(new OnClickListener(){ public void onClick(View arg0){ Singal.startAnimation(bound); about.startAnimation(b22); } }); about.setOnClickListener(new OnClickListener(){ public void onClick(View arg1){ about.startAnimation(bound); Singal.startAnimation(b22); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
d74bdff5fad313a535e851c0a2f0d671b817fa2f
Java
slideclick/Functional-Programming-Patterns-in-Scala-and-Clojure
/JavaExamples/src/main/java/com/mblinn/oo/tinyweb/StrategyView.java
UTF-8
860
2.390625
2
[]
no_license
/*** * Excerpted from "Functional Programming Patterns", * published by The Pragmatic Bookshelf. * Copyrights apply to this code. It may not be used to create training material, * courses, books, articles, and the like. Contact us if you are in doubt. * We make no guarantees that this code is fit for any purpose. * Visit http://www.pragmaticprogrammer.com/titles/mbfpp for more book information. ***/ package com.mblinn.oo.tinyweb; import java.util.List; import java.util.Map; public class StrategyView implements View { private RenderingStrategy viewRenderer; public StrategyView(RenderingStrategy viewRenderer) { this.viewRenderer = viewRenderer; } @Override public String render(Map<String, List<String>> model) { try { return viewRenderer.renderView(model); } catch (Exception e) { throw new RenderingException(e); } } }
true
2bf3b3a60f16184f4a524c10cd47900f194e0edb
Java
Pastew/ingameads-server
/ingameads-ui/src/main/java/com/pastew/ingameadsui/Image/ImageService.java
UTF-8
10,187
1.914063
2
[]
no_license
package com.pastew.ingameadsui.Image; import com.cloudinary.Cloudinary; import com.cloudinary.utils.ObjectUtils; import com.pastew.ingameadsui.Advert.*; import com.pastew.ingameadsui.Game.Game; import com.pastew.ingameadsui.Game.GameRepository; import com.pastew.ingameadsui.User.User; import com.pastew.ingameadsui.User.UserRepository; import com.pastew.ingameadsui.User.UserService; import com.pastew.ingameadsui.dev.Dev; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.core.io.ResourceLoader; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.query.Param; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; @Service @Slf4j public class ImageService { private final ImageRepository imageRepository; private final ResourceLoader resourceLoader; private final UserRepository userRepository; private final GameRepository gameRepository; private final UserService userService; private final PasswordEncoder passwordEncoder; private Cloudinary cloudinary = new Cloudinary(ObjectUtils.asMap( "cloud_name", "ingameads", "api_key", "726636437293547", "api_secret", "cGwYcd8ef5b3xN08im8JmM_I75o", "proxy", "http://10.158.100.2:8080")); public ImageService(ImageRepository imageRepository, ResourceLoader resourceLoader, UserRepository userRepository, GameRepository gameRepository, UserService userService, PasswordEncoder passwordEncoder) { this.imageRepository = imageRepository; this.resourceLoader = resourceLoader; this.userRepository = userRepository; this.gameRepository = gameRepository; this.userService = userService; this.passwordEncoder = passwordEncoder; } public Page<Image> findPage(Pageable pageable) { return imageRepository.findAll(pageable); } public Image createImage(MultipartFile file) throws IOException { if ("".equals(file.getOriginalFilename())) throw new IOException("Filename is empty"); if (file.isEmpty()) throw new IOException("File is empty"); Map uploadResult = cloudinary.uploader().upload(file.getBytes(), ObjectUtils.emptyMap()); String url = (String) uploadResult.get("url"); User currentUser = userService.getLoggedUser(); Image image = new Image(currentUser, url); return imageRepository.save(image); } @PreAuthorize("hasRole('ADMIN')") public void deleteImage(@Param("filename") String url) throws IOException { final Image image = imageRepository.findByUrl(url); Game game = gameRepository.findByImages(image); game.getImages().remove(image); gameRepository.save(game); imageRepository.delete(image); } public List<Image> getCurrentUserImages() { User owner = userService.getLoggedUser(); return imageRepository.findByOwner(owner); } @Bean //@Profile("dev") CommandLineRunner setUp(ImageRepository imagerepository, UserRepository userRepository, GameRepository gameRepository, AdvertOfferRepository advertOfferRepository, AdvertOfferService advertOfferService) throws IOException { return args -> { User greg = userRepository.save(new User(Dev.GREG, passwordEncoder.encode(Dev.userPassword), "greg@qwe.com", "ROLE_USER")); User bob = userRepository.save(new User(Dev.BOB, passwordEncoder.encode(Dev.userPassword), "bob@qwe.com", "ROLE_USER")); Image[] images = { new Image(bob, "http://www.res.cloudinary.com/ingameads/image/upload/v1526309281/watch_dogs_2.png"), new Image(bob, "http://www.res.cloudinary.com/ingameads/image/upload/v1526309280/watch_dogs.png"), new Image(bob, "http://www.res.cloudinary.com/ingameads/image/upload/v1526309281/sonic.jpg"), new Image(greg, "http://www.res.cloudinary.com/ingameads/image/upload/v1526309278/spiderman.jpg"), new Image(greg, "http://res.cloudinary.com/ingameads/image/upload/v1526325835/gta5_0.jpg"), new Image(greg, "http://www.res.cloudinary.com/ingameads/image/upload/v1526309280/gta.jpg"), new Image(greg, "http://res.cloudinary.com/ingameads/image/upload/v1526325836/gta5_2.png"), new Image(greg, "http://res.cloudinary.com/ingameads/image/upload/v1526329519/ingameads.png"), }; for (Image image : images) imagerepository.save(image); Game gta5 = gameRepository.save(new Game("com.rockstar.gta5", "Grand Theft Auto 5", 50, "Piąta, pełnoprawna odsłona niezwykle popularnej serii gier akcji, nad której rozwojem pieczę sprawuje studio Rockstar North we współpracy z koncernem Take Two Interactive. Miejscem akcji Grand Theft Auto V jest fikcyjne miasto Los Santos (wzorowane na Los Angeles), a fabuła koncentruje się na perypetiach trójki bohaterów: Michaela De Santy, Trevora Philipsa i Franklina Clintona, którym nieobce są zatargi z prawem. Twórcy gry pozostali wierni sandboksowemu modelowi rozgrywki, pozwalając graczom na dużą swobodę w wykonywaniu zadań i poruszaniu się po wirtualnym mieście. Koszty produkcji i promocji tytułu oszacowane zostały na ponad 360 milionów dolarów, co pobiło wszystkie wcześniejsze rekordy w branży gier wideo.", bob, Arrays.asList(images[4], images[5], images[6]))); Game watchDogs = gameRepository.save(new Game("com.ubisoft.watch_dogs", "Watch Dogs", 10, "Przygodowa gra akcji z widokiem z perspektywy trzeciej osoby (TPP), za której powstanie odpowiadają studia deweloperskie koncernu Ubisoft na czele z Ubisoft Montreal. Fabuła Watch Dogs przenosi graczy w niedaleką przyszłość do Chicago, jednego z wielu amerykańskich miast, których infrastrukturą zarządza Centralny System Operacyjny (CtOS). Główny bohater to Aiden Pearce, utalentowany haker potrafiący włamać się niemal do każdego urządzenia elektronicznego i wykorzystać jego możliwości, by sprokurować rozwój wypadków lub wpłynąć na zachowanie innych ludzi. Rozgrywka toczy się w otwartym świecie, a gracz ma dużą swobodę w wykonywaniu zadań", bob, Arrays.asList(images[0], images[1]))); Game sonic = gameRepository.save(new Game("com.sega.sonic", "Sonic", 15, "Sonic Generations to zręcznościowa platformówka powstała z myślą o uczczeniu 20. urodzin tytułowego niebieskiego jeża. W grze autorstwa ekipy Sonic Team występują dwa wcielenia Sonika - klasyczny i nowoczesny, które starają się zlikwidować dziury w czasoprzestrzeni. W grze pojawia się wiele lokacji stanowiących nawiązanie do poziomów, znanych fanom wcześniejszych odsłon cyklu", greg, Arrays.asList(images[2]))); Game spiderman = gameRepository.save(new Game("com.activision.spiderman", "Spiderman", 10, "Przygodowa gra akcji ze słynnym superbohaterem w roli głównej. Rozgrywka polega oczywiście na walczeniu z przestępcami. Za produkcję odpowiada słynne studio Insomniac Games, znane m.in. z serii Ratchet & Clank, Resistance czy Sunset Overdrive.", greg, Arrays.asList(images[3]))); Game ingameadsClient = gameRepository.save(new Game("com.pastew.ingameads_client", "InGameAds - przykładowa gra", 2, "Przykładowa gra wizualizująca działanie sytemu. https://github.com/Pastew/ingameads-client", bob, Arrays.asList(images[7]))); Advert advert = new Advert(); advert.setStartDate(1529056800); // 15 June 2018 advert.setEndDate(1529316000); // 18 June 2018 advert.setImageURL("http://www.colouringinteam.co.uk/portfolio/storage/cache/images/000/182/FRijj,large.1433757631.jpg"); advert.setGame(gta5); AdvertOffer advertOffer = new AdvertOffer(); advertOffer.setBuyer(greg); advertOffer.setState(AdvertOfferStates.WAITING_FOR_GAME_OWNER_ACCEPTANCE); advertOffer.setAdvert(advert); advertOffer.setGameOwner(advert.getGame().getOwner()); advertOfferRepository.save(advertOffer); Advert advert2 = new Advert(); advert2.setStartDate(1529056800); // 15 June 2018 advert2.setEndDate(1529316000); // 18 June 2018 advert2.setImageURL("https://orig00.deviantart.net/8854/f/2009/205/c/0/starbucks_advert_by_vinayizblank.jpg"); advert2.setGame(gta5); AdvertOffer advertOffer2 = new AdvertOffer(); advertOffer2.setBuyer(greg); advertOffer2.setState(AdvertOfferStates.ACCEPTED_AND_WAITING_FOR_PAYMENT); advertOffer2.setAdvert(advert2); advertOffer2.setGameOwner(advert2.getGame().getOwner()); advertOfferRepository.save(advertOffer2); Advert advert3 = new Advert(); advert3.setStartDate(1526242800); // 12 may 2018 advert3.setEndDate(1529316000); // 18 June 2018 advert3.setImageURL("https://orig00.deviantart.net/8854/f/2009/205/c/0/starbucks_advert_by_vinayizblank.jpg"); advert3.setGame(ingameadsClient); AdvertOffer advertOffer3 = new AdvertOffer(); advertOffer3.setBuyer(greg); advertOffer3.setState(AdvertOfferStates.ACCEPTED_AND_WAITING_FOR_PAYMENT); advertOffer3.setAdvert(advert3); advertOffer3.setGameOwner(advert3.getGame().getOwner()); advertOfferRepository.save(advertOffer3); //advertOfferService.notifyImageProviderAboutNewAdvert(advertOffer3.getId()); }; } }
true
11dde27f0a8df166e81ac08fa9d51ad53e75f8e0
Java
alankouakou/iskool
/iskool/src/main/java/net/ycod3r/converters/FrenchDateFormatter.java
UTF-8
750
2.59375
3
[]
no_license
package net.ycod3r.converters; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.springframework.format.Formatter; public class FrenchDateFormatter implements Formatter<Date>{ private SimpleDateFormat dateFormatter; public FrenchDateFormatter(String dateFormat){ this.dateFormatter = new SimpleDateFormat(dateFormat); } @Override public String print(Date paramDate, Locale locale) { // TODO Auto-generated method stub return dateFormatter.format(paramDate); } @Override public Date parse(String param, Locale arg1) throws ParseException { // TODO Auto-generated method stub return dateFormatter.parse(param); } }
true
440c2cd2da102bda7680dd777fe1e1a545123f50
Java
shichunlei/Notes
/src/com/leo/notes/view/LoginOneKeyActivity.java
UTF-8
4,814
2
2
[]
no_license
package com.leo.notes.view; import scl.leo.library.utils.other.SPUtils; import net.tsz.afinal.FinalActivity; import net.tsz.afinal.annotation.view.ViewInject; import com.leo.notes.R; import com.leo.notes.been.User; import com.leo.notes.util.Constants; import com.leo.notes.util.ThemeUtil; import com.leo.notes.view.base.BaseActivity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.CountDownTimer; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import cn.bmob.v3.BmobSMS; import cn.bmob.v3.BmobUser; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.LogInListener; import cn.bmob.v3.listener.RequestSMSCodeListener; public class LoginOneKeyActivity extends BaseActivity { private static final String TAG = "LoginOneKeyActivity"; @ViewInject(id = R.id.title_bar) private RelativeLayout title_bar; @ViewInject(id = R.id.img_left, click = "back") private ImageView ivTitleLeft; @ViewInject(id = R.id.tv_title) private TextView tvTitle; private int color; MyCountTimer timer; @ViewInject(id = R.id.et_phone) EditText et_phone; @ViewInject(id = R.id.et_verify_code) EditText et_code; @ViewInject(id = R.id.btn_send, click = "send") Button btn_send; @ViewInject(id = R.id.btn_login, click = "login") Button btn_login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ThemeUtil.setTheme(context); setContentView(R.layout.activity_login_onekey); FinalActivity.initInjectedView(this); init(); } private void init() { color = getResources().getColor( (Integer) SPUtils.get(context, "color", R.color.gray, Constants.COLOR)); title_bar.setBackgroundColor(color); tvTitle.setText(getString(R.string.mobile_login)); ivTitleLeft.setImageResource(R.drawable.icon_back); } public void send(View v) { requestSMSCode(); } public void login(View v) { oneKeyLogin(); } class MyCountTimer extends CountDownTimer { public MyCountTimer(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { btn_send.setText((millisUntilFinished / 1000) + "秒后重发"); } @Override public void onFinish() { btn_send.setText("重新发送验证码"); } } private void requestSMSCode() { String number = et_phone.getText().toString(); if (!TextUtils.isEmpty(number)) { timer = new MyCountTimer(60000, 1000); timer.start(); BmobSMS.requestSMSCode(this, number, "Q_Regist", new RequestSMSCodeListener() { @Override public void done(Integer smsId, BmobException ex) { if (ex == null) {// 验证码发送成功 showToast("验证码发送成功");// 用于查询本次短信发送详情 } else { timer.cancel(); } } }); } else { showToast(getString(R.string.input_mobile)); } } /** * 一键登录操作 * * @method login * @return void * @exception */ private void oneKeyLogin() { final String phone = et_phone.getText().toString(); final String code = et_code.getText().toString(); if (TextUtils.isEmpty(phone)) { showToast(getString(R.string.input_mobile)); return; } if (TextUtils.isEmpty(code)) { showToast(getString(R.string.input_verify_code)); return; } final ProgressDialog progress = new ProgressDialog( LoginOneKeyActivity.this); progress.setMessage("正在验证短信验证码..."); progress.setCanceledOnTouchOutside(false); progress.show(); // V3.3.9提供的一键注册或登录方式,可传手机号码和验证码 BmobUser.signOrLoginByMobilePhone(LoginOneKeyActivity.this, phone, code, new LogInListener<User>() { @Override public void done(User user, BmobException ex) { progress.dismiss(); if (ex == null) { showToast(getString(R.string.login_success)); openActivity(LoginPwdActivity.class, true); } else { showToast(getString(R.string.login_fail)); Log.i(TAG, "登录失败:code=" + ex.getErrorCode() + ",错误描述:" + ex.getLocalizedMessage()); } } }); } public void back(View v) { openActivity(LoginActivity.class, true); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { openActivity(LoginActivity.class, true); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); if (timer != null) { timer.cancel(); } } }
true
b1149ba0d3b79651d34778b648b0d8e26c0652a5
Java
HansiDenis/ProjetH
/src/events/FoodAndDrink.java
UTF-8
1,856
3.375
3
[]
no_license
package events; /** * Authors:MALTESE Salomé et DENIS Hansi **/ /** * Classe représentant les évènements de type Nourriture et boisson */ public class FoodAndDrink extends Event { String kind; //le type, ie si c'est un restaurant, un bar, etc String cuisine; /** * Constructeur * * @param start jour de début * @param end jour de fin * @param place lieu * @param name intitulé de l'évènement * @param genre type d'évènement Food&Drink */ public FoodAndDrink(int start, int end, String place, String name, String genre, String cui) { NUMBER_OF_EVENTS += 1; this.eventNumber = NUMBER_OF_EVENTS; this.start = start; this.end = end; this.place = place; this.name = name; this.type = "f&d"; this.kind = genre; this.cuisine = cui; AllEvents.getInstance().addEvent(this); } /** * Méthode d'affichage de l'évènement */ @Override public void present() { super.present(); System.out.println("Venez vous régaler avec nous dans notre " + this.kind + " et profiter de notre cuisine " + this.cuisine + "."); } /** * Méthode construisant la référence d'accès de l'évènement dans la HashMap hashAll * * @return la référence de l'évènement */ @Override public String reference() { if (kind.length() <= 2) { return "FDE-" + this.kind + eventNumber + "-" + this.start + "-" + this.end; } return "FDE-" + this.kind.substring(0, 2) + eventNumber + "-" + this.start + "-" + this.end; } /** * Méthode disant si l'évènement à un type ou non * * @return false car l'évènement à effectivement un type("f&d") */ public boolean hasNoType() { return false; } }
true
d0972ab72e0cd4d1044ae4f65c261aadf128b00f
Java
MyWorkProj/api_ocr_java
/.svn/pristine/d0/d0972ab72e0cd4d1044ae4f65c261aadf128b00f.svn-base
UTF-8
10,908
2.421875
2
[ "Apache-2.0" ]
permissive
package com.aliyun.api.gateway.demo.util; import com.aliyun.api.gateway.demo.Client; import com.aliyun.api.gateway.demo.Request; import com.aliyun.api.gateway.demo.constant.Constants; import com.aliyun.api.gateway.demo.constant.ContentType; import com.aliyun.api.gateway.demo.constant.HttpHeader; import com.aliyun.api.gateway.demo.constant.HttpSchema; import com.aliyun.api.gateway.demo.enums.Method; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.*; /** * Created by cuiyou.wc on 2016/10/27. */ public class CommonUtil { private String host; private String url; private String app_key; private String app_secret; private List<String> custom_sign_prefix; private String image_path; public CommonUtil(String host,String url,String app_key,String app_secret,List<String> custom_sign_prefix,String image_path){ this.host = host; this.url = url; this.app_key = app_key; this.app_secret = app_secret; this.custom_sign_prefix = custom_sign_prefix; this.image_path = image_path; } public String getHost(){ return this.host; } public void setHost(String host){ this.host = host; } public String getUrl(){ return this.url; } public void setUrl(String url){ this.url = url; } public String getApp_key(){ return this.app_key; } public void setApp_key(String app_key){ this.app_key = app_key; } public String getApp_secret(){ return this.app_secret; } public void setApp_secret(String app_secret){ this.app_secret = app_secret; } public List<String> getCustom_sign_prefix(){ return this.custom_sign_prefix; } public void setCustom_sign_prefix(List<String> custom_sign_prefix){ this.custom_sign_prefix= custom_sign_prefix; } public String getImage_path(){ return this.image_path; } public void setImage_path(String image_path){ this.image_path = image_path; } /** * 打印Response * * @param response * @throws java.io.IOException */ private void print(HttpResponse response) throws IOException { StringBuilder sb = new StringBuilder(); sb.append(response.getStatusLine().getStatusCode()).append(Constants.LF); for (Header header : response.getAllHeaders()) { sb.append(MessageDigestUtil.iso88591ToUtf8(header.getValue())).append(Constants.LF); } sb.append(readStreamAsStr(response.getEntity().getContent())).append(Constants.LF); System.out.println("The response is:" + sb.toString()); //get the response body /*StringBuilder sbBody = new StringBuilder(); sbBody.append(readStreamAsStr(response.getEntity().getContent())).append(Constants.LF); System.out.println("The response body is:" + sbBody.toString());*/ } /** * 将流转换为字符串 * * @param is * @return * @throws IOException */ public static String readStreamAsStr(InputStream is) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); WritableByteChannel dest = Channels.newChannel(bos); ReadableByteChannel src = Channels.newChannel(is); ByteBuffer bb = ByteBuffer.allocate(4096); while (src.read(bb) != -1) { bb.flip(); dest.write(bb); bb.clear(); } src.close(); dest.close(); return new String(bos.toByteArray(), Constants.ENCODING); } /** * 将图片转换为base64编码后的字符串 * @param path * @return * @throws Exception */ public String imgToBase64(String path) throws Exception{ byte[] data = null; InputStream in = new FileInputStream(path); data = new byte[in.available()]; in.read(data); in.close(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); } /** * 对字节数组字符串进行Base64解码并生成图片 * @param base64 * @param path * @return * @throws Exception */ public boolean base64ToImg(String base64, String path) throws Exception{ if(base64 == null){return false;} BASE64Decoder decoder = new BASE64Decoder(); byte[] bytes = decoder.decodeBuffer(base64); for(int i = 0;i < bytes.length; ++i){ if(bytes[i] < 0){//调整异常数据 bytes[i] += 256; } } //生成jpeg图片 OutputStream out = new FileOutputStream(path); out.write(bytes); out.flush(); out.close(); return true; } /** * 请求为字节 * @param body * @throws Exception */ public void HttpsPostBytes(String body) throws Exception { //请求URL String url = "/rest/160601/ocr/ocr_idcard.json"; //Body内容 byte[] bytesBody = body.getBytes(Constants.ENCODING); Map<String, String> headers = new HashMap<String, String>(); //(可选)响应内容序列化格式,默认application/json,目前仅支持application/json headers.put(HttpHeader.HTTP_HEADER_ACCEPT, "application/json"); //(可选)Body MD5,服务端会校验Body内容是否被篡改,建议Body非Form表单时添加此Header headers.put(HttpHeader.HTTP_HEADER_CONTENT_MD5, MessageDigestUtil.base64AndMD5(bytesBody)); //(POST/PUT请求必选)请求Body内容格式 headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_TEXT); Request request = new Request(Method.POST_BYTES, HttpSchema.HTTPS + this.host + url, this.app_key, this.app_secret, Constants.DEFAULT_TIMEOUT); request.setHeaders(headers); request.setSignHeaderPrefixList(this.custom_sign_prefix); request.setBytesBody(bytesBody); //调用服务端 HttpResponse response = Client.execute(request); if(response != null){ String strResult = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println("The response result is:"+strResult); } //print(response); } /** * 请求为string格式 * @param body * @throws Exception */ public void HttpsPostString(String body) throws Exception {; Map<String, String> headers = new HashMap<String, String>(); //(可选)响应内容序列化格式,默认application/json,目前仅支持application/json headers.put(HttpHeader.HTTP_HEADER_ACCEPT, "application/json"); //(可选)Body MD5,服务端会校验Body内容是否被篡改,建议Body非Form表单时添加此Header headers.put(HttpHeader.HTTP_HEADER_CONTENT_MD5, MessageDigestUtil.base64AndMD5(body)); //(POST/PUT请求必选)请求Body内容格式 headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_TEXT); Request request = new Request(Method.POST_STRING, HttpSchema.HTTPS + this.host + this.url, this.app_key, this.app_secret, Constants.DEFAULT_TIMEOUT); request.setHeaders(headers); request.setSignHeaderPrefixList(this.custom_sign_prefix); request.setStringBody(body); //调用服务端 HttpResponse response = Client.execute(request); print(response); } /** * 发送请求获得response * @throws Exception */ public void sendPostRequestWithBody()throws Exception{ String base64Str = imgToBase64(this.image_path); //System.out.println(base64Str); int num = base64Str.length(); System.out.println("The size after encode is:" + num); String body ="{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":" + "\"" + base64Str + "\"" + "}," + "\"configure\":{\"dataType\":50,\"dataValue\":\"{ \\\"side\\\": \\\"face\\\" }\"}}]}"; HttpsPostString(body); } /** * 将json字符串转化为json表述形式 * @param jsonStr * @return */ public String format(String jsonStr) { int level = 0; StringBuffer jsonForMatStr = new StringBuffer(); for(int i=0;i<jsonStr.length();i++){ char c = jsonStr.charAt(i); if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){ jsonForMatStr.append(getLevelStr(level)); } switch (c) { case '{': case '[': jsonForMatStr.append(c+"\n"); level++; break; case ',': jsonForMatStr.append(c+"\n"); break; case '}': case ']': jsonForMatStr.append("\n"); level--; jsonForMatStr.append(getLevelStr(level)); jsonForMatStr.append(c); break; default: jsonForMatStr.append(c); break; } } return jsonForMatStr.toString(); } public static String getLevelStr(int level){ StringBuffer levelStr = new StringBuffer(); for(int levelI = 0;levelI<level ; levelI++){ levelStr.append("\t"); } return levelStr.toString(); } /** * get filenames without sub-directory * @param path * @return */ public static String[] getFileNames(String path){ File file = new File(path); String[] fileName = file.list(); return fileName; } /** * get filenames with sub-directory * @param path * @param fileName */ public static void getAllFileName(String path,ArrayList<String> fileName){ File file = new File(path); File[] files = file.listFiles(); String[] names = file.list(); if(names != null){ fileName.addAll(Arrays.asList(names)); } for(File a:files){ if(a.isDirectory()){ getAllFileName(a.getAbsolutePath(),fileName); } } } }
true
55925e528e43d247fa14f3e6ba36a40e083223d9
Java
samer420/Examples
/Polymorphism/src/com/training/domains/Application.java
UTF-8
1,201
3.078125
3
[]
no_license
package com.training.domains; import java.util.Scanner; import com.training.ifaces.Automobile; public class Application { public static void main(String[] args) { // TODO Auto-generated method stub ShowRoom showRoom = new ShowRoom(); NewShowRoom nShowRoom=new NewShowRoom(); Automobile polyAuto = null; int key = 1; polyAuto = showRoom.getItem(key); Scanner sc = new Scanner(System.in); while(true) { System.out.println("Enter \n 1 for Passanger Car \n 2 for Luxury Car \n 3. for Sports Car \n 4. for SportsBike \n 5. to Terminate"); key=sc.nextInt(); switch(key){ case 1: polyAuto = showRoom.getItem(key); showRoom.printQuote(polyAuto); break; case 2: polyAuto = showRoom.getItem(key); showRoom.printQuote(polyAuto); break; case 3: polyAuto = showRoom.getItem(key); showRoom.printQuote(polyAuto); break; case 4: polyAuto = nShowRoom.getItem(key); showRoom.printQuote(polyAuto); break; case 5: System.out.println("Byee..Byee..."); return; default: System.out.println("Wrong Choice"); break; } } } }
true
dfa0ede26a03a63137f0a3569abbef8b97d8428e
Java
Shreyabhr/Java
/collection-generic-app/src/com/techlab/test/LineItemTest.java
UTF-8
821
3.234375
3
[]
no_license
package com.techlab.test; import java.util.ArrayList; import com.techlab.model.LineItem; public class LineItemTest { public static void main(String[] args) { LineItem item1 = new LineItem(1,"Maggie",10,2); LineItem item2 = new LineItem(2,"Shampoo",50,1); LineItem item3 = new LineItem(3,"Soap",10,3); ArrayList cart = new ArrayList(); cart.add(item1); cart.add(item2); cart.add(item3); cart.add("abc"); printCart(cart); } private static void printCart(ArrayList<LineItem> cart) { double total = 0; for (int i = 0; i < cart.size(); i++) { LineItem item = cart.get(i); item.calculateTotalItemPrice(); total = total + item.getTotalItemCost() ; System.out.println(item); } System.out.println("checkout total price: " +total); } }
true
73216bcfb0a41a7a992dbc1585ee625837030c56
Java
ksoontjens/1_Arteau_de_Meester_Nick_Verstocken
/oefeningen_Nick_Verstocken/oefp31/Oef7/Main.java
UTF-8
1,469
3
3
[]
no_license
public class Main { public static void main(String[] args) { Werknemer nick = new Werknemer("nick", "maris", 1, 2000); Werknemer erik = new Werknemer("erik", "wijnen", 2, 50); Werknemer jorgos = new Werknemer("jorgos", "gilis", 3, 2000000); Werknemer tom = new Werknemer("tom", "niemand", 4, 9000000); PartTimeWerknemer paul = new PartTimeWerknemer("paul", "niemand", 5, 1, 15); PartTimeWerknemer joske = new PartTimeWerknemer("Joske", "Vermeulen", 6, 20, 18); StudentWerknemer jef = new StudentWerknemer("Jef", "baris", 7, 15, 40); nick.salarisVerhogen(10); erik.salarisVerhogen(10); System.out.println(nick.voornaam + ": " + nick.getSalaris()); System.out.println(erik.voornaam + ": " + erik.getSalaris()); System.out.println(jorgos.voornaam + ": " + jorgos.getSalaris()); System.out.println(tom.voornaam + ": " + tom.getSalaris()); paul.salarisVerhogen(10); System.out.println(paul.voornaam + ": " + paul.getWeekloon()); System.out.println(joske.voornaam + ": " + joske.getWeekloon()); System.out.println(erik.voornaam + "'s RSZ percentage: " + erik.getRSZ()); erik.setRSZ(25); System.out.println(erik.voornaam + "'s RSZ percentage: " + erik.getRSZ()); System.out.println(joske.voornaam + "'s RSZ percentage: " + joske.getRSZ()); joske.setRSZ(10); System.out.println(joske.voornaam + "'s RSZ percentage: " + joske.getRSZ()); System.out.println(jef.voornaam + "'s RSZ percentage: " + jef.getRSZ()); } }
true
34bf018a44e7a349dbd9f2eb8c69cf50961f19e2
Java
samienaseem/java-
/new-java-codes/areatest.java
UTF-8
145
1.984375
2
[]
no_license
class areatest { int a=10; int b=20; public static void main(String[] args) { //int c=a*b; System.out.println(new areatest().a*b); } }
true
28e2f3685aa3345bc2b58aa951eed63c10a4c2e3
Java
bloodfinger8/MentorMan
/mentor/src/main/java/adminReply/controller/AdminReplyController.java
UTF-8
5,167
2.0625
2
[]
no_license
package adminReply.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import adminReply.bean.AdminreplyPaging; import adminReply.service.AdminreplyService; import meetingboard.bean.ReviewDTO; import menteeboardReply.bean.MenteeboardReplyDTO; /** * @Title : 관리자페이지 댓글관리 컨트롤러입니다 * @author : 안상구 * @date : 2019. 12. 3. * 이해 안가시는 부분이있으면 연락주세요 */ @Controller @RequestMapping(value="adminreply") public class AdminReplyController { @Autowired private AdminreplyService adminreplyService; @Autowired private AdminreplyPaging adminreplyPaging; /* description : 고맙습니다댓글 화면페이지 & 리스트 뿌리기 & 페이지 처리 */ @RequestMapping(value="adminThankyou",method = RequestMethod.GET) public ModelAndView adminThankyou(ModelAndView mav, @RequestParam (required=false,defaultValue="1") String pg) { int endNum = Integer.parseInt(pg)*10; int startNum = endNum-9; Map<String, Integer> map = new HashMap<String, Integer>(); map.put("startNum", startNum); map.put("endNum", endNum); List<ReviewDTO> list = adminreplyService.getAdminThankyou(map); //페이징 처리 int totalA = adminreplyService.getThankyouTotalA(); adminreplyPaging.setCurrentPage(Integer.parseInt(pg)); adminreplyPaging.setPageBlock(3); adminreplyPaging.setPageSize(10); adminreplyPaging.setTotalA(totalA); adminreplyPaging.tankyouPagingHTML(); mav.addObject("list", list); mav.addObject("pg", pg); mav.addObject("adminreplyPaging", adminreplyPaging); mav.addObject("display", "/adminreply/adminThankyou.jsp"); mav.setViewName("/admin/adminMain"); return mav; } /* description : 고맙습니다 댓글 삭제 12.03추가 */ @RequestMapping(value="meetingReviewDelete",method = RequestMethod.POST) @ResponseBody public void meetingReviewDelete(@RequestParam String[] check) { Map<String, String[]> map = new HashMap<String, String[]>(); map.put("check", check); adminreplyService.meetingReviewDelete(map); } /* description : 고맙습니다 댓글 view 12.04추가 */ @RequestMapping(value="thankyouView",method = RequestMethod.GET) public ModelAndView thankyouView(@RequestParam String seq) { ModelAndView mav = new ModelAndView(); int review_seq = Integer.parseInt(seq); ReviewDTO reviewDTO = adminreplyService.thankyouView(review_seq); mav.addObject("reviewDTO", reviewDTO); mav.addObject("display", "/adminreply/thankyouView.jsp"); mav.setViewName("/admin/adminMain"); return mav; } /* description : 멘티게시판댓글 화면페이지 & 리스트 뿌리기 & 페이지 처리 */ @RequestMapping(value="adminmenteeReply",method = RequestMethod.GET) public ModelAndView adminmenteeReply(ModelAndView mav, @RequestParam (required=false,defaultValue="1") String pg) { int endNum = Integer.parseInt(pg)*10; int startNum = endNum-9; Map<String, Integer> map = new HashMap<String, Integer>(); map.put("startNum", startNum); map.put("endNum", endNum); List<MenteeboardReplyDTO> list= adminreplyService.getAdminmenteeReply(map); //페이징 처리 int totalA = adminreplyService.getMenteeReplyTotalA(); adminreplyPaging.setCurrentPage(Integer.parseInt(pg)); adminreplyPaging.setPageBlock(3); adminreplyPaging.setPageSize(10); adminreplyPaging.setTotalA(totalA); adminreplyPaging.menteeReplyPagingHTML(); mav.addObject("list", list); mav.addObject("pg", pg); mav.addObject("adminreplyPaging", adminreplyPaging); mav.addObject("display", "/adminreply/adminmenteeReply.jsp"); mav.setViewName("/admin/adminMain"); return mav; } /* description : 멘티 댓글 삭제 12.03추가 */ @RequestMapping(value="menteeReplyDelete",method = RequestMethod.POST) @ResponseBody public void menteeReplyDelete(@RequestParam String[] check) { Map<String, String[]> map = new HashMap<String, String[]>(); map.put("check", check); adminreplyService.menteeReplyDelete(map); } /* description : 고맙습니다 댓글 view 12.05추가 */ @RequestMapping(value="menteeReplyView",method = RequestMethod.GET) public ModelAndView menteeReplyView(@RequestParam String seq) { ModelAndView mav = new ModelAndView(); int menteeboardReply_seq = Integer.parseInt(seq); MenteeboardReplyDTO menteeboardReplyDTO = adminreplyService.menteeReplyView(menteeboardReply_seq); mav.addObject("menteeboardReplyDTO", menteeboardReplyDTO); mav.addObject("display", "/adminreply/menteeReplyView.jsp"); mav.setViewName("/admin/adminMain"); return mav; } }
true