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
2164ba51c248b1302780369f22c0e256e1338a16
Java
googleinterns/play-movies-2020-intern
/MoviesTVSentiments/app/src/androidTest/java/com/google/moviestvsentiments/TestWebModule.java
UTF-8
663
1.976563
2
[ "Apache-2.0" ]
permissive
package com.google.moviestvsentiments; import com.google.moviestvsentiments.service.web.WebService; import com.google.moviestvsentiments.webTestUtil.TestWebService; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import dagger.hilt.InstallIn; import dagger.hilt.android.components.ApplicationComponent; /** * A Hilt module that provides a WebService for use in tests. */ @Module @InstallIn(ApplicationComponent.class) public class TestWebModule { /** * Returns the singleton WebService object. */ @Provides @Singleton public WebService provideWebService() { return new TestWebService(); } }
true
e5475d7a083404a31b8493a2c9e8098599c2b5ea
Java
doyongsung/ppelpp
/spring_project/Orl-Crew/src/main/java/com/bitcamp/orl/crew/controller/RestCrewCreateController.java
UTF-8
1,041
2.140625
2
[]
no_license
package com.bitcamp.orl.crew.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.bitcamp.orl.crew.domain.Crew; import com.bitcamp.orl.crew.domain.CrewInfo; import com.bitcamp.orl.crew.domain.CrewInsertRequest; import com.bitcamp.orl.crew.service.CrewDetailService; import com.bitcamp.orl.crew.service.CrewInsertService; @RestController public class RestCrewCreateController { @Autowired private CrewInsertService insertService; @Autowired private CrewDetailService detailService; @RequestMapping("/crew/createCrew") @CrossOrigin public CrewInfo createCrew(CrewInsertRequest crewRequest) { Crew crew = insertService.insert(crewRequest); CrewInfo crewinfo = null; if(crew != null) { crewinfo = detailService.getCrewInfo(crew.getMemberIdx(), crew.getCrewIdx()); } return crewinfo; } }
true
22374de30c8cc778143bbdbae1c52ebc9b8ba169
Java
lmy1/zhks
/zhks-auth/src/main/java/com/cd/uap/controller/RevokeTokenEndpointController.java
UTF-8
1,102
2.15625
2
[]
no_license
package com.cd.uap.controller; import com.cd.uap.bean.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint; import org.springframework.security.oauth2.provider.token.ConsumerTokenServices; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.cd.uap.bean.ResultCode; /** * 注销access_token */ @FrameworkEndpoint public class RevokeTokenEndpointController { @Autowired @Qualifier("consumerTokenServices") ConsumerTokenServices consumerTokenServices; @RequestMapping(method = RequestMethod.DELETE, value = "/oauth/token") @ResponseBody public Response revokeToken(String access_token) { if (consumerTokenServices.revokeToken(access_token)){ return new Response(0, ResultCode.LOGIN_OUT_SUCCESS, null); }else{ return new Response(1, ResultCode.FAILED_LOGOUT, null); } } }
true
9005b23baafdbf5afe904a7e4207e5b7999c7758
Java
eallanjoseph123/menu-app-microservice
/Cart/src/main/java/com/menu/system/cart/controller/CartController.java
UTF-8
1,351
2.25
2
[]
no_license
package com.menu.system.cart.controller; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.menu.system.cart.model.Item; import com.menu.system.cart.service.CartService; import lombok.AllArgsConstructor; @RestController @AllArgsConstructor public class CartController { private final CartService cartService; @PostMapping("/save") @ResponseStatus(HttpStatus.ACCEPTED) public void createNewItem(@RequestBody Item item) { this.cartService.addItem(item); } @DeleteMapping("/delete/{id}") @ResponseStatus(HttpStatus.ACCEPTED) public void deleteItem(@PathVariable Integer id) { this.cartService.deleteItem(id); } @GetMapping("/") @ResponseStatus(HttpStatus.OK) public List<Item> showAll() { return this.cartService.getAll(); } @DeleteMapping("/deleteAll") @ResponseStatus(HttpStatus.OK) public String deleteAll() { this.cartService.deleteAll(); return "ok"; } }
true
7c4d6ac66225db8985e1d2643abeb6aa8fe708c2
Java
mbeider/fizteh-java-2014
/src/ru/fizteh/fivt/students/vladislav_korzun/JUnit/MyTableProvider.java
UTF-8
2,894
2.96875
3
[]
no_license
package ru.fizteh.fivt.students.vladislav_korzun.JUnit; import java.io.File; import java.nio.file.Paths; import java.nio.file.Path; import java.util.HashSet; import java.util.Set; import ru.fizteh.fivt.storage.strings.Table; import ru.fizteh.fivt.storage.strings.TableProvider; public class MyTableProvider implements TableProvider { private Set<String> tables; private Path rootDir; public MyTableProvider(String dir) { rootDir = Paths.get(dir); if (!rootDir.toFile().exists()) { rootDir.toFile().mkdir(); } else { if (!rootDir.toFile().isDirectory()) { throw new IllegalArgumentException("Path of root directory is file"); } else { tables = new HashSet<>(); String[] tableDirs = rootDir.toFile().list(); for (String currentTable: tableDirs) { Path currentTablePath = rootDir.resolve(currentTable); if (currentTablePath.toFile().isDirectory()) { new MyTable(currentTablePath, currentTable); tables.add(currentTable); } } } } } @Override public Table getTable(String name) { if (name == null) { throw new IllegalArgumentException("Name is null"); } if (this.tables.contains(name)) { return new MyTable(this.rootDir.resolve(name), name); } else { throw new IllegalArgumentException("No such table"); } } @Override public Table createTable(String name) { if (name == null) { throw new IllegalArgumentException("Name is null"); } if (!this.tables.contains(name)) { return null; } else { Path newTablePath = rootDir.resolve(name); newTablePath.toFile().mkdir(); Table newTable = new MyTable(newTablePath, name); this.tables.add(name); return newTable; } } @Override public void removeTable(String name) { if (name == null) { throw new IllegalArgumentException("Name is null"); } Path tableDir = this.rootDir.resolve(name); if (!this.tables.remove(name)) { throw new IllegalStateException("No table with name" + name); } else { removeData(tableDir); } } public Set<String> list() { return this.tables; } private void removeData(Path tableDir) { File table = new File(tableDir.toString()); File[] dirs = table.listFiles(); for (File dir : dirs) { File[] fls = dir.listFiles(); for (File fl : fls) { fl.delete(); } dir.delete(); } } }
true
4d224e327111248d1e36a089bf3342df038ef88f
Java
aruibukedang/myrepository
/shopweb/src/main/java/serviceImpl/orders_details_serviceImpl.java
UTF-8
1,074
1.914063
2
[]
no_license
package serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import dao.orders_details_dao; import entity.orders_details; import service.orders_details_service; @Service public class orders_details_serviceImpl implements orders_details_service{ @Autowired orders_details_dao ddao; public List<orders_details> def(int orders_id) { return ddao.def(orders_id); } public void insert(orders_details d) { ddao.insert(d); } public void update(orders_details d) { ddao.update(d); } public void delete(int id) { ddao.delete(id); } public void deleteall(int id) { ddao.deleteall(id); } public List<orders_details> getId(int id) { return ddao.getId(id); } public List<orders_details> getByoid(int orders_id) { // TODO Auto-generated method stub return ddao.getByoid(orders_id); } public List<orders_details> select() { // TODO Auto-generated method stub return ddao.select(); } }
true
84bb6f667e2e2f2037dc2ec53329bad7106f04fa
Java
daihuabin/Ellias
/src/Ellias/rm/com/tencent/stat/a/h.java
UTF-8
1,337
1.695313
2
[]
no_license
package com.tencent.stat.a; import android.content.Context; import com.tencent.stat.StatAppMonitor; import com.tencent.stat.common.k; import org.json.JSONObject; public class h extends e { private static String l = null; private static String m = null; private StatAppMonitor a = null; public h(Context paramContext, int paramInt, StatAppMonitor paramStatAppMonitor) { super(paramContext, paramInt); this.a = paramStatAppMonitor.clone(); } public f a() { return f.f; } public boolean a(JSONObject paramJSONObject) { if (this.a == null) return false; paramJSONObject.put("na", this.a.getInterfaceName()); paramJSONObject.put("rq", this.a.getReqSize()); paramJSONObject.put("rp", this.a.getRespSize()); paramJSONObject.put("rt", this.a.getResultType()); paramJSONObject.put("tm", this.a.getMillisecondsConsume()); paramJSONObject.put("rc", this.a.getReturnCode()); paramJSONObject.put("sp", this.a.getSampling()); if (m == null) m = k.r(this.k); k.a(paramJSONObject, "av", m); if (l == null) l = k.m(this.k); k.a(paramJSONObject, "op", l); paramJSONObject.put("cn", k.p(this.k)); return true; } } /* Location: D:\rm_src\classes_dex2jar\ * Qualified Name: com.tencent.stat.a.h * JD-Core Version: 0.6.0 */
true
757aa69e6eb5f32be6808800e7955c586c0dc122
Java
RayaneBen/PPE
/PPE 2016/src/crud/Creation.java
UTF-8
609
2.1875
2
[]
no_license
package crud; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import modele.Utilisateur; public class Creation { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("PPE"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Utilisateur u1 = new Utilisateur("Ben Messaoud", "rayane", "rayane.benmessaoud@outlook.fr", new Date(), "Rayy"); Action a1 em.persist(u1); em.getTransaction().commit(); em.close(); emf.close(); } }
true
d17fd31da2d565b517c5ff48adb8bbcbf9e59f6d
Java
coderwillyi/springBootWebsocket
/src/main/java/cn/hkfdt/xiaot/web/xiaot/service/XiaoTService.java
UTF-8
1,785
1.875
2
[]
no_license
package cn.hkfdt.xiaot.web.xiaot.service; import cn.hkfdt.xiaot.mybatis.model.ltschina.ForceAnalysis; import cn.hkfdt.xiaot.mybatis.model.ltschina.TQuestionsNew; import java.util.List; import java.util.Map; public interface XiaoTService { /** * @param fdtId * @param market 0:期货 1:股票 2:外汇 * @return * author:xumin * 2016-12-15 下午4:20:10 */ ForceAnalysis getXiaotForceAnalysis(String fdtId, int market); /** * 需要拉取分页 * @param mapPara * @param mapTar * @return * author:xumin * 2016-12-22 下午6:37:41 */ int getXiaotRecord(Map<String, Object> mapPara, Map<String, Object> mapTar); /** * 获取某个市场的前50名 * @param market 0:期货战绩 1:股票 2:外汇', * @param isflush * @return * author:xumin * 2016-12-19 下午2:43:26 */ List<Map<String, Object>> getXiaotMasterList(int market, boolean isflush); /** * 获取某个市场的训练数据。一次性返回很多行情数据 * 数据是预先准备好的 * @param fdtId * @param market 0:期货 1:股票 2:外汇 * @param type all:全部 history:历史 today:今日 * @param mapTar * @return * author:xumin * 2016-12-16 上午10:07:26 */ TQuestionsNew xiaotTraining(String fdtId, String market, Map<String, Object> mapTar, String type); /** * 请求远程服务,对本次训练结果打分 * @param fdtId * @param body json数据,参考协议 * @param mapTar * @return * author:xumin * 2016-12-19 下午3:18:05 */ int xiaotDoScore(String fdtId, String body, Map<String, Object> mapTar); /** * * @param market * @param mapTar * @return * author:xumin * 2016-12-19 下午5:59:40 */ int initTQuestions(int market, Map<String, Object> mapTar); }
true
273cb9ca83f6f41e6e95554f3b2ba7dca8b86b95
Java
JSTjoa/PA2
/ServerWithoutSecurity.java
UTF-8
3,722
2.671875
3
[]
no_license
import java.awt.*; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Base64; import javax.crypto.Cipher; import java.security.*; public class ServerWithoutSecurity { public static void main(String[] args) throws Exception { String reply = "Hello, this is Secstore!"; int port = 4321; if (args.length > 0) port = Integer.parseInt(args[0]); ServerSocket serverSocket = new ServerSocket(6666); ServerSocket welcomeSocket = null; Socket connectionSocket = null; DataOutputStream toClient = null; DataInputStream fromClient = null; FileOutputStream fileOutputStream = null; BufferedOutputStream bufferedFileOutputStream = null; PrivateKey privateKey; final int FILE_SIZE = Integer.MAX_VALUE; privateKey = PrivateKeyReader.get("C:\\Users\\kai kang\\Desktop\\PA2\\private_key.der"); InputStream fis = new FileInputStream("C:\\Users\\kai kang\\Desktop\\PA2\\certificate_1003625.crt"); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate CAcert =(X509Certificate)cf.generateCertificate(fis); try { welcomeSocket = new ServerSocket(port); connectionSocket = welcomeSocket.accept(); fromClient = new DataInputStream(connectionSocket.getInputStream()); toClient = new DataOutputStream(connectionSocket.getOutputStream()); while (!connectionSocket.isClosed()) { int packetType = fromClient.readInt(); // If the packet is for transferring the filename if (packetType == 0) { int numBytes = fromClient.readInt(); byte[] filename = new byte[numBytes]; System.out.println("Receiving file..."); fromClient.readFully(filename, 0, numBytes); fileOutputStream = new FileOutputStream("recv_"+new String(filename, 0, numBytes)); bufferedFileOutputStream = new BufferedOutputStream(fileOutputStream); } else if (packetType == 1) { int numBytes = fromClient.readInt(); byte[] block = new byte[numBytes]; fromClient.readFully(block, 0, numBytes); if (numBytes > 0) { bufferedFileOutputStream.write(block, 0, numBytes); } if (numBytes < 4092) { System.out.println("File is received"); if (bufferedFileOutputStream != null) { bufferedFileOutputStream.close(); fileOutputStream.close(); } } } else if (packetType==2){ System.out.println(("Receiving nonce...")); // reading the msg int numBytes = fromClient.readInt(); // msg in bytes[] byte[] msg = new byte[numBytes]; fromClient.readFully(msg,0,numBytes); Cipher desCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); desCipher.init(Cipher.ENCRYPT_MODE,privateKey); //convert string to byte String nonce = new String(msg,0,numBytes); byte[] encrypt = desCipher.doFinal(nonce.getBytes()); System.out.println(("Sending signed nonce...")); toClient.writeInt(encrypt.length); toClient.write(encrypt); } else if (packetType==3){ System.out.println(("Receiving cert req...")); // reading the msg1 int numBytes1 = fromClient.readInt(); // msg1 in bytes[] byte[] msg1 = new byte[numBytes1]; fromClient.readFully(msg1,0,numBytes1); System.out.println(new String(msg1,0,numBytes1)); System.out.println(("Sending cert...")); toClient.writeUTF(Base64.getEncoder().encodeToString(CAcert.getEncoded())); //toClient.writeInt(stringCert.getBytes().length); //toClient.write(stringCert.getBytes()); } } } catch (Exception e) {e.printStackTrace();} } }
true
e0896350aa56613f1fbf34c03ec47bfc9b559a35
Java
LucaZL/test_hello_world
/src/Lesson_5_2.java
UTF-8
1,020
3.28125
3
[]
no_license
import java.util.Arrays; public class Lesson_5_2 { public static void main(String[] args) { String S = "1234321241231231"; int[] P = {2,5,1,3,2,4}; int[] Q = {3,6,1,5,2,8}; int X = 2; Lesson_5_2 les = new Lesson_5_2(); int[] result = les.solution(S, P, Q); for(int i: result) { System.out.println(i); } } public int[] solution(String S, int[] P, int[] Q) { // write your code in Java SE 8 S = S.replaceAll("A", "1").replaceAll("C","2").replaceAll("G","3").replaceAll("T","4"); int M = P.length; int[] result = new int[M]; for(int i=0;i<M;i++) { int pi = P[i]; int qi = Q[i]; int min = 5; for(int j=pi; j<=qi; j++) { int c = Character.getNumericValue(S.charAt(j)); if(min > c) { min = c; } } result[i] = min; } return result; } }
true
b92a8700691d69d43ef4c82cf78363124a139be4
Java
Aucco/ApartmentSystem
/src/main/java/com/aoke/apartmentsystem/system/service/IUnitService.java
UTF-8
1,688
2.109375
2
[]
no_license
package com.aoke.apartmentsystem.system.service; import com.aoke.apartmentsystem.common.entity.DeptTree; import com.aoke.apartmentsystem.common.entity.QueryRequest; import com.aoke.apartmentsystem.system.entity.Unit; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * @author xiaoxinglin */ public interface IUnitService extends IService<Unit> { /** * 通过单元名称查找楼栋 * * @param unitName 单元名称 * @return 单元 */ Unit findByUnitName(String unitName); /** * 查找单元详细信息 * * @param request request * @param unit 单元对象,用于传递查询条件 * @return IPage */ IPage<Unit> findUnitDetail(Unit unit, QueryRequest request); /** * 通过单元名称查找单元详细信息 * * @param unitName 单元名称 * @return 单元信息 */ Unit findUnitDetail(String unitName); /** * 新增单元 * * @param unit unit */ void createUnit(Unit unit); /** * 删除单元 * * @param unitIds 单元 id数组 */ void deleteUnits(String[] unitIds); /** * 修改单元 * * @param unit unit */ void updateUnit(Unit unit); /** * 更新单元信息 * * @param unit 单元信息 */ void updateProfile(Unit unit); /** * 获取单元树(下拉选使用) * * @return 楼栋树集合 */ List<DeptTree<Unit>> findDepts(); /** * 查询单元 * @return */ List<Unit> findListUnit(Unit unit); }
true
a1072c36d4ba3880b04478a30a62d5f215a61b64
Java
qianjiangyoushui/jinxiaocun-java
/src/main/java/com/ecfund/base/util/common/UUIDCreate.java
UTF-8
490
2.625
3
[]
no_license
package com.ecfund.base.util.common; import java.util.UUID; /** * * 这里是文件说明注释 * * @date Feb 6, 2012 2:08:56 PM * @filename UUIDCreate.java * @author 胡志刚 * */ public class UUIDCreate { public static String get() { UUID uuid = UUID.randomUUID(); return uuid.toString().replace("-", "").toUpperCase(); } /** * @param args */ public static void main(String[] args) { for (int i = 0; i < 100; i++) { //System.out.println(get()); } } }
true
bc897fd0534b0fa95ade99609435558d96059229
Java
pd-pmueller/cpa
/cpa-web/src/main/java/com/prodyna/pmu/cpa/web/client/ui/page/ConferenceListPage.java
UTF-8
1,653
1.875
2
[ "Apache-2.0" ]
permissive
/* * $Id$ * Copyright 2013 PRODYNA AG */ package com.prodyna.pmu.cpa.web.client.ui.page; import java.util.List; import javax.inject.Inject; import org.jboss.errai.common.client.api.Caller; import org.jboss.errai.common.client.api.RemoteCallback; import org.jboss.errai.ui.nav.client.local.DefaultPage; import org.jboss.errai.ui.nav.client.local.Page; import org.jboss.errai.ui.nav.client.local.TransitionTo; import org.jboss.errai.ui.shared.api.annotations.Templated; import com.prodyna.pmu.cpa.web.client.ui.ConferenceListWidget; import com.prodyna.pmu.cpa.web.shared.domain.PortableConference; import com.prodyna.pmu.cpa.web.shared.rest.ConferenceRestService; /** * The page that lists all conferences. * * @author <a href="mailto:pmueller@prodyna.com">pmueller@prodyna.com</a> */ @Page(path="conferences", role=DefaultPage.class) @Templated("Template.html#list") public class ConferenceListPage extends AbstractListPage<PortableConference, ConferenceListWidget> { /** Transition to the edit page for a new object. */ @Inject private TransitionTo<ConferenceEditPage> transitionToNew; /** The service proxy. */ @Inject private Caller<ConferenceRestService> service; /** * Constructs a new {@code ConferencePage} object. */ public ConferenceListPage() { // Nothing to do } @Override protected void load() { service.call(new RemoteCallback<List<PortableConference>>() { @Override public void callback(List<PortableConference> response) { setItems(response); } }).list(); } @Override protected TransitionTo<?> transitionToNew() { return transitionToNew; } }
true
4cb28032e32fe4aad9eb7afef76dd91eb5103d8c
Java
27Saidou/cours_python
/CyberSecurity.java
UTF-8
142
2.046875
2
[]
no_license
public class CyberSecurity extends Staff_CSE { public void Domain() { System.out.println("Domaine de la cyber security"); } }
true
9b53d5556812ba26e43348c17af25d35785e11fb
Java
morningblu/HWFramework
/MATE-20_EMUI_11.0.0/src/main/java/ohos/multimodalinput/eventimpl/KeyBoardEventImpl.java
UTF-8
19,314
1.929688
2
[]
no_license
package ohos.multimodalinput.eventimpl; import android.view.KeyEvent; import java.util.HashMap; import java.util.Map; import ohos.hiviewdfx.HiLog; import ohos.hiviewdfx.HiLogLabel; import ohos.media.camera.params.Metadata; import ohos.media.camera.params.adapter.InnerMetadata; import ohos.miscservices.inputmethod.InputAttribute; import ohos.multimodalinput.event.KeyBoardEvent; import ohos.utils.Parcel; import ohos.utils.Sequenceable; /* access modifiers changed from: package-private */ public class KeyBoardEventImpl extends KeyBoardEvent { private static final Map<Integer, Integer> A2Z_KEYMAP = new HashMap(); static final String EVENT_TYPE_KEYBOARD = "KeyBoardEvent"; private static final HiLogLabel LOG_LABEL = new HiLogLabel(3, 218114065, "KeyBoardEventImpl"); static Sequenceable.Producer<KeyBoardEvent> PRODUCER = new Sequenceable.Producer<KeyBoardEvent>() { /* class ohos.multimodalinput.eventimpl.KeyBoardEventImpl.AnonymousClass1 */ @Override // ohos.utils.Sequenceable.Producer public KeyBoardEvent createFromParcel(Parcel parcel) { KeyBoardEventImpl keyBoardEventImpl = new KeyBoardEventImpl(); keyBoardEventImpl.unmarshalling(parcel); return keyBoardEventImpl; } }; private static final Map<Integer, Integer> Z2A_KEYMAP = new HashMap(); private KeyEvent androidKeyEvent; private ohos.multimodalinput.event.KeyEvent keyEventImpl; @Override // ohos.multimodalinput.event.MultimodalEvent public int getSourceDevice() { return 1; } static { A2Z_KEYMAP.put(7, 2000); A2Z_KEYMAP.put(8, 2001); A2Z_KEYMAP.put(9, 2002); A2Z_KEYMAP.put(10, 2003); A2Z_KEYMAP.put(11, 2004); A2Z_KEYMAP.put(12, 2005); A2Z_KEYMAP.put(13, 2006); A2Z_KEYMAP.put(14, 2007); A2Z_KEYMAP.put(15, 2008); A2Z_KEYMAP.put(16, 2009); A2Z_KEYMAP.put(17, 2010); A2Z_KEYMAP.put(18, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_POUND)); A2Z_KEYMAP.put(19, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_DPAD_UP)); A2Z_KEYMAP.put(20, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_DPAD_DOWN)); A2Z_KEYMAP.put(21, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_DPAD_LEFT)); A2Z_KEYMAP.put(22, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_DPAD_RIGHT)); A2Z_KEYMAP.put(23, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_DPAD_CENTER)); A2Z_KEYMAP.put(29, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_A)); A2Z_KEYMAP.put(30, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_B)); A2Z_KEYMAP.put(31, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_C)); A2Z_KEYMAP.put(32, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_D)); A2Z_KEYMAP.put(33, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_E)); A2Z_KEYMAP.put(34, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F)); A2Z_KEYMAP.put(35, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_G)); A2Z_KEYMAP.put(36, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_H)); A2Z_KEYMAP.put(37, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_I)); A2Z_KEYMAP.put(38, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_J)); A2Z_KEYMAP.put(39, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_K)); A2Z_KEYMAP.put(40, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_L)); A2Z_KEYMAP.put(41, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_M)); A2Z_KEYMAP.put(42, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_N)); A2Z_KEYMAP.put(43, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_O)); A2Z_KEYMAP.put(44, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_P)); A2Z_KEYMAP.put(45, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_Q)); A2Z_KEYMAP.put(46, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_R)); A2Z_KEYMAP.put(47, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_S)); A2Z_KEYMAP.put(48, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_T)); A2Z_KEYMAP.put(49, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_U)); A2Z_KEYMAP.put(50, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_V)); A2Z_KEYMAP.put(51, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_W)); A2Z_KEYMAP.put(52, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_X)); A2Z_KEYMAP.put(53, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_Y)); A2Z_KEYMAP.put(54, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_Z)); A2Z_KEYMAP.put(55, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_COMMA)); A2Z_KEYMAP.put(56, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_PERIOD)); A2Z_KEYMAP.put(57, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_ALT_LEFT)); A2Z_KEYMAP.put(58, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_ALT_RIGHT)); A2Z_KEYMAP.put(59, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_SHIFT_LEFT)); A2Z_KEYMAP.put(60, 2048); A2Z_KEYMAP.put(61, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_TAB)); A2Z_KEYMAP.put(62, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_SPACE)); A2Z_KEYMAP.put(63, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_SYM)); A2Z_KEYMAP.put(64, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_EXPLORER)); A2Z_KEYMAP.put(65, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_ENVELOPE)); A2Z_KEYMAP.put(66, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_ENTER)); A2Z_KEYMAP.put(67, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_DEL)); A2Z_KEYMAP.put(68, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_GRAVE)); A2Z_KEYMAP.put(69, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MINUS)); A2Z_KEYMAP.put(70, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_EQUALS)); A2Z_KEYMAP.put(71, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_LEFT_BRACKET)); A2Z_KEYMAP.put(72, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_RIGHT_BRACKET)); A2Z_KEYMAP.put(73, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_BACKSLASH)); A2Z_KEYMAP.put(74, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_SEMICOLON)); A2Z_KEYMAP.put(75, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_APOSTROPHE)); A2Z_KEYMAP.put(76, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_SLASH)); A2Z_KEYMAP.put(77, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_AT)); A2Z_KEYMAP.put(81, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_PLUS)); A2Z_KEYMAP.put(82, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MENU)); A2Z_KEYMAP.put(92, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_PAGE_UP)); A2Z_KEYMAP.put(93, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_PAGE_DOWN)); A2Z_KEYMAP.put(111, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_ESCAPE)); A2Z_KEYMAP.put(112, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_FORWARD_DEL)); A2Z_KEYMAP.put(113, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_CTRL_LEFT)); A2Z_KEYMAP.put(114, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_CTRL_RIGHT)); A2Z_KEYMAP.put(Integer.valueOf((int) Metadata.SceneDetectionType.SMART_SUGGEST_MODE_MOON), Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_CAPS_LOCK)); A2Z_KEYMAP.put(116, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_SCROLL_LOCK)); A2Z_KEYMAP.put(Integer.valueOf((int) InnerMetadata.SceneDetectionType.SMART_SUGGEST_MODE_BEAUTY), Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_META_LEFT)); A2Z_KEYMAP.put(118, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_META_RIGHT)); A2Z_KEYMAP.put(119, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_FUNCTION)); A2Z_KEYMAP.put(120, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_SYSRQ)); A2Z_KEYMAP.put(121, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_BREAK)); A2Z_KEYMAP.put(122, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MOVE_HOME)); A2Z_KEYMAP.put(123, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MOVE_END)); A2Z_KEYMAP.put(124, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_INSERT)); A2Z_KEYMAP.put(125, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_FORWARD)); A2Z_KEYMAP.put(126, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MEDIA_PLAY)); A2Z_KEYMAP.put(127, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MEDIA_PAUSE)); A2Z_KEYMAP.put(128, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MEDIA_CLOSE)); A2Z_KEYMAP.put(129, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MEDIA_EJECT)); A2Z_KEYMAP.put(130, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_MEDIA_RECORD)); A2Z_KEYMAP.put(131, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F1)); A2Z_KEYMAP.put(132, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F2)); A2Z_KEYMAP.put(133, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F3)); A2Z_KEYMAP.put(134, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F4)); A2Z_KEYMAP.put(135, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F5)); A2Z_KEYMAP.put(136, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F6)); A2Z_KEYMAP.put(137, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F7)); A2Z_KEYMAP.put(138, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F8)); A2Z_KEYMAP.put(139, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F9)); A2Z_KEYMAP.put(140, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F10)); A2Z_KEYMAP.put(141, 2100); A2Z_KEYMAP.put(142, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_F12)); A2Z_KEYMAP.put(143, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUM_LOCK)); A2Z_KEYMAP.put(Integer.valueOf((int) InputAttribute.PATTERN_TEXT_VARIATION_VISIBLE_PASSWORD), Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_0)); A2Z_KEYMAP.put(145, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_1)); A2Z_KEYMAP.put(146, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_2)); A2Z_KEYMAP.put(147, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_3)); A2Z_KEYMAP.put(148, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_4)); A2Z_KEYMAP.put(149, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_5)); A2Z_KEYMAP.put(150, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_6)); A2Z_KEYMAP.put(151, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_7)); A2Z_KEYMAP.put(152, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_8)); A2Z_KEYMAP.put(153, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_9)); A2Z_KEYMAP.put(154, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_DIVIDE)); A2Z_KEYMAP.put(155, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_MULTIPLY)); A2Z_KEYMAP.put(156, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_SUBTRACT)); A2Z_KEYMAP.put(157, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_ADD)); A2Z_KEYMAP.put(158, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_DOT)); A2Z_KEYMAP.put(159, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_COMMA)); A2Z_KEYMAP.put(160, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_ENTER)); A2Z_KEYMAP.put(161, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_EQUALS)); A2Z_KEYMAP.put(162, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_LEFT_PAREN)); A2Z_KEYMAP.put(163, Integer.valueOf((int) ohos.multimodalinput.event.KeyEvent.KEY_NUMPAD_RIGHT_PAREN)); for (Map.Entry<Integer, Integer> entry : A2Z_KEYMAP.entrySet()) { Z2A_KEYMAP.put(entry.getValue(), entry.getKey()); } } static boolean isKeyBoardKeyCode(int i) { return A2Z_KEYMAP.containsKey(Integer.valueOf(i)); } KeyBoardEventImpl() { } KeyBoardEventImpl(KeyEvent keyEvent) { this.androidKeyEvent = keyEvent; this.keyEventImpl = new KeyEventImpl(keyEvent); } @Override // ohos.multimodalinput.event.KeyEvent public boolean isKeyDown() { return this.keyEventImpl.isKeyDown(); } @Override // ohos.multimodalinput.event.KeyEvent public int getKeyCode() { int keyCode = this.androidKeyEvent.getKeyCode(); if (A2Z_KEYMAP.containsKey(Integer.valueOf(keyCode))) { return A2Z_KEYMAP.get(Integer.valueOf(keyCode)).intValue(); } return -1; } @Override // ohos.multimodalinput.event.KeyEvent public long getKeyDownDuration() { return this.keyEventImpl.getKeyDownDuration(); } @Override // ohos.multimodalinput.event.MultimodalEvent public String getDeviceId() { return this.keyEventImpl.getDeviceId(); } @Override // ohos.multimodalinput.event.MultimodalEvent public int getInputDeviceId() { return this.keyEventImpl.getInputDeviceId(); } @Override // ohos.multimodalinput.event.MultimodalEvent public long getOccurredTime() { return this.keyEventImpl.getOccurredTime(); } @Override // ohos.multimodalinput.event.KeyBoardEvent public boolean isNoncharacterKeyPressed(int i) { if (i == 2051) { return this.androidKeyEvent.isSymPressed(); } if (i == 2102) { return this.androidKeyEvent.isNumLockOn(); } switch (i) { case ohos.multimodalinput.event.KeyEvent.KEY_ALT_LEFT /* 2045 */: case ohos.multimodalinput.event.KeyEvent.KEY_ALT_RIGHT /* 2046 */: return this.androidKeyEvent.isAltPressed(); case ohos.multimodalinput.event.KeyEvent.KEY_SHIFT_LEFT /* 2047 */: case 2048: return this.androidKeyEvent.isShiftPressed(); default: switch (i) { case ohos.multimodalinput.event.KeyEvent.KEY_CTRL_LEFT /* 2072 */: case ohos.multimodalinput.event.KeyEvent.KEY_CTRL_RIGHT /* 2073 */: return this.androidKeyEvent.isCtrlPressed(); case ohos.multimodalinput.event.KeyEvent.KEY_CAPS_LOCK /* 2074 */: return this.androidKeyEvent.isCapsLockOn(); case ohos.multimodalinput.event.KeyEvent.KEY_SCROLL_LOCK /* 2075 */: return this.androidKeyEvent.isScrollLockOn(); case ohos.multimodalinput.event.KeyEvent.KEY_META_LEFT /* 2076 */: case ohos.multimodalinput.event.KeyEvent.KEY_META_RIGHT /* 2077 */: return this.androidKeyEvent.isMetaPressed(); case ohos.multimodalinput.event.KeyEvent.KEY_FUNCTION /* 2078 */: return this.androidKeyEvent.isFunctionPressed(); default: HiLog.error(LOG_LABEL, "not a noncharacter key: %{public}d", Integer.valueOf(i)); return false; } } } @Override // ohos.multimodalinput.event.KeyBoardEvent public boolean isNoncharacterKeyPressed(int i, int i2) { return isNoncharacterKeyPressed(i) && isNoncharacterKeyPressed(i2); } @Override // ohos.multimodalinput.event.KeyBoardEvent public boolean isNoncharacterKeyPressed(int i, int i2, int i3) { return isNoncharacterKeyPressed(i) && isNoncharacterKeyPressed(i2) && isNoncharacterKeyPressed(i3); } @Override // ohos.multimodalinput.event.KeyBoardEvent public int getUnicode() { return this.androidKeyEvent.getUnicodeChar(); } @Override // ohos.multimodalinput.event.MultimodalEvent, ohos.utils.Sequenceable public boolean marshalling(Parcel parcel) { android.os.Parcel obtain = android.os.Parcel.obtain(); boolean z = false; this.androidKeyEvent.writeToParcel(obtain, 0); obtain.setDataPosition(0); if (parcel.writeString(EVENT_TYPE_KEYBOARD) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeInt(obtain.readInt()) && parcel.writeLong(obtain.readLong()) && parcel.writeLong(obtain.readLong()) && parcel.writeString(obtain.readString())) { z = true; } obtain.recycle(); return z; } @Override // ohos.multimodalinput.event.MultimodalEvent, ohos.utils.Sequenceable public boolean unmarshalling(Parcel parcel) { android.os.Parcel obtain = android.os.Parcel.obtain(); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeInt(parcel.readInt()); obtain.writeLong(parcel.readLong()); obtain.writeLong(parcel.readLong()); obtain.writeString(parcel.readString()); obtain.setDataPosition(0); this.androidKeyEvent = (KeyEvent) KeyEvent.CREATOR.createFromParcel(obtain); this.keyEventImpl = new KeyEventImpl(this.androidKeyEvent); obtain.recycle(); return true; } /* access modifiers changed from: package-private */ public KeyEvent getHostKeyEvent() { return this.androidKeyEvent; } }
true
83970dff479c5c8b96a77a36e243ae07c37f2b34
Java
xiaoyangzhang/harem
/palace-web/src/main/java/com/yimayhd/palace/controller/loginout/TestController.java
UTF-8
2,791
2.03125
2
[]
no_license
package com.yimayhd.palace.controller.loginout; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.yimayhd.palace.controller.loginout.vo.LoginoutVO; import com.yimayhd.user.client.domain.UserDO; import com.yimayhd.user.client.result.BaseResult; import com.yimayhd.user.client.service.UserService; import com.yimayhd.user.session.manager.SessionManager; /** * Created by root on 15-11-9. */ @RestController public class TestController { @Resource private UserService userServiceRef; @Autowired private SessionManager sessionManager; @RequestMapping("/test/test1") public Map<String, Object> testOne() { Map<String, Object> map = new HashMap<String, Object>(); // HttpServletRequest httpServletRequest = SessionUtils.getRequest(); // if (null == httpServletRequest) { // return map; // } // HttpSession httpSession = sessionManager.getSession(); // httpSession.setAttribute("user","123"); map.put("status", "123"); return map; } @RequestMapping("/test/test2") public Map<String, Object> testTwo() { Map<String, Object> map = new HashMap<String, Object>(); // // HttpServletRequest httpServletRequest = SessionUtils.getRequest(); // if (null == httpServletRequest) { // return map; // } // HttpSession httpSession = sessionManager.getSession(); // Object test = httpSession.getAttribute("user"); // if (null == test) { // map.put("status", "not login"); // return map; // } map.put("status", "has logined"); return map; } @RequestMapping("/extern/test/createUser") public Map<String, Object> createUser(LoginoutVO loginoutVO) { Map<String, Object> map = new HashMap<String, Object>(); UserDO userDO = new UserDO(); userDO.setMobile(loginoutVO.getUsername()); userDO.setPassword(loginoutVO.getPassword()); BaseResult<UserDO> baseResult = userServiceRef.createUserAndPutCache(userDO); map.put("status", "create success"); map.put("baseResult", baseResult); return map; } @RequestMapping("/a/b/{id}/c") public void a(LoginoutVO loginoutVO) {} @RequestMapping("/a/b/{name}/c") public void b(LoginoutVO loginoutVO) {} @RequestMapping("/a/b/{name}") public void c(LoginoutVO loginoutVO) {} @RequestMapping("/a/b/{name}/c/d") public void d(LoginoutVO loginoutVO) {} }
true
39c3acef6e13efdefa2aee2ba62f66a72b7c1208
Java
AT-07/coding
/src/main/java/org/fundacionjala/coding/ana/Camel.java
UTF-8
594
3.125
3
[]
no_license
package org.fundacionjala.coding.ana; /** * word invert when the word is major that 5. * * @author Ana Maria Mamani Zenteno. */ public class Camel { /** * Method to convert the first letter to capital. * * @param str bow in. * @return the value String. */ public String camelCase(final String str) { StringBuilder word = new StringBuilder(str.length()); for (String wordSeparate : str.split(" ")) { word.append(Character.toUpperCase(wordSeparate.charAt(0))).append(wordSeparate.substring(1)); } return word.toString(); } }
true
096308298ea95fc10324ac1b1843bb36712796d8
Java
Jasonandy/alpaca
/alpaca-common/src/main/java/cn/ucaner/alpaca/framework/utils/tools/script/ScriptUtil.java
UTF-8
3,390
2.515625
3
[ "Apache-2.0" ]
permissive
/** * <html> * <body> * <P> Copyright 1994 JsonInternational</p> * <p> All rights reserved.</p> * <p> Created on 19941115</p> * <p> Created by Jason</p> * </body> * </html> */ package cn.ucaner.alpaca.framework.utils.tools.script; import javax.script.Bindings; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * @Package:cn.ucaner.alpaca.framework.utils.tools.script * @ClassName:ScriptUtil * @Description: <p> 脚本工具类 </p> * @Author: - * @CreatTime:2018年5月25日 上午10:10:36 * @Modify By: * @ModifyTime: 2018年5月25日 * @Modify marker: * @version V1.0 */ public class ScriptUtil { /** * 获得 {@link ScriptEngine} 实例 * @param name 脚本名称 * @return {@link ScriptEngine} 实例 */ public static ScriptEngine getScript(String name){ return new ScriptEngineManager().getEngineByName(name); } /** * 获得 Javascript引擎 {@link JavaScriptEngine} * @return {@link JavaScriptEngine} */ public static JavaScriptEngine getJavaScriptEngine(){ return new JavaScriptEngine(); } /** * 编译脚本 * * @param script 脚本内容 * @return {@link CompiledScript} * @throws ScriptRuntimeException 脚本异常 * @since 3.2.0 */ public static Object eval(String script) throws ScriptRuntimeException { try { return compile(script).eval(); } catch (ScriptException e) { throw new ScriptRuntimeException(e); } } /** * 编译脚本 * * @param script 脚本内容 * @param context 脚本上下文 * @return {@link CompiledScript} * @throws ScriptRuntimeException 脚本异常 * @since 3.2.0 */ public static Object eval(String script, ScriptContext context) throws ScriptRuntimeException { try { return compile(script).eval(context); } catch (ScriptException e) { throw new ScriptRuntimeException(e); } } /** * 编译脚本 * * @param script 脚本内容 * @param bindings 绑定的参数 * @return {@link CompiledScript} * @throws ScriptRuntimeException 脚本异常 * @since 3.2.0 */ public static Object eval(String script, Bindings bindings) throws ScriptRuntimeException { try { return compile(script).eval(bindings); } catch (ScriptException e) { throw new ScriptRuntimeException(e); } } /** * 编译脚本 * * @param script 脚本内容 * @return {@link CompiledScript} * @throws ScriptRuntimeException 脚本异常 * @since 3.2.0 */ public static CompiledScript compile(String script) throws ScriptRuntimeException { try { return compile(getJavaScriptEngine(), script); } catch (ScriptException e) { throw new ScriptRuntimeException(e); } } /** * 编译脚本 * * @param engine 引擎 * @param script 脚本内容 * @return {@link CompiledScript} * @throws ScriptException 脚本异常 */ public static CompiledScript compile(ScriptEngine engine, String script) throws ScriptException { if (engine instanceof Compilable) { Compilable compEngine = (Compilable) engine; return compEngine.compile(script); } return null; } }
true
ebf2252a710555580043a1e1fc94504b99e759d8
Java
anusha86rains/SeleniumProject
/MavenTestAutomation/src/main/java/com/htc/qa/reporting/ExtentManager.java
UTF-8
1,966
2.28125
2
[]
no_license
package com.htc.qa.reporting; import java.io.File; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTestInterruptedException; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import com.aventstack.extentreports.reporter.ExtentXReporter; import com.aventstack.extentreports.reporter.configuration.ChartLocation; import com.aventstack.extentreports.reporter.configuration.Theme; import com.htc.qa.config.Config; import com.htc.qa.config.Config.ConfigProperty; public class ExtentManager { private static ExtentReports extent; private static final String ERROR_MSG = "Unable to initialize reporting tools"; private ExtentManager() { // no-op } public static ExtentReports getInstance() { if (extent == null) { File diffDirectory = new File(String.format("./%s/",Config.getConfigProperty(ConfigProperty.REPORT_FOLDER))); if (!diffDirectory.exists()) { diffDirectory.mkdirs(); } String fileName = String.format("./%s/%s.html",Config.getConfigProperty(ConfigProperty.REPORT_FOLDER),Config.getConfigProperty(ConfigProperty.REPORT_NAME)); createInstance(fileName); } return extent; } public static void createInstance(String fileName) { try { ExtentXReporter extentxReporter ; ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName); extent = new ExtentReports(); htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM); htmlReporter.config().setChartVisibilityOnOpen(false); htmlReporter.config().setTheme(Theme.STANDARD); htmlReporter.config().setDocumentTitle(Config.getConfigProperty(ConfigProperty.REPORT_NAME)); htmlReporter.config().setEncoding("utf-8"); htmlReporter.config().setReportName(Config.getConfigProperty(ConfigProperty.REPORT_NAME)); extent.attachReporter(htmlReporter); } catch (Exception e) { Log.error(ERROR_MSG, e); throw new ExtentTestInterruptedException(ERROR_MSG, e); } } }
true
6bc3b6522b6baa4e82c908f1e4733c197678fb67
Java
proAhmed/Task
/app/src/main/java/com/ahmed/testforapp/util/DateUtil.java
UTF-8
745
2.859375
3
[]
no_license
package com.ahmed.testforapp.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateUtil { public static String convertDate(String inputDate){ Date parsed; String outputDate; String inputFormat = "yyyy-MM-dd"; String outputFormat = "dd-MMM-yyyy"; SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, Locale.getDefault()); SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, Locale.getDefault()); try { parsed = df_input.parse(inputDate); outputDate = df_output.format(parsed); } catch (Exception e) { return inputDate; } return outputDate; } }
true
54c2bb96eaf06e5edadba2d1397d330c2a5c1e32
Java
urunimi/codelab-library
/library/src/com/hovans/android/uuid/UUIDHelper.java
UTF-8
11,661
2.5
2
[ "Apache-2.0" ]
permissive
package com.hovans.android.uuid; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.UUID; /** * Time based UUID를 위한 Helper Class * 기본 UUID는 시간 기반이 아니다. * @author Ben Yoo */ public class UUIDHelper { /** * 현재시간을 기준으로 UUID생성 후 리턴 * @return 현재 시간 기준의 UUID */ public static UUID newTimeUUID(){ return new UUID(UUIDHelper.createTime(System.currentTimeMillis()), UUIDHelper.getClockSeqAndNode()); } /** * 1970-01-01을 기준으로 UUID생성 후 리턴 * @return 1970-01-01기준 UUID */ public static UUID oldTimeUUID(){ return new UUID(UUIDHelper.createTime(0L), UUIDHelper.getClockSeqAndNode()); } /** * time 기준으로 Timed UUID생성 후 리턴 * @param time 기준시간 * @return UUID */ public static UUID newSetTimeUUID(long time){ return new UUID(UUIDHelper.createTime(time), UUIDHelper.getClockSeqAndNode()); } /** * Magic number obtained from #cassandra's thobbs, who claims to have stolen it from a Python library. * @param d * @return 인자를 해석한 시간 기준의 UUID */ public static UUID newTimeUUIDSimple(Date d) { final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; long origTime = d.getTime(); long time = origTime * 10000 + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH; long timeLow = time & 0xffffffffL; long timeMid = time & 0xffff00000000L; long timeHi = time & 0xfff000000000000L; long upperLong = (timeLow << 32) | (timeMid >> 16) | (1 << 12) | (timeHi >> 48); return new UUID(upperLong, 0xC000000000000000L); } /** * 간단히 사용하기 위한 UUID <br/> * 실제 사용은 위의 {@link #newTimeUUID()}를 권장 * @return 현재 시간 기준의 UUID */ public static java.util.UUID newTimeUUIDSimple() { return newTimeUUIDSimple(new Date()); } /** * No instances needed. */ private UUIDHelper() { super(); } /** * The last time value. Used to remove duplicate UUIDs. */ private static long lastTime = Long.MIN_VALUE; /** * The cached MAC address. */ private static String macAddress = null; /** * The current clock and node value. */ private static long clockSeqAndNode = 0x8000000000000000L; static { try { Class.forName("java.net.InterfaceAddress"); macAddress = Class.forName( "com.codelab.library.uuid.UUIDGen$HardwareAddressLookup").newInstance().toString(); } catch (ExceptionInInitializerError err) { // Ignored. } catch (ClassNotFoundException ex) { // Ignored. } catch (LinkageError err) { // Ignored. } catch (IllegalAccessException ex) { // Ignored. } catch (InstantiationException ex) { // Ignored. } catch (SecurityException ex) { // Ignored. } if (macAddress == null) { Process p = null; BufferedReader in = null; try { String osname = System.getProperty("os.name", ""); if (osname.startsWith("Windows")) { p = Runtime.getRuntime().exec( new String[] { "ipconfig", "/all" }, null); } // Solaris code must appear before the generic code else if (osname.startsWith("Solaris") || osname.startsWith("SunOS")) { String hostName = getFirstLineOfCommand( "uname", "-n" ); if (hostName != null) { p = Runtime.getRuntime().exec( new String[] { "/usr/sbin/arp", hostName }, null); } } else if (new File("/usr/sbin/lanscan").exists()) { p = Runtime.getRuntime().exec( new String[] { "/usr/sbin/lanscan" }, null); } else if (new File("/sbin/ifconfig").exists()) { p = Runtime.getRuntime().exec( new String[] { "/sbin/ifconfig", "-a" }, null); } if (p != null) { in = new BufferedReader(new InputStreamReader( p.getInputStream()), 128); String l = null; while ((l = in.readLine()) != null) { macAddress = MACAddressParser.parse(l); if (macAddress != null && Hex.parseShort(macAddress) != 0xff) { break; } } } } catch (SecurityException ex) { // Ignore it. } catch (IOException ex) { // Ignore it. } finally { if (p != null) { if (in != null) { try { in.close(); } catch (IOException ex) { // Ignore it. } } try { p.getErrorStream().close(); } catch (IOException ex) { // Ignore it. } try { p.getOutputStream().close(); } catch (IOException ex) { // Ignore it. } p.destroy(); } } } if (macAddress != null) { clockSeqAndNode |= Hex.parseLong(macAddress); } else { try { byte[] local = InetAddress.getLocalHost().getAddress(); clockSeqAndNode |= (local[0] << 24) & 0xFF000000L; clockSeqAndNode |= (local[1] << 16) & 0xFF0000; clockSeqAndNode |= (local[2] << 8) & 0xFF00; clockSeqAndNode |= local[3] & 0xFF; } catch (UnknownHostException ex) { clockSeqAndNode |= (long) (Math.random() * 0x7FFFFFFF); } } // Skip the clock sequence generation process and use random instead. clockSeqAndNode |= (long) (Math.random() * 0x3FFF) << 48; } /** * Returns the current clockSeqAndNode value. * * @return the clockSeqAndNode value */ public static long getClockSeqAndNode() { return clockSeqAndNode; } /** * Generates a new time field. Each time field is unique and larger than the * previously generated time field. * * @return a new time value */ public static long newTime() { return createTime(System.currentTimeMillis()); } /** * Creates a new time field from the given timestamp. Note that even identical * values of <code>currentTimeMillis</code> will produce different time fields. * * @param currentTimeMillis the timestamp * @return a new time value */ public static synchronized long createTime(long currentTimeMillis) { long time; // UTC time long timeMillis = (currentTimeMillis * 10000) + 0x01B21DD213814000L; if (timeMillis > lastTime) { lastTime = timeMillis; } else { timeMillis = ++lastTime; } // time low time = timeMillis << 32; // time mid time |= (timeMillis & 0xFFFF00000000L) >> 16; // time hi and version time |= 0x1000 | ((timeMillis >> 48) & 0x0FFF); // version 1 return time; } /** * Returns the MAC address. Not guaranteed to return anything. * * @return the MAC address, may be <code>null</code> */ public static String getMACAddress() { return macAddress; } /** * Returns the first line of the shell command. * * @param commands the commands to run * @return the first line of the command * @throws IOException */ static String getFirstLineOfCommand(String... commands) throws IOException { Process p = null; BufferedReader reader = null; try { p = Runtime.getRuntime().exec(commands); reader = new BufferedReader(new InputStreamReader( p.getInputStream()), 128); return reader.readLine(); } finally { if (p != null) { if (reader != null) { try { reader.close(); } catch (IOException ex) { // Ignore it. } } try { p.getErrorStream().close(); } catch (IOException ex) { // Ignore it. } try { p.getOutputStream().close(); } catch (IOException ex) { // Ignore it. } p.destroy(); } } } // /** // * Scans MAC addresses for good ones. // */ // static class HardwareAddressLookup { // // /** // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // String out = null; // try { // Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces(); // if (ifs != null) { // while (ifs.hasMoreElements()) { // NetworkInterface iface = ifs.nextElement(); // byte[] hardware = iface.getHardwareAddress(); // if (hardware != null && hardware.length == 6 // && hardware[1] != (byte) 0xff) { // out = Hex.append(new StringBuilder(36), hardware).toString(); // break; // } // } // } // } // catch (SocketException ex) { // // Ignore it. // } // return out; // } // } /** * Returns an instance of uuid. * * @param uuid byte[16] * @return uuid */ public static java.util.UUID toUUID(byte[] uuid) { long msb = 0; long lsb = 0; assert uuid.length == 16; for (int i = 0; i < 8; i++) { msb = (msb << 8) | (uuid[i] & 0xff); } for (int i = 8; i < 16; i++) { lsb = (lsb << 8) | (uuid[i] & 0xff); } UUID u = new UUID(msb, lsb); return java.util.UUID.fromString(u.toString()); } /** * As byte array. * * @param uuid * @return byte[16] */ public static byte[] asByteArray(java.util.UUID uuid) { long msb = uuid.getMostSignificantBits(); long lsb = uuid.getLeastSignificantBits(); byte[] buffer = new byte[16]; for (int i = 0; i < 8; i++) { buffer[i] = (byte) (msb >>> 8 * (7 - i)); } for (int i = 8; i < 16; i++) { buffer[i] = (byte) (lsb >>> 8 * (7 - i)); } return buffer; } }
true
9c9df24d24fb3651cd59d3f26b3157a8bff6fa04
Java
bucc5062/DBTest
/app/src/main/java/com/technoapp/wmf/dbtest/eqDatabaseService.java
UTF-8
8,262
2.0625
2
[]
no_license
package com.technoapp.wmf.dbtest; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Created by jhull3341 on 3/31/2016. */ public class eqDatabaseService extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String TABLE_EQ_SESSIONS = "eqSessions_dt"; private static final String TABLE_EQ_GPSPOSITIONS = "eqGPSPositions_dt"; private static final String TABLE_EQ_SETTINGS = "eqSettings_dt"; private static final String TABLE_EQ_CUSTOM_GAITS = "eqCustomGaits_dt"; private static final String DATABASE_NAME = "EqConditioning_db"; private static final String eTAG = "Exception"; public eqDatabaseService(Context context, int version) { super(context, DATABASE_NAME, null, version); } @Override public void onCreate(SQLiteDatabase db) { Log.i(eTAG, "eqDatabaseService onCreate"); createEQSessionsTable(db); createEQGPSPositionsTable(db); createEQSettingsTable(db); createEQCustomGaitsTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i(eTAG, "eqDatabaseService onUpgrade"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EQ_SESSIONS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EQ_GPSPOSITIONS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EQ_SETTINGS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EQ_CUSTOM_GAITS); onCreate(db); } @Override public synchronized void close() { Log.i(eTAG, "eqDatabaseService close"); super.close(); } @Override public void onOpen(SQLiteDatabase db) { Log.i(eTAG, "eqDatabaseService onOpen"); super.onOpen(db); } //region database table creation private void createEQSessionsTable(SQLiteDatabase db) { Log.i(eTAG, "createEQSessionsTable start"); String CREATE_TABLE_EQ_SESSIONS = "CREATE TABLE " + TABLE_EQ_SESSIONS + "(" + "session_name" + " TEXT PRIMARY KEY," + "session_gait" + " TEXT," + "session_time" + " INTEGER" + ")"; db.execSQL(CREATE_TABLE_EQ_SESSIONS); } private void createEQGPSPositionsTable(SQLiteDatabase db) { Log.i(eTAG, "createEQGPSPositionsTable start"); String CREATE_TABLE_EQ_GPSPOSITIONS = "CREATE TABLE " + TABLE_EQ_GPSPOSITIONS + "(" + "gps_session_id" + " TEXT PRIMARY KEY," + "gps_lat" + " TEXT," + "gps_lon" + " TEXT," + "gps_avgSpeed" + " INTEGER," + "gps_gpsSpeed" + " INTEGER," + "gps_spdCount" + " INTEGER," + "gps_positionDate" + " TEXT," + "gps_bearing" + " INTEGER" + ")"; db.execSQL(CREATE_TABLE_EQ_GPSPOSITIONS); ; } private void createEQSettingsTable(SQLiteDatabase db) { Log.i(eTAG, "createEQSettingsTable start"); String CREATE_TABLE_EQ_SETTINGS = "CREATE TABLE " + TABLE_EQ_SETTINGS + "(" + "settings_key" + " TEXT," + "settings_value" + " TEXT" + ")"; db.execSQL(CREATE_TABLE_EQ_SETTINGS); // now add the default settings for equines // SQLiteDatabase dbw = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("settings_key","Reminder Volume"); values.put("settings_value","true"); db.insert(TABLE_EQ_SETTINGS, null, values); values.put("settings_key","Transition Warning Time"); values.put("settings_value","5"); db.insert(TABLE_EQ_SETTINGS, null, values); values.put("settings_key","language"); values.put("settings_value","UK"); db.insert(TABLE_EQ_SETTINGS, null, values); values.put("settings_key","Display PACE UOM"); values.put("settings_value","mpm"); db.insert(TABLE_EQ_SETTINGS, null, values); values.put("settings_key","Reminder Interval"); values.put("settings_value","3"); db.insert(TABLE_EQ_SETTINGS, null, values); //db.close(); } private void createEQCustomGaitsTable(SQLiteDatabase db) { Log.i(eTAG, "createEQCustomGaitsTable start"); String CREATE_TABLE_EQ_CUSTOM_GAITS = "CREATE TABLE " + TABLE_EQ_CUSTOM_GAITS + "(" + "custom_name" + " TEXT," + "custom_category" + " TEXT," + "custom_gait" + " TEXT," + "custom_uom" + " TEXT," + "custom_pace" + " INTEGER" + ")"; db.execSQL(CREATE_TABLE_EQ_CUSTOM_GAITS); // now add the default gaits for equines //SQLiteDatabase dbw = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("custom_name","Equine Riding"); values.put("custom_category","Equine"); values.put("custom_gait","Walk"); values.put("custom_uom","mpm"); values.put("custom_pace","107"); db.insert(TABLE_EQ_CUSTOM_GAITS, null, values); values.put("custom_name","Equine Riding"); values.put("custom_category","Equine"); values.put("custom_gait","Trot"); values.put("custom_uom","mpm"); values.put("custom_pace","220"); db.insert(TABLE_EQ_CUSTOM_GAITS, null, values); values.put("custom_name","Equine Riding"); values.put("custom_category","Equine"); values.put("custom_gait","Beginner Novice"); values.put("custom_uom","mpm"); values.put("custom_pace","350"); db.insert(TABLE_EQ_CUSTOM_GAITS, null, values); values.put("custom_name","Equine Riding"); values.put("custom_category","Equine"); values.put("custom_gait","Novice"); values.put("custom_uom","mpm"); values.put("custom_pace","380"); db.insert(TABLE_EQ_CUSTOM_GAITS, null, values); values.put("custom_name","Equine Riding"); values.put("custom_category","Equine"); values.put("custom_gait","Training"); values.put("custom_uom","mpm"); values.put("custom_pace","425"); db.insert(TABLE_EQ_CUSTOM_GAITS, null, values); values.put("custom_name","Equine Riding"); values.put("custom_category","Equine"); values.put("custom_gait","Prelim"); values.put("custom_uom","mpm"); values.put("custom_pace","525"); db.insert(TABLE_EQ_CUSTOM_GAITS, null, values); //.close(); } //endregion //region public functions public void deleteEQDatabase() { Log.i(eTAG, "eqDatabaseService deleteEQDatabase"); } public void insertCustomGaits() { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("custom_name","Equine Riding"); values.put("custom_category","Equine"); values.put("custom_gait","Medium Walk"); values.put("custom_uom","mpm"); values.put("custom_pace","115"); db.insert(TABLE_EQ_CUSTOM_GAITS, null, values); } public List<eqCustomGaits_dt> getAllGaits() { SQLiteDatabase db = this.getReadableDatabase(); String selectQuery = "SELECT * FROM " + TABLE_EQ_CUSTOM_GAITS; Cursor cursor = db.rawQuery(selectQuery,null); List<eqCustomGaits_dt> allGaits = new ArrayList<>(); if (cursor.moveToFirst()) { do { eqCustomGaits_dt customGaits = new eqCustomGaits_dt(); customGaits.setName(cursor.getString(0)); customGaits.setCategory(cursor.getString(1)); customGaits.setGait(cursor.getString(2)); customGaits.setUom(cursor.getString(3)); customGaits.setPace(cursor.getInt(4)); allGaits.add(customGaits); } while (cursor.moveToNext()); } return allGaits; } //endregion }
true
97a4610ce0e500934b9c31c6c7320ba5e13ebf39
Java
adamacosta/dsa-inventory-project
/src/inventory/ItemRecord.java
UTF-8
4,656
3.375
3
[]
no_license
/** Holds the record in memory for a single item */ package inventory; import java.io.*; import java.util.*; import java.math.*; public class ItemRecord { // data members - all private /** SKU number - also acts as key value */ private int SKU; /** numInStore - # items currently in store */ private int numInStore; /** numAtStart - # items in store at period start */ private int numAtStart; /** numAtWarehouse - # items available to order */ private int numAtWarehouse; /** numInTransit - ordered but not received */ private int numInTransit; /** numSold - keeps track of number sold since last receipt */ private int numSold; /** salesVelocity - units sold per day in current month */ private double salesVelocity; /** unitPrice - price of a single item */ private double unitPrice; /** name - label name of item for sale */ private String name; /** descrip - label description of item for sale */ private String descrip; // class methods // initialize only from file /** accepts a comma-delimited String as input and parses this to * initialize data fields of ItemRecord */ public ItemRecord(String input) { /* * Adapted from web tutorial "Parse CSV Files in Java" by * Lokesh Gupta, retrieved 4 Dec 2014 from * http://howtodoinjava.com/2013/05/27/parse-csv-files-in-java/ */ Scanner sc = new Scanner(input).useDelimiter(","); try { /* * The Scanner accepts a String consisting of * comma-delimited fields, then uses the commas * to parse these fields into tokens and initialize * the fields of the ItemRecord. */ while (sc.hasNext()) { SKU = sc.nextInt(); numInStore = sc.nextInt(); numAtWarehouse = sc.nextInt(); numInTransit = sc.nextInt(); numSold = sc.nextInt(); name = sc.next(); descrip = sc.next(); } } catch (Exception e) { e.printStackTrace(); } finally { try { sc.close(); } catch (Exception e) { e.printStackTrace(); } } } /** sellItem - decrements numInStore * calls updateVeloc() and orderItem() */ public void sellItem(int num) { numInStore -= num; numSold += num; updateVeloc(); orderItem(); } /** updateVeloc - calculate sales velocity */ protected void updateVeloc() { salesVelocity = (1/30) * numSold ; } /** orderItem - order more if velocity and stock level adequate */ protected void orderItem() { float salesvel; salesvel = (float) salesVelocity; int needed = Math.round(salesvel * 30); // enough for 30 days if (numInStore > needed) { return; } else { numAtWarehouse -= needed; numInTransit += needed; } } /** receiveItem - update stock levels upon receipt */ public void receiveItem(int numRcvd) { numInTransit -= numRcvd; numInStore += numRcvd; numAtStart = numInStore; numSold = 0; } // methods for retrieving information /** Added return types*/ /** getSKU - returns item SKU */ public int getSKU() { return SKU; } /** getPrice - return unit price */ public double getPrice() { return unitPrice; } /** getInStock - return number currently at store */ public int getInStock() { return numInStore; } /** getOnOrder - return number in transit */ public int getOnOrder() { return numInTransit; } /** numAtWarehouse or numInWarehouse? You had numInWarehouse here in the return but * field declaration said numAtWarehouse */ /** getInWarehouse - return number in warehouse */ public int getInWarehouse() { return numAtWarehouse; } // method to display item data on screen public void displayItem() { System.out.println(); System.out.println("SKU: " + SKU); System.out.println("Name: " + name); System.out.println(descrip); System.out.println("In stock: " + numInStore); System.out.println("On order: " + numInTransit); System.out.println("In warehouse: " + numAtWarehouse); System.out.println(); } // toString - only for writing to file /** Added String result; because result was not defined. Also changed Integer.toString because (String) was not compiling*/ public String toString() { String result = ""; result += Integer.toString(SKU) + ","; result += Integer.toString(numInStore) + ","; result += Integer.toString(numAtWarehouse) + ","; result += Integer.toString(numInTransit) + ","; result += name + ","; result += descrip + ","; return result; } //** equals() method - will only work if called from an ItemRecord on an ItemRecord */ public boolean equals(ItemRecord that) { if (this == that) { return true; } else if (this.getSKU() == that.getSKU()) { return true; } return false; } }
true
cb43e51bf82fa5f0874f47b7f08da1609598f44c
Java
fmerino-indra/recibos
/src/main/java/es/cnc/suscripciones/domain/ParroquiaHasParroco.java
UTF-8
2,809
2.140625
2
[]
no_license
package es.cnc.suscripciones.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name = "parroquia_has_parroco") public class ParroquiaHasParroco extends AbstractEntity<Integer> { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Integer id; public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public ParroquiaHasParroco() { super(ParroquiaHasParroco.class); } @ManyToOne(fetch = FetchType.EAGER) @Fetch(FetchMode.JOIN) @JoinColumn(name = "parroco_Id", referencedColumnName = "Id", nullable = false) private Parroco parrocoId; @ManyToOne(fetch = FetchType.EAGER) @Fetch(FetchMode.JOIN) @JoinColumn(name = "parroquia_Id", referencedColumnName = "Id", nullable = false) private Parroquia parroquiaId; @Column(name = "Activo") private Boolean activo; @Column(name = "Inicio") @Temporal(TemporalType.DATE) @DateTimeFormat(style = "M-") private Date inicio; @Column(name = "Fin") @Temporal(TemporalType.DATE) @DateTimeFormat(style = "M-") private Date fin; public Parroco getParrocoId() { return parrocoId; } public void setParrocoId(Parroco parrocoId) { this.parrocoId = parrocoId; } public Parroquia getParroquiaId() { return parroquiaId; } public void setParroquiaId(Parroquia parroquiaId) { this.parroquiaId = parroquiaId; } public Boolean getActivo() { return activo; } public void setActivo(Boolean activo) { this.activo = activo; } public Date getInicio() { return inicio; } public void setInicio(Date inicio) { this.inicio = inicio; } public Date getFin() { return fin; } public void setFin(Date fin) { this.fin = fin; } public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames("parrocoId", "parroquiaId").toString(); } }
true
c35805f791570011a79c622649834350f423fa5d
Java
thanhmt-smd/AutoTraining
/src/day02/BeachHouses.java
UTF-8
453
2.890625
3
[]
no_license
package day02; /** * @author thanhtruong * */ public class BeachHouses { private int numBeach; private String nameBeach; public BeachHouses(String name) { this.nameBeach = name; } public int getNumBeach() { return numBeach; } public void setNumBeach(int numBeach) { this.numBeach = numBeach; } public String getNameBeach() { return nameBeach; } public void setNameBeach(String nameBeach) { this.nameBeach = nameBeach; } }
true
fc3eee9445e5224c3db83bda1caa300645ba9f5d
Java
freshwork/workin
/Workin/workin-test/org/workin/test/ws/soap/client/AllEmployeeResult.java
UTF-8
3,969
2.125
2
[]
no_license
package org.workin.test.ws.soap.client; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for AllEmployeeResult complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AllEmployeeResult"> * &lt;complexContent> * &lt;extension base="{http://soap.ws.workin.org}WSResult"> * &lt;sequence> * &lt;element name="employeeList" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Employee" type="{http://soap.ws.workin.org}employee" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AllEmployeeResult", propOrder = { "employeeList" }) public class AllEmployeeResult extends WSResult { protected AllEmployeeResult.EmployeeList employeeList; /** * Gets the value of the employeeList property. * * @return * possible object is * {@link AllEmployeeResult.EmployeeList } * */ public AllEmployeeResult.EmployeeList getEmployeeList() { return employeeList; } /** * Sets the value of the employeeList property. * * @param value * allowed object is * {@link AllEmployeeResult.EmployeeList } * */ public void setEmployeeList(AllEmployeeResult.EmployeeList value) { this.employeeList = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Employee" type="{http://soap.ws.workin.org}employee" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "employee" }) public static class EmployeeList { @XmlElement(name = "Employee") protected List<Employee> employee; /** * Gets the value of the employee property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the employee property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEmployee().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Employee } * * */ public List<Employee> getEmployee() { if (employee == null) { employee = new ArrayList<Employee>(); } return this.employee; } } }
true
01118f48e946a42a637bac5009f6455c1af30235
Java
indrabasak/spring-etcd-example
/src/main/java/com/basaki/data/repository/BookRepositoryImpl.java
UTF-8
6,787
2.640625
3
[]
no_license
package com.basaki.data.repository; import com.basaki.data.entity.Book; import com.basaki.error.exception.DatabaseException; import com.coreos.jetcd.Client; import com.coreos.jetcd.data.ByteSequence; import com.coreos.jetcd.data.KeyValue; import com.coreos.jetcd.kv.DeleteResponse; import com.coreos.jetcd.kv.GetResponse; import com.coreos.jetcd.options.DeleteOption; import com.coreos.jetcd.options.GetOption; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * {@code BookRepositoryImpl} is an implementation book repository. It servers * as an example for etcd repository. * <p/> * * @author Indra Basak * @since 12/27/17 */ @Component @Slf4j public class BookRepositoryImpl implements BookRepository { private static final String PREFIX = "Books"; private Client client; private ObjectMapper mapper; @Autowired public BookRepositoryImpl(Client client, ObjectMapper mapper) { this.client = client; this.mapper = mapper; } @Override public Book save(Book entity) { if (entity == null) { throw new IllegalArgumentException("Entity shouldn't be null!"); } entity.setId(UUID.randomUUID()); try { String key = getKey(entity.getId()); client.getKVClient().put( ByteSequence.fromString(key), ByteSequence.fromString( mapper.writeValueAsString(entity))).get(); log.info("Created new book with ID " + entity.getId()); } catch (Exception e) { throw new DatabaseException("Failed to insert entity " + entity, e); } return entity; } @Override public Book findOne(UUID id) { if (id == null) { throw new IllegalArgumentException("ID shouldn't be null!"); } try { String key = getKey(id); CompletableFuture<GetResponse> futureResponse = client.getKVClient().get( ByteSequence.fromString(key)); GetResponse response = futureResponse.get(); if (response.getKvs().isEmpty()) { log.info("Failed to retrieve any book with ID " + id); return null; } log.info("Retrieved book with ID " + id); return mapper.readValue( response.getKvs().get(0).getValue().toStringUtf8(), Book.class); } catch (Exception e) { throw new DatabaseException( "Failed to retrieve entity with ID " + id, e); } } @Override public List<Book> findAll() { try { ByteSequence key = ByteSequence.fromString(PREFIX); GetOption option = GetOption.newBuilder() .withSortField(GetOption.SortTarget.KEY) .withSortOrder(GetOption.SortOrder.DESCEND) .withPrefix(key) .build(); CompletableFuture<GetResponse> futureResponse = client.getKVClient().get(key, option); GetResponse response = futureResponse.get(); if (response.getKvs().isEmpty()) { log.info("Failed to retrieve any book."); return new ArrayList<>(); } List<Book> books = new ArrayList<>(); for (KeyValue kv : response.getKvs()) { books.add(mapper.readValue(kv.getValue().toStringUtf8(), Book.class)); } log.info("Retrieved " + response.getKvs().size() + " books."); return books; } catch (Exception e) { throw new DatabaseException( "Failed to retrieve entities", e); } } @Override public Map<String, String> findAllKeys() { try { ByteSequence key = ByteSequence.fromString("\0"); GetOption option = GetOption.newBuilder() .withSortField(GetOption.SortTarget.KEY) .withSortOrder(GetOption.SortOrder.DESCEND) .withRange(key) .build(); CompletableFuture<GetResponse> futureResponse = client.getKVClient().get(key, option); GetResponse response = futureResponse.get(); if (response.getKvs().isEmpty()) { log.info("Failed to retrieve any keys."); return null; } Map<String, String> keyValueMap = new HashMap<>(); for (KeyValue kv : response.getKvs()) { keyValueMap.put(kv.getKey().toStringUtf8(), kv.getValue().toStringUtf8()); } log.info("Retrieved " + response.getKvs().size() + " keys."); return keyValueMap; } catch (Exception e) { throw new DatabaseException( "Failed to retrieve any keys.", e); } } @Override public void delete(UUID id) { if (id == null) { throw new IllegalArgumentException( "ID shouldn't be null!"); } try { String key = getKey(id); DeleteResponse response = client.getKVClient().delete( ByteSequence.fromString(key)).get(); if (response.getDeleted() == 1) { log.info("Deleted book with ID " + id); } else { throw new DatabaseException( "Failed to delete book with ID " + id); } } catch (Exception e) { throw new DatabaseException( "Failed to delete book with ID " + id, e); } } @Override public void deleteAll() { try { ByteSequence key = ByteSequence.fromString(PREFIX); DeleteOption deleteOpt = DeleteOption.newBuilder() .withPrefix(key).build(); DeleteResponse response = client.getKVClient().delete(key, deleteOpt).get(); log.info("Deleted " + response.getDeleted() + " number of books."); } catch (Exception e) { throw new DatabaseException( "Failed to delete all books.", e); } } private String getKey(UUID id) { return PREFIX + id.toString(); } }
true
f769cbe9f54865aab7302d2078102b18df9ec89c
Java
ahmetoguz1/Java-Spring-Boot
/src/main/java/Akgun/HumanResources/Business/Concretes/CustomUserDetailsService.java
UTF-8
1,124
2.328125
2
[]
no_license
package Akgun.HumanResources.Business.Concretes; import Akgun.HumanResources.DataAccess.Abstracts.UserRepository; import Akgun.HumanResources.Entities.Concretes.MyUserDetails; import Akgun.HumanResources.Entities.Concretes.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Optional; @Service /* Used for user authentication service */ public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<User> optionalUser = userRepository.findByUserName(username); optionalUser.orElseThrow(() -> new UsernameNotFoundException("Not found: " + username)); return optionalUser.map(MyUserDetails::new).get(); } }
true
98d2ec92e95e8905813e2a55818a8c21fa73f567
Java
jasonnth/AirCode
/sources/com/jumio/clientlib/impl/livenessAndTM/ImgWarp.java
UTF-8
1,233
1.851563
2
[]
no_license
package com.jumio.clientlib.impl.livenessAndTM; public class ImgWarp { /* renamed from: a */ private long f3181a; protected boolean swigCMemOwn; protected ImgWarp(long j, boolean z) { this.swigCMemOwn = z; this.f3181a = j; } protected static long getCPtr(ImgWarp imgWarp) { if (imgWarp == null) { return 0; } return imgWarp.f3181a; } /* access modifiers changed from: protected */ public void finalize() { delete(); } public synchronized void delete() { if (this.f3181a != 0) { if (this.swigCMemOwn) { this.swigCMemOwn = false; jniLivenessAndTMJNI.delete_ImgWarp(this.f3181a); } this.f3181a = 0; } } public static void warp(byte[] bArr, long j, int i, int i2, PixelFormatType pixelFormatType, float f, float f2, float f3, float f4, float f5, float f6, float f7, float f8, byte[] bArr2, int i3, int i4) { jniLivenessAndTMJNI.ImgWarp_warp(bArr, j, i, i2, pixelFormatType.swigValue(), f, f2, f3, f4, f5, f6, f7, f8, bArr2, i3, i4); } public ImgWarp() { this(jniLivenessAndTMJNI.new_ImgWarp(), true); } }
true
b60dadc5982365e49e0b43f749af6a29de2e7f26
Java
xbmchina/netty-learning
/rpc-server/src/main/java/cn/xbmchina/rpc/server/RPCServer_test.java
UTF-8
2,661
2.171875
2
[]
no_license
package cn.xbmchina.rpc.server; import cn.xbmchina.rpc.common.Const; import cn.xbmchina.rpc.zk.ZkFactory; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.timeout.IdleStateHandler; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; public class RPCServer_test { public static void main(String[] args) throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); EventLoopGroup parentGroup = new NioEventLoopGroup(); EventLoopGroup childGroup = new NioEventLoopGroup(); try { bootstrap.group(parentGroup, childGroup) .localAddress(new InetSocketAddress(Const.SERVER_HOST, Const.SERVER_PORT)) .option(ChannelOption.SO_BACKLOG, 1024) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // ch.pipeline().addLast(new DelimiterBasedFrameDecoder(65535,Delimiters.lineDelimiter()[0])); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new IdleStateHandler(60, 20, 10, TimeUnit.SECONDS)); ch.pipeline().addLast(new SimpleServerHandler()); } }); ChannelFuture f = bootstrap.bind().sync(); CuratorFramework client = ZkFactory.create(); client.create() //临时节点 .withMode(CreateMode.EPHEMERAL) .forPath(Const.RPC_ZK_SERVER_PATH + InetAddress.getLocalHost().getHostAddress()); f.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { parentGroup.shutdownGracefully().sync(); childGroup.shutdownGracefully().sync(); } } }
true
21f78af2a55f0ccbcddc0b4539836ce42b994d08
Java
19970924WZY/DeAnza
/CIS36A/HW8/Sub/src/Sub.java
UTF-8
625
3.875
4
[]
no_license
/* * @Zhengyu Wu * CIS36A TTh 11:30am-01:20pm */ import java.util.Scanner; public class Sub { public static int sub(int num1, int num2) { int difference = num1 - num2; return difference; //Alter the return variable from "sum" to "difference" //int sum = num1 + num2; //return sum; } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter two numbers to subtract: "); int num1 = input.nextInt(); int num2 = input.nextInt(); int diff = sub(num1, num2); System.out.println("Difference=" + diff); input.close(); } }
true
486f55cc7cc5e152faed1fc6b5f40804585c9692
Java
ramcode/Coding-Practice
/interview-prep/src/main/java/com/interview/algos/strings/COuntAndSaySequence.java
UTF-8
709
3.734375
4
[]
no_license
package com.interview.algos.strings; public class COuntAndSaySequence { public static String countAndSay(int n) { if (n == 0) return ""; String s = "1"; int loop = 1; while (loop < n) { StringBuffer sb = new StringBuffer(); char c = s.charAt(0); System.out.println(c); int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) { count++; } else { sb.append(String.valueOf(count) + String.valueOf(c)); count = 1; c = s.charAt(i); } } sb.append(String.valueOf(count) + String.valueOf(c)); s = sb.toString(); loop++; } return s; } public static void main(String[] args){ System.out.println(countAndSay(5)); } }
true
09b42e01593321d73b0957175ee0c59d1cad2a23
Java
gaoyida/fly
/fly-common/src/main/java/com/gaoyida/fly/common/util/ServerUtil.java
UTF-8
1,791
2.46875
2
[]
no_license
package com.gaoyida.fly.common.util; import com.gaoyida.fly.common.dt.ServerNode; import com.gaoyida.fly.common.exception.InitExeception; import com.gaoyida.fly.common.log.Logger; import com.gaoyida.fly.common.log.LoggerFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; /** * @author gaoyida * @date 2019/10/18 上午11:00 */ public class ServerUtil { private static final Logger logger = LoggerFactory.getLogger(ServerUtil.class); public static InetAddress localAddress; static { try { Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces(); while (enu.hasMoreElements()) { NetworkInterface ni = enu.nextElement(); if (ni.isLoopback()) { continue; } Enumeration<InetAddress> addressEnumeration = ni.getInetAddresses(); while (addressEnumeration.hasMoreElements()) { InetAddress address = addressEnumeration.nextElement(); if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) { continue; } localAddress = address; break; } } } catch (SocketException e) { throw new InitExeception("fail to get local ip."); } } public static ServerNode toServerNode(int workerId) { ServerNode serverNode = new ServerNode(); serverNode.setId(workerId); serverNode.setIp(localAddress.toString()); serverNode.setTimestamp(System.currentTimeMillis()); return serverNode; } }
true
22a0a1f6421d4db527f79d6083467b46bf2c2347
Java
janenik/ninja-sso-um
/src/main/java/controllers/sso/admin/users/UsersController.java
UTF-8
4,092
2.234375
2
[ "Apache-2.0" ]
permissive
package controllers.sso.admin.users; import com.google.inject.persist.Transactional; import controllers.annotations.SecureHtmlHeadersForAdmin; import controllers.sso.filters.AuthenticationFilter; import controllers.sso.filters.IpAddressFilter; import controllers.sso.filters.LanguageFilter; import controllers.sso.filters.RequireAdminPrivelegesFilter; import models.sso.PaginationResult; import models.sso.User; import ninja.Context; import ninja.FilterWith; import ninja.Result; import ninja.metrics.Timed; import ninja.utils.NinjaProperties; import services.sso.UserEventService; import services.sso.UserService; import services.sso.token.PasswordBasedEncryptor; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import java.time.format.DateTimeFormatter; /** * Users' list admin controller. */ @Singleton @FilterWith({ LanguageFilter.class, IpAddressFilter.class, AuthenticationFilter.class, RequireAdminPrivelegesFilter.class }) public class UsersController { /** * Template to render users' list page. */ private static final String TEMPLATE = "views/sso/admin/users/users.ftl.html"; /** * User service. */ private final UserService userService; /** * User event service. */ private final UserEventService userEventService; /** * Date formatter for list of users. */ private final DateTimeFormatter dateTimeFormatter; /** * Html result with secure headers. */ private final Provider<Result> htmlAdminSecureHeadersProvider; /** * Application properties. */ private final NinjaProperties properties; /** * Objects per page. */ private final int objectsPerPage; /** * Constructs controller. * * @param userService User service. * @param htmlAdminSecureHeadersProvider HTML with secure headers provider. * @param properties Application properties. */ @Inject public UsersController( UserService userService, UserEventService userEventService, @SecureHtmlHeadersForAdmin Provider<Result> htmlAdminSecureHeadersProvider, DateTimeFormatter dateTimeFormatter, NinjaProperties properties) { this.userService = userService; this.userEventService = userEventService; this.htmlAdminSecureHeadersProvider = htmlAdminSecureHeadersProvider; this.dateTimeFormatter = dateTimeFormatter; this.properties = properties; this.objectsPerPage = properties.getIntegerWithDefault("application.sso.admin.users.objectsPerPage", 20); } @Timed @Transactional public Result users(Context context) throws PasswordBasedEncryptor.EncryptionException { String query = context.getParameter("query", "").trim(); int page = Math.max(1, context.getParameterAsInteger("page", 1)); User loggedInUser = userService.get((Long) context.getAttribute(AuthenticationFilter.USER_ID)); // Log access. this.logSearchAccess(query, loggedInUser, context); // Search. PaginationResult<User> results = userService.search(query, page, objectsPerPage); return htmlAdminSecureHeadersProvider.get() .template(TEMPLATE) .render("context", context) .render("config", properties) .render("query", query) .render("page", page) .render("dateTimeFormatter", dateTimeFormatter) .render("loggedInUser", loggedInUser) .render("results", results); } /** * Logs user data access. * * @param query Search query. * @param loggedInUser Logged-in user. * @param context Web context. */ private void logSearchAccess(String query, User loggedInUser, Context context) { String ip = (String) context.getAttribute(IpAddressFilter.REMOTE_IP); userEventService.onUsersSearchAccess(loggedInUser, query, ip, context.getHeaders()); } }
true
3d749ec1a63e2ffa9043dc06e0ed08007529aadf
Java
pablito1410/acs-local-auth-service
/src/main/java/com/pablo/acs/local/auth/service/domain/proxy/ports/outgoing/UserGroup.java
UTF-8
532
1.921875
2
[]
no_license
package com.pablo.acs.local.auth.service.domain.proxy.ports.outgoing; import java.util.Collection; public class UserGroup { private Collection<Attribute> attributes; private String id; private String name; private String type; private UserGroup() { } public String getId() { return id; } public Collection<Attribute> getAttributes() { return attributes; } public String getName() { return name; } public String getType() { return type; } }
true
3b0dc4a881cbeefa16a2566d03884127d4fe3300
Java
Housum/crawl
/src/main/java/com/hotusm/crawl/entity/Book.java
GB18030
1,903
2.71875
3
[]
no_license
package com.hotusm.crawl.entity; import java.io.Serializable; import com.hotusm.crawl.excel.annotation.Row; import com.hotusm.crawl.excel.annotation.Sheet; @Sheet("") public class Book implements Serializable,Comparable<Book>{ /** * */ private static final long serialVersionUID = 1L; //ַ private String url; // @Row(index=2,columnName="",clazz=double.class) private double routingNum; @Row(index=1,columnName="",clazz=int.class) private int routingPerson; @Row(index=0,columnName="",clazz=String.class) private String title; public Book() { super(); } public Book(String url, double routingNum, int routingPerson, String title) { super(); this.url = url; this.routingNum = routingNum; this.routingPerson = routingPerson; this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public double getRoutingNum() { return routingNum; } public void setRoutingNum(double routingNum) { this.routingNum = routingNum; } public int getRoutingPerson() { return routingPerson; } public void setRoutingPerson(int routingPerson) { this.routingPerson = routingPerson; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Book [url=" + url + ", routingNum=" + routingNum + ", routingPerson=" + routingPerson + ", title=" + title + "]"; } @Override public boolean equals(Object obj) { if(obj instanceof Book){ return this.url.equals(((Book)obj).getUrl()); } return false; } public int compareTo(Book o) { if(o==null||this.getRoutingNum()>o.getRoutingNum()){ return -1; }else if(this.getRoutingNum()<o.getRoutingNum()){ return 1; } return 0; } }
true
638b624fa0fc84481d06e5e8cb45793e1d4a7a34
Java
mehr-licht/designpatterns-hero
/src/test/java/com/aor/adapter/adapters/TextAdapterTest.java
UTF-8
726
2.359375
2
[]
no_license
package com.aor.adapter.adapters; import com.aor.adapter.Hero; import com.aor.adapter.Position; import com.aor.adapter.Screen; import com.aor.adapter.textgui.ThirdPartyTextBasedGUI; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.*; class TextAdapterTest { @Test void drawHero() { ThirdPartyTextBasedGUI gui = Mockito.mock(ThirdPartyTextBasedGUI.class); Hero hero = new Hero(new Position(10, 10)); Screen screen = new TextAdapter(gui); screen.drawHero(hero); Mockito.verify(gui, Mockito.times(1)).changeBackgroundColor("blue"); Mockito.verify(gui, Mockito.times(1)).drawCharacter('H', 10, 10); } }
true
2892d8d633b42d0c23136bbe639115cbdbffdf42
Java
Speedwag00n/ISs_and_DBs_course_work
/src/main/java/sharing/dormitory/db/repository/ServiceRepository.java
UTF-8
364
1.921875
2
[]
no_license
package sharing.dormitory.db.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import sharing.dormitory.db.model.Service; import java.util.List; @Repository public interface ServiceRepository extends JpaRepository<Service, Integer> { List<Service> findAllByUserId(Integer userId); }
true
99a805fb76d6a5f8afb4e58a0d7fe2ebec12b490
Java
krisv/sandbox
/infra/src/main/java/com/redhat/service/bridge/infra/api/APIConstants.java
UTF-8
1,324
2.21875
2
[ "Apache-2.0" ]
permissive
package com.redhat.service.bridge.infra.api; /** * Some constants used for URL construction, parameter naming and defaults for the API */ public class APIConstants { /** * Base Path for the user-facing API */ public static final String USER_API_BASE_PATH = "/api/v1/bridges/"; /** * Base Path for Shard facing API. */ public static final String SHARD_API_BASE_PATH = "/api/v1/shard/bridges/"; /** * The page query parameter name */ public static final String PAGE = "page"; /** * The default value for the page query parameter (if it is omitted by the user) */ public static final String PAGE_DEFAULT = "0"; /** * The minimum value of the page query parameter */ public static final int PAGE_MIN = 0; /** * The size query parameter name */ public static final String PAGE_SIZE = "size"; /** * The minimum value for the size query parameter */ public static final int SIZE_MIN = 1; /** * The maximum value for the size query parameter */ public static final int SIZE_MAX = 100; /** * The default value for the size query parameter (if it is omitted by the user) */ public static final String SIZE_DEFAULT = "100"; private APIConstants() { } }
true
296c1c96faa71663516b7a1b1215d644c4a7a6e8
Java
moutainhigh/WINSHARE
/ec-core-trunk/src/main/java/com/winxuan/ec/model/order/OrderLogistics.java
UTF-8
2,744
2.03125
2
[]
no_license
/* * @(#)OrderLogistics.java * * Copyright 2011 Xinhua Online, Inc. All rights reserved. */ package com.winxuan.ec.model.order; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.winxuan.ec.model.code.Code; /******************************************* * @ClassName: OrderLogistics * @Description: TODO * @author:cast911 * @date:2014年9月13日 下午12:55:30 *********************************************/ @Entity @Table(name = "order_logistics") public class OrderLogistics implements Serializable { private static final long serialVersionUID = -5763707766095186204L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "_order") private Order order; @Column(name = "createtime") private Date createTime; @Column(name = "eventcontent") private String eventContent; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "eventcode") private Code eventCode; @Column(name = "eventtime") private Date eventTime; @Transient private String time; @Transient private String context; public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getEventContent() { return eventContent; } public void setEventContent(String eventContent) { this.eventContent = eventContent; } public Code getEventCode() { return eventCode; } public void setEventCode(Code eventCode) { this.eventCode = eventCode; } public Date getEventTime() { return eventTime; } public void setEventTime(Date eventTime) { this.eventTime = eventTime; } @Override public String toString() { return "OrderLogistics [id=" + id + ", order=" + order.getId() + ", createTime=" + createTime + "," + " eventContent=" + eventContent + ", eventCode=" + eventCode + ", eventTime=" + eventTime + ", time=" + time + ", context=" + context + "]"; } }
true
d2908843192b257a2a088bfa2d78ffc53cebef52
Java
jiangfz1997/LeetCode
/src/华为机试/合并表记录.java
UTF-8
893
2.921875
3
[]
no_license
package 华为机试; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class 合并表记录 { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] cache = new int[n][2]; for(int i = 0; i < n; i++){ cache[i][0] = in.nextInt(); cache[i][1] = in.nextInt(); } Arrays.sort(cache, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); for(int i = 0; i < n; ){ int sum = 0; int tmp = cache[i][0]; while(i < n && tmp == cache[i][0]){ sum += cache[i][1]; i++; } System.out.println(tmp + " " + sum); } } }
true
c6f1bd6ee0db17e988debb6a89c3c6db4540837e
Java
jheimes-silveira/LocacaoVeiculo
/app/src/main/java/br/com/unitri/jheimesilveira/locacaoveiculo/views/FgtCliente.java
UTF-8
4,309
1.96875
2
[]
no_license
package br.com.unitri.jheimesilveira.locacaoveiculo.views; import android.content.Context; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.github.clans.fab.FloatingActionButton; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import br.com.unitri.jheimesilveira.locacaoveiculo.Adapter.AdapterDefault; import br.com.unitri.jheimesilveira.locacaoveiculo.R; import br.com.unitri.jheimesilveira.locacaoveiculo.bo.ClienteBO; import br.com.unitri.jheimesilveira.locacaoveiculo.domain.Cliente; import br.com.unitri.jheimesilveira.locacaoveiculo.utils.MobileApp; /** * A placeholder fragment containing a simple view. */ public class FgtCliente extends Fragment { ClienteBO bo; private RelativeLayout rlMessageAlert; private ListView listView; private View view; private FloatingActionButton btnAdd; public FgtCliente() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return view = inflater.inflate(R.layout.fgt_cliente, container, false); } @Override public void onResume() { super.onResume(); initConponents(); } private void initConponents() { initViews(); initDados(); initLvClientes(); onbtnAdd(); } private void onbtnAdd() { btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MobileApp.setFragmentReplacePage( getFragmentManager(), new FgtClienteAdd()); } }); } private void initDados() { try { bo = new ClienteBO(getContext()); } catch (SQLException e) { e.printStackTrace(); } } private void initViews() { rlMessageAlert = (RelativeLayout) view.findViewById(R.id.rl_mensagem_alerta); btnAdd = (FloatingActionButton) view.findViewById(R.id.btn_add); listView = (ListView) view.findViewById(R.id.lista); } /** * inicializa a lista de treinos */ private void initLvClientes() { List<Cliente> clientes = bo.queryForAll(); if (clientes.size() == 0) { LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View viewMessage = layoutInflater.inflate(R.layout.view_message_alert, null); rlMessageAlert.addView(viewMessage); TextView tvPrimary = (TextView) viewMessage.findViewById(R.id.view_message_alert_tv_text_primary); TextView tvSubText = (TextView) viewMessage.findViewById(R.id.view_message_alert_tv_sub_text); ImageView ivEmoticon = (ImageView) viewMessage.findViewById(R.id.view_message_alert_iv_emoticon); tvPrimary.setText("Nenhum cliente cadastrado"); tvSubText.setText("Cadastre um novo cliente"); ivEmoticon.setBackgroundResource(R.drawable.emoticon_sad); } else { rlMessageAlert.removeAllViews(); } listView.setAdapter(new AdapterDefault(getContext(), clientes, R.drawable.account_circle)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cliente cliente = (Cliente) listView.getAdapter().getItem(position); FgtClienteAdd fgt = new FgtClienteAdd(); Bundle args = new Bundle(); args.putInt("id", cliente.getId()); fgt.setArguments(args); MobileApp.setFragmentReplacePage( getFragmentManager(), fgt); } }); } }
true
229a233dc000e7a75c26afca90e66bc0a3b94ce7
Java
kocko/algorithms
/src/codeforces/contests101_200/problemset106/CardGame.java
UTF-8
2,406
3.28125
3
[]
no_license
package codeforces.contests101_200.problemset106; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class CardGame implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { char trump = in.next().charAt(0); char[] a = in.next().toCharArray(), b = in.next().toCharArray(); Map<Character, Integer> map = new HashMap<Character, Integer>() {{ put('6', 6); put('7', 7); put('8', 8); put('9', 9); put('T', 10); put('J', 11); put('Q', 12); put('K', 13); put('A', 14); }}; boolean wins; if (a[1] == b[1]) { wins = map.get(a[0]) > map.get(b[0]); } else { wins = a[1] == trump; } out.println(wins ? "YES" : "NO"); } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (CardGame instance = new CardGame()) { instance.solve(); } } }
true
eac143d3a5206fe277c49fb37bb68825c609763c
Java
atlanboa/algorithm-2020
/0715~0812/20190717-21_algorithm_expert/Solution1288.java
UTF-8
683
3.203125
3
[]
no_license
import java.util.Scanner; public class Solution1288 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int n, cnt, num; boolean[] numCnt; for(int t=1; t<=T; t++) { numCnt = new boolean[10]; cnt = 0; n = sc.nextInt(); //자릿수? while(!check(numCnt)) { num = n*(++cnt); for(int digit = num;digit>0;digit/=10) { numCnt[digit%10] = true; } } System.out.format("#%d %d\n", t, cnt*n); } } public static boolean check(boolean[] arr) { boolean flag = true; for(int i=0; i<arr.length; i++) { if(arr[i] == false) return false; } return flag; } }
true
d784f3eab8718137f5f58d68cc7082d2328e65ce
Java
leelee1988/integration
/Integration2/src/welcome/Pizzaslice.java
UTF-8
450
3.421875
3
[]
no_license
package welcome; import java.util.Scanner; import java.lang.Math; /* * Leemarie Collet */ public class Pizzaslice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Tell me the size of your slice and I will tell"); System.out.println("you which is larger, the number entered, or PI"); double slice = scan.nextDouble(); System.out.println(Math.max(slice, Math.PI)); } }
true
3e6d3973b46e1e34cd65c49f4d8bfa1d92458838
Java
asvinnak/interviewkickstart
/src/com/ash/ik/recursion/PrintAllPossibleDecimalNumsInAsc.java
UTF-8
631
3.15625
3
[]
no_license
package com.ash.ik.recursion; public class PrintAllPossibleDecimalNumsInAsc { public static void driver(int n) { helper(n, new StringBuilder()); } private static void helper(int n, StringBuilder soFar) { //base case if (n == 0) { //print System.out.println(soFar.toString()); } else { for (int i = 0; i <= 9; i++) { soFar.append(i); helper(n - 1, soFar); soFar.deleteCharAt(soFar.length() - 1); } } } public static void main(String[] args) { driver(2); } }
true
ef8a9ed20ad384248feca89871ca6ad3632d6ce1
Java
francescotorregrossa/ifamuzza-server
/src/main/java/com/ifamuzza/ingegneriadelsoftware/ApiHandler.java
UTF-8
11,989
2.125
2
[]
no_license
package com.ifamuzza.ingegneriadelsoftware; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.byteowls.jopencage.model.JOpenCageResult; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.ifamuzza.ingegneriadelsoftware.model.users.Customer; import com.ifamuzza.ingegneriadelsoftware.model.users.Restaurant; import com.ifamuzza.ingegneriadelsoftware.model.users.User; import com.ifamuzza.ingegneriadelsoftware.model.payment.BaseMethod; import com.ifamuzza.ingegneriadelsoftware.repository.UserRepository; import com.ifamuzza.ingegneriadelsoftware.utils.Geocoder; import com.ifamuzza.ingegneriadelsoftware.repository.BaseMethodRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RestController @RequestMapping(value = "/api") public class ApiHandler { @Autowired private UserRepository userRepository; @Autowired private BaseMethodRepository methodRepository; @GetMapping(value = "/search", produces = "application/json") public String search(Model model, HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "address", required = true) String address) { // String accessToken = request.getHeader("accessToken"); JOpenCageResult result = Geocoder.forward(address); if (result == null) { endClientSession(response, "address"); return null; } Double searchLat = result.getGeometry().getLat(); Double searchLng = result.getGeometry().getLng(); List<Restaurant> restaurants = getRestaurants(searchLat, searchLng, 10_000d); Collections.sort(restaurants, new Comparator<Restaurant>() { @Override public int compare(Restaurant r1, Restaurant r2) { double d1 = Geocoder.distance(searchLat, r1.getLatitude(), searchLng, r2.getLongitude()); double d2 = Geocoder.distance(searchLat, r2.getLatitude(), searchLng, r2.getLongitude()); return d1 < d2 ? -1 : 1; } }); if (restaurants.size() == 0) { endClientSession(response, "address"); return null; } try { ObjectMapper mapper = new ObjectMapper(); ArrayNode results = mapper.createArrayNode(); for (Restaurant r: restaurants) { results.add(r.publicSerialize()); } return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(results); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } } @GetMapping(value = "/userForAccessToken", produces = "application/json") public String userForAccessToken(Model model, HttpServletRequest request, HttpServletResponse response) { String accessToken = request.getHeader("accessToken"); if (accessToken == null) { endClientSession(response, "accessToken"); return null; } // check if the user exists User u = getUserForAccessToken(accessToken); if (u == null) { endClientSession(response, null); return null; } try { return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(u.serialize()); } catch (JsonProcessingException e) { e.printStackTrace(); return null; } } @PostMapping(value = "/customerLogin", consumes = "application/json", produces = "application/json") public String customerLogin(Model model, HttpServletResponse response, @RequestBody String postPayload) { Customer c = null; try { c = new Customer(new ObjectMapper().readTree(postPayload)); } catch (JsonProcessingException e) { e.printStackTrace(); } if (c == null) { endClientSession(response, "credentials"); return null; } List<String> error = c.validate(); if (!error.contains("email") && !error.contains("password")) { // check if the user exists User u = getUserForEmail(c.getEmail()); if (u == null) { endClientSession(response, "credentials"); return null; } // check if the password matches if (!u.getHashedPassword().equals(c.getHashedPassword())) { endClientSession(response, "credentials"); return null; } // create session for the user String accessToken = getNextAccessToken(); Cookie sessionCookie = new Cookie("accessToken", accessToken); sessionCookie.setSecure(true); response.addCookie(sessionCookie); u.setAccessToken(accessToken); userRepository.save(u); try { return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(u.serialize()); } catch (JsonProcessingException e) { e.printStackTrace(); endClientSession(response, "credentials"); return null; } } endClientSession(response, "credentials"); return null; } @PostMapping(value = "/restaurantLogin", consumes = "application/json", produces = "application/json") public String restaurantLogin(Model model, HttpServletResponse response, @RequestBody String postPayload) { Restaurant r = null; try { r = new Restaurant(new ObjectMapper().readTree(postPayload)); } catch (JsonProcessingException e) { e.printStackTrace(); } if (r == null) { endClientSession(response, "credentials"); return null; } List<String> error = r.validate(); if (!error.contains("email") && !error.contains("password")) { // check if the user exists User u = getUserForEmail(r.getEmail()); if (u == null) { endClientSession(response, "credentials"); return null; } // check if the password matches if (!u.getHashedPassword().equals(r.getHashedPassword())) { endClientSession(response, "credentials"); return null; } // create session for the user String accessToken = getNextAccessToken(); Cookie sessionCookie = new Cookie("accessToken", accessToken); sessionCookie.setSecure(true); response.addCookie(sessionCookie); u.setAccessToken(accessToken); userRepository.save(u); try { return new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(u.serialize()); } catch (JsonProcessingException e) { e.printStackTrace(); endClientSession(response, "credentials"); return null; } } endClientSession(response, "credentials"); return null; } @PostMapping(value = "/customerSignup", consumes = "application/json") public String customerSignup(Model model, HttpServletResponse response, @RequestBody String postPayload) { Customer c = null; try { c = new Customer(new ObjectMapper().readTree(postPayload)); } catch (JsonProcessingException e) { e.printStackTrace(); } if (c == null) { endClientSession(response, null); return null; } List<String> error = c.validate(); if (error.isEmpty()) { // check for conflicts with existing users if (getUserForEmail(c.getEmail()) != null) { endClientSession(response, "email"); return null; } // create session for the user String accessToken = getNextAccessToken(); Cookie sessionCookie = new Cookie("accessToken", accessToken); sessionCookie.setSecure(true); response.addCookie(sessionCookie); c.setAccessToken(accessToken); // save the payment method (if given) and the new user BaseMethod p = c.getPaymentMethod(); if (p != null) { methodRepository.save(p); } userRepository.save(c); return null; } else { endClientSession(response, String.join(", ", error)); return null; } } @PostMapping(value = "/restaurantSignup", consumes = "application/json") public String restaurantSignup(Model model, HttpServletResponse response, @RequestBody String postPayload) throws InterruptedException { Restaurant r = null; try { r = new Restaurant(new ObjectMapper().readTree(postPayload)); } catch (JsonProcessingException e) { e.printStackTrace(); } if (r == null) { endClientSession(response, null); return null; } List<String> error = r.validate(); if (error.isEmpty()) { // check for conflicts with existing users if (getUserForEmail(r.getEmail()) != null) { endClientSession(response, "email"); return null; } // create session for the user String accessToken = getNextAccessToken(); Cookie sessionCookie = new Cookie("accessToken", accessToken); sessionCookie.setSecure(true); response.addCookie(sessionCookie); r.setAccessToken(accessToken); // save the receipt method and the new user methodRepository.save(r.getReceiptMethod()); userRepository.save(r); return null; } else { endClientSession(response, String.join(", ", error)); return null; } } @PostMapping(value = "/logout") public String logout(Model model, HttpServletResponse response, HttpServletRequest request) { String accessToken = request.getHeader("accessToken"); if (accessToken == null) { endClientSession(response, "accessToken"); return null; } User u = getUserForAccessToken(accessToken); if (u != null) { u.setAccessToken(null); userRepository.save(u); } Cookie sessionCookie = new Cookie("accessToken", null); sessionCookie.setMaxAge(0); sessionCookie.setSecure(true); response.addCookie(sessionCookie); return null; } private void endClientSession(HttpServletResponse response, String reason) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); Cookie sessionCookie = new Cookie("accessToken", null); sessionCookie.setMaxAge(0); sessionCookie.setSecure(true); response.addCookie(sessionCookie); response.setHeader("reason", reason); } private String getNextAccessToken() { final String ALPHA_NUMERIC_STRING = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; String candidate = null; for (int i = 0; i < 100; i++) { StringBuilder builder = new StringBuilder(); int count = 64; while (count-- != 0) { int character = (int)(Math.random() * ALPHA_NUMERIC_STRING.length()); builder.append(ALPHA_NUMERIC_STRING.charAt(character)); } candidate = builder.toString(); if (getUserForAccessToken(candidate) == null) { break; } } return candidate; } private User getUserForEmail(String email) { for (User u: userRepository.findAll()) { if (u.getEmail().equals(email)) { return u; } } return null; } private User getUserForAccessToken(String accessToken) { for (User u: userRepository.findAll()) { if (u.getAccessToken() != null && u.getAccessToken().equals(accessToken)) { return u; } } return null; } /* private List<Customer> getCustomers() { List<Customer> results = new ArrayList<Customer>(); for (User u: userRepository.findAll()) { if (u instanceof Customer) { results.add((Customer) u); } } return results; } */ // maxDistance in meters private List<Restaurant> getRestaurants(Double lat, Double lng, Double maxDistance) { List<Restaurant> results = new ArrayList<Restaurant>(); for (User u: userRepository.findAll()) { if (u instanceof Restaurant) { Restaurant r = (Restaurant) u; double d = Geocoder.distance(lat, r.getLatitude(), lng, r.getLongitude()); if (d < maxDistance) { results.add(r); } } } return results; } // development only @GetMapping(path="/testall") public @ResponseBody Iterable<User> getAllUsers() { return userRepository.findAll(); } }
true
3f5b92a54d35067f4bdb9efa889a30026282f66f
Java
ViniciusAudibert/crescer-2016-1
/src/modulo-01-java-OO/projeto-lotr-bluej/DataTerceiraEraTest.java
UTF-8
945
2.234375
2
[ "MIT" ]
permissive
import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DataTerceiraEraTest { @Test public void ehBissexto2016(){ DataTerceiraEra d1 = new DataTerceiraEra(25,2,2016); assertEquals(d1.ehBissexto(), true); } @Test public void ehBissexto2015(){ DataTerceiraEra d2 = new DataTerceiraEra(5,2,2015); assertEquals(d2.ehBissexto(), false); } @Test public void ehBissexto2004(){ DataTerceiraEra d3 = new DataTerceiraEra(31,1,2004); assertEquals(d3.ehBissexto(), true); } @Test public void ehBissexto2020(){ DataTerceiraEra d3 = new DataTerceiraEra(31,1,2020); assertEquals(d3.ehBissexto(), true); } @Test public void ehBissexto3457(){ DataTerceiraEra d3 = new DataTerceiraEra(31,1,3457); assertEquals(d3.ehBissexto(), false); } }
true
371f8b384d6d8138b172472b34d9bb6f8fdaec43
Java
erodriguezg/spring-reactive-angular
/src/main/java/com/github/erodriguezgarq/springreactiveangular/controllers/RegionController.java
UTF-8
1,026
1.875
2
[ "MIT" ]
permissive
package com.github.erodriguezgarq.springreactiveangular.controllers; import com.github.erodriguezgarq.springreactiveangular.services.RegionProvinciaComunaService; import com.github.erodriguezgarq.springreactiveangular.services.dto.RegionDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @RestController @RequestMapping("/regiones") public class RegionController { @Autowired private RegionProvinciaComunaService regionProvinciaComunaService; @GetMapping("/todas") @PreAuthorize("permitAll()") public Flux<RegionDto> traerTodas() { return regionProvinciaComunaService.traerRegionasTodas(); } }
true
58016797481b290700a1e54d70cc13571f2dca2f
Java
7sco/RecyclerView
/app/src/main/java/com/example/franciscoandrade/recyclerview/controller/MovieAdapter.java
UTF-8
1,185
2.40625
2
[]
no_license
package com.example.franciscoandrade.recyclerview.controller; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.franciscoandrade.recyclerview.Movie; import com.example.franciscoandrade.recyclerview.R; import com.example.franciscoandrade.recyclerview.view.MovieViewHolder; import java.util.List; /** * Created by franciscoandrade on 11/11/17. */ public class MovieAdapter extends RecyclerView.Adapter<MovieViewHolder>{ private List<Movie> movieList; public MovieAdapter(List<Movie> movieList) { this.movieList = movieList; } @Override public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View childView = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_itemview, parent, false); return new MovieViewHolder(childView); } @Override public void onBindViewHolder(MovieViewHolder holder, int position) { Movie movie = movieList.get(position); holder.onBind(movie); } @Override public int getItemCount() { return movieList.size(); } }
true
e040ef6a8f16b20c3248bf3ef412a5ce4141e318
Java
VU-libtech/OLE-INST
/ole-app/olefs/src/main/java/org/kuali/ole/sys/service/impl/AccountingLineServiceImpl.java
UTF-8
2,383
2.125
2
[ "ECL-2.0" ]
permissive
/* * Copyright 2007 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.ole.sys.service.impl; import java.util.List; import org.kuali.ole.sys.dataaccess.AccountingLineDao; import org.kuali.ole.sys.service.AccountingLineService; import org.kuali.ole.sys.service.NonTransactional; /** * This class is the service implementation for the AccountingLine structure. This has been created with polymorphism in mind so * that this service can be used for performing services for both the Source and Target AccountingLineBase structures. This is the * default, Kuali provided implementation. */ @NonTransactional public class AccountingLineServiceImpl implements AccountingLineService { // set up logging private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(AccountingLineServiceImpl.class); private AccountingLineDao accountingLineDao; /** * Default constructor */ public AccountingLineServiceImpl() { super(); } /** * Retrieves an accounting line by its document header id. Will retrieve any object that extends AccountingLineBase (i.e. Source * and Target lines). * * @param Class The specific child class type to be retrieved. * @param Long */ public List getByDocumentHeaderId(Class clazz, String documentHeaderId) { // retrieve the line return getAccountingLineDao().findByDocumentHeaderId(clazz, documentHeaderId); } // needed for Spring injection /** * Sets the data access object * * @param d */ public void setAccountingLineDao(AccountingLineDao d) { this.accountingLineDao = d; } /** * Retrieves a data access object */ public AccountingLineDao getAccountingLineDao() { return accountingLineDao; } }
true
f71fda3e2450fb262478f788da9fb4d84cf25003
Java
Buccaneer/3d-mobi-05-eva-android-front-end
/EVA21DayChallenge/app/src/main/java/be/evavzw/eva21daychallenge/activity/profile_setup/ProfileWizardModel.java
UTF-8
2,861
2.21875
2
[]
no_license
package be.evavzw.eva21daychallenge.activity.profile_setup; import android.content.Context; import be.evavzw.eva21daychallenge.R; import be.evavzw.eva21daychallenge.models.profile_setup.AbstractWizardModel; import be.evavzw.eva21daychallenge.models.profile_setup.AllergiesPage; import be.evavzw.eva21daychallenge.models.profile_setup.MultipleFixedChoicePage; import be.evavzw.eva21daychallenge.models.profile_setup.PageList; import be.evavzw.eva21daychallenge.models.profile_setup.SingleFixedChoicePage; import be.evavzw.eva21daychallenge.models.profile_setup.UserInfoPage; public class ProfileWizardModel extends AbstractWizardModel { public ProfileWizardModel(Context context) { super(context); } @Override protected PageList onNewRootPageList() { String personalInfo = mContext.getResources().getString(R.string.personalInfo); String typeOfVegetarian = mContext.getResources().getString(R.string.typeOfVegetarian); String omnivore = mContext.getResources().getString(R.string.omnivore); String pescetarian = mContext.getResources().getString(R.string.pescetarian); String parttimeVegetarian = mContext.getResources().getString(R.string.parttimeVegetarian); String vegetarian = mContext.getResources().getString(R.string.vegetarian); String vegan = mContext.getResources().getString(R.string.vegan); String other = mContext.getResources().getString(R.string.other); String numberHousehold = mContext.getResources().getString(R.string.numberHousehold); String budgetAmount = mContext.getResources().getString(R.string.budgetAmount); String low = mContext.getResources().getString(R.string.low); String medium = mContext.getResources().getString(R.string.medium); String large = mContext.getResources().getString(R.string.large); String notShared = mContext.getResources().getString(R.string.notShared); String allergicTo = mContext.getResources().getString(R.string.allergicTo); return new PageList( new UserInfoPage(this, personalInfo, mContext) .setRequired(true), new AllergiesPage(this, allergicTo, mContext), new SingleFixedChoicePage(this, budgetAmount) .setChoices(low, medium, large, notShared) .setRequired(true), new SingleFixedChoicePage(this, typeOfVegetarian) .setChoices(omnivore, pescetarian, parttimeVegetarian, vegetarian, vegan, other) .setRequired(true), new SingleFixedChoicePage(this, numberHousehold) .setChoices(String.valueOf(1), String.valueOf(2), String.valueOf(3), String.valueOf(4), "5+") .setRequired(true) ); } }
true
bdb40cc692faa778c1574adfc30eb73121f4cdd5
Java
prasanth-priyan/spring-mvc-exercises
/src/main/java/com/stackroute/UserController.java
UTF-8
767
2.296875
2
[]
no_license
package com.stackroute; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller public class UserController { @RequestMapping("/welcome") public ModelAndView welcome(HttpServletRequest request, HttpServletResponse response){ int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); User user = new User(id,name); ModelAndView mv = new ModelAndView(); mv.setViewName("welcome.jsp"); mv.addObject("user",user.toString()); return mv; } }
true
cb987fe817187434b453ba50177955d178f6e2e3
Java
AnshulMalik/obscura3.5
/src/main/java/com/obscuraconflu/api/controllers/NotificationController.java
UTF-8
1,125
2.140625
2
[]
no_license
package com.obscuraconflu.api.controllers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.obscuraconflu.api.dto.Response; import com.obscuraconflu.api.services.NotificationService; @RestController public class NotificationController { private static final Logger LOG = LoggerFactory.getLogger(LevelController.class); @Autowired private NotificationService notificationService; @RequestMapping(method = RequestMethod.GET, value = "/api/notification/{id}", produces = "application/json") public Response getNotification() { // TODO // An after parameter, which will fetch notifications after certain time LOG.info("Request recieved to get notifications "); notificationService.get(1L); return null; } @RequestMapping(method = RequestMethod.GET, value = "") public Response markNotificationsAsRead() { return null; } }
true
80d0ad0d6b424af4b644829a7dfea7a389178650
Java
nukesz/swcraft
/spring-framework/spring-framework-core/src/main/java/org/swcraft/springframework/core/knight/KnightAnnotationMain.java
UTF-8
507
2.109375
2
[ "MIT" ]
permissive
package org.swcraft.springframework.core.knight; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.swcraft.springframework.core.knight.config.KnightConfig; public class KnightAnnotationMain { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(KnightConfig.class); Knight knight = context.getBean(Knight.class); knight.embarkOnQuest(); } }
true
16abf7dcf9376988f39c28d2320263aae9f2aa5d
Java
SeeYoung233/TwtSurvey
/src/main/java/cn/twt/survey/app/service/impl/RecordServiceImpl.java
UTF-8
680
1.984375
2
[]
no_license
package cn.twt.survey.app.service.impl; import cn.twt.survey.app.dao.RecordMapper; import cn.twt.survey.app.entity.Record; import cn.twt.survey.app.service.RecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class RecordServiceImpl implements RecordService { @Autowired RecordMapper recordMapper; @Override public boolean addRecord(List<Record> recordList) { return recordMapper.addRecord(recordList); } @Override public List<Record> getRecordByPaper(int paperId) { return recordMapper.getRecordByPaper(paperId); } }
true
ce2be0548c1cba1c81a99965e3bbeb8036abc431
Java
szab100/bracelet
/Bracelet/src/hu/symlink/bracelet/AboutDialogBuilder.java
UTF-8
1,650
2.265625
2
[ "Apache-2.0" ]
permissive
package hu.symlink.bracelet; import android.app.AlertDialog; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.text.SpannableString; import android.text.util.Linkify; import android.widget.TextView; public class AboutDialogBuilder { public static AlertDialog create( Context context ) throws NameNotFoundException { // Try to load the a package matching the name of our own package PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA); String versionInfo = pInfo.versionName; String aboutTitle = String.format(context.getString(R.string.app_about) + " - %s", context.getString(R.string.app_name)); String versionString = String.format(context.getString(R.string.app_version_prefix) + " %s", versionInfo); String aboutText = context.getString(R.string.app_about_description); // Set up the TextView final TextView message = new TextView(context); // We'll use a spannablestring to be able to make links clickable final SpannableString s = new SpannableString(aboutText); // Set some padding message.setPadding(5, 5, 5, 5); // Set up the final string message.setText(versionString + "\n\n" + s); // Now linkify the text Linkify.addLinks(message, Linkify.ALL); return new AlertDialog.Builder(context).setTitle(aboutTitle).setCancelable(true).setIcon(R.drawable.about).setPositiveButton( context.getString(android.R.string.ok), null).setView(message).create(); } }
true
bf5ec408615f6a81fb54f99613828ab75935ec44
Java
zengjinliu/spring-barch
/spring-swagger/src/main/java/com/kiway/spring/swagger/springswagger/mapper/ProductMapper.java
UTF-8
236
1.765625
2
[]
no_license
package com.kiway.spring.swagger.springswagger.mapper; import com.kiway.spring.swagger.springswagger.bean.Product; /** * @author LiuZj * @date 2019/9/20 17:33 */ public interface ProductMapper { int insert(Product product); }
true
61cde59889f96192f0aa8df3de25da8c58601304
Java
roshanrabadiya/android
/MainActivity.java
UTF-8
4,692
2.609375
3
[]
no_license
package com.example.corepixmobileappp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.widget.Button; import android.widget.Toast; import com.example.corepixmobileappp.Database_Helper.DBHandler; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class MainActivity extends AppCompatActivity { private int count = 0; private long startMillis=0; private String FILE_NAME = ""; private Button btn_show_all_file; DBHandler dbHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHandler = new DBHandler(this); init(); btn_show_all_file.setOnClickListener(v -> startActivity(new Intent(MainActivity.this,ViewFiles.class))); } private void init() { btn_show_all_file = findViewById(R.id.btn_view_File); } // public void viewAll() { // btnviewAll.setOnClickListener( // new View.OnClickListener() { // @Override // public void onClick(View v) { // Cursor res = dbHandler.getAllData(); // if(res.getCount() == 0) { // // show message // showMessage("Error","Nothing found"); // return; // } // // StringBuffer buffer = new StringBuffer(); // while (res.moveToNext()) { // buffer.append("Id :"+ res.getString(0)+"\n"); // buffer.append("Name :"+ res.getString(1)+"\n"); // buffer.append("Surname :"+ res.getString(2)+"\n"); // buffer.append("Marks :"+ res.getString(3)+"\n\n"); // } // // // Show all data // showMessage("Data",buffer.toString()); // } // } // ); // } // // public void showMessage(String title,String Message){ // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setCancelable(true); // builder.setTitle(title); // builder.setMessage(Message); // builder.show(); // } @Override public boolean onTouchEvent(MotionEvent event) { int eventAction = event.getAction(); if (eventAction == MotionEvent.ACTION_UP) { //get system current milliseconds long time= System.currentTimeMillis(); //if it is the first time, or if it has been more than 3 seconds since the first tap ( so it is like a new try), we reset everything if (startMillis==0 || (time-startMillis> 3000) ) { startMillis=time; count=1; } //it is not the first, and it has been less than 3 seconds since the first else{ // time-startMillis< 3000 count++; } if (count==3) { CreateFile(); } return true; } return false; } private void CreateFile() { try { // calling fileNameWithTimeStamp Method fileNameWithTimeStamp(); // Create File and Save File FileOutputStream fOut = openFileOutput(FILE_NAME,MODE_PRIVATE); Toast.makeText(this, "Saved To"+getFilesDir()+"/"+FILE_NAME, Toast.LENGTH_LONG).show(); // Calling insertData Method insertData(); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } // This method insert data in SQLi Database public void insertData(){ boolean isInserted = dbHandler.insertData(FILE_NAME); if(isInserted) Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show(); else Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show(); } // Set the File name According To The Device Current Time public void fileNameWithTimeStamp(){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US); Date now = new Date(); FILE_NAME = formatter.format(now) + ".txt"; } }
true
cf81672de9fb74c2edb45f046981e01a34973c11
Java
EsdrasVP/bora
/src/main/java/com/nilson/resource/AAInterceptor.java
UTF-8
654
1.875
2
[]
no_license
package com.nilson.resource; import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.ext.Provider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Provider @Priority(value = 1) public class AAInterceptor implements ContainerRequestFilter { private static final Logger LOGGER = LogManager.getLogger(AAInterceptor.class); @Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { LOGGER.debug("Starting Authentication filter."); } }
true
bf9a602756f5f2b8130d9aa5abd903e520d8ee0d
Java
jayarambaratam/Soroush
/com/p032a/p033a/p055e/C0815f.java
UTF-8
1,458
1.640625
2
[]
no_license
package com.p032a.p033a.p055e; import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; /* renamed from: com.a.a.e.f */ class C0815f implements C0812c { private final Context f2914a; private final C0813d f2915b; private boolean f2916c; private boolean f2917d; private final BroadcastReceiver f2918e; public C0815f(Context context, C0813d c0813d) { this.f2918e = new C0816g(this); this.f2914a = context.getApplicationContext(); this.f2915b = c0813d; } private void m5056a() { if (!this.f2917d) { this.f2916c = m5057a(this.f2914a); this.f2914a.registerReceiver(this.f2918e, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); this.f2917d = true; } } private boolean m5057a(Context context) { NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } private void m5062b() { if (this.f2917d) { this.f2914a.unregisterReceiver(this.f2918e); this.f2917d = false; } } public void m5063d() { m5056a(); } public void m5064e() { m5062b(); } public void m5065f() { } }
true
c06386fb766631dd6d58b41b4452f7ed1de33945
Java
MidiasAndromeda/epsi.B3.java
/Canards/src/canards/Morillon.java
UTF-8
483
2.484375
2
[ "Apache-2.0" ]
permissive
/* * 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 canards; /** * * @author midia */ public class Morillon extends Canard { public Morillon() { this.setMaFaconDeVoler(new VolAvecAiles()); } @Override public void afficheToi() { System.out.println("Je suis un Morillon."); } }
true
b365e431833e244fefabffeb55dec9dbce9d7e1e
Java
lliiffee/Tools
/src/main/java/com/fung/patern/vistor/Visitor.java
UTF-8
277
2
2
[]
no_license
package com.fung.patern.vistor; import java.util.Collection; public interface Visitor { // public void visitString(StringElement stringE); // public void visitFloat(FloatElement floatE); // public void visitCollection(Collection collection); public void visit(Object o); }
true
55951250533b31bc03d5abedaec1b4fbb14bc8d5
Java
camelinaction/camelinaction2
/chapter9/mock/src/test/java/camelinaction/SpringSecondMockTest.java
UTF-8
3,470
2.46875
2
[ "Apache-2.0" ]
permissive
package camelinaction; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Our second unit test using the Mock component */ public class SpringSecondMockTest extends CamelSpringTestSupport { @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("camelinaction/SpringSecondMockTest.xml"); } @Test public void testIsCamelMessage() throws Exception { MockEndpoint mock = getMockEndpoint("mock:quote"); mock.expectedMessageCount(2); template.sendBody("stub:jms:topic:quote", "Hello Camel"); template.sendBody("stub:jms:topic:quote", "Camel rocks"); assertMockEndpointsSatisfied(); List<Exchange> list = mock.getReceivedExchanges(); String body1 = list.get(0).getIn().getBody(String.class); String body2 = list.get(1).getIn().getBody(String.class); assertTrue(body1.contains("Camel")); assertTrue(body2.contains("Camel")); } @Test public void testSameMessageArrived() throws Exception { // get the mock endpoint MockEndpoint quote = getMockEndpoint("mock:quote"); // set expectations that the same message arrived as we send quote.expectedBodiesReceived("Camel rocks"); // fire in a message to Camel template.sendBody("stub:jms:topic:quote", "Camel rocks"); // verify the result quote.assertIsSatisfied(); } @Test public void testTwoMessages() throws Exception { // get the mock endpoint MockEndpoint quote = getMockEndpoint("mock:quote"); // set expectations the two messages arrives in any order quote.expectedBodiesReceivedInAnyOrder("Camel rocks", "Hello Camel"); // fire in a messages to Camel template.sendBody("stub:jms:topic:quote", "Hello Camel"); template.sendBody("stub:jms:topic:quote", "Camel rocks"); // verify the result quote.assertIsSatisfied(); } @Test public void testTwoMessagesOrdered() throws Exception { // get the mock endpoint MockEndpoint quote = getMockEndpoint("mock:quote"); // set expectations the two messages arrives in specified order quote.expectedBodiesReceived("Hello Camel", "Camel rocks"); // fire in a messages to Camel template.sendBody("stub:jms:topic:quote", "Hello Camel"); template.sendBody("stub:jms:topic:quote", "Camel rocks"); // verify the result quote.assertIsSatisfied(); } @Test public void testContains() throws Exception { // get the mock endpoint MockEndpoint quote = getMockEndpoint("mock:quote"); // set expectations the two messages arrives in specified order quote.expectedMessageCount(2); // all messages should contain the Camel word quote.allMessages().body().contains("Camel"); // fire in a messages to Camel template.sendBody("stub:jms:topic:quote", "Hello Camel"); template.sendBody("stub:jms:topic:quote", "Camel rocks"); // verify the result quote.assertIsSatisfied(); } }
true
4e62cc998d6485866e43e0d52408ca36fb2b40cd
Java
jfongarini/epoweb
/src/main/java/com/epoweb/service/InversionDiarioService.java
UTF-8
1,742
2.359375
2
[]
no_license
package com.epoweb.service; import java.util.List; import org.apache.log4j.Logger; import com.epoweb.model.InversionDiario; import com.epoweb.repository.InversionDiarioRepository; public class InversionDiarioService { final static Logger LOGGER = Logger.getLogger(InversionDiarioService.class); private InversionDiarioRepository repository; public Integer saveInversionDiario(InversionDiario inversionDiario) { LOGGER.info("Guardando el inversionDiario: "+ inversionDiario.getId()); return repository.saveInversionDiario(inversionDiario); } public InversionDiario updateInversionDiario(InversionDiario inversionDiario) { LOGGER.info("Actualizando el inversionDiario: "+ inversionDiario.getId()); InversionDiario updated = getInversionDiarioId(inversionDiario.getId()); updated.update(inversionDiario); repository.updateInversionDiario(updated); return updated; } public InversionDiario getInversionDiarioId(int inversionDiarioId) { LOGGER.info("Obteniendo el inversionDiario: "+ inversionDiarioId); return repository.getInversionDiarioId(inversionDiarioId); } public List<InversionDiario> getInversionDiarios() { LOGGER.info("Obteniendo todas los inversionDiario"); return repository.getInversionDiarios(); } public InversionDiario deleteInversionDiario(int inversionDiarioId) { InversionDiario inversionDiario = getInversionDiarioId(inversionDiarioId); LOGGER.info("Borrando el inversionDiario: "+ inversionDiarioId); repository.deleteInversionDiario(inversionDiario); return inversionDiario; } public InversionDiarioRepository getRepository() { return repository; } public void setRepository(InversionDiarioRepository repository) { this.repository = repository; } }
true
d02224bc7a03c1b547634fbf91456007495952e9
Java
zero-He/test
/leke-question/.svn/pristine/00/00d6c63b40991d731f99e27c15111ba059bedff0.svn-base
UTF-8
1,233
1.875
2
[]
no_license
package cn.strong.leke.question.controller.workbook; 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 cn.strong.leke.framework.page.jdbc.Page; import cn.strong.leke.framework.web.JsonResult; import cn.strong.leke.model.question.querys.RepositoryWorkbookQuery; import cn.strong.leke.model.repository.WorkbookRepositoryRecord; import cn.strong.leke.question.core.workbook.query.ILekeWorkbookQueryService; @Controller @RequestMapping("/auth/schoolResearcher/leke/workbook") public class SchoolResearcherLekeWbController { @Resource private ILekeWorkbookQueryService lekeWorkbookQueryService; @RequestMapping("list") public void list() { // nothing to do } @RequestMapping("details") @ResponseBody public JsonResult details(RepositoryWorkbookQuery query, Page page) { JsonResult result = new JsonResult(); page.setPageSize(12); List<WorkbookRepositoryRecord> records = lekeWorkbookQueryService.queryLekeWorkbooks(query, page); result.addDatas("records", records); result.addDatas("page", page); return result; } }
true
1c41b16b128fbe04654691c023c3142bdef144e1
Java
PhenomenX/ChatSpring
/src/main/java/com/epam/chatspring/config/ApplicationContextConfig.java
UTF-8
2,764
1.945313
2
[]
no_license
package com.epam.chatspring.config; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.core.io.FileSystemResource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.support.StandardServletMultipartResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import com.epam.chatspring.dao.MessageDAO; import com.epam.chatspring.dao.UserDAO; import com.epam.chatspring.dao.oracledb.OracleMessageDAO; import com.epam.chatspring.dao.oracledb.OracleUserDAO; import com.epam.chatspring.model.User; @Configuration @ComponentScan("com.epam.chatspring.*") public class ApplicationContextConfig { @Bean(name = "multipartResolver") public MultipartResolver getMultipartResolver() { StandardServletMultipartResolver resolver = new StandardServletMultipartResolver(); return resolver; } @Bean public FileSystemResource imageResource() { return new FileSystemResource("D://images//"); } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.ENGLISH); return slr; } @Bean public DataSource myOracleDataSource() { Locale.setDefault(Locale.ENGLISH); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver"); dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:XE"); dataSource.setUsername("SYSTEM"); dataSource.setPassword("zver12"); return dataSource; } @Bean public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(myOracleDataSource()); } @Bean(name = "userDAO") public UserDAO userDAO() { UserDAO userDAO = new OracleUserDAO(); return userDAO; } @Bean(value = "messageDAO") public MessageDAO getMessageDAO() { MessageDAO messageDAO = new OracleMessageDAO(); return messageDAO; } @Bean @Scope("Singleton") public Map<String, User> onlineUsers() { return new HashMap<String, User>(); } @Bean(name = "currentUser") @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public User currentUser() { return new User(); } }
true
f05b89c8123f1e61ea123bf38d00081aa650aba2
Java
chenyi136/leetcode
/IdeaProjects/leetcode/src/FractionToRecuringDecimal.java
UTF-8
986
3.046875
3
[]
no_license
import java.util.HashMap; import java.util.Map; /** * @ClassNameFractionToRecuringDecimal * @Author jianwen * @Date 19-11-2 下午8:55 * @Version V1.0 */ public class FractionToRecuringDecimal { public String fractionToDecimal(int numerator, int denominator){ if(numerator==0) return "0"; StringBuilder builder=new StringBuilder(); if((numerator<0)^(numerator<0)){ builder.append("-"); } long n=Math.abs((long)numerator); long d=Math.abs((long)denominator); builder.append((n/d)); if((n%d==0)) return builder.toString(); builder.append("."); Map<Long,Integer> numerators=new HashMap<>(); while(!numerators.containsKey(n)){ numerators.put(n,builder.length()); n*=10; builder.append(n/d); if((n%d)==0) return builder.toString(); } return builder.insert(numerators.get(n),"(").append(")").toString(); } }
true
bbe639d16330b505a42400f791461a8df1f7e184
Java
kshine/demo
/test/src/main/java/com/freedom/okhttp/Demo01.java
UTF-8
2,196
2.234375
2
[]
no_license
package com.freedom.okhttp; import com.freedom.util.HttpUtils; import com.google.gson.Gson; import okhttp3.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Created by kuiyuxiang on 2017/4/14. * 商用域地址:211.138.118.14:1100 * Host:aep.api.cmccopen.cn * * 测试域地址:211.138.118.15:1100 * Host:aep.test.api.cmccopen.cn * * App标识 * 889890ad6f9844b1929e65a4c376656a * * App密钥 * 3b7f06fb3ec9991f * * * 476affecfe1a48dc9c78b7f7ad01cb71 * da7e1886f2d07cbe */ public class Demo01 { public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public static void main(String[] args) throws IOException { String appSign = "889890ad6f9844b1929e65a4c376656a"; String appKey = "3b7f06fb3ec9991f"; Map<String,String> headersMap = HttpUtils.getHeaders(appSign,appKey); String url = "http://211.138.118.14:1100/callshine/qryUserCondition/v1"; Headers headers =new Headers.Builder() .add("Host","aep.api.cmccopen.cn") .add("Authorization",headersMap.get("Authorization")) .add("X-WSSE",headersMap.get("X-WSSE")) .add("Content-Type",headersMap.get("Content-Type")) .build(); Gson gson = new Gson(); Map<String,String> map = new HashMap<String,String>(); map.put("msisdn", "15168598761"); map.put("subTitle","001"); String json =gson.toJson(map); RequestBody body = RequestBody.create(JSON, json); System.out.println(body); // RequestBody formBody = new FormBody.Builder() // .add("msisdn", "15168598761") // .add("subTitle","001") // .build(); final OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(url) .headers(headers) .post(body) .build(); Response response = okHttpClient.newCall(request).execute(); //code description System.out.println(response); System.out.println(response.headers()); } }
true
3b44580266f6cb3064b78dfdb0123ef7ae59c658
Java
Ritesh-krr/hacktoberfest2020
/GraphPath.java
UTF-8
3,366
3.171875
3
[]
no_license
import java.util.Scanner; import java.util.ArrayList; import java.io.File; import java.io.PrintStream; class GraphPath{ static Scanner sc; public static void main(String args[]){ try{ File file = new File("C:\\Users\\Tanisha\\Desktop\\inputGraph2.txt"); sc = new Scanner(file); } catch(Exception e){ System.out.println("Error"); System.out.println(e.getMessage()); } String initialInfo; if(sc.hasNextLine()) initialInfo = sc.next(); else initialInfo = ""; String[] arr = initialInfo.split(","); int n = Integer.parseInt(arr[0]); ArrayList<Integer>[] graph = new ArrayList[n]; for(int i=0; i<n; i++) { graph[i] = new ArrayList<>(); } sc.next(); if(arr[1].equals("u")){ while (sc.hasNext()){ String s = sc.next(); String[] arr1 = s.split(","); if(!sc.hasNext()) { boolean[] vis = new boolean[graph.length]; try{ PrintStream ps = new PrintStream(new File("out2.txt")); PrintStream console = System.out; System.setOut(ps); System.out.println((hasPath((Integer.parseInt(arr1[0])),(Integer.parseInt(arr1[arr1.length-1])),vis,"",graph)?1:0 +" ")); } catch(Exception e){ System.out.println(e.getMessage()); } } graph[Integer.parseInt(arr1[0])-1].add(Integer.parseInt(arr1[1])); graph[Integer.parseInt(arr1[1])-1].add(Integer.parseInt(arr1[0])); } } else if(arr[1].equals("d")){ while (sc.hasNext()){ String s = sc.next(); String[] arr1 = s.split(","); if(!sc.hasNext()) { boolean[] vis = new boolean[graph.length]; try{ PrintStream ps = new PrintStream(new File("graph_Path_out.txt")); PrintStream console = System.out; System.setOut(ps); System.out.println((hasPath((Integer.parseInt(arr1[0])),(Integer.parseInt(arr1[arr1.length-1])),vis,"",graph)?1:0 +" ")); } catch(Exception e){ System.out.println(e.getMessage()); } } graph[Integer.parseInt(arr1[0])-1] .add(Integer.parseInt(arr1[1])); } } //System.out.println(hasPath(1,4,vis,"",graph)); } public static boolean hasPath(int src, int desti, boolean[] vis, String ans, ArrayList<Integer>[] graph) { if (src == desti){ //System.out.println(ans + " " + desti); return true; } vis[src] = true; boolean res = false; for (int edge : graph[src]){ if (!vis[edge]) res = res || hasPath(edge, desti, vis, ans + src + " ", graph); } return res; } }
true
d926ea1021bc53100aea984bf7f100cff6b6ce9a
Java
xiongxcodes/haohope-security-oauth
/haohope-oauth/src/main/java/org/minbox/framework/oauth/response/DefaultAuthorizationDeniedResponse.java
UTF-8
1,136
2.1875
2
[ "Apache-2.0" ]
permissive
package org.minbox.framework.oauth.response; import com.fasterxml.jackson.core.JsonGenerator; import org.minbox.framework.oauth.exception.OAuth2Exception; import org.springframework.http.HttpStatus; import org.springframework.web.util.HtmlUtils; /** * The default {@link AuthorizationDeniedResponse} support * Provide default OAuth2Exception exception response content * * @author 恒宇少年 * @see org.minbox.framework.oauth.translator.WebResponseExceptionTranslator * @see org.minbox.framework.oauth.exception.OAuth2Exception */ public class DefaultAuthorizationDeniedResponse implements AuthorizationDeniedResponse { @Override public void serializeResponse(OAuth2Exception e, JsonGenerator generator) { try { String message = e.getMessage(); if (message != null) { message = HtmlUtils.htmlEscape(message); } generator.writeObjectField("errorMessage", message); generator.writeObjectField("errorCode", HttpStatus.UNAUTHORIZED.getReasonPhrase()); } catch (Exception ex) { ex.printStackTrace(); } } }
true
e2ac887fc1b7a8318b304ee18dac92551a27aa0c
Java
AhmedSobhy93/TaskManager
/src/com/beans/TaskBean.java
UTF-8
1,263
2.359375
2
[]
no_license
package com.beans; public class TaskBean { private int taskID; private String projectName; private int owner; private String title; private String comment; private String dateInserted; private String generatedTaskId; public String getGeneratedTaskId() { return generatedTaskId; } public void setGeneratedTaskId(String generatedtaskId) { this.generatedTaskId = generatedtaskId; } public int getTaskID() { return taskID; } public void setTaskID(int taskID) { this.taskID = taskID; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public int getOwner() { return owner; } public void setOwner(int owner) { this.owner = owner; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String toString(){ return taskID +"-"+owner; } public String getDateInserted() { return dateInserted; } public void setDateInserted(String dateInserted) { this.dateInserted = dateInserted; } }
true
b71f80f078ec83769ec4a1f419a5ccb06b0512e1
Java
GitHub-Zlg/yangquan
/app/src/main/java/app/com/yangquan/adapter/TagSelectAdapter.java
UTF-8
1,048
2.40625
2
[]
no_license
package app.com.yangquan.adapter; import android.view.View; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import app.com.yangquan.R; public class TagSelectAdapter extends BaseQuickAdapter<String> { public TagSelectAdapter() { super(R.layout.item_tag_select, null); } @Override protected void convert(BaseViewHolder holder, String s) { holder.setText(R.id.tv_tag,s); holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener!=null){ listener.onDeleteClick(s,holder.getAdapterPosition()); } } }); } public interface TagDeleteClickListener{ void onDeleteClick(String tag,int position); } public TagDeleteClickListener listener; public void setOnTagDeleteClickListener(TagDeleteClickListener linsener){ this.listener = linsener; } }
true
be2074642f0a3bea1caac73a020d64b9213adfbc
Java
LiamCoffey1/Algorithms
/src/GenericStack.java
UTF-8
813
3.421875
3
[]
no_license
import java.util.ArrayList; public class GenericStack<Type> { int maxSize; ArrayList<Type> elements; public GenericStack(int maxSize) { this.maxSize = maxSize; elements = new ArrayList<Type>(); } public int size() { return elements.size(); } public Type pop() { if(isEmpty()) return null; Type element = elements.get(elements.size() - 1); elements.remove(element); return element; } public Type peek() { if(isEmpty()) return null; Type element = elements.get(elements.size() - 1); return element; } public void push(Type element) { if(!isFull()) elements.add(element); else throw new IndexOutOfBoundsException(); } public boolean isFull() { return elements.size() == maxSize; } public boolean isEmpty() { return elements.size() == 0; } }
true
31e316d26f81a5b12a36cd62c768eca86de35ef6
Java
DotOS/android_frameworks_base
/packages/CarSystemUI/tests/src/com/android/systemui/car/navigationbar/ButtonRoleHolderControllerTest.java
UTF-8
7,776
1.679688
2
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.car.navigationbar; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import android.app.role.RoleManager; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.UserHandle; import android.testing.AndroidTestingRunner; import android.testing.TestableLooper; import android.view.LayoutInflater; import android.widget.LinearLayout; import androidx.test.filters.SmallTest; import com.android.systemui.SysuiTestCase; import com.android.systemui.car.CarDeviceProvisionedController; import com.android.systemui.car.CarSystemUiTest; import com.android.systemui.tests.R; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.List; @CarSystemUiTest @RunWith(AndroidTestingRunner.class) @TestableLooper.RunWithLooper @SmallTest public class ButtonRoleHolderControllerTest extends SysuiTestCase { private static final String TEST_VALID_PACKAGE_NAME = "foo"; private static final String TEST_INVALID_PACKAGE_NAME = "bar"; private static final UserHandle TEST_CURRENT_USER = UserHandle.of(100); private static final UserHandle TEST_NON_CURRENT_USER = UserHandle.of(101); private LinearLayout mTestView; private CarNavigationButton mNavButtonDefaultAppIconForRoleWithEnabled; private CarNavigationButton mNavButtonDefaultAppIconForRoleWithDisabled; private ButtonRoleHolderController mControllerUnderTest; private Drawable mAppIcon; @Mock private RoleManager mRoleManager; @Mock private CarDeviceProvisionedController mDeviceProvisionedController; @Mock private PackageManager mPackageManager; @Mock private ApplicationInfo mApplicationInfo; @Before public void setUp() throws PackageManager.NameNotFoundException { MockitoAnnotations.initMocks(this); mTestView = (LinearLayout) LayoutInflater.from(mContext).inflate( R.layout.button_role_holder_controller_test, /* root= */ null); mNavButtonDefaultAppIconForRoleWithEnabled = mTestView .findViewById(R.id.assistant_role_button); mNavButtonDefaultAppIconForRoleWithDisabled = mTestView .findViewById(R.id.assistant_role_disabled_button); mAppIcon = mContext.getDrawable(R.drawable.car_ic_apps); when(mApplicationInfo.loadIcon(any())).thenReturn(mAppIcon); doThrow(new PackageManager.NameNotFoundException()).when(mPackageManager) .getApplicationInfo(any(), anyInt()); doReturn(mApplicationInfo).when(mPackageManager) .getApplicationInfo(eq(TEST_VALID_PACKAGE_NAME), anyInt()); when(mDeviceProvisionedController .getCurrentUser()) .thenReturn(TEST_CURRENT_USER.getIdentifier()); mControllerUnderTest = new ButtonRoleHolderController(mContext, mPackageManager, mRoleManager, mDeviceProvisionedController); } @Test public void addAllButtonsWithRoleName_roleAssigned_appIconEnabled_useAssignedAppIcon() { when(mRoleManager.getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(List.of(TEST_VALID_PACKAGE_NAME)); mControllerUnderTest.addAllButtonsWithRoleName(mTestView); assertThat(mNavButtonDefaultAppIconForRoleWithEnabled.getAppIcon()).isEqualTo(mAppIcon); } @Test public void addAllButtonsWithRoleName_roleUnassigned_appIconEnabled_useDefaultIcon() { when(mRoleManager.getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(null); mControllerUnderTest.addAllButtonsWithRoleName(mTestView); assertThat(mNavButtonDefaultAppIconForRoleWithEnabled.getAppIcon()).isNull(); } @Test public void onRoleChanged_currentUser_appIconEnabled_useAssignedAppIcon() { when(mRoleManager.getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(null); mControllerUnderTest.addAllButtonsWithRoleName(mTestView); when(mRoleManager .getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(List.of(TEST_VALID_PACKAGE_NAME)); mControllerUnderTest.onRoleChanged(RoleManager.ROLE_ASSISTANT, TEST_CURRENT_USER); assertThat(mNavButtonDefaultAppIconForRoleWithEnabled.getAppIcon()).isEqualTo(mAppIcon); } @Test public void onRoleChanged_nonCurrentUser_appIconEnabled_iconIsNotUpdated() { when(mRoleManager .getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(null); mControllerUnderTest.addAllButtonsWithRoleName(mTestView); Drawable beforeIcon = mNavButtonDefaultAppIconForRoleWithEnabled.getAppIcon(); when(mRoleManager .getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(List.of(TEST_VALID_PACKAGE_NAME)); mControllerUnderTest.onRoleChanged(RoleManager.ROLE_ASSISTANT, TEST_NON_CURRENT_USER); Drawable afterIcon = mNavButtonDefaultAppIconForRoleWithEnabled.getAppIcon(); assertThat(afterIcon).isEqualTo(beforeIcon); } @Test public void onRoleChanged_invalidPackage_useDefaultIcon() { when(mRoleManager .getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(List.of(TEST_INVALID_PACKAGE_NAME)); mControllerUnderTest.addAllButtonsWithRoleName(mTestView); assertThat(mNavButtonDefaultAppIconForRoleWithEnabled.getAppIcon()).isNull(); } @Test public void addAllButtonsWithRoleName_appIconDisabled_useDefaultIcon() { when(mRoleManager .getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(List.of(TEST_VALID_PACKAGE_NAME)); mControllerUnderTest.addAllButtonsWithRoleName(mTestView); assertThat(mNavButtonDefaultAppIconForRoleWithDisabled.getAppIcon()).isNull(); } @Test public void onRoleChanged_roleAssigned_appIconDisabled_useDefaultIcon() { when(mRoleManager .getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(null); mControllerUnderTest.addAllButtonsWithRoleName(mTestView); assertThat(mNavButtonDefaultAppIconForRoleWithDisabled.getAppIcon()).isNull(); when(mRoleManager .getRoleHoldersAsUser(eq(RoleManager.ROLE_ASSISTANT), any())) .thenReturn(List.of(TEST_VALID_PACKAGE_NAME)); mControllerUnderTest.onRoleChanged(RoleManager.ROLE_ASSISTANT, TEST_CURRENT_USER); assertThat(mNavButtonDefaultAppIconForRoleWithDisabled.getAppIcon()).isNull(); } }
true
0b1c3e00586a62507473fc66dfbd49da9e9ae9be
Java
ievans3024/bosrewards
/src/ievans3024/bosrewards/main/Messages.java
UTF-8
2,151
2.6875
3
[]
no_license
package ievans3024.bosrewards.main; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; public final class Messages { // colors public static final String COLOR_BAD = ChatColor.RED + "" + ChatColor.ITALIC; public static final String COLOR_SYNTAX_ERROR = ChatColor.DARK_AQUA + "" + ChatColor.ITALIC; public static final String COLOR_SUCCESS = ChatColor.RESET + "" + ChatColor.GREEN; public static final String COLOR_INFO = ChatColor.RESET + "" + ChatColor.GRAY; // "bad" messages public static final String NO_CONSOLE = COLOR_BAD + "Console can't use this subcommand"; public static final String NO_PERMISSION = COLOR_BAD + "You do not have permission to use this"; public static void sendNoPermsError(CommandSender sender) { if (sender instanceof ConsoleCommandSender) { sender.sendMessage(NO_CONSOLE); } else if (sender instanceof Player){ sender.sendMessage(NO_PERMISSION); } } // "syntax error" messages public static final String[] NOT_A_SUBCMD = { COLOR_SYNTAX_ERROR + "That subcommand does not exist", COLOR_SYNTAX_ERROR + "Try /rewards help for a list of subcommands" }; public static final String[] NOT_A_REWARD = { COLOR_SYNTAX_ERROR + "That reward does not exist!", COLOR_SYNTAX_ERROR + "Find the reward ID by typing /rewards list" }; public static final String[] NOT_ENOUGH_ARGS = { COLOR_SYNTAX_ERROR + "Not enough arguments for that command", COLOR_SYNTAX_ERROR + "Try /rewards help <command> for more info" }; public static final String INVALID_ARGUMENT = COLOR_SYNTAX_ERROR + "Invalid argument: "; // "success" messages public static final String SUCCESS_ADD = COLOR_SUCCESS + "Added reward "; public static final String SUCCESS_REMOVE = COLOR_SUCCESS + "Removed reward "; public static final String SUCCESS_EDIT = COLOR_SUCCESS + "Edited reward "; // "fail" messages public static final String FAIL_REDEEM_NEGCOST = COLOR_BAD + "This reward is disabled."; public static final String FAIL_REDEEM_NOPERM = COLOR_BAD + "You do not have permission to get this reward."; }
true
4c50f1fa745038b8f68822a81ab47d3b9b88ce1e
Java
squirlemaster42/Fantasy-FRC
/Libs/spreadsheet-2.0.1/vaadin-spreadsheet/src/test/java/com/vaadin/addon/spreadsheet/test/demoapps/TouchUI.java
UTF-8
648
2
2
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
package com.vaadin.addon.spreadsheet.test.demoapps; import com.vaadin.addon.spreadsheet.Spreadsheet; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Viewport; import com.vaadin.annotations.Widgetset; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.UI; @Viewport("width=device-width, initial-scale=1") @Theme("demo") @Widgetset("com.vaadin.addon.spreadsheet.Widgetset") public class TouchUI extends UI { @Override protected void init(VaadinRequest request) { Spreadsheet ss = new Spreadsheet(); ss.reset(); setContent(ss); ss.setSizeFull(); setSizeFull(); } }
true
60f6b4037a876e010d5106c9d337a28dd1502d09
Java
kakacordovil/javabank
/src/main/java/org/academiadecodigo/javabank/services/mock/MockAccountService.java
UTF-8
3,385
2.75
3
[]
no_license
package org.academiadecodigo.javabank.services.mock; import org.academiadecodigo.javabank.exceptions.AccountNotFoundException; import org.academiadecodigo.javabank.exceptions.CustomerNotFoundException; import org.academiadecodigo.javabank.exceptions.TransactionInvalidException; import org.academiadecodigo.javabank.persistence.model.Customer; import org.academiadecodigo.javabank.persistence.model.account.Account; import org.academiadecodigo.javabank.persistence.model.account.SavingsAccount; import org.academiadecodigo.javabank.services.AccountService; import org.academiadecodigo.javabank.services.CustomerService; import java.util.Optional; /** * A mock {@link AccountService} implementation */ public class MockAccountService extends AbstractMockService<Account> implements AccountService { private CustomerService customerService; /** * Sets the customer service * * @param customerService the customer service to set */ public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } /** * @see AccountService#get(Integer) */ @Override public Account get(Integer id) { return modelMap.get(id); } /** * @see AccountService#deposit(Integer, Integer, double) */ @Override public void deposit(Integer id, Integer customerId, double amount) throws CustomerNotFoundException, AccountNotFoundException, TransactionInvalidException { Customer customer = Optional.ofNullable(customerService.get(customerId)) .orElseThrow(CustomerNotFoundException::new); Account account = Optional.ofNullable(modelMap.get(id)) .orElseThrow(AccountNotFoundException::new); if (!account.getCustomer().getId().equals(customerId)) { throw new AccountNotFoundException(); } if (!account.canCredit(amount)) { throw new TransactionInvalidException(); } for (Account a : customer.getAccounts()) { if (a.getId().equals(id)) { a.credit(amount); } } account.credit(amount); } /** * @see AccountService#withdraw(Integer, Integer, double) */ @Override public void withdraw(Integer id, Integer customerId, double amount) throws CustomerNotFoundException, AccountNotFoundException, TransactionInvalidException { Customer customer = Optional.ofNullable(customerService.get(customerId)) .orElseThrow(CustomerNotFoundException::new); Account account = Optional.ofNullable(get(id)) .orElseThrow(AccountNotFoundException::new); if (!account.getCustomer().getId().equals(customerId)) { throw new AccountNotFoundException(); } // in UI the user cannot click on Withdraw so this is here just for safety if (account instanceof SavingsAccount) { throw new TransactionInvalidException(); } // make sure transaction can be performed if (!account.canDebit(amount)) { throw new TransactionInvalidException(); } for (Account a : customer.getAccounts()) { if (a.getId().equals(id)) { a.debit(amount); } } account.debit(amount); } }
true
13d9f284e5a223b869de9949032cd583b6e8f4e0
Java
LarsDietrich/eventmanager
/src/com/anudeep/eventmanager/activity/ListTicketsActivity.java
UTF-8
2,630
2.140625
2
[]
no_license
package com.anudeep.eventmanager.activity; import com.anudeep.eventmanager.R; import com.anudeep.eventmanager.dao.EventDao; import com.anudeep.eventmanager.dao.TicketDao; import com.anudeep.eventmanager.model.Event; import com.anudeep.eventmanager.model.Ticket; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.AdapterView.AdapterContextMenuInfo; public class ListTicketsActivity extends ListActivity { private static final int DELETE_ID = Menu.FIRST; private TicketDao ticketDao; private Long mEventId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tickets_list); ticketDao = new TicketDao(this); ticketDao.open(); Bundle extras = getIntent().getExtras(); mEventId = extras != null ? extras.getLong(EventDao.KEY_EVENT_ID) : null; fillData(); registerForContextMenu(getListView()); } private void fillData(){ Cursor cursor = ticketDao.fetchTickets(mEventId); startManagingCursor(cursor); String[] from = new String[]{TicketDao.KEY_TICKET_ID, TicketDao.KEY_TICKET_STATE }; int[] to = new int[]{R.id.ticketIdText,R.id.stateText}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.tickets_row, cursor, from, to); // ArrayAdapter<Ticket> adapter = new ArrayAdapter<Ticket>(this, // android.R.layout.simple_list_item_1, ticketDao.getTickets(mEventId)); setListAdapter(adapter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0,DELETE_ID,0,R.string.menu_delete_ticket); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { switch(item.getItemId()) { case DELETE_ID: AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); ticketDao.deleteTicket(info.id); fillData(); return true; } return super.onContextItemSelected(item); }; @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Intent i = new Intent(this, ShowTicket.class); i.putExtra(TicketDao.KEY_TICKET_ID, id); i.putExtra(TicketDao.KEY_TICKET_EVENT_ID, mEventId); startActivity(i); } }
true
f950e4ba0229776e87b9c95d57db1dae5c5a6ee5
Java
zhiyuan4j/mahjong-zj
/src/main/java/red/zhiyuan/mahjongzj/MahjongZjApplication.java
UTF-8
332
1.554688
2
[]
no_license
package red.zhiyuan.mahjongzj; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MahjongZjApplication { public static void main(String[] args) { SpringApplication.run(MahjongZjApplication.class, args); } }
true
d22133cd50b8bd72b833bacd86e12d17bb6f88cc
Java
kricen/tennis
/src/main/java/com/tennis/util/wechat/TemplateUtil.java
UTF-8
2,976
1.976563
2
[]
no_license
package com.tennis.util.wechat; import com.tennis.handler.wechat.AccessTokenHandler; import com.tennis.model.db.Match; import com.tennis.model.db.User; import com.tennis.model.wechat.TemplateData; import com.tennis.model.wechat.TemplateMessage; import com.tennis.util.common.CommonUtil; import com.tennis.util.common.DateUtil; import net.sf.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * All rights Reserved, Designed By lixiao * Copyright (c) 2017 by Shanghai lixiao * * @PROJECT_NAME: tennis * @author: lixiao * @version: V1.0 * @Date: 2017/4/24 * @Description: */ public class TemplateUtil { public static void sendResultTemplate(Match match, User user, String formId) { TemplateMessage templateMessage = new TemplateMessage(); templateMessage.setTouser(user.getOpenid()); templateMessage.setTemplate_id("qgse1mxX0CH7-3-jWUxjVIS4mEiZjLIOQJAkoA4Izpk"); templateMessage.setForm_id(formId); templateMessage.setPage("/pages/self/self"); Map<String, TemplateData> m = new HashMap<String, TemplateData>(); //比赛比分 TemplateData keyword1; //比赛地址 TemplateData keyword2 = new TemplateData(); keyword2.setColor("#173177"); keyword2.setValue(match.getMatchAddr()); //比赛时间 TemplateData keyword3 = new TemplateData(); keyword3.setColor("#173177"); keyword3.setValue(DateUtil.getStringDate(DateUtil.TimestampToDate(match.getStartTime()), DateUtil.DATE_YY_MM_DD)); //备注 TemplateData keyword4; if (match.getChallengeMainUser().equals(user.getId()) || match.getChallengeMinUser().equals(user.getId())) { keyword1 = new TemplateData(); keyword1.setColor("#173177"); keyword1.setValue(match.getChallengeScore() + ":" + match.getDefenderScore()); } else { keyword1 = new TemplateData(); keyword1.setColor("#173177"); keyword1.setValue(match.getDefenderScore() + ":" + match.getChallengeScore()); } keyword4 = new TemplateData(); keyword4.setColor("#173177"); keyword4.setValue("对方已经填写比赛成绩,请注意查看,如你在完成后七天未填写比赛成绩,以对方填写的比赛为主!"); m.put("keyword1", keyword1); m.put("keyword2", keyword2); m.put("keyword3", keyword3); m.put("keyword4", keyword4); templateMessage.setData(m); String templage_message = JSONObject.fromObject(templateMessage).toString(); String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN"; url = url.replace("ACCESS_TOKEN", AccessTokenHandler.getAccessToken()); JSONObject postStr = CommonUtil.httpsRequest(url, "POST", templage_message); System.out.println("==============="); System.out.println(user.getOpenid()); System.out.println(">>>>>>>>>>>>>>>>"); System.out.println(formId); System.out.println(">>>>>>>>>>>>>>>>"); System.out.println(postStr); System.out.println("==============="); } public void sendGameAnnounce(Match match, User user) { } }
true
a41f58444d8b4040b73c6f569c9783e6987b8243
Java
zyjiahui/Myjava
/reStudyJava/src/cn/jiahui/IO/ZiJieShuZuOutput.java
UTF-8
1,156
3.453125
3
[]
no_license
package cn.jiahui.IO; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * 字节数组输出流(4步)ByteArrayOutputStream * 1、创建源:内部维护 * 2、选择流:不关联源 * 3、操作(写出操作) * 4、释放资源:可以不用 * * 增加:获取数据 toByteArray();方法获取 * * */ public class ZiJieShuZuOutput { public static void main(String[] args) { //创建源 byte[] dest = null; //选择流 ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); String msg = "show your code"; byte[] datas = msg.getBytes(); baos.write(datas,0,datas.length); baos.flush(); //获取数据 dest = baos.toByteArray(); System.out.println(dest.length + "-->"+new String(dest,0,baos.size())); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { } } }
true
f1f5ff0342725d6dc9714d6591831061d711d83a
Java
shinhermit/Projet-SD-M1
/src/communication/ReliabilitySetting.java
UTF-8
3,711
2.984375
3
[]
no_license
/* Coyright Eric Cariou, 2009 - 2011 */ package communication; /** * Set the reliabily settings for a communication element. */ public class ReliabilitySetting { /** * Precise if debug information, concerning message lost and transmission delays, * must be printed on standard output */ private boolean reliable = true; private FaultLevel packetLostLevel = FaultLevel.NONE; private FaultLevel transmissionDelayLowerBound = FaultLevel.NONE; private FaultLevel transmissionDelayUpperBound = FaultLevel.NONE; private FaultLevel crashLevel = FaultLevel.NONE; private boolean debugFault = false; public boolean isDebugFault() { return debugFault; } public FaultLevel getPacketLostLevel() { return packetLostLevel; } public boolean isReliable() { return reliable; } public FaultLevel getTransmissionDelayLowerBound() { return transmissionDelayLowerBound; } public FaultLevel getTransmissionDelayUpperBound() { return transmissionDelayUpperBound; } public FaultLevel getCrashLevel() { return crashLevel; } /** * @param reliable the reliable to set */ public void setReliable(boolean reliable) { this.reliable = reliable; } /** * @param packetLostLevel the packetLostLevel to set */ public void setPacketLostLevel(FaultLevel packetLostLevel) { this.packetLostLevel = packetLostLevel; } /** * @param transmissionDelayLowerBound the transmissionDelayLowerBound to set */ public void setTransmissionDelayLowerBound(FaultLevel transmissionDelayLowerBound) { this.transmissionDelayLowerBound = transmissionDelayLowerBound; } /** * @param transmissionDelayUpperBound the transmissionDelayUpperBound to set */ public void setTransmissionDelayUpperBound(FaultLevel transmissionDelayUpperBound) { this.transmissionDelayUpperBound = transmissionDelayUpperBound; } /** * @param crashLevel the crashLevel to set */ public void setCrashLevel(FaultLevel crashLevel) { this.crashLevel = crashLevel; } /** * @param debugFault the debugFault to set */ public void setDebugFault(boolean debugFault) { this.debugFault = debugFault; } /** * Create a set of reliabily values for a communication element * @param reliable reliabily (information on packet losts when sending messages) of the communication * @param packetLostLevel level of lost of packet send through the network * @param transmissionDelayLowerBound level of the minimum delay for a message to join the receiver element * @param transmissionDelayUpperBound level of the minimum delay for a message to join the receiver element * @param crashLevel level of process crash * @param debugFault precise if debug information, concerning message lost and transmission delays, * must be printed on standard output */ public ReliabilitySetting(boolean reliable, FaultLevel packetLostLevel, FaultLevel transmissionDelayLowerBound, FaultLevel transmissionDelayUpperBound, FaultLevel crashLevel, boolean debugFault) { this.reliable = reliable; this.packetLostLevel = packetLostLevel; this.transmissionDelayLowerBound = transmissionDelayLowerBound; this.transmissionDelayUpperBound = transmissionDelayUpperBound; this.crashLevel = crashLevel; this.debugFault = debugFault; } /** * Create a set of reliability values for a communication with default value (no error). */ public ReliabilitySetting() { } }
true
e4aad3f5b7226ecae512110b188418847f306cd0
Java
Imperio-Inka/SO-Android
/app/src/main/java/com/android/showmeeapp/util/MeteorOAuthServices.java
UTF-8
1,618
2.0625
2
[]
no_license
package com.android.showmeeapp.util; import android.util.Base64; import java.nio.charset.Charset; /** * Created by kushahuja on 6/15/16. */ public class MeteorOAuthServices { public static String google(String clientId) { String token = "YCE4ggWJ0n7h7ZnEOHCxSAoJDjqqCOaAYNq3x5hVpBJpNkZX8bCJYQLu4jZzSjEB"; // String httpUrl = getHttpUrl(); // String redirect = httpUrl+"/_oauth/google"; String redirect = "https://www.loopcowstudio.com" + "/_oauth/google"; String state = stateParam(token, redirect); String scope = "email+https://www.googleapis.com/auth/calendar"; // String scope = "email"; String url = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=22026107675-jfeoijhr5qlpvds0v0dtlvpsv8njsioq.apps.googleusercontent.com"; url += "&approval_prompt=force"; url += "&access_type=offline"; url += "&redirect_uri=" + redirect; url += "&scope=" + scope; url += "&state=" + state; return url; } private static String stateParam(String credentialToken, String redirectUrl) { String objectString = "{\"redirectUrl\":\"" + redirectUrl + "\",\"loginStyle\":\"redirect\",\"isCordova\":\"false\",\"credentialToken\":\"" + credentialToken + "\"}"; return toBase64(objectString); } private static String toBase64(String str) { byte[] bytesEncoded = Base64.encode(str.getBytes(), Base64.DEFAULT); return new String(bytesEncoded, Charset.forName("UTF-8")); } public static String getHttpUrl() { String httpUrl = "https://www.loopcowstudio.com"; return httpUrl; } }
true
3de4389b84345528674b21ef3bf6b4a064c2da6c
Java
reed07/MyPreferencePal
/jadx-MFP/src/main/java/com/myfitnesspal/feature/addentry/ui/dialog/SearchViewItemContextualDialog.java
UTF-8
5,039
1.8125
2
[]
no_license
package com.myfitnesspal.feature.addentry.ui.dialog; import android.app.Dialog; import android.os.Bundle; import android.view.ContextThemeWrapper; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import com.myfitnesspal.android.R; import com.myfitnesspal.shared.constants.Constants.Extras; import com.myfitnesspal.shared.model.v1.Food; import com.myfitnesspal.shared.service.foods.FoodService; import com.myfitnesspal.shared.ui.dialog.CustomLayoutBaseDialogFragment; import com.myfitnesspal.shared.ui.dialog.DialogListTextResItem; import com.myfitnesspal.shared.ui.dialog.MfpAlertDialogBuilder; import java.util.ArrayList; import javax.inject.Inject; public class SearchViewItemContextualDialog extends CustomLayoutBaseDialogFragment { @Inject FoodService foodService; public static SearchViewItemContextualDialog newInstance(long j, Food food, boolean z) { SearchViewItemContextualDialog searchViewItemContextualDialog = new SearchViewItemContextualDialog(); Bundle bundle = new Bundle(); bundle.putLong("food_master_id", food.getMasterDatabaseId()); bundle.putString("food_uid", food.getUid()); bundle.putBoolean(Extras.FOOD_HAS_MASTER_ID, food.hasMasterDatabaseId()); bundle.putLong(Extras.FOOD_ORIGINAL_MASTER_ID, food.getOriginalMasterId()); bundle.putString(Extras.FOOD_ORIGINAL_UID, food.getOriginalUid()); bundle.putBoolean(Extras.HIDE_WHEN_DELETED, z); bundle.putLong("food_local_id", food.getLocalId()); bundle.putLong("meal_id", j); bundle.putLong(Extras.FOOD_ORIGINAL_ID, food.getOriginalId()); searchViewItemContextualDialog.setArguments(bundle); return searchViewItemContextualDialog; } public Dialog onCreateDialog(Bundle bundle) { component().inject(this); Bundle arguments = getArguments(); long j = arguments.getLong("food_master_id"); String string = arguments.getString("food_uid"); boolean z = arguments.getBoolean(Extras.FOOD_HAS_MASTER_ID); long j2 = arguments.getLong(Extras.FOOD_ORIGINAL_MASTER_ID); String string2 = arguments.getString(Extras.FOOD_ORIGINAL_UID); boolean z2 = arguments.getBoolean(Extras.HIDE_WHEN_DELETED); long j3 = arguments.getLong("food_local_id"); long j4 = arguments.getLong("meal_id"); long j5 = arguments.getLong(Extras.FOOD_ORIGINAL_ID); ContextThemeWrapper dialogContextThemeWrapper = getDialogContextThemeWrapper(); ArrayList arrayList = new ArrayList(1); arrayList.add(new DialogListTextResItem(R.string.delete)); MfpAlertDialogBuilder mfpAlertDialogBuilder = new MfpAlertDialogBuilder(dialogContextThemeWrapper); $$Lambda$SearchViewItemContextualDialog$8PP6IqbYq47mAw5erOErvXzG5Nw r20 = r1; ArrayList arrayList2 = arrayList; MfpAlertDialogBuilder mfpAlertDialogBuilder2 = mfpAlertDialogBuilder; $$Lambda$SearchViewItemContextualDialog$8PP6IqbYq47mAw5erOErvXzG5Nw r1 = new OnItemClickListener(z2, j3, z, j, string, j2, string2, j5, j4) { private final /* synthetic */ boolean f$1; private final /* synthetic */ long f$2; private final /* synthetic */ boolean f$3; private final /* synthetic */ long f$4; private final /* synthetic */ String f$5; private final /* synthetic */ long f$6; private final /* synthetic */ String f$7; private final /* synthetic */ long f$8; private final /* synthetic */ long f$9; { this.f$1 = r2; this.f$2 = r3; this.f$3 = r5; this.f$4 = r6; this.f$5 = r8; this.f$6 = r9; this.f$7 = r11; this.f$8 = r12; this.f$9 = r14; } public final void onItemClick(AdapterView adapterView, View view, int i, long j) { SearchViewItemContextualDialog.lambda$onCreateDialog$0(SearchViewItemContextualDialog.this, this.f$1, this.f$2, this.f$3, this.f$4, this.f$5, this.f$6, this.f$7, this.f$8, this.f$9, adapterView, view, i, j); } }; return mfpAlertDialogBuilder2.setItems(arrayList2, r20).create(); } public static /* synthetic */ void lambda$onCreateDialog$0(SearchViewItemContextualDialog searchViewItemContextualDialog, boolean z, long j, boolean z2, long j2, String str, long j3, String str2, long j4, long j5, AdapterView adapterView, View view, int i, long j6) { SearchViewItemContextualDialog searchViewItemContextualDialog2 = searchViewItemContextualDialog; if (i != 0) { return; } if (!z) { searchViewItemContextualDialog2.foodService.deleteFood(j, z2, j2, str, j3, str2, true, true); } else { searchViewItemContextualDialog2.foodService.hideFood(j2, str, j, j4, j3, str2, j5); } } }
true
56f47db06a042e2a76d580a9108e407b72a4e277
Java
rpmiskin/store-usage
/src/main/java/in/misk/timed/route/SlowConsumer.java
UTF-8
1,122
2.328125
2
[]
no_license
package in.misk.timed.route; import org.apache.camel.spring.SpringRouteBuilder; import org.springframework.stereotype.Component; @Component public class SlowConsumer extends SpringRouteBuilder { public static final String QUEUE = "embedded-from:a.queue"; private static final String QUEUE2 = "embedded-from:another.queue"; @Override public void configure() throws Exception { //@formatter:off onException(Exception.class) .useOriginalMessage() .log("Exception: ${body}") .handled(true) .to(QUEUE); // Slow consumer, limited to 1 message a second from(QUEUE+"?maxConcurrentConsumers=20") .log(".........SLOW") .throttle(1) .to(QUEUE2) .stop(); // Messages are sent here by the slow consumer from(QUEUE2+"?maxConcurrentConsumers=20") .throttle(1) .log("...........................QUEUE2") .stop(); //@formatter:on } }
true
b2210591f3820aab692a9268f1b3e95cd97b4644
Java
huyhue/jsp_servlet
/website/src/ducky/listeners/WebsiteSession.java
UTF-8
543
2.53125
3
[]
no_license
package ducky.listeners; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class WebsiteSession implements HttpSessionListener{ private static int numberofSession = 0; @Override public void sessionCreated(HttpSessionEvent se) { se.getSession().getServletContext().log("A new session was created " + ++numberofSession); } @Override public void sessionDestroyed(HttpSessionEvent se) { se.getSession().getServletContext().log("A session was desployed " + --numberofSession); } }
true
928b942531222f7749fce4c3fac92e5b12570e30
Java
Yunshuaiwei/Study
/2019_11_8/src/java3/NumThread.java
UTF-8
1,646
3.375
3
[]
no_license
package java3; import com.sun.media.sound.SoftTuning; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; /** * @ProjectName Study * @ClassName NumThread * Description * @Auther YunSW * @Date 2019/11/10 17:52 * @Version 1.0 **/ public class NumThread { public static void main(String[] args) { //3、创建Callable接口实现类的对象 ThreadNew threadNew = new ThreadNew(); //4、将次Callable接口实现类的对象作为参数传递到FutureTask构造器中,创建FutureTaste的对象 FutureTask task = new FutureTask(threadNew); //5、将FutureTaste的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start方法 new Thread(task).start(); try { //6、获取Callable中call的返回值 //get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值 Object o = task.get(); System.out.println("总和为"+o); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } //1、创建一个实现Callable的实现类 class ThreadNew implements Callable{ //2、实现call方法,将此线程需要的操作声明在call中 @Override public Object call() throws Exception { int sum=0; for (int i = 1; i <=100 ; i++) { System.out.println(i); sum+=i; } return sum; } }
true
268fecbe1211423fb0604addd309979f122e0b83
Java
PlayersCommittee/gemp-swccg-public
/gemp-swccg-logic/src/main/java/com/gempukku/swccgo/logic/effects/PlaceHandInUsedPileEffect.java
UTF-8
544
2.578125
3
[ "MIT" ]
permissive
package com.gempukku.swccgo.logic.effects; import com.gempukku.swccgo.logic.timing.Action; /** * An effect to put all cards from hand on Used Pile. */ public class PlaceHandInUsedPileEffect extends PutCardsFromHandOnUsedPileEffect { /** * Creates an effect that causes the player to put all cards from hand on Used Pile. * @param action the action performing this effect * @param playerId the player */ public PlaceHandInUsedPileEffect(Action action, String playerId) { super(action, playerId); } }
true
24aabc95b46f659233237e5d8f451069c7370bc4
Java
jngeiger/oop2
/JAVA_FX/src/oop2/taschenrechner_properties/Person.java
UTF-8
104
1.53125
2
[]
no_license
package oop2.taschenrechner_properties; public class Person { public String y; public int x; }
true
e45f4b5ad0af34ec77e63284974bc86f407578db
Java
jiachen1120/jiachenRepo
/InsertSort.java
UTF-8
310
3.015625
3
[]
no_license
package jiachen.algorithm; public class InsertSort { public static void sort(int[] data) { for(int x = 1; x < data.length; x++) { int current = data[x]; int y = x - 1; while(y >= 0 && data[y] >= current) { data[y + 1] = data[y]; y--; } data[y + 1] = current; } } }
true
b6b04f12780478063b98cb813ce406d6686b8699
Java
dalalsunil1986/Jvav_Dumps_OCPJP
/src/ocpjp/dumps/excteptions/Exceptions.java
UTF-8
379
2.234375
2
[]
no_license
package ocpjp.dumps.excteptions; import java.io.IOException; /** * @author Alexander_Shushunov@epam.com. */ public class Exceptions { public static void main(String[] args) { try { foo(); } // wrong // IOException - checked. // catch (IOException e){ // // } finally { } } static void foo() { } }
true
e4f884db0536302f90ae3af6fa2311ece5a6568b
Java
rakeshrana87/mektoubtools
/teachertools/web/src/main/java/org/teachertools/web/controller/EleveController.java
UTF-8
4,274
2.578125
3
[]
no_license
package org.teachertools.web.controller; import java.util.LinkedList; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.teachertools.data.Eleve; import org.teachertools.services.EleveService; import org.teachertools.services.exception.ServiceException; import org.teachertools.web.validator.EleveValidator; @Controller @RequestMapping(value = { "/eleves/*" }) public class EleveController { private static final Logger logger = Logger.getLogger(EleveController.class); @Resource private EleveService eleveService; @RequestMapping(value = { "show" }) public String searchEleves(ModelMap model, @ModelAttribute Eleve eleve) throws ServiceException { logger.debug("method searchEleves called in the controller"); List<Eleve> eleves = this.eleveService.searchByExample(eleve); if (logger.isDebugEnabled()) { logger.debug("Found " + eleves.size() + " students"); } model.addAttribute("eleves", eleves); return "eleves/show"; } @RequestMapping(value = { "ajax/show" }) public String ajaxSearchEleves(ModelMap model, @ModelAttribute Eleve eleve) throws ServiceException { logger.debug("Ajax Invocation of searchEleves"); searchEleves(model, eleve); return "eleves/results"; } @RequestMapping(value = "add", method = RequestMethod.GET) public String prepareAddEleve(ModelMap model) throws ServiceException { logger.debug("method prepareAddEleve called in the controller"); model.addAttribute("eleve", new Eleve()); return "eleves/view"; } @RequestMapping(value = "add", method = RequestMethod.POST) public String addEleve(ModelMap model, @ModelAttribute Eleve eleve, BindingResult result) throws ServiceException { logger.debug("method addEleve called in the controller"); new EleveValidator().validate(eleve, result); if (result.hasErrors()) { logger.debug("Validation has errors, no action"); return "eleves/view"; } else { this.eleveService.save(eleve); } LinkedList<String> messages = new LinkedList<String>(); messages.add("success.save"); model.addAttribute("messages", messages); return searchEleves(model, new Eleve());// getEleves(model); } @RequestMapping(value = "view/{id}", method = RequestMethod.GET) public String viewEleve(ModelMap model, @PathVariable("id") long eleveId) throws ServiceException { logger.debug("method viewEleve called in the controller"); model.addAttribute("eleve", this.eleveService.get(eleveId)); return "eleves/view"; } @RequestMapping(value = "update", method = RequestMethod.POST) public String updateEleve(ModelMap model, @ModelAttribute Eleve eleve, BindingResult result) throws ServiceException { logger.debug("method updateEleve called in the controller"); new EleveValidator().validate(eleve, result); Eleve loadedEleve = this.eleveService.get(eleve.getId()); eleve.setNotes(loadedEleve.getNotes()); this.eleveService.update(eleve); LinkedList<String> messages = new LinkedList<String>(); messages.add("success.save"); model.addAttribute("messages", messages); return viewEleve(model, eleve.getId()); } @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) public String deleteEleve(ModelMap model, @PathVariable("id") long eleveId) throws ServiceException { logger.debug("method deleteEleve called in the controller"); this.eleveService.deleteById(eleveId); return searchEleves(model, new Eleve());// getEleves(model); } }
true
1bb5dbc691004c3b35efbb36f86a21c365e68169
Java
EnduranceCode/academia-java-agenda-digital
/playground/src/pt/com/everis/academia/java/ArrayIndexOutOfBoundsException.java
UTF-8
392
2.78125
3
[]
no_license
package pt.com.everis.academia.java; import java.util.ArrayList; import java.util.List; public class ArrayIndexOutOfBoundsException { public static void main(String[] args) { List<String> myArray = new ArrayList<>(); myArray.add("Valor 001"); myArray.add("Valor 002"); myArray.add("Valor 003"); myArray.add("Valor 004"); myArray.add("Valor 005"); myArray.get(-1); } }
true
bbd7912bc681dc010a60d2490a0ccc06d642d7c9
Java
ArkilGaming/swingPaint
/Source/src/paint/FreeLine.java
UTF-8
862
2.84375
3
[]
no_license
package paint; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; public class FreeLine extends Tool { private boolean erease = false; FreeLine() { super(); } FreeLine(Point p, Color c, float s) { super(p, c, s); } public void draw(Graphics g) { var g2d = (Graphics2D)g; g2d.setStroke(new BasicStroke(this.size, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 1.0f)); g2d.setColor(this.drawHue); for (int i = 1; i < this.pnt.size(); ++i) { var x = this.pnt.elementAt(i-1).x; var y = this.pnt.elementAt(i-1).y; var x2 = this.pnt.elementAt(i).x; var y2 = this.pnt.elementAt(i).y; g2d.drawLine(x, y, x2, y2); } } public boolean getErease() { return erease; } public void setErease(boolean erease) { this.erease = erease; } }
true
84a01b623ef69357fa72ee38978f8a046942da92
Java
XCXCXCXCX/myshop-web
/divide-service/divide-api/src/main/java/com/xcxcxcxcx/myshop/dto/TopicPreFetchResponse.java
UTF-8
322
1.554688
2
[]
no_license
package com.xcxcxcxcx.myshop.dto; import com.xcxcxcxcx.service.support.core.response.AbstractResponse; /** * @author XCXCXCXCX * @date 2018/11/2 * @comments */ public class TopicPreFetchResponse extends AbstractResponse{ @Override public String toString() { return "TopicPreFetchResponse{}"; } }
true
0cdae2bb840c6d0f1d642ab48659cba2e2529415
Java
795294/APCS_Apklopp
/Labs/Lab912/Lab912a - SimpleCalc/SimpleCalc.java
UTF-8
634
3.390625
3
[]
no_license
/** * Write a description of class SimpleCalc here. * * @author (Peter Klopp) * @version (Lab912) */ public class SimpleCalc { public SimpleCalc() { } public double add(double a, double b){ return a+b; } public double subtract(double a, double b){ return a-b; } public double multiply(double a, double b){ return a*b; } public double divide(double a, double b){ if(b != 0){ return a/b; } else { return 9999999; } } public int moduloDivide(int a, int b){ return a%b; } }
true
8458a7b2c4fdaf28a64391b3dc254e5216f3605f
Java
nsimsiri/cp
/xo.java
UTF-8
2,223
3.421875
3
[]
no_license
import java.util.*; public class xo { public static class board{ String[][] bd; public board(){ bd = new String[3][3]; for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ bd[i][j]="("+(i*3+j)+")"; } } } public void print(){ for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(bd[i][j] == null ? "." : bd[i][j] + "\t|\t"); } System.out.println(); } } public void put(int x, int y, String s){ bd[x][y] = s; } public boolean winner(String s){ for(int i= 0; i<3; i++){ if (bd[0][i].equals(s)&&bd[1][i].equals(s)&&bd[2][i].equals(s)){ return true; } if (bd[i][0].equals(s)&&bd[i][1].equals(s)&&bd[i][2].equals(s)){ return true; } } return (bd[0][0].equals(s) && bd[1][1].equals(s) && bd[2][2].equals(s)) || (bd[2][0].equals(s) && bd[1][1].equals(s) && bd[0][2].equals(s)); } public boolean has(int x, int y){ return !(bd[x][y].charAt(0) == '('); } } public static void game(){ int p = 1; Scanner in = new Scanner(System.in); board xo = new board(); Map<Integer, String> m = new HashMap<>(); m.put(1,"X"); m.put(2, "O"); while(true){ System.out.print("\033[H\033[2J"); xo.print(); System.out.format("\nPlayer %s 's turn: ", p); int inp = Integer.parseInt(in.nextLine()); int x = inp/3; int y = inp%3; if(!xo.has(x,y)){ xo.put(x,y,m.get(p)); if(xo.winner(m.get(p))){ xo.print(); System.out.format("Player %d is the winner!\n", p); break; } p = 3 - p; } else{ System.out.println("try again! :( "); } } } public static void main(String[] args){ game(); } }
true
641e505f54d3960c79a7ee08be2d2d0f8d27f488
Java
skrusche63/storm-samples
/src/main/java/de/kp/storm/util/TableInfo.java
UTF-8
623
2.453125
2
[]
no_license
package de.kp.storm.util; import java.util.List; public class TableInfo { private static TableInfo instance = new TableInfo(); private List<ColumnInfo> columnInfo; private TableInfo() { } public static TableInfo getInstance() { if (instance == null) instance = new TableInfo(); return instance; } public List<ColumnInfo> getColumnInfo() { return columnInfo; } public void setColumnInfo(List<ColumnInfo> columnInfo) { this.columnInfo = columnInfo; } public ColumnInfo getColumn(int index) { return this.columnInfo.get(index); } public int size() { return this.columnInfo.size(); } }
true