blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
3fd45b4477665b80155a47783b98c73e0d2c16fd
12,773,232,804,931
0932200cbc66008e0b69eb76b3af9090c410ac8b
/src/main/java/mjh/tm/restapi/resource/ProjectResource.java
fd78982989390331758d4b01b43281f5331bdedb
[]
no_license
MikeHake/task-manager-jee
https://github.com/MikeHake/task-manager-jee
a4870c9e29fd4e6aa9a321b88a139e94a4fbdb04
13f8664d3f8c0636068714b6ae19e79d2c0ed02f
refs/heads/master
2021-01-23T07:21:39.966000
2015-01-19T15:47:39
2015-01-19T15:47:39
28,672,284
0
0
null
false
2015-01-16T16:26:48
2014-12-31T18:25:49
2015-01-09T22:40:25
2015-01-16T16:26:46
204
0
0
0
Java
null
null
package mjh.tm.restapi.resource; import java.util.List; import javax.annotation.Resource; import javax.annotation.security.DeclareRoles; import javax.annotation.security.RolesAllowed; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.inject.Inject; import javax.json.JsonObject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import mjh.tm.service.ProjectService; import mjh.tm.service.TaskService; import mjh.tm.service.entity.Project; import mjh.tm.service.exception.ForbiddenException; import mjh.tm.service.exception.IllegalNameException; import mjh.tm.service.exception.ProjectAlreadyExistsException; import mjh.tm.service.exception.ProjectNotFoundException; @DeclareRoles({ "USER", "ADMIN" }) @Stateless @Path("projects") public class ProjectResource { @Inject ProjectService projectController; @Inject TaskService taskController; @Resource SessionContext sessionContext; /** * Create a new project and return the URI location to that new user * * @return newly created project * @throws ProjectAlreadyExistsException */ @RolesAllowed("ADMIN") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createProject(Project project) throws ProjectAlreadyExistsException, IllegalNameException{ project = projectController.createProject(project); return Response.status(Status.CREATED).entity(project).type(RESTConfiguration.OBJECT_JSON).build(); } /** * Modify project and return * * @return nothing * @throws ProjectNotFoundException * @throws ForbiddenException */ @RolesAllowed("USER") @PUT @Consumes(MediaType.APPLICATION_JSON) @Path("{projectName}") public Response modifyProject(@Context UriInfo uriInfo, @PathParam("projectName") String projectName, Project project) throws ProjectNotFoundException, ForbiddenException { projectController.modifyProject(projectName, project.getDisplayName(), project.getDescription()); return Response.status(Status.NO_CONTENT).build(); } /** * Delete project * * @param projectName * @return * @throws ProjectNotFoundException * @throws ForbiddenException */ @RolesAllowed("ADMIN") @DELETE @Path("{projectName}") public Response deleteProject(@PathParam("projectName") String projectName) throws ProjectNotFoundException, ForbiddenException { projectController.deleteProject(projectName); return Response.status(Status.NO_CONTENT).build(); } @RolesAllowed("USER") @GET @Produces(MediaType.APPLICATION_JSON) public Response getAllProjects(@Context UriInfo uriInfo) { List<Project> projects = projectController.getAllProjects(); // Wrap projects in a GenericEntity to preserve Type information // so the proper MessageBodyWriter is selected. GenericEntity<List<Project>> entity = new GenericEntity<List<Project>>(projects){}; Response response = Response.ok(entity, RESTConfiguration.OBJECT_JSON).build(); return response; } @RolesAllowed("USER") @GET @Produces(MediaType.APPLICATION_JSON) @Path("{projectName}") public Response getProject(@Context UriInfo uriInfo, @PathParam("projectName") String projectName) throws ProjectNotFoundException, ForbiddenException { Project project = projectController.getProject(projectName); return Response.ok(project, RESTConfiguration.OBJECT_JSON).build(); } }
UTF-8
Java
3,994
java
ProjectResource.java
Java
[]
null
[]
package mjh.tm.restapi.resource; import java.util.List; import javax.annotation.Resource; import javax.annotation.security.DeclareRoles; import javax.annotation.security.RolesAllowed; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.inject.Inject; import javax.json.JsonObject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import mjh.tm.service.ProjectService; import mjh.tm.service.TaskService; import mjh.tm.service.entity.Project; import mjh.tm.service.exception.ForbiddenException; import mjh.tm.service.exception.IllegalNameException; import mjh.tm.service.exception.ProjectAlreadyExistsException; import mjh.tm.service.exception.ProjectNotFoundException; @DeclareRoles({ "USER", "ADMIN" }) @Stateless @Path("projects") public class ProjectResource { @Inject ProjectService projectController; @Inject TaskService taskController; @Resource SessionContext sessionContext; /** * Create a new project and return the URI location to that new user * * @return newly created project * @throws ProjectAlreadyExistsException */ @RolesAllowed("ADMIN") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createProject(Project project) throws ProjectAlreadyExistsException, IllegalNameException{ project = projectController.createProject(project); return Response.status(Status.CREATED).entity(project).type(RESTConfiguration.OBJECT_JSON).build(); } /** * Modify project and return * * @return nothing * @throws ProjectNotFoundException * @throws ForbiddenException */ @RolesAllowed("USER") @PUT @Consumes(MediaType.APPLICATION_JSON) @Path("{projectName}") public Response modifyProject(@Context UriInfo uriInfo, @PathParam("projectName") String projectName, Project project) throws ProjectNotFoundException, ForbiddenException { projectController.modifyProject(projectName, project.getDisplayName(), project.getDescription()); return Response.status(Status.NO_CONTENT).build(); } /** * Delete project * * @param projectName * @return * @throws ProjectNotFoundException * @throws ForbiddenException */ @RolesAllowed("ADMIN") @DELETE @Path("{projectName}") public Response deleteProject(@PathParam("projectName") String projectName) throws ProjectNotFoundException, ForbiddenException { projectController.deleteProject(projectName); return Response.status(Status.NO_CONTENT).build(); } @RolesAllowed("USER") @GET @Produces(MediaType.APPLICATION_JSON) public Response getAllProjects(@Context UriInfo uriInfo) { List<Project> projects = projectController.getAllProjects(); // Wrap projects in a GenericEntity to preserve Type information // so the proper MessageBodyWriter is selected. GenericEntity<List<Project>> entity = new GenericEntity<List<Project>>(projects){}; Response response = Response.ok(entity, RESTConfiguration.OBJECT_JSON).build(); return response; } @RolesAllowed("USER") @GET @Produces(MediaType.APPLICATION_JSON) @Path("{projectName}") public Response getProject(@Context UriInfo uriInfo, @PathParam("projectName") String projectName) throws ProjectNotFoundException, ForbiddenException { Project project = projectController.getProject(projectName); return Response.ok(project, RESTConfiguration.OBJECT_JSON).build(); } }
3,994
0.727842
0.727842
118
32.847458
29.433529
156
false
false
0
0
0
0
0
0
0.483051
false
false
6
615675755d0663f523644ae49c1bed072f7df0e4
13,718,125,555,780
b39700bdcf98596b7c6f073cacabe29860e2e0fd
/CoreJava/src/com/tech/ninzaz/JavaNewFeatures/java7/MultiCatchEx.java
539dc7e83142a67fa44be20d2b5f2bea68af0afc
[]
no_license
Gizmosoft/CoreJava-Practice
https://github.com/Gizmosoft/CoreJava-Practice
2d721cfdfea4c439af95fc5b39a71f0a81073816
f7affea4152fa7f52a53d6de0fc3186d2627c032
refs/heads/master
2021-06-08T15:37:56.086000
2021-05-05T06:21:27
2021-05-05T06:21:27
173,529,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tech.ninzaz.JavaNewFeatures.java7; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; public class MultiCatchEx { public static void main(String[] args) { testMultiCatchPreJava7(); testMultiCatchJava7(); } public static void testMultiCatchPreJava7(){ try { throw new FileNotFoundException("FileNotFoundException"); } catch (FileNotFoundException fnfo) { fnfo.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } @SuppressWarnings("unused") public static void testMultiCatchJava7(){ try { if(1==2){ throw new FirstException("FileNotFoundException"); } else{ throw new SecondException("Second Exception"); } }catch(FirstException | SecondException fnfo) { fnfo.printStackTrace(); } } } class FirstException extends Exception { public FirstException(String msg) { super(msg); } } class SecondException extends Exception { public SecondException(String msg) { super(msg); } }
UTF-8
Java
1,087
java
MultiCatchEx.java
Java
[]
null
[]
package com.tech.ninzaz.JavaNewFeatures.java7; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; public class MultiCatchEx { public static void main(String[] args) { testMultiCatchPreJava7(); testMultiCatchJava7(); } public static void testMultiCatchPreJava7(){ try { throw new FileNotFoundException("FileNotFoundException"); } catch (FileNotFoundException fnfo) { fnfo.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } @SuppressWarnings("unused") public static void testMultiCatchJava7(){ try { if(1==2){ throw new FirstException("FileNotFoundException"); } else{ throw new SecondException("Second Exception"); } }catch(FirstException | SecondException fnfo) { fnfo.printStackTrace(); } } } class FirstException extends Exception { public FirstException(String msg) { super(msg); } } class SecondException extends Exception { public SecondException(String msg) { super(msg); } }
1,087
0.684453
0.678013
55
18.781818
19.04224
67
false
false
0
0
0
0
0
0
1.290909
false
false
6
4c64d79198fd6d5de66ae47b881916a67983836c
231,928,246,676
09a7db94de11030b01b077962da86547cac07d74
/PROYECTO/src/main/java/net/osgg/papeleria/clienteRepository.java
2a057f5fc90a6672db7e3ebdefe76611992fba7e
[]
no_license
LuisBuenanio/PAPELERIA
https://github.com/LuisBuenanio/PAPELERIA
7f27bb388e66637eef665bae002f8f9e2ca5fdb1
27eeea05343b42906234de59c7f5e418f77b3902
refs/heads/master
2022-11-22T02:41:33.959000
2020-07-25T18:23:09
2020-07-25T18:23:09
282,499,280
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* ------------------------------------------------------------------- | | CRUDyLeaf - A Domain Specific Language for generating Spring Boot | REST resources from entity CRUD operations. | Author: Omar S. G�mez (2020) | File Date: Tue Jul 21 20:30:04 COT 2020 | ------------------------------------------------------------------- */ package net.osgg.papeleria; import net.osgg.papeleria.cliente; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; import javax.transaction.Transactional; @Repository public interface clienteRepository extends JpaRepository<cliente, Long> { Optional <cliente> findByIdcliente(Long idcliente); @Transactional void deleteByIdcliente(Long idcliente); }
UTF-8
Java
849
java
clienteRepository.java
Java
[ { "context": " resources from entity CRUD operations.\r\n| Author: Omar S. G�mez (2020)\r\n| File Date: Tue Jul 21 20:30:04 COT 2020", "end": 235, "score": 0.9998943209648132, "start": 222, "tag": "NAME", "value": "Omar S. G�mez" } ]
null
[]
/* ------------------------------------------------------------------- | | CRUDyLeaf - A Domain Specific Language for generating Spring Boot | REST resources from entity CRUD operations. | Author: <NAME> (2020) | File Date: Tue Jul 21 20:30:04 COT 2020 | ------------------------------------------------------------------- */ package net.osgg.papeleria; import net.osgg.papeleria.cliente; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; import javax.transaction.Transactional; @Repository public interface clienteRepository extends JpaRepository<cliente, Long> { Optional <cliente> findByIdcliente(Long idcliente); @Transactional void deleteByIdcliente(Long idcliente); }
840
0.602125
0.583235
28
27.678572
25.163826
73
false
false
0
0
0
0
0
0
1.428571
false
false
6
4cfc0806ba639ba4ba451980ed96afcaa0910c7e
17,952,963,338,264
b085e5ae552567f375fad2376ec61755e0dc2902
/Android-Tutorial/app-service/src/main/java/com/kk/service/SpecialService.java
08a54dbeabdcedd9df54915b7664558b5f801edb
[]
no_license
kamaihamaiha/Tutorial
https://github.com/kamaihamaiha/Tutorial
50aff4d8a69fb6831107d4af85a2325d23686c59
c1f2bfaf53703c36f1c4c45308b11b49ec09b917
refs/heads/master
2023-06-02T21:18:23.572000
2021-06-18T03:52:07
2021-06-18T03:52:07
207,139,444
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kk.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; /** * @Author: kk * @Create Date: 19-3-9 下午10:35 * @E-mail: kamaihamaiha@gmail.com * @Motto: 人生苦短,就是干! * @Des: this is SpecialService * 服务,可与 activity 进行双向通信 */ public class SpecialService extends Service { private static final String TAG = SpecialService.class.getSimpleName(); private boolean running = false; private String data; private Callback callback; public SpecialService() { } public void setCallback(Callback callback) { this.callback = callback; } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return new MyBinder(); } public class MyBinder extends Binder { /** * 外部传递数据给服务 * * @param data */ public void setData(String data) { SpecialService.this.data = data; } /** * 对外提供获取服务实例的方法 * * @return */ public SpecialService getService() { return SpecialService.this; } } @Override public void onCreate() { super.onCreate(); running = true; Log.d(TAG, "onCreate: 服务创建了×××××××××××××××××××"); new Thread() { @Override public void run() { int i = 0; while (running) { try { i++; String strData = i + ":" + data; Log.d(TAG, "run: 特殊服务正在运行...\n数据:" + data); if (callback != null) { callback.onDataChange(strData); } sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { String dataStr = intent.getStringExtra("data"); Log.d(TAG, "onStartCommand: 调用一次服务... " + dataStr); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); running = false; Log.d(TAG, "onDestroy: 特殊服务停止了..."); } /** * 服务的回调类 */ public static interface Callback { void onDataChange(String data); } }
UTF-8
Java
2,771
java
SpecialService.java
Java
[ { "context": "IBinder;\nimport android.util.Log;\n\n/**\n * @Author: kk\n * @Create Date: 19-3-9 下午10:35\n * @E-mail: kamai", "end": 181, "score": 0.9991698861122131, "start": 179, "tag": "USERNAME", "value": "kk" }, { "context": "or: kk\n * @Create Date: 19-3-9 下午10:35\n * @E-mail: kamaihamaiha@gmail.com\n * @Motto: 人生苦短,就是干!\n * @Des: this is SpecialServ", "end": 248, "score": 0.9999221563339233, "start": 226, "tag": "EMAIL", "value": "kamaihamaiha@gmail.com" } ]
null
[]
package com.kk.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; /** * @Author: kk * @Create Date: 19-3-9 下午10:35 * @E-mail: <EMAIL> * @Motto: 人生苦短,就是干! * @Des: this is SpecialService * 服务,可与 activity 进行双向通信 */ public class SpecialService extends Service { private static final String TAG = SpecialService.class.getSimpleName(); private boolean running = false; private String data; private Callback callback; public SpecialService() { } public void setCallback(Callback callback) { this.callback = callback; } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return new MyBinder(); } public class MyBinder extends Binder { /** * 外部传递数据给服务 * * @param data */ public void setData(String data) { SpecialService.this.data = data; } /** * 对外提供获取服务实例的方法 * * @return */ public SpecialService getService() { return SpecialService.this; } } @Override public void onCreate() { super.onCreate(); running = true; Log.d(TAG, "onCreate: 服务创建了×××××××××××××××××××"); new Thread() { @Override public void run() { int i = 0; while (running) { try { i++; String strData = i + ":" + data; Log.d(TAG, "run: 特殊服务正在运行...\n数据:" + data); if (callback != null) { callback.onDataChange(strData); } sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { String dataStr = intent.getStringExtra("data"); Log.d(TAG, "onStartCommand: 调用一次服务... " + dataStr); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); running = false; Log.d(TAG, "onDestroy: 特殊服务停止了..."); } /** * 服务的回调类 */ public static interface Callback { void onDataChange(String data); } }
2,756
0.511951
0.506939
105
23.704762
18.797125
75
false
false
0
0
0
0
0
0
0.380952
false
false
6
1c4c1769e6375e273dd7190046e4e63cd29b34a2
2,808,908,633,689
b880f7901f73ef3c52d8677b929f40e7072ad0b6
/src/main/java/momah/Utils/OrderHelperValidator.java
936d0900ff6265fddbbdb5916492a490ee7b10d5
[]
no_license
motios/demo2
https://github.com/motios/demo2
9e15022845c31f34ae6675b2ee9c7069f2fad2cd
fe7d8ac640844e3323ce508a3ac839f48277cd0f
refs/heads/master
2021-08-24T03:20:29.546000
2017-12-07T21:26:51
2017-12-07T21:26:51
113,473,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package momah.Utils; public class OrderHelperValidator { public static final int CUSTOMER_ID_DEFAULT = -1; public static final double PRICE_DEFAULT = 0.00; }
UTF-8
Java
167
java
OrderHelperValidator.java
Java
[]
null
[]
package momah.Utils; public class OrderHelperValidator { public static final int CUSTOMER_ID_DEFAULT = -1; public static final double PRICE_DEFAULT = 0.00; }
167
0.742515
0.718563
6
26.833334
21.674999
53
false
false
0
0
0
0
0
0
0.5
false
false
6
9b7808639a4843e50a847743990be9925c29e922
26,860,725,522,171
71fdaa2d8263591b684042a92acf9be1365f6710
/src/test/java/com/adu/org/apache/commons/lang3/tuple/MutableTripleTest.java
4650590edcd93327b28fdedde0e62008c788673f
[]
no_license
zouyq/adu-test
https://github.com/zouyq/adu-test
9811958c793c3cd489eacf87fbcc3ddbc918d73b
ce65ccce187ff99e8912e00301b0800acb8a025a
refs/heads/master
2023-05-07T12:27:29.129000
2020-12-17T07:37:10
2020-12-17T07:37:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.adu.org.apache.commons.lang3.tuple; import org.apache.commons.lang3.tuple.MutableTriple; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MutableTripleTest { MutableTriple<Integer, String, String> triple = MutableTriple.of(1, "adu", "Male"); private Logger logger = LoggerFactory.getLogger(this.getClass()); @Test public void of() { MutableTriple<Integer, String, String> res = MutableTriple.of(1, "adu", "Male"); logger.debug("res={}", res); } @Test public void new1() { MutableTriple<Integer, String, String> res = new MutableTriple<>(1, "adu", "Male"); logger.debug("res={}", res); } @Test public void setLeft() { triple.setLeft(2); logger.debug("triple={}", triple); } @Test public void setRight() { triple.setMiddle("aduadu"); logger.debug("triple={}", triple); } @Test public void setValue() { triple.setRight("Female"); logger.debug("triple={}", triple); } }
UTF-8
Java
1,078
java
MutableTripleTest.java
Java
[]
null
[]
package com.adu.org.apache.commons.lang3.tuple; import org.apache.commons.lang3.tuple.MutableTriple; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MutableTripleTest { MutableTriple<Integer, String, String> triple = MutableTriple.of(1, "adu", "Male"); private Logger logger = LoggerFactory.getLogger(this.getClass()); @Test public void of() { MutableTriple<Integer, String, String> res = MutableTriple.of(1, "adu", "Male"); logger.debug("res={}", res); } @Test public void new1() { MutableTriple<Integer, String, String> res = new MutableTriple<>(1, "adu", "Male"); logger.debug("res={}", res); } @Test public void setLeft() { triple.setLeft(2); logger.debug("triple={}", triple); } @Test public void setRight() { triple.setMiddle("aduadu"); logger.debug("triple={}", triple); } @Test public void setValue() { triple.setRight("Female"); logger.debug("triple={}", triple); } }
1,078
0.616883
0.608534
42
24.666666
24.682426
91
false
false
0
0
0
0
0
0
0.809524
false
false
6
ede854610b38ecec5cb2b9e669ff0d0fb90186c2
14,714,557,965,328
e354e28058c35fa87cb666fe29b9ff38f2c2d8ef
/src/main/java/com/lgq/servlet/DispatcherServlet.java
ff42b5a3f871e6a203e3e0abbd37b118c291a4bc
[ "Apache-2.0" ]
permissive
ygs12/spring-mvc-custom
https://github.com/ygs12/spring-mvc-custom
2d632425115795c0fe28c05631cbf9b469a6111e
7c2ddf212ef8e49d764a4a1c7e58f53e57c5e0af
refs/heads/master
2021-04-01T21:29:42.305000
2020-03-03T11:22:26
2020-03-03T11:22:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lgq.servlet; import com.lgq.adapter.HandlerAdapter; import com.lgq.handler.HandlerMapping; import com.lgq.ioc.BeanFactory; import com.lgq.model.ModelAndView; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.List; import java.util.Map; /** * @author lgq * @date 2019/10/25 */ public class DispatcherServlet extends FrameworkServlet{ private List<HandlerMapping> handlerMappings = null; private List<HandlerAdapter> handlerAdapters = null; /** * 初始化bean工厂 * @param config servlet全局配置 */ private void initBeanFactory(ServletConfig config) { // 获取web.xml中配置的contextConfigLocation 即spring-mvc文件路径 String contextLocation = config.getInitParameter("contextConfigLocation"); // 初始化容器 BeanFactory.initBeanFactory(contextLocation); } /** * 初始化handlerMappings */ private void initHandlerMappings() { handlerMappings = BeanFactory.getBeansOfType(HandlerMapping.class); } /** * 初始化handler适配器集合 */ private void initHandlerAdapters() { handlerAdapters = BeanFactory.getBeansOfType(HandlerAdapter.class); } /** * 在初始化servlet的时候进行 工厂的初始化 handlerMapping初始化 * 和 handlerAdapter的初始化 * @param config servlet配置信息 * @throws ServletException 异常 */ @Override public void init(ServletConfig config) throws ServletException { initBeanFactory(config); initHandlerMappings(); initHandlerAdapters(); } private Object getHandler(HttpServletRequest request) throws Exception { if (handlerMappings != null && handlerMappings.size() > 0) { // 遍历处理器映射集合并获取相应的处理器 for (HandlerMapping handlerMapping: handlerMappings) { Object handler = handlerMapping.getHandler(request); if (handler != null) { return handler; } } } return null; } private HandlerAdapter getHandlerAdapter(Object handler) { System.out.println(handlerAdapters.size()); if (handlerAdapters != null && handlerAdapters.size() > 0) { // 遍历处理器适配器集合获取能够适配处理器的适配器 for (HandlerAdapter handlerAdapter: handlerAdapters) { if (handlerAdapter.support(handler)) { return handlerAdapter; } } } return null; } @Override public void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { // 获取处理器 Object handler = getHandler(request); if (handler != null) { // 获取处理器对应的处理器适配器 HandlerAdapter handlerAdapter = getHandlerAdapter(handler); if (handlerAdapter != null) { ModelAndView modelAndView = handlerAdapter.handleRequest(request, response, handler); if (modelAndView != null) { Map<String, Object> model = modelAndView.getModel(); PrintWriter writer = response.getWriter(); for (String string: model.keySet()) { writer.write(string); } writer.close(); } } } } }
UTF-8
Java
3,760
java
DispatcherServlet.java
Java
[ { "context": "ist;\n import java.util.Map;\n\n/**\n * @author lgq\n * @date 2019/10/25\n */\npublic class DispatcherSe", "end": 519, "score": 0.9996205568313599, "start": 516, "tag": "USERNAME", "value": "lgq" } ]
null
[]
package com.lgq.servlet; import com.lgq.adapter.HandlerAdapter; import com.lgq.handler.HandlerMapping; import com.lgq.ioc.BeanFactory; import com.lgq.model.ModelAndView; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.List; import java.util.Map; /** * @author lgq * @date 2019/10/25 */ public class DispatcherServlet extends FrameworkServlet{ private List<HandlerMapping> handlerMappings = null; private List<HandlerAdapter> handlerAdapters = null; /** * 初始化bean工厂 * @param config servlet全局配置 */ private void initBeanFactory(ServletConfig config) { // 获取web.xml中配置的contextConfigLocation 即spring-mvc文件路径 String contextLocation = config.getInitParameter("contextConfigLocation"); // 初始化容器 BeanFactory.initBeanFactory(contextLocation); } /** * 初始化handlerMappings */ private void initHandlerMappings() { handlerMappings = BeanFactory.getBeansOfType(HandlerMapping.class); } /** * 初始化handler适配器集合 */ private void initHandlerAdapters() { handlerAdapters = BeanFactory.getBeansOfType(HandlerAdapter.class); } /** * 在初始化servlet的时候进行 工厂的初始化 handlerMapping初始化 * 和 handlerAdapter的初始化 * @param config servlet配置信息 * @throws ServletException 异常 */ @Override public void init(ServletConfig config) throws ServletException { initBeanFactory(config); initHandlerMappings(); initHandlerAdapters(); } private Object getHandler(HttpServletRequest request) throws Exception { if (handlerMappings != null && handlerMappings.size() > 0) { // 遍历处理器映射集合并获取相应的处理器 for (HandlerMapping handlerMapping: handlerMappings) { Object handler = handlerMapping.getHandler(request); if (handler != null) { return handler; } } } return null; } private HandlerAdapter getHandlerAdapter(Object handler) { System.out.println(handlerAdapters.size()); if (handlerAdapters != null && handlerAdapters.size() > 0) { // 遍历处理器适配器集合获取能够适配处理器的适配器 for (HandlerAdapter handlerAdapter: handlerAdapters) { if (handlerAdapter.support(handler)) { return handlerAdapter; } } } return null; } @Override public void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { // 获取处理器 Object handler = getHandler(request); if (handler != null) { // 获取处理器对应的处理器适配器 HandlerAdapter handlerAdapter = getHandlerAdapter(handler); if (handlerAdapter != null) { ModelAndView modelAndView = handlerAdapter.handleRequest(request, response, handler); if (modelAndView != null) { Map<String, Object> model = modelAndView.getModel(); PrintWriter writer = response.getWriter(); for (String string: model.keySet()) { writer.write(string); } writer.close(); } } } } }
3,760
0.605983
0.603134
111
30.621622
25.14393
103
false
false
0
0
0
0
0
0
0.342342
false
false
6
70b98a0c957dc3ed3853c295ebb32d9b2233b2c7
24,060,406,818,037
455f8fe40c7f256ac75059586c8925a00550d41f
/backend/homfitchallenge/src/main/java/com/ssafy/homfit/api/ChallengeRepository.java
24d22c56ee4919afe0ed73c81f5d1eb5bcf777a7
[]
no_license
ekgml3765/Homfit-Challenge
https://github.com/ekgml3765/Homfit-Challenge
6324ab825ff805a4058243b8ded62f061ebfe2f6
1f101b6644ab6d7649bb20ec07685d5195c55087
refs/heads/master
2023-07-12T01:53:25.413000
2021-08-15T14:37:11
2021-08-15T14:37:11
373,220,431
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssafy.homfit.api; import org.springframework.data.repository.CrudRepository; import com.ssafy.homfit.model.Challenge; public interface ChallengeRepository extends CrudRepository<Challenge, Integer>{ }
UTF-8
Java
219
java
ChallengeRepository.java
Java
[]
null
[]
package com.ssafy.homfit.api; import org.springframework.data.repository.CrudRepository; import com.ssafy.homfit.model.Challenge; public interface ChallengeRepository extends CrudRepository<Challenge, Integer>{ }
219
0.826484
0.826484
10
20.9
27.998035
80
false
false
0
0
0
0
0
0
0.5
false
false
6
adf76f9863f8bc0057957cf56af0a9d12c5bdd79
5,823,975,694,355
fc049dde0440056d95baacb25ad8224c96088678
/src/main/java/com/c9/survival/controller/MovePointController.java
e940521632c092378539778e66cc359306bf1e43
[]
no_license
Kprunning/c9Plugin
https://github.com/Kprunning/c9Plugin
bc8235965d4b6c6c6ea26aa9111bcc8981b4115c
d83bd94b5ec51f294971c631f721dabc2560ff52
refs/heads/master
2022-11-19T22:44:09.046000
2020-07-14T03:26:12
2020-07-14T03:27:22
279,470,526
12
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.c9.survival.controller; import com.c9.survival.service.MovePointService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/movePoint") public class MovePointController { @Autowired private MovePointService movePointServic; /** * 功能:移动到1大陆生存点 */ @RequestMapping(value="/shengCun1",produces={"application/json;charset=UTF-8"}) @ResponseBody public String flyToShengCunPoint() { movePointServic.moveShengCun1(); return "成功飞跃到生存点"; } }
UTF-8
Java
718
java
MovePointController.java
Java
[]
null
[]
package com.c9.survival.controller; import com.c9.survival.service.MovePointService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/movePoint") public class MovePointController { @Autowired private MovePointService movePointServic; /** * 功能:移动到1大陆生存点 */ @RequestMapping(value="/shengCun1",produces={"application/json;charset=UTF-8"}) @ResponseBody public String flyToShengCunPoint() { movePointServic.moveShengCun1(); return "成功飞跃到生存点"; } }
718
0.800587
0.791789
25
26.280001
23.473423
80
false
false
0
0
0
0
0
0
1
false
false
6
0c135b10f3c2090fe7b47a05be8cd5a1c2523d1a
28,587,302,350,797
ec1e385a1001801f85272ae6f5ff8461dda77c63
/src/com/playthatchord/model/note/Note.java
a6f3a3a737faad5f13ba43d80deee7b862fb7e4e
[]
no_license
baotpham/PlayThatChord
https://github.com/baotpham/PlayThatChord
429d518e09ff9e590b972cf64cb6f195dbbff33f
8995737bde3fd87881e2b934f10b11a1dee2752f
refs/heads/master
2020-04-23T09:45:05.005000
2019-03-20T19:37:40
2019-03-20T19:37:40
171,079,794
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.playthatchord.model.note; public interface Note { String getNoteName(); int[][] getNotePositions(); }
UTF-8
Java
125
java
Note.java
Java
[]
null
[]
package com.playthatchord.model.note; public interface Note { String getNoteName(); int[][] getNotePositions(); }
125
0.696
0.696
8
14.625
14.890748
37
false
false
0
0
0
0
0
0
0.375
false
false
6
de6610ace1afd9caac77b6c8f462160f782491a0
25,494,925,910,934
05f3869d5c276b76d2ee4553686b8eaf96dea03f
/src/uk/ac/isc/Test_DatePicker.java
4a54b3e00625a026e187a4b01d365a3e57bdf5a4
[]
no_license
saifulkhan/scheduling-system
https://github.com/saifulkhan/scheduling-system
077b080b6246bcce8ca818f9ee17e029c86a02ee
bac7c8c03eade9f06e9803cd49bce6939514ba50
refs/heads/master
2021-01-18T19:31:42.906000
2017-05-05T13:05:50
2017-05-05T13:05:50
72,102,862
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 uk.ac.isc; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import org.jdesktop.swingx.JXDatePicker; /** * * */ public class Test_DatePicker { public static void main (String [] args) { // Establish a look and feel for this application’s GUI. setLookAndFeel (); // Create a frame window whose GUI presents the date picker and provides // a list of supported date formats. final JFrame frame = new JFrame ("Date Picker Month View Demo #1"); frame.getContentPane ().setLayout (new GridLayout (2, 1)); // Tell application to automatically exit when the user selects the Close // menu item from the frame window’s system menu. frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // Create GUI: date picker at the top and a combo box of date formats -- // that the date picker supports for entering dates via the editor -- at // the bottom. JPanel panel = new JPanel (); panel.add (new JLabel ("Enter date (if desired) and click button")); final JXDatePicker datePicker; datePicker = new JXDatePicker (); ActionListener al = new ActionListener () { public void actionPerformed (ActionEvent e) { System.out.println (datePicker.getDate ()); } }; datePicker.addActionListener (al); panel.add (datePicker); frame.getContentPane ().add (panel); panel = new JPanel (); panel.setLayout (new FlowLayout (FlowLayout.LEFT)); panel.add (new JLabel ("Supported date formats")); DateFormat [] dfs = datePicker.getFormats (); String [] fmts = new String [dfs.length]; for (int i = 0; i < dfs.length; i++) fmts [i] = (dfs [i] instanceof SimpleDateFormat) ? ((SimpleDateFormat) dfs [i]).toPattern () : dfs [i].toString (); panel.add (new JComboBox (fmts)); frame.getContentPane ().add (panel); // Size frame window to fit the preferred size and layouts of its // components. frame.pack (); // Display GUI and start the AWT’s event-dispatching thread. frame.setVisible (true); } static void setLookAndFeel () { try { // Return the name of the LookAndFeel class that implements the // native OS look and feel. If there is no such look and feel, return // the name of the default cross platform LookAndFeel class. String slafcn = UIManager.getSystemLookAndFeelClassName (); // Set the current look and feel to the look and feel identified by // the LookAndFeel class name. UIManager.setLookAndFeel (slafcn); } catch(Exception e) { } } }
UTF-8
Java
3,253
java
Test_DatePicker.java
Java
[]
null
[]
/* * 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 uk.ac.isc; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import org.jdesktop.swingx.JXDatePicker; /** * * */ public class Test_DatePicker { public static void main (String [] args) { // Establish a look and feel for this application’s GUI. setLookAndFeel (); // Create a frame window whose GUI presents the date picker and provides // a list of supported date formats. final JFrame frame = new JFrame ("Date Picker Month View Demo #1"); frame.getContentPane ().setLayout (new GridLayout (2, 1)); // Tell application to automatically exit when the user selects the Close // menu item from the frame window’s system menu. frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // Create GUI: date picker at the top and a combo box of date formats -- // that the date picker supports for entering dates via the editor -- at // the bottom. JPanel panel = new JPanel (); panel.add (new JLabel ("Enter date (if desired) and click button")); final JXDatePicker datePicker; datePicker = new JXDatePicker (); ActionListener al = new ActionListener () { public void actionPerformed (ActionEvent e) { System.out.println (datePicker.getDate ()); } }; datePicker.addActionListener (al); panel.add (datePicker); frame.getContentPane ().add (panel); panel = new JPanel (); panel.setLayout (new FlowLayout (FlowLayout.LEFT)); panel.add (new JLabel ("Supported date formats")); DateFormat [] dfs = datePicker.getFormats (); String [] fmts = new String [dfs.length]; for (int i = 0; i < dfs.length; i++) fmts [i] = (dfs [i] instanceof SimpleDateFormat) ? ((SimpleDateFormat) dfs [i]).toPattern () : dfs [i].toString (); panel.add (new JComboBox (fmts)); frame.getContentPane ().add (panel); // Size frame window to fit the preferred size and layouts of its // components. frame.pack (); // Display GUI and start the AWT’s event-dispatching thread. frame.setVisible (true); } static void setLookAndFeel () { try { // Return the name of the LookAndFeel class that implements the // native OS look and feel. If there is no such look and feel, return // the name of the default cross platform LookAndFeel class. String slafcn = UIManager.getSystemLookAndFeelClassName (); // Set the current look and feel to the look and feel identified by // the LookAndFeel class name. UIManager.setLookAndFeel (slafcn); } catch(Exception e) { } } }
3,253
0.643671
0.642439
105
29.923809
26.045635
81
false
false
0
0
0
0
0
0
0.428571
false
false
6
9916f64a1d52112cf0550b9151fdda615a1b07ad
31,765,578,157,093
f2fcc0e25e0f64e5b47aa72ae085e5bf6f1e3156
/src/AST/VarType/String_type.java
3fac27b795bda412e5df09c1801b388d50441550
[]
no_license
906476903/A-Compiler-for-modified-C
https://github.com/906476903/A-Compiler-for-modified-C
4854878750a215e805b24825a290d58fc5e5ebc4
35cdffca7407a35892a3253ea47515d50687082d
refs/heads/master
2021-01-19T09:17:31.381000
2017-02-15T18:07:52
2017-02-15T18:07:52
82,090,338
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package AST.VarType; import IR.ILOC.Reg; /** * Created by xsc on 2016/3/31. */ public class String_type { public String s; public boolean is_lvalue; public Reg pl; public String_type(){} public String_type(boolean s){is_lvalue = s;} public String_type(Reg tmp){pl = tmp;} }
UTF-8
Java
304
java
String_type.java
Java
[ { "context": "T.VarType;\n\nimport IR.ILOC.Reg;\n\n/**\n * Created by xsc on 2016/3/31.\n */\npublic class String_type {\n ", "end": 64, "score": 0.9995430707931519, "start": 61, "tag": "USERNAME", "value": "xsc" } ]
null
[]
package AST.VarType; import IR.ILOC.Reg; /** * Created by xsc on 2016/3/31. */ public class String_type { public String s; public boolean is_lvalue; public Reg pl; public String_type(){} public String_type(boolean s){is_lvalue = s;} public String_type(Reg tmp){pl = tmp;} }
304
0.641447
0.618421
17
16.882353
15.296606
49
false
false
0
0
0
0
0
0
0.411765
false
false
6
5fa5c1823a27637188842cd1b0d5603014eb5e81
20,186,346,331,058
f864c784f759f555669e9357fee7f531e34a37dd
/src/test/java/com/szucsatti/lemkehowson/MatrixOperationsTest.java
f37da6887371ad69da7023e2326452584a2b1cee
[]
no_license
szucsatti/nash-equilibrium
https://github.com/szucsatti/nash-equilibrium
4b519a304c397e02e635b52785f28169ae94a157
f0d3a56c139b8e05a5575ab9766fd39c0eeb05e7
refs/heads/master
2020-09-17T03:50:49.713000
2019-12-04T13:45:47
2019-12-04T13:45:47
223,978,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.szucsatti.lemkehowson; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import static com.szucsatti.lemkehowson.Rational.valueOf; class MatrixOperationsTest { private Matrix xMatrix = new Matrix(new long[][]{ {1, 2, 3}, {7, -8, 9}, {13, 14, 15}}); private Matrix yMatrix = new Matrix(new long[][]{ {4, 5, 6}, {10, 11, 12}, {16, -17, 18}}); private Matrix nonZero = new Matrix(new long[][]{ {4, 5, 6, 100, 200}, {10, 0, 12, 101, 0}, {16, -17, 18, 102, 202}}); private int NORMALIZATION_CONST = 18; private Matrix xyJoined = new Matrix(new long[][]{ {1, 2, 3, 4, 5, 6,}, {7, -8, 9, 10, 11, 12}, {13, 14, 15, 16, -17, 18}}); private Matrix expectedNormalized = new Matrix(new long[][]{ {1 + NORMALIZATION_CONST, 2 + NORMALIZATION_CONST, 3 + NORMALIZATION_CONST, 4 + NORMALIZATION_CONST, 5 + NORMALIZATION_CONST, 6 + NORMALIZATION_CONST,}, {7 + NORMALIZATION_CONST, -8 + NORMALIZATION_CONST, 9 + NORMALIZATION_CONST, 10 + NORMALIZATION_CONST, 11 + NORMALIZATION_CONST, 12 + NORMALIZATION_CONST}, {13 + NORMALIZATION_CONST, 14 + NORMALIZATION_CONST, 15 + NORMALIZATION_CONST, 16 + NORMALIZATION_CONST, -17 + NORMALIZATION_CONST, 18 + NORMALIZATION_CONST}}); @Test public void givenMatrix_OnMinimumValue_returnMinimumValue() { Assertions.assertEquals(valueOf(-8), xMatrix.getMinimumValue()); Assertions.assertEquals(valueOf(-17), yMatrix.getMinimumValue()); } @Test public void givenMatrix_OnCopy_returnsCopy(){ Matrix copy = new Matrix(xMatrix); Assertions.assertEquals(xMatrix, copy); } @Test public void givenMatrix_OnNormalize_returnNormalized(){ Matrix normalized = this.xyJoined.normalize(); Assertions.assertEquals(this.expectedNormalized, normalized); } @Test public void givenMatrices_OnJoin_returnJoinedBiMatrix(){ Matrix joined = xMatrix.join(yMatrix); Assertions.assertEquals(this.xyJoined, joined); } @Test public void givenBiMatrix_onSplit_returnSplitMatrices(){ Matrix[] split = this.xyJoined.split(); Assertions.assertEquals(xMatrix, split[0]); Assertions.assertEquals(yMatrix, split[1]); } @Test public void givenMatrix_onRatio_calculateRatio(){ Assertions.assertEquals(xMatrix.ratio(1, 2, 0, 2), valueOf(3)); Assertions.assertEquals(xMatrix.ratio(2, 1, 1, 1), valueOf(-14, 8)); Assertions.assertEquals(xMatrix.ratio(2, 2, 1, 2), valueOf(15, 9)); } @Test public void givenMatrix_onMultiplyRowByPositiveNumber_multipliesRow(){ Matrix actualMatrix = xMatrix.multiplyRow(0, valueOf(5)); Assertions.assertEquals(new Matrix(new long[][]{ {5, 10, 15}, {7, -8, 9}, {13, 14, 15}}), actualMatrix); } @Test public void givenMatrix_onMultiplyRowByNegativeNumber_multipliesRow(){ Matrix actualMatrix = xMatrix.multiplyRow(1, valueOf(-1,2)); Assertions.assertEquals(new Matrix(new Rational[][]{ {valueOf(1), valueOf(2), valueOf(3)}, {valueOf(-7,2), valueOf(4), valueOf(-9,2)}, {valueOf(13), valueOf(14), valueOf(15)}}), actualMatrix); } @Test public void givenMatrix_onSubtract_doSubtraction(){ final Matrix actualMatrix = xMatrix.subtract(0, 1); Assertions.assertEquals(new Matrix(new long[][]{ {1, 2, 3}, {6, -10, 6}, {13, 14, 15}}), actualMatrix); } @Test public void givenMatrix_OnNoZeroCols_findNonZeroCols(){ Assertions.assertEquals(Arrays.asList(0,2,3), nonZero.getNoZeroCols()); } @Test public void givenMatrix_OnSwitchRowsWithCols_doSwitching(){ Matrix switched = xMatrix.switchRowsWithCols(); Assertions.assertEquals(new Matrix(new long[][]{ {1, 7, 13}, {2, -8, 14}, {3, 9, 15}}), switched); } }
UTF-8
Java
4,211
java
MatrixOperationsTest.java
Java
[]
null
[]
package com.szucsatti.lemkehowson; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import static com.szucsatti.lemkehowson.Rational.valueOf; class MatrixOperationsTest { private Matrix xMatrix = new Matrix(new long[][]{ {1, 2, 3}, {7, -8, 9}, {13, 14, 15}}); private Matrix yMatrix = new Matrix(new long[][]{ {4, 5, 6}, {10, 11, 12}, {16, -17, 18}}); private Matrix nonZero = new Matrix(new long[][]{ {4, 5, 6, 100, 200}, {10, 0, 12, 101, 0}, {16, -17, 18, 102, 202}}); private int NORMALIZATION_CONST = 18; private Matrix xyJoined = new Matrix(new long[][]{ {1, 2, 3, 4, 5, 6,}, {7, -8, 9, 10, 11, 12}, {13, 14, 15, 16, -17, 18}}); private Matrix expectedNormalized = new Matrix(new long[][]{ {1 + NORMALIZATION_CONST, 2 + NORMALIZATION_CONST, 3 + NORMALIZATION_CONST, 4 + NORMALIZATION_CONST, 5 + NORMALIZATION_CONST, 6 + NORMALIZATION_CONST,}, {7 + NORMALIZATION_CONST, -8 + NORMALIZATION_CONST, 9 + NORMALIZATION_CONST, 10 + NORMALIZATION_CONST, 11 + NORMALIZATION_CONST, 12 + NORMALIZATION_CONST}, {13 + NORMALIZATION_CONST, 14 + NORMALIZATION_CONST, 15 + NORMALIZATION_CONST, 16 + NORMALIZATION_CONST, -17 + NORMALIZATION_CONST, 18 + NORMALIZATION_CONST}}); @Test public void givenMatrix_OnMinimumValue_returnMinimumValue() { Assertions.assertEquals(valueOf(-8), xMatrix.getMinimumValue()); Assertions.assertEquals(valueOf(-17), yMatrix.getMinimumValue()); } @Test public void givenMatrix_OnCopy_returnsCopy(){ Matrix copy = new Matrix(xMatrix); Assertions.assertEquals(xMatrix, copy); } @Test public void givenMatrix_OnNormalize_returnNormalized(){ Matrix normalized = this.xyJoined.normalize(); Assertions.assertEquals(this.expectedNormalized, normalized); } @Test public void givenMatrices_OnJoin_returnJoinedBiMatrix(){ Matrix joined = xMatrix.join(yMatrix); Assertions.assertEquals(this.xyJoined, joined); } @Test public void givenBiMatrix_onSplit_returnSplitMatrices(){ Matrix[] split = this.xyJoined.split(); Assertions.assertEquals(xMatrix, split[0]); Assertions.assertEquals(yMatrix, split[1]); } @Test public void givenMatrix_onRatio_calculateRatio(){ Assertions.assertEquals(xMatrix.ratio(1, 2, 0, 2), valueOf(3)); Assertions.assertEquals(xMatrix.ratio(2, 1, 1, 1), valueOf(-14, 8)); Assertions.assertEquals(xMatrix.ratio(2, 2, 1, 2), valueOf(15, 9)); } @Test public void givenMatrix_onMultiplyRowByPositiveNumber_multipliesRow(){ Matrix actualMatrix = xMatrix.multiplyRow(0, valueOf(5)); Assertions.assertEquals(new Matrix(new long[][]{ {5, 10, 15}, {7, -8, 9}, {13, 14, 15}}), actualMatrix); } @Test public void givenMatrix_onMultiplyRowByNegativeNumber_multipliesRow(){ Matrix actualMatrix = xMatrix.multiplyRow(1, valueOf(-1,2)); Assertions.assertEquals(new Matrix(new Rational[][]{ {valueOf(1), valueOf(2), valueOf(3)}, {valueOf(-7,2), valueOf(4), valueOf(-9,2)}, {valueOf(13), valueOf(14), valueOf(15)}}), actualMatrix); } @Test public void givenMatrix_onSubtract_doSubtraction(){ final Matrix actualMatrix = xMatrix.subtract(0, 1); Assertions.assertEquals(new Matrix(new long[][]{ {1, 2, 3}, {6, -10, 6}, {13, 14, 15}}), actualMatrix); } @Test public void givenMatrix_OnNoZeroCols_findNonZeroCols(){ Assertions.assertEquals(Arrays.asList(0,2,3), nonZero.getNoZeroCols()); } @Test public void givenMatrix_OnSwitchRowsWithCols_doSwitching(){ Matrix switched = xMatrix.switchRowsWithCols(); Assertions.assertEquals(new Matrix(new long[][]{ {1, 7, 13}, {2, -8, 14}, {3, 9, 15}}), switched); } }
4,211
0.60437
0.556875
127
32.157482
33.209293
172
false
false
0
0
0
0
0
0
1.307087
false
false
6
e49e8556dec22bc92681c58f5b931f716ffad3ea
26,603,027,463,879
4939d585ba2801b5b332bd6e30be112e71988bd0
/src/main/java/com/jm3200104/spring/mvc/model/Student.java
9c61223fdbe1e01e2cfca7350dc98666e049190b
[]
no_license
codewnw/JM3200104
https://github.com/codewnw/JM3200104
14edd8eb8333991d5b16512a2417612e70ea6839
c3a923d4a81a3caceab4a8e03c9804cfea745f8f
refs/heads/master
2022-12-21T12:00:24.025000
2020-04-25T04:51:47
2020-04-25T04:51:47
232,623,982
0
0
null
false
2022-12-15T23:35:37
2020-01-08T17:48:31
2020-04-25T04:51:44
2022-12-15T23:35:35
90
0
0
8
Java
false
false
package com.jm3200104.spring.mvc.model; public class Student { private String name; private int age; private String gender; private String country; private String[] courses; private boolean graduate; private String comment; public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public boolean isGraduate() { return graduate; } public void setGraduate(boolean graduate) { this.graduate = graduate; } public String[] getCourses() { return courses; } public void setCourses(String[] courses) { this.courses = courses; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student() { super(); // TODO Auto-generated constructor stub } }
UTF-8
Java
1,337
java
Student.java
Java
[]
null
[]
package com.jm3200104.spring.mvc.model; public class Student { private String name; private int age; private String gender; private String country; private String[] courses; private boolean graduate; private String comment; public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public boolean isGraduate() { return graduate; } public void setGraduate(boolean graduate) { this.graduate = graduate; } public String[] getCourses() { return courses; } public void setCourses(String[] courses) { this.courses = courses; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student() { super(); // TODO Auto-generated constructor stub } }
1,337
0.629768
0.624533
86
13.546512
14.483075
56
false
false
0
0
0
0
0
0
1.22093
false
false
6
8ceff33e22637a7b40364caec6fbd973623add90
1,675,037,295,356
6e2e383a00778d826c451a4d9274fc49e0cff41c
/hackerrank/src/ds/H_Queue_TruckTour.java
491248ee743ba1abd9f2783330ca35a63e9cbb84
[]
no_license
kenvifire/AlgorithmPractice
https://github.com/kenvifire/AlgorithmPractice
d875df9d13a76a02bce9ce0b90a8fad5ba90f832
e16315ca2ad0476f65f087f608cc9424710e0812
refs/heads/master
2022-12-17T23:45:37.784000
2020-09-22T14:45:46
2020-09-22T14:45:46
58,105,208
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by kenvi on 16/5/21. */ public class H_Queue_TruckTour { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int min = 0; int a,d; int total = 0; int start = 0; int index = 0; int n = N; while (N --> 0) { a = scanner.nextInt(); d = scanner.nextInt(); total += (a-d); if(total < min) { min = total; start = index; } index ++; } System.out.print((start + 1) % n); } }
UTF-8
Java
725
java
H_Queue_TruckTour.java
Java
[ { "context": "List;\nimport java.util.Scanner;\n\n/**\n * Created by kenvi on 16/5/21.\n */\npublic class H_Queue_TruckTour {\n", "end": 101, "score": 0.9981463551521301, "start": 96, "tag": "USERNAME", "value": "kenvi" } ]
null
[]
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by kenvi on 16/5/21. */ public class H_Queue_TruckTour { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int min = 0; int a,d; int total = 0; int start = 0; int index = 0; int n = N; while (N --> 0) { a = scanner.nextInt(); d = scanner.nextInt(); total += (a-d); if(total < min) { min = total; start = index; } index ++; } System.out.print((start + 1) % n); } }
725
0.456552
0.441379
36
19.138889
14.246155
49
false
false
0
0
0
0
0
0
0.527778
false
false
6
525c612dd82926f1d79f73c50694d64cac30ff95
27,152,783,274,954
7051d41edfbee034cc50e0d4dc2b294e0f9391d9
/src/Solution581.java
fb9cf8536ca6762109bb5dd2431f94b0e6eaf2fc
[]
no_license
Ryougi-Shiki0/Leetcode-Practice
https://github.com/Ryougi-Shiki0/Leetcode-Practice
5d073df139e4fefc7fce0a10dcd87c091849e0de
f2125a57210bbafc96874e76f368db349320f493
refs/heads/master
2022-07-15T11:20:05.353000
2022-06-06T17:17:12
2022-06-06T17:17:12
233,251,796
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @author Arthas */ public class Solution581 { public int findUnsortedSubarray(int[] nums) { int length = nums.length; int l = length - 1; int r = 0; int max = nums[0]; int min = nums[length-1]; for (int i = 0;i < length;i++) { max = Math.max(nums[i],max); min = Math.min(nums[length-i-1],min); if (nums[i] < max) { r = i; } if (nums[length-i-1] > min) { l = length-i-1; } } if (l >= r) { return 0; } return r-l+1; } public static void main(String[] args) { Solution581 t=new Solution581(); int[] nums={2,6,4,8,10,9,15}; System.out.println(t.findUnsortedSubarray(nums)); } }
UTF-8
Java
819
java
Solution581.java
Java
[ { "context": "\n/**\n * @author Arthas\n */\npublic class Solution581 {\n public int fin", "end": 22, "score": 0.9998445510864258, "start": 16, "tag": "NAME", "value": "Arthas" } ]
null
[]
/** * @author Arthas */ public class Solution581 { public int findUnsortedSubarray(int[] nums) { int length = nums.length; int l = length - 1; int r = 0; int max = nums[0]; int min = nums[length-1]; for (int i = 0;i < length;i++) { max = Math.max(nums[i],max); min = Math.min(nums[length-i-1],min); if (nums[i] < max) { r = i; } if (nums[length-i-1] > min) { l = length-i-1; } } if (l >= r) { return 0; } return r-l+1; } public static void main(String[] args) { Solution581 t=new Solution581(); int[] nums={2,6,4,8,10,9,15}; System.out.println(t.findUnsortedSubarray(nums)); } }
819
0.443223
0.409035
32
24.5625
15.576299
57
false
false
0
0
0
0
0
0
0.75
false
false
6
f648c2b69da095e0a290d21730c82b27f7e4463f
30,691,836,344,535
558ead99189c8a17337bcbebb2693c8aad007f0b
/src/test/java/com/yusufsoysal/algorithms/interview/IteratorCollapseTest.java
e5c801e826b26e51308dfb52e6de51a2503a9fd6
[]
no_license
yusufsoysal/Katas
https://github.com/yusufsoysal/Katas
723dcb6eb4dd8fb27bbd5942f466c5056baaeb13
a9e175667cb3027ae898a053d838b94e347c719e
refs/heads/master
2021-01-18T08:32:42.328000
2017-12-14T22:04:27
2017-12-14T22:04:27
57,919,093
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yusufsoysal.algorithms.interview; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class IteratorCollapseTest { private final IteratorCollapse collapser = new IteratorCollapse(); @Test public void shouldReturnEmptyIteratorWhenValueIsNull(){ Iterator<String> iterator = collapser.singleIterator(null); assertThat(iterator.hasNext(), equalTo(false)); } @Test public void shouldReturnIteratorWhenOnlyOneIteratorSupplied(){ List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5); Iterator<Integer> iterator = integerList.iterator(); Iterator<Integer> returnedIterator = collapser.singleIterator(iterator); int currentIndex = 0; while( returnedIterator.hasNext() ){ assertThat(returnedIterator.next(), equalTo( integerList.get(currentIndex++) )); } assertThat(currentIndex, equalTo(5)); } @Test public void shouldReturnIteratorWhenMoreThanOneIteratorSupplied(){ List<List<Integer>> integerList = new ArrayList<>(); integerList.add( Arrays.asList(1, 2, 3, 4, 5) ); integerList.add( Arrays.asList(6, 7, 8, 9) ); integerList.add( Arrays.asList(10, 11, 12) ); Iterator<Integer> iterator1 = integerList.get(0).iterator(); Iterator<Integer> iterator2 = integerList.get(1).iterator(); Iterator<Integer> iterator3 = integerList.get(2).iterator(); Iterator<Integer> returnedIterator = collapser.singleIterator(iterator1, iterator2, iterator3); int currentIndex = 0; int totalValue = 0; int listIndex = 0; while( returnedIterator.hasNext() ){ List<Integer> currentList = integerList.get(listIndex); assertThat(returnedIterator.next(), equalTo( currentList.get(currentIndex++) )); if( currentIndex >= currentList.size() ){ listIndex++; currentIndex = 0; } ++totalValue; } assertThat(totalValue, equalTo(12)); } }
UTF-8
Java
2,231
java
IteratorCollapseTest.java
Java
[]
null
[]
package com.yusufsoysal.algorithms.interview; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class IteratorCollapseTest { private final IteratorCollapse collapser = new IteratorCollapse(); @Test public void shouldReturnEmptyIteratorWhenValueIsNull(){ Iterator<String> iterator = collapser.singleIterator(null); assertThat(iterator.hasNext(), equalTo(false)); } @Test public void shouldReturnIteratorWhenOnlyOneIteratorSupplied(){ List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5); Iterator<Integer> iterator = integerList.iterator(); Iterator<Integer> returnedIterator = collapser.singleIterator(iterator); int currentIndex = 0; while( returnedIterator.hasNext() ){ assertThat(returnedIterator.next(), equalTo( integerList.get(currentIndex++) )); } assertThat(currentIndex, equalTo(5)); } @Test public void shouldReturnIteratorWhenMoreThanOneIteratorSupplied(){ List<List<Integer>> integerList = new ArrayList<>(); integerList.add( Arrays.asList(1, 2, 3, 4, 5) ); integerList.add( Arrays.asList(6, 7, 8, 9) ); integerList.add( Arrays.asList(10, 11, 12) ); Iterator<Integer> iterator1 = integerList.get(0).iterator(); Iterator<Integer> iterator2 = integerList.get(1).iterator(); Iterator<Integer> iterator3 = integerList.get(2).iterator(); Iterator<Integer> returnedIterator = collapser.singleIterator(iterator1, iterator2, iterator3); int currentIndex = 0; int totalValue = 0; int listIndex = 0; while( returnedIterator.hasNext() ){ List<Integer> currentList = integerList.get(listIndex); assertThat(returnedIterator.next(), equalTo( currentList.get(currentIndex++) )); if( currentIndex >= currentList.size() ){ listIndex++; currentIndex = 0; } ++totalValue; } assertThat(totalValue, equalTo(12)); } }
2,231
0.66069
0.644106
68
31.82353
28.673077
103
false
false
0
0
0
0
0
0
0.794118
false
false
6
2b3bf22c9cc4ec24b0987b2838c4991442632229
19,361,712,604,171
6368775cff70e45b16590b5bff5a09a5262fc67f
/src/test/java/ch/ethz/globis/phtree/bits/TestBitsLong.java
8b3853e1d2972e7443877743977e83f64f26d7df
[ "Apache-2.0" ]
permissive
tzaeschke/phtree
https://github.com/tzaeschke/phtree
2f348a7363e27ee432a9bec5d1068a0edeade137
04fa75a3680a5115e2d3d022ff27fce4d3bc3f47
refs/heads/master
2023-08-09T18:04:02.026000
2023-07-29T17:12:51
2023-07-29T17:12:51
41,664,931
110
21
Apache-2.0
false
2023-07-29T17:07:11
2015-08-31T08:36:51
2023-07-23T17:31:18
2023-07-29T17:07:09
3,679
111
20
6
Java
false
false
/* * Copyright 2011 ETH Zurich. All Rights Reserved. * * This software is the proprietary information of ETH Zurich. * Use is subject to license terms. */ package ch.ethz.globis.phtree.bits; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.Random; import org.junit.Test; import ch.ethz.globis.phtree.util.BitsLong; import ch.ethz.globis.phtree.v11.Bits; /** * * @author ztilmann * */ public class TestBitsLong { private static final int BITS = 64; @Test public void testCopy1() { long[] s = newBA(0xFFFF, 0xFFFF); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 0, t, 0, 128); check(t, 0xFFFF, 0xFFFF); } @Test public void testCopy2() { long[] s = newBA(0x0F0F, 0xF0F0); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 0, t, 0, 128); check(t, 0x0F0F, 0xF0F0); } @Test public void testCopy3() { long[] s = newBA(0x0F, 0xF000000000000000L); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 60, t, 56, 64); check(t, 0xFF, 0); } @Test public void testCopy4() { long[] s = newBA(0x0F, 0xF000000000000000L); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 60, t, 64, 64); check(t, 0, 0xFF00000000000000L); } /** * Check retain set bits. */ @Test public void testCopy5() { long[] s = newBA(0x00, 0x00); long[] t = newBA(0xFF, 0xFF00000000000000L); BitsLong.copyBitsLeft(s, 60, t, 60, 8); check(t, 0xF0, 0x0F00000000000000L); } /** * Check retain set bits. */ @Test public void testCopy6() { long[] s = newBA(0xF0, 0x0F00000000000000L); long[] t = newBA(0x0F, 0xF000000000000000L); BitsLong.copyBitsLeft(s, 60, t, 60, 8); check(t, 0x00, 0x00); } /** * Check retain set bits. */ @Test public void testCopySingle1() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 60, s, 59, 1); check(s, 0xAAAAAAAAAAAAAABAL, 0xAAAAAAAAAAAAAAAAL); } /** * Check retain set bits. */ @Test public void testCopySingle2() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 59, s, 60, 1); check(s, 0xAAAAAAAAAAAAAAA2L, 0xAAAAAAAAAAAAAAAAL); } /** * Check retain set bits. */ @Test public void testCopySingle3a() { long[] s = newBA(0x0008, 0x00); long[] t = newBA(0x00, 0x00); BitsLong.copyBitsLeft(s, 60, t, 59, 1); check(t, 0x0010, 0x00); } /** * Check retain set bits. */ @Test public void testCopySingle3b() { long[] s = newBA(0xFFFFFFFFFFFFFFF7L, 0xFFFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 60, t, 59, 1); check(t, 0xFFFFFFFFFFFFFFEFL, 0xFFFFFFFFFFFFFFFFL); } /** * Check retain set bits. */ @Test public void testCopySingle4a() { long[] s = newBA(0x0010, 0x00); long[] t = newBA(0x00, 0x00); BitsLong.copyBitsLeft(s, 59, t, 60, 1); check(t, 0x08, 0x00); } /** * Check retain set bits. */ @Test public void testCopySingle4b() { long[] s = newBA(0xFFFFFFFFFFFFFFEFL, 0xFFFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 59, t, 60, 1); check(t, 0xFFFFFFFFFFFFFFF7L, 0xFFFFFFFFFFFFFFFFL); } @Test public void testCopyShift1_OneByteToTwoByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x0AAAAAAAAAAAAAAAL); long[] t = newBA(0xAAAAAAAAAAAAAAAAL, 0x0AAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 60, t, 62, 4); check(t, 0xAAAAAAAAAAAAAAAAL, 0x8AAAAAAAAAAAAAAAL); } @Test public void testCopyShift1_TwoByteToOneByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xF5AAAAAAAAAAAAAAL); long[] t = newBA(0xAAAAAAAAAAAAAAAAL, 0xF5AAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 62, t, 64, 4); check(t, 0xAAAAAAAAAAAAAAAAL, 0xB5AAAAAAAAAAAAAAL); } @Test public void testCopyLong1() { long[] s = newBA(0x000A, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); long[] t = newBA(0x000A, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 60, t, 65, 129); check(t, 0x000A, 0xD555555555555555L, 0x5555555555555555L, 0x6AAAAAAAAAAAAAAAL); } @Test public void testCopySplitForwardA() { long[] s = newBA(0x000F, 0xF000000000000000L); long[] t = newBA(0x0000, 0x00000000); BitsLong.copyBitsLeft(s, 60, t, 61, 8); check(t, 0x0007, 0xF800000000000000L); } @Test public void testCopySplitForwardB() { long[] s = newBA(0xFFFFFFFFFFFFFFF0L, 0x0FFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 60, t, 61, 8); check(t, 0xFFFFFFFFFFFFFFF8L, 0x07FFFFFFFFFFFFFFL); } @Test public void testCopySplitBackwardA() { long[] s = newBA(0x000F, 0xF000000000000000L); long[] t = newBA(0x0000, 0x00000000); BitsLong.copyBitsLeft(s, 60, t, 59, 8); check(t, 0x001F, 0xE000000000000000L); } @Test public void testCopySplitBackwardB() { long[] s = newBA(0xFFFFFFFFFFFFFFF0L, 0x0FFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 60, t, 59, 8); check(t, 0xFFFFFFFFFFFFFFE0L, 0x1FFFFFFFFFFFFFFFL); } @Test public void testCopyLeftA() { long[] s = newBA(0xFFFFFFFFFFFFFFFFL, 0x00, 0x00); BitsLong.copyBitsLeft(s, 64, s, 62, 126); check(s, 0xFFFFFFFFFFFFFFFCL, 0x00, 0x00); } @Test public void testCopyLeftB() { long[] s = newBA(0x00, 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 64, s, 62, 126); check(s, 0x03, 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); } @Test public void testInsert1_OneByteToTwoByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 60, 5); check(60, 5, s, 0xAAAAAAAAAAAAAAAAL, 0xD555000000000000L); } @Test public void testInsert1_TwoByteToOneByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 60, 3); check(60, 3, s, 0xAAAAAAAAAAAAAAABL, 0x5554000000000000L); } @Test public void testInsert1_OneByteToTwoByteBIG() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xCCCCCCCCCCCCCCCCL, 0xCCCCCCCCCCCCCCCCL, 0xAAA0000000000000L); long[] s2 = s.clone(); BitsLong.insertBits(s, 60, 5+128); insertBitsSlow(s2, 60, 5+128); check(60, 5+128, s, s2); } @Test public void testInsert1_TwoByteToOneByteBIG() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xCCCCCCCCCCCCCCCCL, 0xCCCCCCCCCCCCCCCCL, 0xAAA0000000000000L); BitsLong.insertBits(s, 60, 3+128); check(60, 3+128, s, 0xAAAAAAAAAAAAAAABL, 0x5554000000000000L); } @Test public void testInsert2() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 64, 1); check(s, 0xAAAAAAAAAAAAAAAAL, 0xD550000000000000L); } @Test public void testInsert3() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 63, 1); check(s, 0xAAAAAAAAAAAAAAAAL, 0x5550000000000000L); } @Test public void testInsert4() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x5555); BitsLong.insertBits(s, 0, 64); check(0, 64, s, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); } @Test public void testInsert5() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAA55000000000000L); BitsLong.insertBits(s, 64, 64); check(64, 64, s, 0xAAAAAAAAAAAAAAAAL, 0xAA55000000000000L); } @Test public void testInsert_Bug1() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 193, 5); check(s, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xA955555555555555L); } @Test public void testInsert_Bug2() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 128, 67); check(s, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xB555555555555555L); } @Test public void testInsert_Bug2b() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x0000); BitsLong.insertBits(s, 0, 67); check(s, 0xAAAAAAAAAAAAAAAAL, 0x1555555555555555L); } @Test public void testInsert_Bug2c() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 0, 3); check(s, 0xB555555555555555L); } @Test public void testInsertRandom() { Random r = new Random(0); int N = 1000*1000; long[][] data = new long[N][]; long[][] data2 = new long[N][]; int[] start = new int[N]; int[] ins = new int[N]; // long t1 = System.currentTimeMillis(); for (int i = 0; i < N; i++) { int LEN = r.nextInt(14)+1; data[i] = newBaPattern(LEN, r); data2[i] = data[i].clone(); start[i] = r.nextInt(LEN*BITS+1); int maxIns = LEN*BITS-start[i]; ins[i] = r.nextInt(maxIns+1); } // long t2 = System.currentTimeMillis(); // System.out.println("prepare: " + (t2-t1)); // t1 = System.currentTimeMillis(); for (int i = 0; i < N; i++) { BitsLong.insertBits(data[i], start[i], ins[i]); //This is the old version BitsLong.insertBits1(data2[i], start[i], ins[i]); // System.out.println("s=" + start + " i=" + ins); // System.out.println("x=" + BitsLong.toBinary(x)); // System.out.println("s=" + BitsLong.toBinary(s)); check(data2[i], data[i]); } // t2 = System.currentTimeMillis(); // System.out.println("shift: " + (t2-t1)); // System.out.println("n=" + BitsLong.getStats()); } @Test public void testInsert_Bug3() { long[] s = newBA(0x804D3F2, 0xF130A329, 0xE8DAF3B7, 0x9CF00000, 0x0, 0x0, 0x0, 0x0); long[] t = newBA(0x804D3F2, 0xF130A329, 0xE8DAF3B7, 0x9CF00000, 0x0, 0x0, 0x0, 0x0); BitsLong.insertBits(s, 13, 192); BitsLong.insertBits1(t, 13, 192); check(13, 192, s, t); } @Test public void testInsert_BugI1() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); long[] t = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 54, 4); BitsLong.insertBits1(t, 54, 4); check(s, t); } @Test public void testCopyLeftRandom() { Random rnd = new Random(0); int BA_LEN = 6; long[] ba = new long[BA_LEN]; for (int i1 = 0; i1 < 1000000; i1++) { //populate for (int i2 = 0; i2 < ba.length; i2++) { ba[i2] = rnd.nextLong(); } //clone long[] ba1 = Arrays.copyOf(ba, ba.length); long[] ba2 = Arrays.copyOf(ba, ba.length); int start = rnd.nextInt(64) + 64; //start somewhere in fourth short int nBits = rnd.nextInt(64 * 3); //remove up to two shorts //compute //System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); BitsLong.copyBitsLeft(ba1, start+nBits, ba1, start, ba1.length*BITS-start-nBits); //compute backup copyBitsLeftSlow(ba2, start+nBits, ba2, start, ba2.length*BITS-start-nBits); //check if (!Arrays.equals(ba2, ba1)) { System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); System.out.println("i=" + i1 + " posSrc=" + (start+nBits) + " posTrg=" + start + " n=" + (ba1.length*BITS-start-nBits)); System.out.println("ori. = " + BitsLong.toBinary(ba)); System.out.println("act. = " + BitsLong.toBinary(ba1)); System.out.println("exp. = " + BitsLong.toBinary(ba2)); System.out.println("ori. = " + Arrays.toString(ba)); System.out.println("act. = " + Arrays.toString(ba1)); System.out.println("exp. = " + Arrays.toString(ba2)); fail(); } } } @Test public void testCopyLeftRandomRndLen() { Random rnd = new Random(0); int BA_LEN = 10;//TODO long[] ba = new long[BA_LEN]; for (int i1 = 0; i1 < 1000000; i1++) { //populate for (int i2 = 0; i2 < ba.length; i2++) { ba[i2] = rnd.nextLong(); } //clone long[] ba1 = Arrays.copyOf(ba, ba.length); long[] ba2 = Arrays.copyOf(ba, ba.length); int start = rnd.nextInt(ba.length*BITS); //start somewhere in fourth short int dest = rnd.nextInt(start+1); //can be 0! int nBits = rnd.nextInt(ba.length*BITS-start); //compute //System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); BitsLong.copyBitsLeft(ba1, start, ba1, dest, nBits); //compute backup copyBitsLeftSlow(ba2, start, ba2, dest, nBits); //check if (!Arrays.equals(ba2, ba1)) { System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); System.out.println("i=" + i1 + " posSrc=" + (start) + " posTrg=" + dest + " nBits=" + nBits); System.out.println("ori. = " + BitsLong.toBinary(ba)); System.out.println("act. = " + BitsLong.toBinary(ba1)); System.out.println("exp. = " + BitsLong.toBinary(ba2)); System.out.println("ori. = " + Arrays.toString(ba)); System.out.println("act. = " + Arrays.toString(ba1)); System.out.println("exp. = " + Arrays.toString(ba2)); check(ba1, ba2); fail(); } } } /** * Copy to other allows start<dest. */ @Test public void testCopyLeftRandomToOther() { Random rnd = new Random(0); int BA_LEN = 10; long[] ba = new long[BA_LEN]; for (int i1 = 0; i1 < 1000000; i1++) { //populate for (int i2 = 0; i2 < ba.length; i2++) { ba[i2] = rnd.nextLong(); } //clone long[] src = newBaPattern(BA_LEN, rnd); long[] ba1 = Arrays.copyOf(src, src.length); long[] ba2 = Arrays.copyOf(src, src.length); int start = rnd.nextInt(ba.length*BITS); //start somewhere in fourth short int dest = rnd.nextInt(ba.length*BITS); //can be 0! int nBits = rnd.nextInt(ba.length*BITS-(start<dest?dest:start)); //compute //System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); BitsLong.copyBitsLeft(src, start, ba1, dest, nBits); //compute backup copyBitsLeftSlow(src, start, ba2, dest, nBits); //check if (!Arrays.equals(ba2, ba1)) { System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); System.out.println("i=" + i1 + " posSrc=" + (start) + " posTrg=" + dest + " nBits=" + nBits); System.out.println("ori. = " + BitsLong.toBinary(ba)); System.out.println("act. = " + BitsLong.toBinary(ba1)); System.out.println("exp. = " + BitsLong.toBinary(ba2)); System.out.println("ori. = " + Arrays.toString(ba)); System.out.println("act. = " + Arrays.toString(ba1)); System.out.println("exp. = " + Arrays.toString(ba2)); fail(); } } } @Test public void testGetBit() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x5555555555555555L, 0xFFFFFFFFFFFFFFFFL, 0x0L, 0xAAAA0000FFFF5555L); long[] t = newBA(0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L); for (int i = 0; i < BITS*s.length; i++) { BitsLong.setBit(t, i, BitsLong.getBit(s, i)); } check(t, s); } @Test public void testCopySlow() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x5555555555555555L, 0xFFFFFFFFFFFFFFFFL, 0x0L, 0xAAAA0000FFFF5555L); long[] t = newBA(0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L); copyBitsLeftSlow(s, 0, t, 0, BITS*s.length); check(t, s); long[] t2 = newBA(0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L); BitsLong.copyBitsLeft(s, 0, t2, 0, BITS*s.length); check(t2, s); } @Test public void testCopyLeftBug1() { long[] s = {-1155484576, -723955400, 1033096058, -1690734402, -1557280266, 1327362106}; //long[] t = new long[6]; //act. = [-591608102401, -370665164800, 528945182207, -865656013313, -797327496192, 1327362106] long[] e = {-591608102401L, -370665164800L, 528945182207L, -865656013313L, -797327496192L, 679609398330L}; //ori. = 11111111.11111111.11111111.11111111.10111011.00100000.10110100.01100000, 11111111.11111111.11111111.11111111.11010100.11011001.01010001.00111000, 00000000.00000000.00000000.00000000.00111101.10010011.11001011.01111010, 11111111.11111111.11111111.11111111.10011011.00111001.01110000.10111110, 11111111.11111111.11111111.11111111.10100011.00101101.11001001.11110110, 00000000.00000000.00000000.00000000.01001111.00011101.11110000.00111010, //act. = 11111111.11111111.11111111.01110110.01000001.01101000.11000001.11111111, 11111111.11111111.11111111.10101001.10110010.10100010.01110000.00000000, 00000000.00000000.00000000.01111011.00100111.10010110.11110101.11111111, 11111111.11111111.11111111.00110110.01110010.11100001.01111101.11111111, 11111111.11111111.11111111.01000110.01011011.10010011.11101100.00000000, 00000000.00000000.00000000.00000000.01001111.00011101.11110000.00111010, //exp. = 11111111.11111111.11111111.01110110.01000001.01101000.11000001.11111111, 11111111.11111111.11111111.10101001.10110010.10100010.01110000.00000000, 00000000.00000000.00000000.01111011.00100111.10010110.11110101.11111111, 11111111.11111111.11111111.00110110.01110010.11100001.01111101.11111111, 11111111.11111111.11111111.01000110.01011011.10010011.11101100.00000000, 00000000.00000000.00000000.10011110.00111011.11100000.01110100.00111010, BitsLong.copyBitsLeft(s, 21, s, 12, 363); check(s, e); } @Test public void testCopyLeftBug2() { long[] s = {1842130704, 1599145891, -1341955486, 1631478226, 1754478786, -1370798799}; //long[] t = new long[6]; //act. = [-591608102401, -370665164800, 528945182207, -865656013313, -797327496192, 1327362106] long[] e = {1842130704, 1599145891, -1341955486, 1631478226, 1754478786, -1370798799}; //ori. = 00000000.00000000.00000000.00000000.01101101.11001100.10101111.00010000, 00000000.00000000.00000000.00000000.01011111.01010001.00000111.10100011, 11111111.11111111.11111111.11111111.10110000.00000011.01100010.01100010, 00000000.00000000.00000000.00000000.01100001.00111110.01100001.11010010, 00000000.00000000.00000000.00000000.01101000.10010011.00111000.11000010, 11111111.11111111.11111111.11111111.10101110.01001011.01000101.00110001, //act. = 00000000.00000000.00000000.00000000.01101101.11001100.10101111.00010000, 00000000.00000000.00000000.00000000.01011111.01010001.00000111.10100011, 00000000.00111111.11111111.11111111.10110000.00000011.01100010.01100010, 00000000.00000000.00000000.00000000.01100001.00111110.01100001.11010010, 00000000.00000000.00000000.00000000.01101000.10010011.00111000.11000010, 00000000.00111111.11111111.11111111.10101110.01001011.01000101.00110001, //exp. = 00000000.00000000.00000000.00000000.01101101.11001100.10101111.00010000, 00000000.00000000.00000000.00000000.01011111.01010001.00000111.10100011, 11111111.11111111.11111111.11111111.10110000.00000011.01100010.01100010, 00000000.00000000.00000000.00000000.01100001.00111110.01100001.11010010, 00000000.00000000.00000000.00000000.01101000.10010011.00111000.11000010, 11111111.11111111.11111111.11111111.10101110.01001011.01000101.00110001, BitsLong.copyBitsLeft(s, 10, s, 10, 374); check(s, e); } @Test public void testCopyLeftBug3() { //src=01100000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000111.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00110000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] src1 = {6989516252934832128L, 287948901175001088L, 576179277326712832L, 562949953421312L, 3458764513820540928L, 0}; //p1=8 //dst=01100010.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] dst1a={7061644215716937728L, 0, 0, 0, 0, 0, 0, 0}; long[] dst1b={7061644215716937728L, 0, 0, 0, 0, 0, 0, 0}; //p2=10 //n=124 BitsLong.copyBitsLeft(src1, 8, dst1a, 10, 124); copyBitsLeftSlow(src1, 8, dst1b, 10, 124); //System.out.println(BitsLong.toBinary(src1)); check(dst1a, dst1b); //src=01100000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000111.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00110000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] src2 = {6989516252934832128L, 287948901175001088L, 576179277326712832L, 562949953421312L, 3458764513820540928L, 0}; //p1=134 //dst=01100011.00111111.11110000.00000000.00000000.00000000.00000000.00000000, 00000000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] dst2a = {7151698616078303232L, 71987225293750272L, 0, 0, 0, 0, 0, 0}; long[] dst2b = {7151698616078303232L, 71987225293750272L, 0, 0, 0, 0, 0, 0}; //p2=134 //n=124 BitsLong.copyBitsLeft(src2, 134, dst2a, 134, 124); copyBitsLeftSlow(src2, 134, dst2b, 134, 124); check(dst2a, dst2b); //src=01100000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000111.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00110000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] src3 = {6989516252934832128L, 287948901175001088L, 576179277326712832L, 562949953421312L, 3458764513820540928L, 0}; //p1=260 //dst=01100011.01111111.11110000.00000000.00000000.00000000.00000000.00000000, 00000000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] dst3a = {7169713014587785216L, 71987225293750272L, 287948901175001088L, 562949953421312L, 0, 0, 0, 0}; long[] dst3b = {7169713014587785216L, 71987225293750272L, 287948901175001088L, 562949953421312L, 0, 0, 0, 0}; //p2=382 //n=124 BitsLong.copyBitsLeft(src3, 260, dst3a, 382, 124); copyBitsLeftSlow(src3, 260, dst3b, 382, 124); check(dst3a, dst3b); } @Test public void copyBitsLeftBug4() { long[] s = {//-4922475540349336432L, -3370274031255729188L, -2971948390163211717L, //-8730854458729406051L, -1856941488587171136L, //2470753881526567411L, //1532230816302433446L, //-395233716872471639L, -5121607137339136235L, -5256749969541153749L}; // long[] r1 = {-4922475540349336432L, -3370274031255729188L, -2971948390163211717L, // -8730854458729406051L, -1856941488587171136L, 2480197071496421608L, // 8671562125591512230L, -395233716872471639L, -5121607137339136235L, // -5256749969541153749L}; // long[] r2 = {-4922475540349336432L, -3370274031255729188L, -2971948390163211717L, // -8730854458729406051L, -1856941488587171136L, 2480197071496421608L, // 8737990220095227046L, -395233716872471639L, -5121607137339136235L, // -5256749969541153749L}; long[] b1 = s.clone(); long[] b2 = s.clone(); int posSrc=59;//123;//251;//571; int posTrg=10;//330; int nBits=61; BitsLong.copyBitsLeft(b1, posSrc, b1, posTrg, nBits); copyBitsLeftSlow(b2, posSrc, b2, posTrg, nBits); check(b1, b2); } @Test public void copyBitsLeftBug5() { long[] s = {//2256040733390859228L, -7415412748790187952L, 5988196814927695714L, //6456740631013180783L, //492044650721807007L, -5612393831914860878L, 4754515495077470782L, -1948216037247540742L, -5215875920690959100L, };//-8889461600749447869L}; long[] b1 = s.clone(); long[] b2 = s.clone(); int posSrc=95;//223;//479; int posTrg=44;//300; int nBits=84; BitsLong.copyBitsLeft(b1, posSrc, b1, posTrg, nBits); copyBitsLeftSlow(b2, posSrc, b2, posTrg, nBits); check(b1, b2); } @Test public void copyBitsLeftBug6() { long[] s = {//26658067013538148L, -7165901376423424552L, 3830723913108681159L, -7477064955817770196L, 2470570724734906539L, 4372500218542924969L, //1592114322442893905L, //-3029650008794553899L, 4082479205780751270L, };//-4513395991245529464L}; long[] b1 = s.clone(); long[] b2 = s.clone(); int posSrc=45;//237; int posTrg=70;//262; int nBits=86;//278; //System.out.println("ori: " + BitsLong.toBinary(s)); BitsLong.copyBitsLeft(s, posSrc, b1, posTrg, nBits); copyBitsLeftSlow(s, posSrc, b2, posTrg, nBits); check(b1, b2); } @Test public void copyBitsLeftBug7() { // long[] s = new long[155]; // long[] b1 = new long[158]; // Arrays.fill(s,0x5555555555555555L); // Arrays.fill(b1,0xAAAAAAAAAAAAAAAAL); // long[] b2 = b1.clone(); // // int posSrc=9600+5; // int posTrg=32 + 315*31; // int nBits=315; long[] s = new long[2]; long[] b1 = new long[3]; Arrays.fill(s,0x5555555555555555L); Arrays.fill(b1,0xAAAAAAAAAAAAAAAAL); long[] b2 = b1.clone(); int posSrc=9600+5 - 150*64; int posTrg=32 + 315*31 -152*64; int nBits=315-64*3; // System.out.println("s="+ posSrc + " t=" + posTrg + " l=" + nBits + " 158*64=" + 158*64); // System.out.println("s+n= "+ (posSrc+nBits) + " t+n=" + (posTrg+nBits)); // System.out.println("ori: " + BitsLong.toBinary(s)); copyBitsLeftSlow(s, posSrc, b2, posTrg, nBits); // System.out.println("b2 : " + BitsLong.toBinary(b2)); BitsLong.copyBitsLeft(s, posSrc, b1, posTrg, nBits); check(b1, b2); } private void insertBitsSlow(long[] ba, int start, int nBits) { int bitsToShift = ba.length*BITS - start - nBits; for (int i = 0; i < bitsToShift; i++) { int srcBit = ba.length*BITS - nBits - i - 1; int trgBit = ba.length*BITS - i - 1; BitsLong.setBit(ba, trgBit, BitsLong.getBit(ba, srcBit)); } } // private void removetBitsSlow(long[] ba, int start, int nBits) { // int bitsToShift = ba.length*BITS - start - (nBits); // for (int i = 0; i < bitsToShift; i++) { // int srcBit = start + (nBits) + i; // int trgBit = start + i; // BitsLong.setBit(ba, trgBit, BitsLong.getBit(ba, srcBit)); // } // } public static void copyBitsLeftSlow(long[] src, int posSrc, long[] trg, int posTrg, int nBits) { for (int i = 0; i < nBits; i++) { BitsLong.setBit(trg, posTrg + i, BitsLong.getBit(src, posSrc + i)); } } @Test public void testNumberOfConflictingBits() { assertEquals(0, Bits.getMaxConflictingBits(0, 0, 0, 63)); assertEquals(64, Bits.getMaxConflictingBits(0, -1L, 0, 63)); assertEquals(64, Bits.getMaxConflictingBits(0, -1L, 63, 63)); assertEquals(1, Bits.getMaxConflictingBits(0, -1L, 0, 0)); assertEquals(0, Bits.getMaxConflictingBits(0, 1, 1, 1)); } @Test public void testBinarySearch() { long[] ba = {1, 34, 43, 123, 255, 1000}; checkBinarySearch(ba, 0); checkBinarySearch(ba, 1); checkBinarySearch(ba, 2); checkBinarySearch(ba, 34); checkBinarySearch(ba, 40); checkBinarySearch(ba, 43); checkBinarySearch(ba, 45); checkBinarySearch(ba, 123); checkBinarySearch(ba, 255); checkBinarySearch(ba, 999); checkBinarySearch(ba, 1000); checkBinarySearch(ba, 1001); } private void checkBinarySearch(long[] ba, int key) { int i1 = Arrays.binarySearch(ba, key); int i2 = BitsLong.binarySearch(ba, 0, ba.length, key, 64, 0); assertEquals(i1, i2); } private void check(long[] t, long ... expected) { for (int i = 0; i < expected.length; i++) { if (expected[i] != t[i]) { System.out.println("i=" + i); System.out.println("act:" + BitsLong.toBinary(t) + "/ " + t[i]); System.out.println("exp:" + BitsLong.toBinary(expected) + " / " + expected[i]); assertEquals("i=" + i + " | " + BitsLong.toBinary(expected) + " / " + BitsLong.toBinary(t), expected[i], t[i]); } } } private void check(int posIgnore, int lenIgnore, long[] t, long ... expected) { for (int i = 0; i < expected.length; i++) { if (posIgnore / 64 <= i && i <= (posIgnore + lenIgnore)/64) { long mask = -1L; if (posIgnore / 64 == i) { mask = (mask<<(posIgnore%64)) >>> (posIgnore%64); } if (i == (posIgnore + lenIgnore)/64) { int end = (posIgnore+lenIgnore) % 64; mask = (mask >>> (64-end)) << (64-end); } mask = ~mask; // System.out.println("c-mask: "+ Bits.toBinary(mask)); t[i] &= mask; expected[i] &= mask; } // System.out.println("i=" + i + " \nex= " + BitsLong.toBinary(expected, 32) + " \nac= " + // BitsLong.toBinary(t)); assertEquals("i=" + i + " | " + BitsLong.toBinary(expected) + " / " + BitsLong.toBinary(t), expected[i], t[i]); } } private long[] newBA(long...ints) { long[] ba = new long[ints.length]; for (int i = 0; i < ints.length; i++) { ba[i] = ints[i]; } return ba; } private long[] newBaPattern(int n, Random r) { long[] ba = new long[n]; for (int i = 0; i < n; i++) { ba[i] = r.nextLong(); } return ba; } }
UTF-8
Java
30,074
java
TestBitsLong.java
Java
[ { "context": "h.ethz.globis.phtree.v11.Bits;\n\n/**\n * \n * @author ztilmann\n *\n */\npublic class TestBitsLong {\n\n\tprivate stat", "end": 466, "score": 0.9979772567749023, "start": 458, "tag": "USERNAME", "value": "ztilmann" } ]
null
[]
/* * Copyright 2011 ETH Zurich. All Rights Reserved. * * This software is the proprietary information of ETH Zurich. * Use is subject to license terms. */ package ch.ethz.globis.phtree.bits; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.Random; import org.junit.Test; import ch.ethz.globis.phtree.util.BitsLong; import ch.ethz.globis.phtree.v11.Bits; /** * * @author ztilmann * */ public class TestBitsLong { private static final int BITS = 64; @Test public void testCopy1() { long[] s = newBA(0xFFFF, 0xFFFF); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 0, t, 0, 128); check(t, 0xFFFF, 0xFFFF); } @Test public void testCopy2() { long[] s = newBA(0x0F0F, 0xF0F0); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 0, t, 0, 128); check(t, 0x0F0F, 0xF0F0); } @Test public void testCopy3() { long[] s = newBA(0x0F, 0xF000000000000000L); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 60, t, 56, 64); check(t, 0xFF, 0); } @Test public void testCopy4() { long[] s = newBA(0x0F, 0xF000000000000000L); long[] t = new long[2]; BitsLong.copyBitsLeft(s, 60, t, 64, 64); check(t, 0, 0xFF00000000000000L); } /** * Check retain set bits. */ @Test public void testCopy5() { long[] s = newBA(0x00, 0x00); long[] t = newBA(0xFF, 0xFF00000000000000L); BitsLong.copyBitsLeft(s, 60, t, 60, 8); check(t, 0xF0, 0x0F00000000000000L); } /** * Check retain set bits. */ @Test public void testCopy6() { long[] s = newBA(0xF0, 0x0F00000000000000L); long[] t = newBA(0x0F, 0xF000000000000000L); BitsLong.copyBitsLeft(s, 60, t, 60, 8); check(t, 0x00, 0x00); } /** * Check retain set bits. */ @Test public void testCopySingle1() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 60, s, 59, 1); check(s, 0xAAAAAAAAAAAAAABAL, 0xAAAAAAAAAAAAAAAAL); } /** * Check retain set bits. */ @Test public void testCopySingle2() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 59, s, 60, 1); check(s, 0xAAAAAAAAAAAAAAA2L, 0xAAAAAAAAAAAAAAAAL); } /** * Check retain set bits. */ @Test public void testCopySingle3a() { long[] s = newBA(0x0008, 0x00); long[] t = newBA(0x00, 0x00); BitsLong.copyBitsLeft(s, 60, t, 59, 1); check(t, 0x0010, 0x00); } /** * Check retain set bits. */ @Test public void testCopySingle3b() { long[] s = newBA(0xFFFFFFFFFFFFFFF7L, 0xFFFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 60, t, 59, 1); check(t, 0xFFFFFFFFFFFFFFEFL, 0xFFFFFFFFFFFFFFFFL); } /** * Check retain set bits. */ @Test public void testCopySingle4a() { long[] s = newBA(0x0010, 0x00); long[] t = newBA(0x00, 0x00); BitsLong.copyBitsLeft(s, 59, t, 60, 1); check(t, 0x08, 0x00); } /** * Check retain set bits. */ @Test public void testCopySingle4b() { long[] s = newBA(0xFFFFFFFFFFFFFFEFL, 0xFFFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 59, t, 60, 1); check(t, 0xFFFFFFFFFFFFFFF7L, 0xFFFFFFFFFFFFFFFFL); } @Test public void testCopyShift1_OneByteToTwoByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x0AAAAAAAAAAAAAAAL); long[] t = newBA(0xAAAAAAAAAAAAAAAAL, 0x0AAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 60, t, 62, 4); check(t, 0xAAAAAAAAAAAAAAAAL, 0x8AAAAAAAAAAAAAAAL); } @Test public void testCopyShift1_TwoByteToOneByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xF5AAAAAAAAAAAAAAL); long[] t = newBA(0xAAAAAAAAAAAAAAAAL, 0xF5AAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 62, t, 64, 4); check(t, 0xAAAAAAAAAAAAAAAAL, 0xB5AAAAAAAAAAAAAAL); } @Test public void testCopyLong1() { long[] s = newBA(0x000A, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); long[] t = newBA(0x000A, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.copyBitsLeft(s, 60, t, 65, 129); check(t, 0x000A, 0xD555555555555555L, 0x5555555555555555L, 0x6AAAAAAAAAAAAAAAL); } @Test public void testCopySplitForwardA() { long[] s = newBA(0x000F, 0xF000000000000000L); long[] t = newBA(0x0000, 0x00000000); BitsLong.copyBitsLeft(s, 60, t, 61, 8); check(t, 0x0007, 0xF800000000000000L); } @Test public void testCopySplitForwardB() { long[] s = newBA(0xFFFFFFFFFFFFFFF0L, 0x0FFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 60, t, 61, 8); check(t, 0xFFFFFFFFFFFFFFF8L, 0x07FFFFFFFFFFFFFFL); } @Test public void testCopySplitBackwardA() { long[] s = newBA(0x000F, 0xF000000000000000L); long[] t = newBA(0x0000, 0x00000000); BitsLong.copyBitsLeft(s, 60, t, 59, 8); check(t, 0x001F, 0xE000000000000000L); } @Test public void testCopySplitBackwardB() { long[] s = newBA(0xFFFFFFFFFFFFFFF0L, 0x0FFFFFFFFFFFFFFFL); long[] t = newBA(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 60, t, 59, 8); check(t, 0xFFFFFFFFFFFFFFE0L, 0x1FFFFFFFFFFFFFFFL); } @Test public void testCopyLeftA() { long[] s = newBA(0xFFFFFFFFFFFFFFFFL, 0x00, 0x00); BitsLong.copyBitsLeft(s, 64, s, 62, 126); check(s, 0xFFFFFFFFFFFFFFFCL, 0x00, 0x00); } @Test public void testCopyLeftB() { long[] s = newBA(0x00, 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); BitsLong.copyBitsLeft(s, 64, s, 62, 126); check(s, 0x03, 0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL); } @Test public void testInsert1_OneByteToTwoByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 60, 5); check(60, 5, s, 0xAAAAAAAAAAAAAAAAL, 0xD555000000000000L); } @Test public void testInsert1_TwoByteToOneByte() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 60, 3); check(60, 3, s, 0xAAAAAAAAAAAAAAABL, 0x5554000000000000L); } @Test public void testInsert1_OneByteToTwoByteBIG() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xCCCCCCCCCCCCCCCCL, 0xCCCCCCCCCCCCCCCCL, 0xAAA0000000000000L); long[] s2 = s.clone(); BitsLong.insertBits(s, 60, 5+128); insertBitsSlow(s2, 60, 5+128); check(60, 5+128, s, s2); } @Test public void testInsert1_TwoByteToOneByteBIG() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xCCCCCCCCCCCCCCCCL, 0xCCCCCCCCCCCCCCCCL, 0xAAA0000000000000L); BitsLong.insertBits(s, 60, 3+128); check(60, 3+128, s, 0xAAAAAAAAAAAAAAABL, 0x5554000000000000L); } @Test public void testInsert2() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 64, 1); check(s, 0xAAAAAAAAAAAAAAAAL, 0xD550000000000000L); } @Test public void testInsert3() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAA0000000000000L); BitsLong.insertBits(s, 63, 1); check(s, 0xAAAAAAAAAAAAAAAAL, 0x5550000000000000L); } @Test public void testInsert4() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x5555); BitsLong.insertBits(s, 0, 64); check(0, 64, s, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); } @Test public void testInsert5() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAA55000000000000L); BitsLong.insertBits(s, 64, 64); check(64, 64, s, 0xAAAAAAAAAAAAAAAAL, 0xAA55000000000000L); } @Test public void testInsert_Bug1() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 193, 5); check(s, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xA955555555555555L); } @Test public void testInsert_Bug2() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 128, 67); check(s, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xB555555555555555L); } @Test public void testInsert_Bug2b() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x0000); BitsLong.insertBits(s, 0, 67); check(s, 0xAAAAAAAAAAAAAAAAL, 0x1555555555555555L); } @Test public void testInsert_Bug2c() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 0, 3); check(s, 0xB555555555555555L); } @Test public void testInsertRandom() { Random r = new Random(0); int N = 1000*1000; long[][] data = new long[N][]; long[][] data2 = new long[N][]; int[] start = new int[N]; int[] ins = new int[N]; // long t1 = System.currentTimeMillis(); for (int i = 0; i < N; i++) { int LEN = r.nextInt(14)+1; data[i] = newBaPattern(LEN, r); data2[i] = data[i].clone(); start[i] = r.nextInt(LEN*BITS+1); int maxIns = LEN*BITS-start[i]; ins[i] = r.nextInt(maxIns+1); } // long t2 = System.currentTimeMillis(); // System.out.println("prepare: " + (t2-t1)); // t1 = System.currentTimeMillis(); for (int i = 0; i < N; i++) { BitsLong.insertBits(data[i], start[i], ins[i]); //This is the old version BitsLong.insertBits1(data2[i], start[i], ins[i]); // System.out.println("s=" + start + " i=" + ins); // System.out.println("x=" + BitsLong.toBinary(x)); // System.out.println("s=" + BitsLong.toBinary(s)); check(data2[i], data[i]); } // t2 = System.currentTimeMillis(); // System.out.println("shift: " + (t2-t1)); // System.out.println("n=" + BitsLong.getStats()); } @Test public void testInsert_Bug3() { long[] s = newBA(0x804D3F2, 0xF130A329, 0xE8DAF3B7, 0x9CF00000, 0x0, 0x0, 0x0, 0x0); long[] t = newBA(0x804D3F2, 0xF130A329, 0xE8DAF3B7, 0x9CF00000, 0x0, 0x0, 0x0, 0x0); BitsLong.insertBits(s, 13, 192); BitsLong.insertBits1(t, 13, 192); check(13, 192, s, t); } @Test public void testInsert_BugI1() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); long[] t = newBA(0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL, 0xAAAAAAAAAAAAAAAAL); BitsLong.insertBits(s, 54, 4); BitsLong.insertBits1(t, 54, 4); check(s, t); } @Test public void testCopyLeftRandom() { Random rnd = new Random(0); int BA_LEN = 6; long[] ba = new long[BA_LEN]; for (int i1 = 0; i1 < 1000000; i1++) { //populate for (int i2 = 0; i2 < ba.length; i2++) { ba[i2] = rnd.nextLong(); } //clone long[] ba1 = Arrays.copyOf(ba, ba.length); long[] ba2 = Arrays.copyOf(ba, ba.length); int start = rnd.nextInt(64) + 64; //start somewhere in fourth short int nBits = rnd.nextInt(64 * 3); //remove up to two shorts //compute //System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); BitsLong.copyBitsLeft(ba1, start+nBits, ba1, start, ba1.length*BITS-start-nBits); //compute backup copyBitsLeftSlow(ba2, start+nBits, ba2, start, ba2.length*BITS-start-nBits); //check if (!Arrays.equals(ba2, ba1)) { System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); System.out.println("i=" + i1 + " posSrc=" + (start+nBits) + " posTrg=" + start + " n=" + (ba1.length*BITS-start-nBits)); System.out.println("ori. = " + BitsLong.toBinary(ba)); System.out.println("act. = " + BitsLong.toBinary(ba1)); System.out.println("exp. = " + BitsLong.toBinary(ba2)); System.out.println("ori. = " + Arrays.toString(ba)); System.out.println("act. = " + Arrays.toString(ba1)); System.out.println("exp. = " + Arrays.toString(ba2)); fail(); } } } @Test public void testCopyLeftRandomRndLen() { Random rnd = new Random(0); int BA_LEN = 10;//TODO long[] ba = new long[BA_LEN]; for (int i1 = 0; i1 < 1000000; i1++) { //populate for (int i2 = 0; i2 < ba.length; i2++) { ba[i2] = rnd.nextLong(); } //clone long[] ba1 = Arrays.copyOf(ba, ba.length); long[] ba2 = Arrays.copyOf(ba, ba.length); int start = rnd.nextInt(ba.length*BITS); //start somewhere in fourth short int dest = rnd.nextInt(start+1); //can be 0! int nBits = rnd.nextInt(ba.length*BITS-start); //compute //System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); BitsLong.copyBitsLeft(ba1, start, ba1, dest, nBits); //compute backup copyBitsLeftSlow(ba2, start, ba2, dest, nBits); //check if (!Arrays.equals(ba2, ba1)) { System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); System.out.println("i=" + i1 + " posSrc=" + (start) + " posTrg=" + dest + " nBits=" + nBits); System.out.println("ori. = " + BitsLong.toBinary(ba)); System.out.println("act. = " + BitsLong.toBinary(ba1)); System.out.println("exp. = " + BitsLong.toBinary(ba2)); System.out.println("ori. = " + Arrays.toString(ba)); System.out.println("act. = " + Arrays.toString(ba1)); System.out.println("exp. = " + Arrays.toString(ba2)); check(ba1, ba2); fail(); } } } /** * Copy to other allows start<dest. */ @Test public void testCopyLeftRandomToOther() { Random rnd = new Random(0); int BA_LEN = 10; long[] ba = new long[BA_LEN]; for (int i1 = 0; i1 < 1000000; i1++) { //populate for (int i2 = 0; i2 < ba.length; i2++) { ba[i2] = rnd.nextLong(); } //clone long[] src = newBaPattern(BA_LEN, rnd); long[] ba1 = Arrays.copyOf(src, src.length); long[] ba2 = Arrays.copyOf(src, src.length); int start = rnd.nextInt(ba.length*BITS); //start somewhere in fourth short int dest = rnd.nextInt(ba.length*BITS); //can be 0! int nBits = rnd.nextInt(ba.length*BITS-(start<dest?dest:start)); //compute //System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); BitsLong.copyBitsLeft(src, start, ba1, dest, nBits); //compute backup copyBitsLeftSlow(src, start, ba2, dest, nBits); //check if (!Arrays.equals(ba2, ba1)) { System.out.println("i=" + i1 + " start=" + start + " nBits=" + nBits); System.out.println("i=" + i1 + " posSrc=" + (start) + " posTrg=" + dest + " nBits=" + nBits); System.out.println("ori. = " + BitsLong.toBinary(ba)); System.out.println("act. = " + BitsLong.toBinary(ba1)); System.out.println("exp. = " + BitsLong.toBinary(ba2)); System.out.println("ori. = " + Arrays.toString(ba)); System.out.println("act. = " + Arrays.toString(ba1)); System.out.println("exp. = " + Arrays.toString(ba2)); fail(); } } } @Test public void testGetBit() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x5555555555555555L, 0xFFFFFFFFFFFFFFFFL, 0x0L, 0xAAAA0000FFFF5555L); long[] t = newBA(0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L); for (int i = 0; i < BITS*s.length; i++) { BitsLong.setBit(t, i, BitsLong.getBit(s, i)); } check(t, s); } @Test public void testCopySlow() { long[] s = newBA(0xAAAAAAAAAAAAAAAAL, 0x5555555555555555L, 0xFFFFFFFFFFFFFFFFL, 0x0L, 0xAAAA0000FFFF5555L); long[] t = newBA(0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L); copyBitsLeftSlow(s, 0, t, 0, BITS*s.length); check(t, s); long[] t2 = newBA(0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L, 0xF0F0F0F0F0F0F0F0L); BitsLong.copyBitsLeft(s, 0, t2, 0, BITS*s.length); check(t2, s); } @Test public void testCopyLeftBug1() { long[] s = {-1155484576, -723955400, 1033096058, -1690734402, -1557280266, 1327362106}; //long[] t = new long[6]; //act. = [-591608102401, -370665164800, 528945182207, -865656013313, -797327496192, 1327362106] long[] e = {-591608102401L, -370665164800L, 528945182207L, -865656013313L, -797327496192L, 679609398330L}; //ori. = 11111111.11111111.11111111.11111111.10111011.00100000.10110100.01100000, 11111111.11111111.11111111.11111111.11010100.11011001.01010001.00111000, 00000000.00000000.00000000.00000000.00111101.10010011.11001011.01111010, 11111111.11111111.11111111.11111111.10011011.00111001.01110000.10111110, 11111111.11111111.11111111.11111111.10100011.00101101.11001001.11110110, 00000000.00000000.00000000.00000000.01001111.00011101.11110000.00111010, //act. = 11111111.11111111.11111111.01110110.01000001.01101000.11000001.11111111, 11111111.11111111.11111111.10101001.10110010.10100010.01110000.00000000, 00000000.00000000.00000000.01111011.00100111.10010110.11110101.11111111, 11111111.11111111.11111111.00110110.01110010.11100001.01111101.11111111, 11111111.11111111.11111111.01000110.01011011.10010011.11101100.00000000, 00000000.00000000.00000000.00000000.01001111.00011101.11110000.00111010, //exp. = 11111111.11111111.11111111.01110110.01000001.01101000.11000001.11111111, 11111111.11111111.11111111.10101001.10110010.10100010.01110000.00000000, 00000000.00000000.00000000.01111011.00100111.10010110.11110101.11111111, 11111111.11111111.11111111.00110110.01110010.11100001.01111101.11111111, 11111111.11111111.11111111.01000110.01011011.10010011.11101100.00000000, 00000000.00000000.00000000.10011110.00111011.11100000.01110100.00111010, BitsLong.copyBitsLeft(s, 21, s, 12, 363); check(s, e); } @Test public void testCopyLeftBug2() { long[] s = {1842130704, 1599145891, -1341955486, 1631478226, 1754478786, -1370798799}; //long[] t = new long[6]; //act. = [-591608102401, -370665164800, 528945182207, -865656013313, -797327496192, 1327362106] long[] e = {1842130704, 1599145891, -1341955486, 1631478226, 1754478786, -1370798799}; //ori. = 00000000.00000000.00000000.00000000.01101101.11001100.10101111.00010000, 00000000.00000000.00000000.00000000.01011111.01010001.00000111.10100011, 11111111.11111111.11111111.11111111.10110000.00000011.01100010.01100010, 00000000.00000000.00000000.00000000.01100001.00111110.01100001.11010010, 00000000.00000000.00000000.00000000.01101000.10010011.00111000.11000010, 11111111.11111111.11111111.11111111.10101110.01001011.01000101.00110001, //act. = 00000000.00000000.00000000.00000000.01101101.11001100.10101111.00010000, 00000000.00000000.00000000.00000000.01011111.01010001.00000111.10100011, 00000000.00111111.11111111.11111111.10110000.00000011.01100010.01100010, 00000000.00000000.00000000.00000000.01100001.00111110.01100001.11010010, 00000000.00000000.00000000.00000000.01101000.10010011.00111000.11000010, 00000000.00111111.11111111.11111111.10101110.01001011.01000101.00110001, //exp. = 00000000.00000000.00000000.00000000.01101101.11001100.10101111.00010000, 00000000.00000000.00000000.00000000.01011111.01010001.00000111.10100011, 11111111.11111111.11111111.11111111.10110000.00000011.01100010.01100010, 00000000.00000000.00000000.00000000.01100001.00111110.01100001.11010010, 00000000.00000000.00000000.00000000.01101000.10010011.00111000.11000010, 11111111.11111111.11111111.11111111.10101110.01001011.01000101.00110001, BitsLong.copyBitsLeft(s, 10, s, 10, 374); check(s, e); } @Test public void testCopyLeftBug3() { //src=01100000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000111.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00110000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] src1 = {6989516252934832128L, 287948901175001088L, 576179277326712832L, 562949953421312L, 3458764513820540928L, 0}; //p1=8 //dst=01100010.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] dst1a={7061644215716937728L, 0, 0, 0, 0, 0, 0, 0}; long[] dst1b={7061644215716937728L, 0, 0, 0, 0, 0, 0, 0}; //p2=10 //n=124 BitsLong.copyBitsLeft(src1, 8, dst1a, 10, 124); copyBitsLeftSlow(src1, 8, dst1b, 10, 124); //System.out.println(BitsLong.toBinary(src1)); check(dst1a, dst1b); //src=01100000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000111.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00110000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] src2 = {6989516252934832128L, 287948901175001088L, 576179277326712832L, 562949953421312L, 3458764513820540928L, 0}; //p1=134 //dst=01100011.00111111.11110000.00000000.00000000.00000000.00000000.00000000, 00000000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] dst2a = {7151698616078303232L, 71987225293750272L, 0, 0, 0, 0, 0, 0}; long[] dst2b = {7151698616078303232L, 71987225293750272L, 0, 0, 0, 0, 0, 0}; //p2=134 //n=124 BitsLong.copyBitsLeft(src2, 134, dst2a, 134, 124); copyBitsLeftSlow(src2, 134, dst2b, 134, 124); check(dst2a, dst2b); //src=01100000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000111.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00110000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] src3 = {6989516252934832128L, 287948901175001088L, 576179277326712832L, 562949953421312L, 3458764513820540928L, 0}; //p1=260 //dst=01100011.01111111.11110000.00000000.00000000.00000000.00000000.00000000, 00000000.11111111.11000000.00000000.00000000.00000000.00000000.00000000, 00000011.11111111.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000010.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, 00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000, long[] dst3a = {7169713014587785216L, 71987225293750272L, 287948901175001088L, 562949953421312L, 0, 0, 0, 0}; long[] dst3b = {7169713014587785216L, 71987225293750272L, 287948901175001088L, 562949953421312L, 0, 0, 0, 0}; //p2=382 //n=124 BitsLong.copyBitsLeft(src3, 260, dst3a, 382, 124); copyBitsLeftSlow(src3, 260, dst3b, 382, 124); check(dst3a, dst3b); } @Test public void copyBitsLeftBug4() { long[] s = {//-4922475540349336432L, -3370274031255729188L, -2971948390163211717L, //-8730854458729406051L, -1856941488587171136L, //2470753881526567411L, //1532230816302433446L, //-395233716872471639L, -5121607137339136235L, -5256749969541153749L}; // long[] r1 = {-4922475540349336432L, -3370274031255729188L, -2971948390163211717L, // -8730854458729406051L, -1856941488587171136L, 2480197071496421608L, // 8671562125591512230L, -395233716872471639L, -5121607137339136235L, // -5256749969541153749L}; // long[] r2 = {-4922475540349336432L, -3370274031255729188L, -2971948390163211717L, // -8730854458729406051L, -1856941488587171136L, 2480197071496421608L, // 8737990220095227046L, -395233716872471639L, -5121607137339136235L, // -5256749969541153749L}; long[] b1 = s.clone(); long[] b2 = s.clone(); int posSrc=59;//123;//251;//571; int posTrg=10;//330; int nBits=61; BitsLong.copyBitsLeft(b1, posSrc, b1, posTrg, nBits); copyBitsLeftSlow(b2, posSrc, b2, posTrg, nBits); check(b1, b2); } @Test public void copyBitsLeftBug5() { long[] s = {//2256040733390859228L, -7415412748790187952L, 5988196814927695714L, //6456740631013180783L, //492044650721807007L, -5612393831914860878L, 4754515495077470782L, -1948216037247540742L, -5215875920690959100L, };//-8889461600749447869L}; long[] b1 = s.clone(); long[] b2 = s.clone(); int posSrc=95;//223;//479; int posTrg=44;//300; int nBits=84; BitsLong.copyBitsLeft(b1, posSrc, b1, posTrg, nBits); copyBitsLeftSlow(b2, posSrc, b2, posTrg, nBits); check(b1, b2); } @Test public void copyBitsLeftBug6() { long[] s = {//26658067013538148L, -7165901376423424552L, 3830723913108681159L, -7477064955817770196L, 2470570724734906539L, 4372500218542924969L, //1592114322442893905L, //-3029650008794553899L, 4082479205780751270L, };//-4513395991245529464L}; long[] b1 = s.clone(); long[] b2 = s.clone(); int posSrc=45;//237; int posTrg=70;//262; int nBits=86;//278; //System.out.println("ori: " + BitsLong.toBinary(s)); BitsLong.copyBitsLeft(s, posSrc, b1, posTrg, nBits); copyBitsLeftSlow(s, posSrc, b2, posTrg, nBits); check(b1, b2); } @Test public void copyBitsLeftBug7() { // long[] s = new long[155]; // long[] b1 = new long[158]; // Arrays.fill(s,0x5555555555555555L); // Arrays.fill(b1,0xAAAAAAAAAAAAAAAAL); // long[] b2 = b1.clone(); // // int posSrc=9600+5; // int posTrg=32 + 315*31; // int nBits=315; long[] s = new long[2]; long[] b1 = new long[3]; Arrays.fill(s,0x5555555555555555L); Arrays.fill(b1,0xAAAAAAAAAAAAAAAAL); long[] b2 = b1.clone(); int posSrc=9600+5 - 150*64; int posTrg=32 + 315*31 -152*64; int nBits=315-64*3; // System.out.println("s="+ posSrc + " t=" + posTrg + " l=" + nBits + " 158*64=" + 158*64); // System.out.println("s+n= "+ (posSrc+nBits) + " t+n=" + (posTrg+nBits)); // System.out.println("ori: " + BitsLong.toBinary(s)); copyBitsLeftSlow(s, posSrc, b2, posTrg, nBits); // System.out.println("b2 : " + BitsLong.toBinary(b2)); BitsLong.copyBitsLeft(s, posSrc, b1, posTrg, nBits); check(b1, b2); } private void insertBitsSlow(long[] ba, int start, int nBits) { int bitsToShift = ba.length*BITS - start - nBits; for (int i = 0; i < bitsToShift; i++) { int srcBit = ba.length*BITS - nBits - i - 1; int trgBit = ba.length*BITS - i - 1; BitsLong.setBit(ba, trgBit, BitsLong.getBit(ba, srcBit)); } } // private void removetBitsSlow(long[] ba, int start, int nBits) { // int bitsToShift = ba.length*BITS - start - (nBits); // for (int i = 0; i < bitsToShift; i++) { // int srcBit = start + (nBits) + i; // int trgBit = start + i; // BitsLong.setBit(ba, trgBit, BitsLong.getBit(ba, srcBit)); // } // } public static void copyBitsLeftSlow(long[] src, int posSrc, long[] trg, int posTrg, int nBits) { for (int i = 0; i < nBits; i++) { BitsLong.setBit(trg, posTrg + i, BitsLong.getBit(src, posSrc + i)); } } @Test public void testNumberOfConflictingBits() { assertEquals(0, Bits.getMaxConflictingBits(0, 0, 0, 63)); assertEquals(64, Bits.getMaxConflictingBits(0, -1L, 0, 63)); assertEquals(64, Bits.getMaxConflictingBits(0, -1L, 63, 63)); assertEquals(1, Bits.getMaxConflictingBits(0, -1L, 0, 0)); assertEquals(0, Bits.getMaxConflictingBits(0, 1, 1, 1)); } @Test public void testBinarySearch() { long[] ba = {1, 34, 43, 123, 255, 1000}; checkBinarySearch(ba, 0); checkBinarySearch(ba, 1); checkBinarySearch(ba, 2); checkBinarySearch(ba, 34); checkBinarySearch(ba, 40); checkBinarySearch(ba, 43); checkBinarySearch(ba, 45); checkBinarySearch(ba, 123); checkBinarySearch(ba, 255); checkBinarySearch(ba, 999); checkBinarySearch(ba, 1000); checkBinarySearch(ba, 1001); } private void checkBinarySearch(long[] ba, int key) { int i1 = Arrays.binarySearch(ba, key); int i2 = BitsLong.binarySearch(ba, 0, ba.length, key, 64, 0); assertEquals(i1, i2); } private void check(long[] t, long ... expected) { for (int i = 0; i < expected.length; i++) { if (expected[i] != t[i]) { System.out.println("i=" + i); System.out.println("act:" + BitsLong.toBinary(t) + "/ " + t[i]); System.out.println("exp:" + BitsLong.toBinary(expected) + " / " + expected[i]); assertEquals("i=" + i + " | " + BitsLong.toBinary(expected) + " / " + BitsLong.toBinary(t), expected[i], t[i]); } } } private void check(int posIgnore, int lenIgnore, long[] t, long ... expected) { for (int i = 0; i < expected.length; i++) { if (posIgnore / 64 <= i && i <= (posIgnore + lenIgnore)/64) { long mask = -1L; if (posIgnore / 64 == i) { mask = (mask<<(posIgnore%64)) >>> (posIgnore%64); } if (i == (posIgnore + lenIgnore)/64) { int end = (posIgnore+lenIgnore) % 64; mask = (mask >>> (64-end)) << (64-end); } mask = ~mask; // System.out.println("c-mask: "+ Bits.toBinary(mask)); t[i] &= mask; expected[i] &= mask; } // System.out.println("i=" + i + " \nex= " + BitsLong.toBinary(expected, 32) + " \nac= " + // BitsLong.toBinary(t)); assertEquals("i=" + i + " | " + BitsLong.toBinary(expected) + " / " + BitsLong.toBinary(t), expected[i], t[i]); } } private long[] newBA(long...ints) { long[] ba = new long[ints.length]; for (int i = 0; i < ints.length; i++) { ba[i] = ints[i]; } return ba; } private long[] newBaPattern(int n, Random r) { long[] ba = new long[n]; for (int i = 0; i < n; i++) { ba[i] = r.nextLong(); } return ba; } }
30,074
0.697879
0.407661
799
36.639549
61.049461
592
false
false
0
0
0
0
0
0
3.329161
false
false
6
bc41a91d98477b88f9f3bd565a8c945c8bb57917
19,361,712,606,818
54bb6ba4a094962eb044a80410fd791acebb0a27
/app/src/main/java/com/sohu/focus/salesmaster/utils/UpgradeUtil.java
0b7e1b2b4396475ebc7d2935e838fbafcb917cda
[]
no_license
justicejia/salesMaster
https://github.com/justicejia/salesMaster
a002cc5c35abb73eaf6d9eeecd05bb9863b7ad26
b450878b18b3daf7a06ca2980daf7f348c60b788
refs/heads/master
2020-03-21T22:01:14.645000
2018-06-29T04:11:31
2018-06-29T04:11:31
139,099,287
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sohu.focus.salesmaster.utils; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import com.sohu.focus.salesmaster.R; import com.sohu.focus.salesmaster.kernal.BaseApplication; import com.sohu.focus.salesmaster.kernal.http.HttpDownloadEngine; import com.sohu.focus.salesmaster.kernal.http.download.DownInfo; import com.sohu.focus.salesmaster.kernal.http.download.DownState; import com.sohu.focus.salesmaster.kernal.http.listener.HttpDownListener; import com.sohu.focus.salesmaster.kernal.utils.NetUtil; import com.sohu.focus.salesmaster.kernal.utils.StorageUtil; import com.sohu.focus.salesmaster.kernal.utils.ToastUtil; import java.io.File; import static android.os.Build.VERSION_CODES.N; /** * 更新并下载安装包 * Created by yuanminjia on 17-12-13. */ public enum UpgradeUtil { INSTANCE; public static final int NOTIFICATION_ID = 1234; public boolean downloading = false, downloaded = false; NotificationManager mNotifyManager; NotificationCompat.Builder mBuilder; String apkName = "FocusUpdateApk.apk"; UpgradeUtil() { mNotifyManager = (NotificationManager) BaseApplication.getApplication().getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(BaseApplication.getApplication()); mBuilder.setContentTitle("下载焦点效率新版应用").setContentText("正在下载").setSmallIcon(R.mipmap .ic_launcher); } public void startDownloadApk(String apkUrl) { ToastUtil.toast("正在为您准备新版应用,请稍候"); downloading = true; File output = new File(SalesFileUtil.getDownLoadPath(), apkName); DownInfo downInfo = new DownInfo(apkUrl); downInfo.setState(DownState.START); downInfo.setSavePath(output.getAbsolutePath()); downInfo.setConnectonTime(NetUtil.TIMEOUT_TIME); downInfo.setRange(false); downInfo.setListener(new ApkDownloadListener()); HttpDownloadEngine httpDownloadEngine = HttpDownloadEngine.getInstance(); httpDownloadEngine.startDown(downInfo); } public void installNewApk(File file) { Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= N) { promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } promptInstall.setDataAndType(StorageUtil.getUri(BaseApplication.getApplication(), file), "application/vnd.android.package-archive"); BaseApplication.getApplication().startActivity(promptInstall); } private class ApkDownloadListener extends HttpDownListener<DownInfo> { @Override public void onNext(DownInfo baseDownEntity) { downloading = false; downloaded = true; mBuilder.setContentText("下载完毕~") .setProgress(0, 0, false); mBuilder.setAutoCancel(true); mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build()); mNotifyManager.cancel(NOTIFICATION_ID); if (!TextUtils.isEmpty(baseDownEntity.getSavePath())) { installNewApk(new File(baseDownEntity.getSavePath())); } } @Override public void onStart() { downloading = true; } @Override public void onComplete() { downloading = false; mBuilder.setContentText("下载完毕~") .setProgress(0, 0, false); mBuilder.setAutoCancel(true); mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build()); } @Override public void onError(Throwable e) { downloading = false; } @Override public void updateProgress(long readLength, long countLength) { int progress = (int) ((float) readLength / countLength * 100); if (progress % 5 == 0) { mBuilder.setProgress(100, progress, false); mBuilder.setContentText("正在下载 " + progress + "%"); mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build()); } } } }
UTF-8
Java
4,376
java
UpgradeUtil.java
Java
[ { "context": "d.VERSION_CODES.N;\n\n\n/**\n * 更新并下载安装包\n * Created by yuanminjia on 17-12-13.\n */\n\npublic enum UpgradeUtil {\n\n ", "end": 905, "score": 0.9993810653686523, "start": 895, "tag": "USERNAME", "value": "yuanminjia" } ]
null
[]
package com.sohu.focus.salesmaster.utils; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import com.sohu.focus.salesmaster.R; import com.sohu.focus.salesmaster.kernal.BaseApplication; import com.sohu.focus.salesmaster.kernal.http.HttpDownloadEngine; import com.sohu.focus.salesmaster.kernal.http.download.DownInfo; import com.sohu.focus.salesmaster.kernal.http.download.DownState; import com.sohu.focus.salesmaster.kernal.http.listener.HttpDownListener; import com.sohu.focus.salesmaster.kernal.utils.NetUtil; import com.sohu.focus.salesmaster.kernal.utils.StorageUtil; import com.sohu.focus.salesmaster.kernal.utils.ToastUtil; import java.io.File; import static android.os.Build.VERSION_CODES.N; /** * 更新并下载安装包 * Created by yuanminjia on 17-12-13. */ public enum UpgradeUtil { INSTANCE; public static final int NOTIFICATION_ID = 1234; public boolean downloading = false, downloaded = false; NotificationManager mNotifyManager; NotificationCompat.Builder mBuilder; String apkName = "FocusUpdateApk.apk"; UpgradeUtil() { mNotifyManager = (NotificationManager) BaseApplication.getApplication().getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(BaseApplication.getApplication()); mBuilder.setContentTitle("下载焦点效率新版应用").setContentText("正在下载").setSmallIcon(R.mipmap .ic_launcher); } public void startDownloadApk(String apkUrl) { ToastUtil.toast("正在为您准备新版应用,请稍候"); downloading = true; File output = new File(SalesFileUtil.getDownLoadPath(), apkName); DownInfo downInfo = new DownInfo(apkUrl); downInfo.setState(DownState.START); downInfo.setSavePath(output.getAbsolutePath()); downInfo.setConnectonTime(NetUtil.TIMEOUT_TIME); downInfo.setRange(false); downInfo.setListener(new ApkDownloadListener()); HttpDownloadEngine httpDownloadEngine = HttpDownloadEngine.getInstance(); httpDownloadEngine.startDown(downInfo); } public void installNewApk(File file) { Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= N) { promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } promptInstall.setDataAndType(StorageUtil.getUri(BaseApplication.getApplication(), file), "application/vnd.android.package-archive"); BaseApplication.getApplication().startActivity(promptInstall); } private class ApkDownloadListener extends HttpDownListener<DownInfo> { @Override public void onNext(DownInfo baseDownEntity) { downloading = false; downloaded = true; mBuilder.setContentText("下载完毕~") .setProgress(0, 0, false); mBuilder.setAutoCancel(true); mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build()); mNotifyManager.cancel(NOTIFICATION_ID); if (!TextUtils.isEmpty(baseDownEntity.getSavePath())) { installNewApk(new File(baseDownEntity.getSavePath())); } } @Override public void onStart() { downloading = true; } @Override public void onComplete() { downloading = false; mBuilder.setContentText("下载完毕~") .setProgress(0, 0, false); mBuilder.setAutoCancel(true); mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build()); } @Override public void onError(Throwable e) { downloading = false; } @Override public void updateProgress(long readLength, long countLength) { int progress = (int) ((float) readLength / countLength * 100); if (progress % 5 == 0) { mBuilder.setProgress(100, progress, false); mBuilder.setContentText("正在下载 " + progress + "%"); mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build()); } } } }
4,376
0.675164
0.669785
116
35.870689
28.235624
140
false
false
0
0
0
0
0
0
0.637931
false
false
6
00acf7529904b9f4aa0797b0acd545abac5b0a7f
34,849,364,666,452
459db55d82c8307736b3a0d04f958a7299dcd7d1
/app/src/main/java/youthvine/internshiptask/Sign_In.java
8f195ddb638879f85c23dbe114e9868dc168551f
[]
no_license
AbbyB97/InternshipTask
https://github.com/AbbyB97/InternshipTask
6560da4084805091554c9ce3806593d4c33aaff8
220e0efefc9bb5024663b4467806b8984f0c4fdb
refs/heads/master
2020-03-21T04:55:51.937000
2018-06-22T10:28:59
2018-06-22T10:28:59
138,134,836
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package youthvine.internshiptask; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.wang.avi.AVLoadingIndicatorView; public class Sign_In extends AppCompatActivity { SignInButton button; Button fbbtn; private final static int RC_SIGN_IN = 2; FirebaseAuth mAuth; GoogleSignInClient mGoogleSignInClient; EditText reg_email, reg_password; String user_name_str, user_email_str, user_password_str; AVLoadingIndicatorView av; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign__in); mAuth = FirebaseAuth.getInstance(); // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); // Build a GoogleSignInClient with the options specified by gso. mGoogleSignInClient = GoogleSignIn.getClient(this, gso); fbbtn = findViewById(R.id.button3); fbbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), FacebookLogin.class)); } }); button = findViewById(R.id.googleBtn); reg_email = findViewById(R.id.reg_email); reg_password = findViewById(R.id.reg_password); av = findViewById(R.id.progressD); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { av.show(); signIn(); } }); findViewById(R.id.reg_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { av.show(); user_email_str = reg_email.getText().toString(); user_password_str = reg_password.getText().toString(); //user registration using email and password //email and password registration code without email verification /* boolean isemailvalid = android.util.Patterns.EMAIL_ADDRESS.matcher(user_email_str).matches(); if (isemailvalid == true) { if (user_password_str.length() >= 6) { mAuth = FirebaseAuth.getInstance(); mAuth.createUserWithEmailAndPassword(user_email_str, user_password_str) .addOnCompleteListener(Sign_In.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d("", "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(Sign_In.this, "User Registered", Toast.LENGTH_SHORT).show(); av.hide(); startActivity(new Intent(Sign_In.this, welcome.class)); } else { // If sign in fails, display a message to the user. Log.e("em pw auth fail", "createUserWithEmail:failure", task.getException()); Toast.makeText(Sign_In.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); av.hide(); } // ... } }); } else { Toast.makeText(Sign_In.this, "at least 6 digit password", Toast.LENGTH_SHORT).show(); av.hide(); } } else { Toast.makeText(Sign_In.this, "Please enter valid email address", Toast.LENGTH_SHORT).show(); av.hide(); }*/ //user registration using email and link mAuth.createUserWithEmailAndPassword(user_email_str, user_password_str) .addOnCompleteListener(Sign_In.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d("usercreated", "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(Sign_In.this, "user created " + user.getEmail(), Toast.LENGTH_SHORT).show(); user.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d("verification", "Email sent."); Toast.makeText(Sign_In.this, "verification email sent", Toast.LENGTH_SHORT).show(); FirebaseAuth.getInstance().signOut(); } } }); av.hide(); } else { // If sign in fails, display a message to the user. Log.w("no usercreated", "createUserWithEmail:failure", task.getException()); Toast.makeText(Sign_In.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); av.hide(); } // ... } }); } }); } @Override protected void onStart() { super.onStart(); //if the user is already signed in //we will close this activity //and take the user to profile activity //uncomment this if we want to use just email and password verification if (mAuth.getCurrentUser() != null) { finish(); startActivity(new Intent(this, welcome.class)); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w("Reason ", "Google sign in failed", e); Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show(); // ... } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d("begin auth", "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d("Auth Success LOG :", "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(Sign_In.this, "user is now signed in", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Sign_In.this, welcome.class)); } else { // If sign in fails, display a message to the user. Log.w("Auth fail LOG", "signInWithCredential:failure", task.getException()); Toast.makeText(Sign_In.this, "Authentication Failed", Toast.LENGTH_SHORT).show(); } // ... } }); } private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } public void gototwitter(View v) { startActivity(new Intent(this, twiitter_login.class)); } public void gotologin(View v) { Intent next = new Intent(this, email_login.class); startActivity(next); } }
UTF-8
Java
11,095
java
Sign_In.java
Java
[]
null
[]
package youthvine.internshiptask; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.wang.avi.AVLoadingIndicatorView; public class Sign_In extends AppCompatActivity { SignInButton button; Button fbbtn; private final static int RC_SIGN_IN = 2; FirebaseAuth mAuth; GoogleSignInClient mGoogleSignInClient; EditText reg_email, reg_password; String user_name_str, user_email_str, user_password_str; AVLoadingIndicatorView av; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign__in); mAuth = FirebaseAuth.getInstance(); // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); // Build a GoogleSignInClient with the options specified by gso. mGoogleSignInClient = GoogleSignIn.getClient(this, gso); fbbtn = findViewById(R.id.button3); fbbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), FacebookLogin.class)); } }); button = findViewById(R.id.googleBtn); reg_email = findViewById(R.id.reg_email); reg_password = findViewById(R.id.reg_password); av = findViewById(R.id.progressD); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { av.show(); signIn(); } }); findViewById(R.id.reg_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { av.show(); user_email_str = reg_email.getText().toString(); user_password_str = reg_password.getText().toString(); //user registration using email and password //email and password registration code without email verification /* boolean isemailvalid = android.util.Patterns.EMAIL_ADDRESS.matcher(user_email_str).matches(); if (isemailvalid == true) { if (user_password_str.length() >= 6) { mAuth = FirebaseAuth.getInstance(); mAuth.createUserWithEmailAndPassword(user_email_str, user_password_str) .addOnCompleteListener(Sign_In.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d("", "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(Sign_In.this, "User Registered", Toast.LENGTH_SHORT).show(); av.hide(); startActivity(new Intent(Sign_In.this, welcome.class)); } else { // If sign in fails, display a message to the user. Log.e("em pw auth fail", "createUserWithEmail:failure", task.getException()); Toast.makeText(Sign_In.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); av.hide(); } // ... } }); } else { Toast.makeText(Sign_In.this, "at least 6 digit password", Toast.LENGTH_SHORT).show(); av.hide(); } } else { Toast.makeText(Sign_In.this, "Please enter valid email address", Toast.LENGTH_SHORT).show(); av.hide(); }*/ //user registration using email and link mAuth.createUserWithEmailAndPassword(user_email_str, user_password_str) .addOnCompleteListener(Sign_In.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d("usercreated", "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(Sign_In.this, "user created " + user.getEmail(), Toast.LENGTH_SHORT).show(); user.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d("verification", "Email sent."); Toast.makeText(Sign_In.this, "verification email sent", Toast.LENGTH_SHORT).show(); FirebaseAuth.getInstance().signOut(); } } }); av.hide(); } else { // If sign in fails, display a message to the user. Log.w("no usercreated", "createUserWithEmail:failure", task.getException()); Toast.makeText(Sign_In.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); av.hide(); } // ... } }); } }); } @Override protected void onStart() { super.onStart(); //if the user is already signed in //we will close this activity //and take the user to profile activity //uncomment this if we want to use just email and password verification if (mAuth.getCurrentUser() != null) { finish(); startActivity(new Intent(this, welcome.class)); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w("Reason ", "Google sign in failed", e); Toast.makeText(this, "" + e.getMessage(), Toast.LENGTH_SHORT).show(); // ... } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d("begin auth", "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d("Auth Success LOG :", "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(Sign_In.this, "user is now signed in", Toast.LENGTH_SHORT).show(); startActivity(new Intent(Sign_In.this, welcome.class)); } else { // If sign in fails, display a message to the user. Log.w("Auth fail LOG", "signInWithCredential:failure", task.getException()); Toast.makeText(Sign_In.this, "Authentication Failed", Toast.LENGTH_SHORT).show(); } // ... } }); } private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } public void gototwitter(View v) { startActivity(new Intent(this, twiitter_login.class)); } public void gotologin(View v) { Intent next = new Intent(this, email_login.class); startActivity(next); } }
11,095
0.524651
0.5242
234
46.414532
33.408684
139
false
false
0
0
0
0
0
0
0.709402
false
false
10
9fe0e5ea8d2f1cef02a879c9ca2f5af6a01b3293
36,713,380,461,367
079ea997708e7c6d99981b081ef697b52182e496
/app/src/main/java/profilecom/connectgujarat/HomePageFragment.java
31385ee094ad0de459c8fab65924460350c01c3a
[]
no_license
connectgujarat/connectgujarat_org
https://github.com/connectgujarat/connectgujarat_org
a4863993e4d15f663ce93cb7ce263dc34d94d809
7564afb38b8977df6da85081477b6acfa8dddbd9
refs/heads/master
2021-01-20T01:45:40.808000
2017-07-24T12:37:11
2017-07-24T12:37:11
89,326,176
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package profilecom.connectgujarat; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import profilecom.connectgujarat.DataServices.NewPostCacheManager; import profilecom.connectgujarat.R; public class HomePageFragment extends Fragment { RelativeLayout home_page_overlay_rl; ImageView home_page_overlay_image; TextView home_page_overlay_headline; TextView home_page_overlay_date; TextView home_page_overlay_category; TextView home_page_overlay_user; ImageView home_page_overlay_down; public HomePageFragment() { } /* public static Fragment newInstance(Context cxt, String title, int position) { context = cxt; Bundle args = new Bundle(); args.putString("title", title); args.putInt("position", position); HomePageFragment fragment = new HomePageFragment(); fragment.setArguments(args); return fragment; }*/ LinearLayout llll; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_homepage, container, false); llll = (LinearLayout) view.findViewById(R.id.llll); home_page_overlay_rl = (RelativeLayout) view.findViewById(R.id.home_page_overlay_rl); home_page_overlay_image = (ImageView) view.findViewById(R.id.home_page_overlay_image); home_page_overlay_headline = (TextView) view.findViewById(R.id.home_page_overlay_headline); home_page_overlay_date = (TextView) view.findViewById(R.id.home_page_overlay_date); home_page_overlay_category = (TextView) view.findViewById(R.id.home_page_overlay_category); home_page_overlay_user = (TextView) view.findViewById(R.id.home_page_overlay_user); home_page_overlay_down = (ImageView) view.findViewById(R.id.home_page_overlay_down); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Typeface roboto = Typeface.createFromAsset(getActivity().getAssets(), "font/Roboto-Regular.ttf"); NewPostCacheManager cacheManager = new NewPostCacheManager(getActivity()); NewsListActivity.categoriesIds = cacheManager.GetAllCategoriesIds(); NewsListActivity.categoriesNames = cacheManager.GetAllCategoriesNames(); home_page_overlay_rl.setVisibility(View.VISIBLE); if(NewsListActivity.categoriesIds.size()>0) NewsListActivity.list = cacheManager. GetFirstCatPosts(NewsListActivity.categoriesIds.get(0)); if (NewsListActivity.list != null && NewsListActivity.list.size()>0) { final Locality home = NewsListActivity.list .get(0); Picasso.with(getActivity()) .load(home.getAttUrl()) .placeholder(R.drawable.placeholder) .noFade() .into(home_page_overlay_image); home_page_overlay_image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), NewsDetailsActivity.class); intent.putExtra("title", home.getTitle()); intent.putExtra("author", home.getAuthorName()); intent.putExtra("date", home.getDate()); intent.putExtra("url", home.getAttUrl()); intent.putExtra("content", home.getContent()); intent.putExtra("cat", home.getCatid()); intent.putExtra("posturl", home.getPosturl()); intent.putExtra("postId", home.getId()); startActivity(intent); } }); final Animation animShow = AnimationUtils.loadAnimation( getActivity(), R.anim.view_show); final Animation animHide = AnimationUtils.loadAnimation( getActivity(), R.anim.view_hide); llll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { home_page_overlay_rl.startAnimation( animHide); home_page_overlay_rl.setVisibility(View.GONE); } }); home_page_overlay_headline.setText(Html.fromHtml(home.getTitle())); home_page_overlay_headline.setTypeface(roboto); Date formattedDate = null; String finalFormattedDate = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat formatter2 = new SimpleDateFormat("EEE, dd MMM yyyy"); try { formattedDate = formatter.parse(home.getDate()); finalFormattedDate = formatter2.format(formattedDate); } catch (ParseException e) { e.printStackTrace(); } if (formattedDate != null) { home_page_overlay_date.setText("Date : " + finalFormattedDate); home_page_overlay_date.setTypeface(roboto); } home_page_overlay_user.setText(home.getAuthorName()); home_page_overlay_user.setTypeface(roboto); int pos = 1; for (int i = 0; i < NewsListActivity.categoriesIds.size(); i++) { if (home.getCatid() == NewsListActivity.categoriesIds.get(i)) { pos = i; break; } } home_page_overlay_category.setText(NewsListActivity.categoriesNames.get(pos)); home_page_overlay_category.setTypeface(roboto); home_page_overlay_down.setVisibility(View.VISIBLE); /* home_page_overlay_down.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { home_page_overlay_rl.setVisibility(View.GONE); } });*/ }else{ Picasso.with(getActivity()) .load(R.drawable.placeholder) .noFade() .into(home_page_overlay_image); } } public String getTitle() { return getArguments().getString("title"); } public int getPosition() { return getArguments().getInt("position"); } }
UTF-8
Java
7,033
java
HomePageFragment.java
Java
[]
null
[]
package profilecom.connectgujarat; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import profilecom.connectgujarat.DataServices.NewPostCacheManager; import profilecom.connectgujarat.R; public class HomePageFragment extends Fragment { RelativeLayout home_page_overlay_rl; ImageView home_page_overlay_image; TextView home_page_overlay_headline; TextView home_page_overlay_date; TextView home_page_overlay_category; TextView home_page_overlay_user; ImageView home_page_overlay_down; public HomePageFragment() { } /* public static Fragment newInstance(Context cxt, String title, int position) { context = cxt; Bundle args = new Bundle(); args.putString("title", title); args.putInt("position", position); HomePageFragment fragment = new HomePageFragment(); fragment.setArguments(args); return fragment; }*/ LinearLayout llll; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_homepage, container, false); llll = (LinearLayout) view.findViewById(R.id.llll); home_page_overlay_rl = (RelativeLayout) view.findViewById(R.id.home_page_overlay_rl); home_page_overlay_image = (ImageView) view.findViewById(R.id.home_page_overlay_image); home_page_overlay_headline = (TextView) view.findViewById(R.id.home_page_overlay_headline); home_page_overlay_date = (TextView) view.findViewById(R.id.home_page_overlay_date); home_page_overlay_category = (TextView) view.findViewById(R.id.home_page_overlay_category); home_page_overlay_user = (TextView) view.findViewById(R.id.home_page_overlay_user); home_page_overlay_down = (ImageView) view.findViewById(R.id.home_page_overlay_down); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Typeface roboto = Typeface.createFromAsset(getActivity().getAssets(), "font/Roboto-Regular.ttf"); NewPostCacheManager cacheManager = new NewPostCacheManager(getActivity()); NewsListActivity.categoriesIds = cacheManager.GetAllCategoriesIds(); NewsListActivity.categoriesNames = cacheManager.GetAllCategoriesNames(); home_page_overlay_rl.setVisibility(View.VISIBLE); if(NewsListActivity.categoriesIds.size()>0) NewsListActivity.list = cacheManager. GetFirstCatPosts(NewsListActivity.categoriesIds.get(0)); if (NewsListActivity.list != null && NewsListActivity.list.size()>0) { final Locality home = NewsListActivity.list .get(0); Picasso.with(getActivity()) .load(home.getAttUrl()) .placeholder(R.drawable.placeholder) .noFade() .into(home_page_overlay_image); home_page_overlay_image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), NewsDetailsActivity.class); intent.putExtra("title", home.getTitle()); intent.putExtra("author", home.getAuthorName()); intent.putExtra("date", home.getDate()); intent.putExtra("url", home.getAttUrl()); intent.putExtra("content", home.getContent()); intent.putExtra("cat", home.getCatid()); intent.putExtra("posturl", home.getPosturl()); intent.putExtra("postId", home.getId()); startActivity(intent); } }); final Animation animShow = AnimationUtils.loadAnimation( getActivity(), R.anim.view_show); final Animation animHide = AnimationUtils.loadAnimation( getActivity(), R.anim.view_hide); llll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { home_page_overlay_rl.startAnimation( animHide); home_page_overlay_rl.setVisibility(View.GONE); } }); home_page_overlay_headline.setText(Html.fromHtml(home.getTitle())); home_page_overlay_headline.setTypeface(roboto); Date formattedDate = null; String finalFormattedDate = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat formatter2 = new SimpleDateFormat("EEE, dd MMM yyyy"); try { formattedDate = formatter.parse(home.getDate()); finalFormattedDate = formatter2.format(formattedDate); } catch (ParseException e) { e.printStackTrace(); } if (formattedDate != null) { home_page_overlay_date.setText("Date : " + finalFormattedDate); home_page_overlay_date.setTypeface(roboto); } home_page_overlay_user.setText(home.getAuthorName()); home_page_overlay_user.setTypeface(roboto); int pos = 1; for (int i = 0; i < NewsListActivity.categoriesIds.size(); i++) { if (home.getCatid() == NewsListActivity.categoriesIds.get(i)) { pos = i; break; } } home_page_overlay_category.setText(NewsListActivity.categoriesNames.get(pos)); home_page_overlay_category.setTypeface(roboto); home_page_overlay_down.setVisibility(View.VISIBLE); /* home_page_overlay_down.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { home_page_overlay_rl.setVisibility(View.GONE); } });*/ }else{ Picasso.with(getActivity()) .load(R.drawable.placeholder) .noFade() .into(home_page_overlay_image); } } public String getTitle() { return getArguments().getString("title"); } public int getPosition() { return getArguments().getInt("position"); } }
7,033
0.62221
0.62093
200
34.165001
29.974785
103
false
false
0
0
0
0
0
0
0.59
false
false
10
9ec1ab014d38b24085969e87fa6c3491f01b6113
35,433,480,209,640
d20d7afc0d8542e3bd8764875f563b059261698f
/proxypool/src/main/java/com/cv4j/proxy/ProxyManager.java
bfd67564968d297d0c5db2723b7eebe977037888
[ "Apache-2.0" ]
permissive
frankies/ProxyPool
https://github.com/frankies/ProxyPool
8a6f7c2d6395a5dd69dd85ef817311972b41a26f
1ea007b155df4f2f379bc2423055829a8c7346d9
refs/heads/master
2020-08-28T19:58:40.464000
2019-09-06T12:46:11
2019-09-06T12:46:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cv4j.proxy; import com.cv4j.proxy.domain.Proxy; import com.cv4j.proxy.http.HttpManager; import com.cv4j.proxy.task.ProxyPageCallable; import com.safframework.tony.common.utils.Preconditions; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpHost; import org.reactivestreams.Publisher; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Created by tony on 2017/10/25. */ @Slf4j public class ProxyManager { private ProxyManager() { } public static ProxyManager get() { return ProxyManager.Holder.MANAGER; } private static class Holder { private static final ProxyManager MANAGER = new ProxyManager(); } /** * 抓取代理,成功的代理存放到ProxyPool中 */ public void start() { Flowable.fromIterable(ProxyPool.proxyMap.keySet()) .parallel(ProxyPool.proxyMap.size()) .map(new Function<String, List<Proxy>>() { @Override public List<Proxy> apply(String s) throws Exception { try { return new ProxyPageCallable(s).call(); } catch (Exception e) { e.printStackTrace(); } return new ArrayList<Proxy>(); } }) .flatMap(new Function<List<Proxy>, Publisher<Proxy>>() { @Override public Publisher<Proxy> apply(List<Proxy> proxies) throws Exception { if (Preconditions.isNotBlank(proxies)) { List<Proxy> result = proxies .stream() .parallel() .filter(new Predicate<Proxy>() { @Override public boolean test(Proxy proxy) { HttpHost httpHost = new HttpHost(proxy.getIp(), proxy.getPort(), proxy.getType()); boolean result = HttpManager.get().checkProxy(httpHost); if(result) log.info("checkProxy " + proxy.getProxyStr() +", "+result); return result; } }).collect(Collectors.toList()); return Flowable.fromIterable(result); } return Flowable.empty(); } }) .runOn(Schedulers.io()) .sequential() .subscribe(new Consumer<Proxy>() { @Override public void accept(Proxy proxy) throws Exception { if (proxy!=null) { log.info("accept " + proxy.getProxyStr()); proxy.setLastSuccessfulTime(new Date().getTime()); ProxyPool.proxyList.add(proxy); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { log.error("ProxyManager is error: "+throwable.getMessage()); } }); } }
UTF-8
Java
3,839
java
ProxyManager.java
Java
[ { "context": "java.util.stream.Collectors;\r\n\r\n/**\r\n * Created by tony on 2017/10/25.\r\n */\r\n@Slf4j\r\npublic class ProxyMa", "end": 654, "score": 0.9928829669952393, "start": 650, "tag": "USERNAME", "value": "tony" } ]
null
[]
package com.cv4j.proxy; import com.cv4j.proxy.domain.Proxy; import com.cv4j.proxy.http.HttpManager; import com.cv4j.proxy.task.ProxyPageCallable; import com.safframework.tony.common.utils.Preconditions; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpHost; import org.reactivestreams.Publisher; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Created by tony on 2017/10/25. */ @Slf4j public class ProxyManager { private ProxyManager() { } public static ProxyManager get() { return ProxyManager.Holder.MANAGER; } private static class Holder { private static final ProxyManager MANAGER = new ProxyManager(); } /** * 抓取代理,成功的代理存放到ProxyPool中 */ public void start() { Flowable.fromIterable(ProxyPool.proxyMap.keySet()) .parallel(ProxyPool.proxyMap.size()) .map(new Function<String, List<Proxy>>() { @Override public List<Proxy> apply(String s) throws Exception { try { return new ProxyPageCallable(s).call(); } catch (Exception e) { e.printStackTrace(); } return new ArrayList<Proxy>(); } }) .flatMap(new Function<List<Proxy>, Publisher<Proxy>>() { @Override public Publisher<Proxy> apply(List<Proxy> proxies) throws Exception { if (Preconditions.isNotBlank(proxies)) { List<Proxy> result = proxies .stream() .parallel() .filter(new Predicate<Proxy>() { @Override public boolean test(Proxy proxy) { HttpHost httpHost = new HttpHost(proxy.getIp(), proxy.getPort(), proxy.getType()); boolean result = HttpManager.get().checkProxy(httpHost); if(result) log.info("checkProxy " + proxy.getProxyStr() +", "+result); return result; } }).collect(Collectors.toList()); return Flowable.fromIterable(result); } return Flowable.empty(); } }) .runOn(Schedulers.io()) .sequential() .subscribe(new Consumer<Proxy>() { @Override public void accept(Proxy proxy) throws Exception { if (proxy!=null) { log.info("accept " + proxy.getProxyStr()); proxy.setLastSuccessfulTime(new Date().getTime()); ProxyPool.proxyList.add(proxy); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { log.error("ProxyManager is error: "+throwable.getMessage()); } }); } }
3,839
0.468906
0.46497
100
36.110001
27.223848
126
false
false
0
0
0
0
0
0
0.4
false
false
10
f5274cbf3f736f23cf2c82f47667f6a8fb4fd68d
18,700,287,655,065
5e0c7b28e9f08ec9466ce3e8afd78a57384fb912
/src/Grader.java
e31d1af3b143c5c95059f404ab02603287454dde
[]
no_license
bdevo1896/learning-java-p3
https://github.com/bdevo1896/learning-java-p3
7954e5e2ea8ca74e4d2276c76c9c5c726d9ee013
a6e56ea4b78d7c24400a2bbb59e017a7c203c337
refs/heads/master
2020-06-28T13:19:35.386000
2019-08-02T14:08:22
2019-08-02T14:08:22
200,244,448
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Grader { /* * -----|BREAKDOWN OF GRADER|----- * 1) * Create a method to ask the user for a certain category of grades and the number of grades they * want to enter. Then return the array created from the user input. *Note: This method will have * an "int" parameter for creating a hard-coded list.* * * 2) * Create a method to take in the grades for a category and return its average for that category * as a "double". * * 3) * Create a method to show the letter grade. It will take a "double" parameter and give the letter * grade based off of that. It will return a "String". * */ //This method will create a "double" array through user input. It will store the category type to inform the user //what type of grades are being entered. public static double[] createDoubleArray(String category, int numberOfElements){ if(numberOfElements == 0 || numberOfElements < 0){ Magic.println("How many "+category+" grades will you enter?"); numberOfElements = Magic.nextInt(); } double[] data = new double[numberOfElements]; for(int i = 0; i < data.length; i++){ Magic.println("Please enter "+category+" grade ("+(i+1)+")"); data[i] = Magic.nextInt(); } return data; } //This method will take an "int" array as a parameter, and then it will calculate the average from the elements //in the array. *Note: will later round up if needed.* public static double getAverage(double[] data){ if(data.length > 0){ double avg = 0.0; double sum = 0.0; for(int i = 0; i < data.length; i++){ sum += data[i]; } avg = sum / data.length; double roundedAvg = avg; //This will check to see if the grade can be rounded up. if(avg % (int)avg >= 5 ){ roundedAvg = Math.ceil(avg); } return roundedAvg; } else{ return -1.0; } } //This method will return a "String" to indicate the letter //grade. public static String getLetterGrade(double grade){ int roundedGrade = (int) grade; String letter = ""; if(roundedGrade < 60){ letter = "F"; } else if(roundedGrade >= 60 && roundedGrade < 64){ letter = "D-"; } else if(roundedGrade >= 64 && roundedGrade < 67){ letter = "D"; } else if(roundedGrade >= 67 && roundedGrade < 70){ letter = "D+"; } else if(roundedGrade >= 70 && roundedGrade < 73){ letter = "C-"; } else if(roundedGrade >= 74 && roundedGrade < 77){ letter = "C"; } else if(roundedGrade >= 77 && roundedGrade < 80){ letter = "C+"; } else if(roundedGrade >= 80 && roundedGrade < 84){ letter = "B-"; } else if(roundedGrade >= 84 && roundedGrade < 87){ letter = "B"; } else if(roundedGrade >= 87 && roundedGrade < 90){ letter = "B+"; } else if(roundedGrade >= 90 && roundedGrade < 94){ letter = "A-"; } else if(roundedGrade >= 94 && roundedGrade < 97){ letter = "A"; } else { letter = "A+"; } return letter; } public static void main(String[] args) { double[] tests = createDoubleArray("Test",4); double[] quizzes = createDoubleArray("Quiz",0); double[] labs = createDoubleArray("Lab",0); double averageOfTests = getAverage(tests); double averageOfQuizzes = getAverage(quizzes); double averageOfLabs = getAverage(labs); double grade = (averageOfTests * .5) + (averageOfQuizzes * .05) + (averageOfLabs * .4); Magic.println("Your grade was: "+grade+" so you get a "+ getLetterGrade(grade)); } }
UTF-8
Java
3,485
java
Grader.java
Java
[]
null
[]
public class Grader { /* * -----|BREAKDOWN OF GRADER|----- * 1) * Create a method to ask the user for a certain category of grades and the number of grades they * want to enter. Then return the array created from the user input. *Note: This method will have * an "int" parameter for creating a hard-coded list.* * * 2) * Create a method to take in the grades for a category and return its average for that category * as a "double". * * 3) * Create a method to show the letter grade. It will take a "double" parameter and give the letter * grade based off of that. It will return a "String". * */ //This method will create a "double" array through user input. It will store the category type to inform the user //what type of grades are being entered. public static double[] createDoubleArray(String category, int numberOfElements){ if(numberOfElements == 0 || numberOfElements < 0){ Magic.println("How many "+category+" grades will you enter?"); numberOfElements = Magic.nextInt(); } double[] data = new double[numberOfElements]; for(int i = 0; i < data.length; i++){ Magic.println("Please enter "+category+" grade ("+(i+1)+")"); data[i] = Magic.nextInt(); } return data; } //This method will take an "int" array as a parameter, and then it will calculate the average from the elements //in the array. *Note: will later round up if needed.* public static double getAverage(double[] data){ if(data.length > 0){ double avg = 0.0; double sum = 0.0; for(int i = 0; i < data.length; i++){ sum += data[i]; } avg = sum / data.length; double roundedAvg = avg; //This will check to see if the grade can be rounded up. if(avg % (int)avg >= 5 ){ roundedAvg = Math.ceil(avg); } return roundedAvg; } else{ return -1.0; } } //This method will return a "String" to indicate the letter //grade. public static String getLetterGrade(double grade){ int roundedGrade = (int) grade; String letter = ""; if(roundedGrade < 60){ letter = "F"; } else if(roundedGrade >= 60 && roundedGrade < 64){ letter = "D-"; } else if(roundedGrade >= 64 && roundedGrade < 67){ letter = "D"; } else if(roundedGrade >= 67 && roundedGrade < 70){ letter = "D+"; } else if(roundedGrade >= 70 && roundedGrade < 73){ letter = "C-"; } else if(roundedGrade >= 74 && roundedGrade < 77){ letter = "C"; } else if(roundedGrade >= 77 && roundedGrade < 80){ letter = "C+"; } else if(roundedGrade >= 80 && roundedGrade < 84){ letter = "B-"; } else if(roundedGrade >= 84 && roundedGrade < 87){ letter = "B"; } else if(roundedGrade >= 87 && roundedGrade < 90){ letter = "B+"; } else if(roundedGrade >= 90 && roundedGrade < 94){ letter = "A-"; } else if(roundedGrade >= 94 && roundedGrade < 97){ letter = "A"; } else { letter = "A+"; } return letter; } public static void main(String[] args) { double[] tests = createDoubleArray("Test",4); double[] quizzes = createDoubleArray("Quiz",0); double[] labs = createDoubleArray("Lab",0); double averageOfTests = getAverage(tests); double averageOfQuizzes = getAverage(quizzes); double averageOfLabs = getAverage(labs); double grade = (averageOfTests * .5) + (averageOfQuizzes * .05) + (averageOfLabs * .4); Magic.println("Your grade was: "+grade+" so you get a "+ getLetterGrade(grade)); } }
3,485
0.626112
0.606313
129
26.007751
27.776655
114
false
false
0
0
0
0
0
0
2.449612
false
false
10
15e841eb72c66444ea3b99edf1b364fef494b643
36,094,905,169,437
6d59613a8f0bf44f419de91d6ffe7cdcd6653001
/cloud-app/app-system/src/main/java/com/union/aimei/system/service/BaseHomepageGuidePageService.java
bb6765fa7898bc83af792c2a3f9c48eb0e0cca91
[]
no_license
moutainhigh/amez-springcloud
https://github.com/moutainhigh/amez-springcloud
a343ce35e47af9281002e17d9f7707728ba86600
b2880475ec454fa88b2d0ab6885a5a0ee7d6059a
refs/heads/master
2021-10-22T13:50:55.343000
2019-03-11T09:31:21
2019-03-11T09:31:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.union.aimei.system.service; import com.github.pagehelper.PageInfo; import com.union.aimei.common.model.system.BaseHomepageGuidePage; /** * @author liufeihua */ public interface BaseHomepageGuidePageService { /** * 基本操作 * @param id * @return */ int deleteByPrimaryKey(Integer id); /** * 基本操作 * @param record * @return */ int insertSelective(BaseHomepageGuidePage record); /** * 基本操作 * @param id * @return */ BaseHomepageGuidePage selectByPrimaryKey(Integer id); /** * 基本操作 * @param record * @return */ int updateByPrimaryKeySelective(BaseHomepageGuidePage record); /** * 查看 * @param pageNo * @param pageSize * @param record * @return */ PageInfo<BaseHomepageGuidePage> selectListByConditions(Integer pageNo, Integer pageSize, BaseHomepageGuidePage record); }
UTF-8
Java
958
java
BaseHomepageGuidePageService.java
Java
[ { "context": "model.system.BaseHomepageGuidePage;\n/**\n * @author liufeihua\n */\npublic interface BaseHomepageGuidePageService", "end": 170, "score": 0.9995172619819641, "start": 161, "tag": "USERNAME", "value": "liufeihua" } ]
null
[]
package com.union.aimei.system.service; import com.github.pagehelper.PageInfo; import com.union.aimei.common.model.system.BaseHomepageGuidePage; /** * @author liufeihua */ public interface BaseHomepageGuidePageService { /** * 基本操作 * @param id * @return */ int deleteByPrimaryKey(Integer id); /** * 基本操作 * @param record * @return */ int insertSelective(BaseHomepageGuidePage record); /** * 基本操作 * @param id * @return */ BaseHomepageGuidePage selectByPrimaryKey(Integer id); /** * 基本操作 * @param record * @return */ int updateByPrimaryKeySelective(BaseHomepageGuidePage record); /** * 查看 * @param pageNo * @param pageSize * @param record * @return */ PageInfo<BaseHomepageGuidePage> selectListByConditions(Integer pageNo, Integer pageSize, BaseHomepageGuidePage record); }
958
0.635575
0.635575
41
21.512196
23.502073
123
false
false
0
0
0
0
0
0
0.243902
false
false
10
86d26fd9dc3b53c292f0cbc18d7a373100786572
33,689,723,514,044
c054af6f9badce2b31e2f1a7dd1408e1dec3f991
/src/com/cocobabys/log/LogWriter.java
85d79e5e44b82506af43e7b026c8b1ae4a23040b
[]
no_license
amoydream/Android_app
https://github.com/amoydream/Android_app
aacfd978746798ba47e7a9a8c282ac0ec54d9a39
24add584b2abcf136c98e11aa47fcc0b39199ac4
refs/heads/master
2021-12-07T19:13:24.891000
2015-12-28T14:54:22
2015-12-28T14:54:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cocobabys.log; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import com.cocobabys.activities.MyApplication; import com.cocobabys.utils.Utils; import android.util.Log; public class LogWriter { private static LogWriter mLogWriter; private static Writer mWriter; private static SimpleDateFormat df; private boolean debug = true; private LogWriter() { debug = MyApplication.getInstance().isForTest(); } public static synchronized LogWriter getInstance() { try { if (mLogWriter == null) { String path = Utils.getSDCardFileDir(Utils.APP_COMMON_LOGS).getAbsolutePath(); path = path + File.separator + new SimpleDateFormat("[yy-MM-dd]").format(new Date()) + ".txt"; Log.d("", "LogWriter path=" + path); mLogWriter = new LogWriter(); mWriter = new BufferedWriter(new FileWriter(path, true), 2048); df = new SimpleDateFormat("[yy-MM-dd hh:mm:ss]: "); } } catch (Exception e) { e.printStackTrace(); } return mLogWriter; } public synchronized void close() { Utils.close(mWriter); mWriter = null; } public void print(String log) { if (!debug) { return; } try { mWriter.write(df.format(new Date())); mWriter.write(log); mWriter.write("\r\n"); mWriter.flush(); } catch (Exception e) { e.printStackTrace(); } Log.w("", log); } public void print(Class<?> cls, String log) { // 如果还想看是在哪个类里可以用这个方法 if (!debug) { return; } Log.w("", log); try { mWriter.write(df.format(new Date())); mWriter.write(cls.getSimpleName() + " "); mWriter.write(log); mWriter.write("\r\n"); mWriter.flush(); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
1,822
java
LogWriter.java
Java
[]
null
[]
package com.cocobabys.log; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import com.cocobabys.activities.MyApplication; import com.cocobabys.utils.Utils; import android.util.Log; public class LogWriter { private static LogWriter mLogWriter; private static Writer mWriter; private static SimpleDateFormat df; private boolean debug = true; private LogWriter() { debug = MyApplication.getInstance().isForTest(); } public static synchronized LogWriter getInstance() { try { if (mLogWriter == null) { String path = Utils.getSDCardFileDir(Utils.APP_COMMON_LOGS).getAbsolutePath(); path = path + File.separator + new SimpleDateFormat("[yy-MM-dd]").format(new Date()) + ".txt"; Log.d("", "LogWriter path=" + path); mLogWriter = new LogWriter(); mWriter = new BufferedWriter(new FileWriter(path, true), 2048); df = new SimpleDateFormat("[yy-MM-dd hh:mm:ss]: "); } } catch (Exception e) { e.printStackTrace(); } return mLogWriter; } public synchronized void close() { Utils.close(mWriter); mWriter = null; } public void print(String log) { if (!debug) { return; } try { mWriter.write(df.format(new Date())); mWriter.write(log); mWriter.write("\r\n"); mWriter.flush(); } catch (Exception e) { e.printStackTrace(); } Log.w("", log); } public void print(Class<?> cls, String log) { // 如果还想看是在哪个类里可以用这个方法 if (!debug) { return; } Log.w("", log); try { mWriter.write(df.format(new Date())); mWriter.write(cls.getSimpleName() + " "); mWriter.write(log); mWriter.write("\r\n"); mWriter.flush(); } catch (Exception e) { e.printStackTrace(); } } }
1,822
0.665733
0.663494
87
19.528736
19.963667
98
false
false
0
0
0
0
0
0
1.954023
false
false
10
b5dbc234308406da25939c2874751c39196671d0
27,453,431,022,675
303b697e2499f60975679fe889619a68145f57df
/KharkivJavaTask4/src/shop/repository/ShopRepository.java
22f729850a8b3af5dcf476df4d531b57fbb65826
[]
no_license
Arsalan1357/preprod
https://github.com/Arsalan1357/preprod
ba1135392e8441e0f95a4949972f19c2125bb4f4
cb73d5fceeca8aeed98e92729296fa5ed2296a6d
refs/heads/master
2021-01-13T14:28:31.728000
2016-12-30T13:33:17
2016-12-30T13:33:17
72,885,105
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package shop.repository; import shop.entity.product.Product; import shop.entity.shop.Shop; import java.util.Date; import java.util.Map; /** * @author Arsalan * template shop.repository for shop */ public interface ShopRepository { /** * Makes order and adds it to list order * * @param date date of order * @param cart shop cart */ public void addOrder(Date date, Map<Product, Integer> cart); /** * @return shop */ public Shop getShop(); }
UTF-8
Java
468
java
ShopRepository.java
Java
[ { "context": "a.util.Date;\nimport java.util.Map;\n\n/**\n * @author Arsalan\n * template shop.repository for shop\n */\npublic i", "end": 161, "score": 0.9345543384552002, "start": 154, "tag": "NAME", "value": "Arsalan" } ]
null
[]
package shop.repository; import shop.entity.product.Product; import shop.entity.shop.Shop; import java.util.Date; import java.util.Map; /** * @author Arsalan * template shop.repository for shop */ public interface ShopRepository { /** * Makes order and adds it to list order * * @param date date of order * @param cart shop cart */ public void addOrder(Date date, Map<Product, Integer> cart); /** * @return shop */ public Shop getShop(); }
468
0.688034
0.688034
29
15.137931
15.947596
61
false
false
0
0
0
0
0
0
0.689655
false
false
10
d8ab16c8457697ebe4167819fb867c5f848b6575
24,893,630,483,125
020b281e80e22d661803520c041b04846f3a5f91
/src/main/java/com/hiqes/andele/RequestOwnerFragment.java
cbceaa6b97b9f22e8fae62c0f08194070a125cf9
[]
no_license
hiqes/andele
https://github.com/hiqes/andele
67b18f2b49f61cf1903e257f4b27beb58a82c0f5
f62829b4d5b94b9616c7732a83bff86ef972642b
refs/heads/master
2021-01-10T10:00:50.401000
2020-01-17T18:26:43
2020-01-17T18:26:43
45,207,946
71
8
null
false
2020-01-17T18:26:44
2015-10-29T20:12:48
2020-01-17T14:32:16
2020-01-17T18:26:43
144
61
7
6
Java
false
false
/* * Copyright (C) 2015 HIQES LLC * * 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.hiqes.andele; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.Fragment; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.view.View; import java.lang.ref.WeakReference; class RequestOwnerFragment extends RequestOwner { private static final String TAG = RequestOwnerFragment.class.getSimpleName(); private static final int REQ_CODE_MASK = 0x7F; private WeakReference<Fragment> mFragmentRef; private ComponentName mActivityCompName; private int mId; private String mTag; private Fragment getFragment() { return mFragmentRef.get(); } RequestOwnerFragment(Fragment fragment) { mFragmentRef = new WeakReference<>(fragment); mActivityCompName = fragment.getActivity().getComponentName(); mId = fragment.getId(); mTag = fragment.getTag(); } //@TargetApi(Build.VERSION_CODES.M) @TargetApi(23) @Override public int checkSelfPermission(String permission) { int ret = PackageManager.PERMISSION_GRANTED; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Fragment frag = getFragment(); if (frag == null) { // The Fragment has been garbage collected, should NOT // happen but fail gracefully with a log Log.e(TAG, "checkSelfPermission: Fragment no long valid, assume DENIED"); ret = PackageManager.PERMISSION_DENIED; } else { ret = frag.getActivity().checkSelfPermission(permission); } } return ret; } //@TargetApi(Build.VERSION_CODES.M) @TargetApi(23) @Override public void requestPermissions(String[] permissions, int code) { Fragment frag = getFragment(); if (frag == null) { throw new IllegalStateException("Fragment no longer valid"); } frag.requestPermissions(permissions, code); } //@TargetApi(Build.VERSION_CODES.M) @TargetApi(23) @Override public boolean shouldShowRequestPermissionRationale(String permission) { boolean ret = false; Fragment frag = getFragment(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (frag == null) { Log.e(TAG, "shouldShowRequestPermissionRationale: Fragment no longer valid, assume FALSE"); } else { ret = frag.shouldShowRequestPermissionRationale(permission); } } return ret; } @Override public boolean isSameOwner(RequestOwner otherOwner) { boolean ret = false; RequestOwnerFragment otherOwnerFrag; try { otherOwnerFrag = (RequestOwnerFragment)otherOwner; // Verify the parent activity is the same component if (mActivityCompName.equals(otherOwnerFrag.mActivityCompName)) { // Tag may or may not be set. If it is, make sure they // match. Otherwise, check the IDs. if ((mTag != null) && (otherOwnerFrag.mTag != null) && mTag.equals(otherOwnerFrag.mTag)) { ret = true; } else if (mId == otherOwnerFrag.mId) { ret = true; } } } catch (ClassCastException e) { // Ignore } return ret; } @Override public boolean isParentActivity(Object obj) { boolean ret = false; Activity otherAct; Fragment frag = getFragment(); try { otherAct = (Activity)obj; if (frag != null) { Activity parentAct = frag.getActivity(); if ((parentAct != null) && (parentAct == otherAct)) { ret = true; } } } catch (ClassCastException e) { // Ignore } return ret; } @Override PackageManager getPackageManager() { Fragment frag = getFragment(); // Do not check for null, if this fails we have a state problem and // the NPE we'll get will be helpful to track it down. return frag.getActivity().getPackageManager(); } @Override Application getApplication() { return getFragment().getActivity().getApplication(); } @Override public int getReqeuestCodeMask() { return REQ_CODE_MASK; } @Override public Context getUiContext() { return getFragment().getActivity(); } @Override public View getRootView() { return getFragment().getActivity().findViewById(android.R.id.content); } }
UTF-8
Java
5,661
java
RequestOwnerFragment.java
Java
[]
null
[]
/* * Copyright (C) 2015 HIQES LLC * * 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.hiqes.andele; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.Fragment; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.view.View; import java.lang.ref.WeakReference; class RequestOwnerFragment extends RequestOwner { private static final String TAG = RequestOwnerFragment.class.getSimpleName(); private static final int REQ_CODE_MASK = 0x7F; private WeakReference<Fragment> mFragmentRef; private ComponentName mActivityCompName; private int mId; private String mTag; private Fragment getFragment() { return mFragmentRef.get(); } RequestOwnerFragment(Fragment fragment) { mFragmentRef = new WeakReference<>(fragment); mActivityCompName = fragment.getActivity().getComponentName(); mId = fragment.getId(); mTag = fragment.getTag(); } //@TargetApi(Build.VERSION_CODES.M) @TargetApi(23) @Override public int checkSelfPermission(String permission) { int ret = PackageManager.PERMISSION_GRANTED; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Fragment frag = getFragment(); if (frag == null) { // The Fragment has been garbage collected, should NOT // happen but fail gracefully with a log Log.e(TAG, "checkSelfPermission: Fragment no long valid, assume DENIED"); ret = PackageManager.PERMISSION_DENIED; } else { ret = frag.getActivity().checkSelfPermission(permission); } } return ret; } //@TargetApi(Build.VERSION_CODES.M) @TargetApi(23) @Override public void requestPermissions(String[] permissions, int code) { Fragment frag = getFragment(); if (frag == null) { throw new IllegalStateException("Fragment no longer valid"); } frag.requestPermissions(permissions, code); } //@TargetApi(Build.VERSION_CODES.M) @TargetApi(23) @Override public boolean shouldShowRequestPermissionRationale(String permission) { boolean ret = false; Fragment frag = getFragment(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (frag == null) { Log.e(TAG, "shouldShowRequestPermissionRationale: Fragment no longer valid, assume FALSE"); } else { ret = frag.shouldShowRequestPermissionRationale(permission); } } return ret; } @Override public boolean isSameOwner(RequestOwner otherOwner) { boolean ret = false; RequestOwnerFragment otherOwnerFrag; try { otherOwnerFrag = (RequestOwnerFragment)otherOwner; // Verify the parent activity is the same component if (mActivityCompName.equals(otherOwnerFrag.mActivityCompName)) { // Tag may or may not be set. If it is, make sure they // match. Otherwise, check the IDs. if ((mTag != null) && (otherOwnerFrag.mTag != null) && mTag.equals(otherOwnerFrag.mTag)) { ret = true; } else if (mId == otherOwnerFrag.mId) { ret = true; } } } catch (ClassCastException e) { // Ignore } return ret; } @Override public boolean isParentActivity(Object obj) { boolean ret = false; Activity otherAct; Fragment frag = getFragment(); try { otherAct = (Activity)obj; if (frag != null) { Activity parentAct = frag.getActivity(); if ((parentAct != null) && (parentAct == otherAct)) { ret = true; } } } catch (ClassCastException e) { // Ignore } return ret; } @Override PackageManager getPackageManager() { Fragment frag = getFragment(); // Do not check for null, if this fails we have a state problem and // the NPE we'll get will be helpful to track it down. return frag.getActivity().getPackageManager(); } @Override Application getApplication() { return getFragment().getActivity().getApplication(); } @Override public int getReqeuestCodeMask() { return REQ_CODE_MASK; } @Override public Context getUiContext() { return getFragment().getActivity(); } @Override public View getRootView() { return getFragment().getActivity().findViewById(android.R.id.content); } }
5,661
0.586822
0.583996
179
30.625698
25.348513
107
false
false
0
0
0
0
0
0
0.391061
false
false
10
23263d82ead40e535176f3ea8fac024dba9c9458
31,447,750,571,912
5e3235edf3de262f4d10b9e9e1fcc3bd13d6b8b1
/Code Snippet Repository/Spring/Spring8439.java
9a593662172e13c022a3f1ce0b6bbb679c100f0f
[]
no_license
saber13812002/DeepCRM
https://github.com/saber13812002/DeepCRM
3336a244d4852a364800af3181e03e868cf6f9f5
be3e5e50e34a042d5ba7259ff5ff75c08ab32bb9
refs/heads/master
2023-03-16T00:08:06.473000
2018-04-18T05:29:50
2018-04-18T05:29:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
@Test public void localConfigWithCustomValues() throws Exception { Method method = getClass().getMethod("localConfigMethodWithCustomValues"); SqlConfig localSqlConfig = method.getAnnotation(Sql.class).config(); MergedSqlConfig cfg = new MergedSqlConfig(localSqlConfig, getClass()); assertNotNull(cfg); assertEquals("dataSource", "ds", cfg.getDataSource()); assertEquals("transactionManager", "txMgr", cfg.getTransactionManager()); assertEquals("transactionMode", ISOLATED, cfg.getTransactionMode()); assertEquals("encoding", "enigma", cfg.getEncoding()); assertEquals("separator", "\n", cfg.getSeparator()); assertEquals("commentPrefix", "`", cfg.getCommentPrefix()); assertEquals("blockCommentStartDelimiter", "<<", cfg.getBlockCommentStartDelimiter()); assertEquals("blockCommentEndDelimiter", ">>", cfg.getBlockCommentEndDelimiter()); assertEquals("errorMode", IGNORE_FAILED_DROPS, cfg.getErrorMode()); }
UTF-8
Java
937
java
Spring8439.java
Java
[]
null
[]
@Test public void localConfigWithCustomValues() throws Exception { Method method = getClass().getMethod("localConfigMethodWithCustomValues"); SqlConfig localSqlConfig = method.getAnnotation(Sql.class).config(); MergedSqlConfig cfg = new MergedSqlConfig(localSqlConfig, getClass()); assertNotNull(cfg); assertEquals("dataSource", "ds", cfg.getDataSource()); assertEquals("transactionManager", "txMgr", cfg.getTransactionManager()); assertEquals("transactionMode", ISOLATED, cfg.getTransactionMode()); assertEquals("encoding", "enigma", cfg.getEncoding()); assertEquals("separator", "\n", cfg.getSeparator()); assertEquals("commentPrefix", "`", cfg.getCommentPrefix()); assertEquals("blockCommentStartDelimiter", "<<", cfg.getBlockCommentStartDelimiter()); assertEquals("blockCommentEndDelimiter", ">>", cfg.getBlockCommentEndDelimiter()); assertEquals("errorMode", IGNORE_FAILED_DROPS, cfg.getErrorMode()); }
937
0.760939
0.760939
16
57.5
25.181839
88
false
false
0
0
0
0
0
0
3.75
false
false
10
3179d1a73baac26464ae359c4cacef05bb361baf
31,447,750,572,173
1582714ec085c95cffef85cb7d49ad15e1e7e36b
/app/src/main/java/com/example/configurar/sistema_clinico/ReactivosDAO.java
f7e5177d0f88e30bd4c43c45895527ff90ca2488
[]
no_license
aureliomigueltu/SISTEMA_CLINICO
https://github.com/aureliomigueltu/SISTEMA_CLINICO
2014d559ea5b128d7aa2a44f78a8a69263500184
240c2d9a40f85a0e7d9047d7dbcf884ea526582f
refs/heads/master
2023-02-03T10:30:30.372000
2015-08-04T23:53:07
2015-08-04T23:53:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.configurar.sistema_clinico; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ReactivosDAO { private DBHelper helper; private SQLiteDatabase db,db2; public ReactivosDAO(Context context) { helper = new DBHelper(context, "analisis_clinico_bd.db", null, 1); //db= helper.getWritableDatabase(); } public void open()throws SQLException { db = helper.getWritableDatabase(); db2 = helper.getReadableDatabase(); } public void close(){ helper.close(); } public long insertarReactivosSQL(String cod_reactivos, String nom_reactivo, String grupo_reactivo,String unidad_reactivo,String esp_quimica){ long estado = 0; try { ContentValues valores=new ContentValues(); valores.put("cod_reactivos",cod_reactivos); valores.put("nom_reactivo",nom_reactivo); valores.put("grupo_reactivo",grupo_reactivo); valores.put("unidad_reactivo",unidad_reactivo); valores.put("esp_quimica",esp_quimica); estado=db.insert("REACTIVOS",null,valores); } catch (Exception e){ estado = 0; } return estado; } public List VerReactivosSQL() { List<String> lista = new ArrayList<String>(); Cursor cur = db2.rawQuery("SELECT * FROM REACTIVOS", null); while (cur.moveToNext()) { lista.add("1."+cur.getString(0) + " | 2." + cur.getString(1)+ " | 3." + cur.getString(2)+ " | 4." + cur.getString(3)+ " | 5." + cur.getString(4) ); } cur.close(); return (lista); } public long eliminarReactivosSQL(String cod_reactivos){ long estado=0; try { estado= db.delete("REACTIVOS","cod_reactivos=?",new String[]{String.valueOf(cod_reactivos)}); } catch (Exception e){ estado = 0; } return estado; } }
UTF-8
Java
2,141
java
ReactivosDAO.java
Java
[]
null
[]
package com.example.configurar.sistema_clinico; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ReactivosDAO { private DBHelper helper; private SQLiteDatabase db,db2; public ReactivosDAO(Context context) { helper = new DBHelper(context, "analisis_clinico_bd.db", null, 1); //db= helper.getWritableDatabase(); } public void open()throws SQLException { db = helper.getWritableDatabase(); db2 = helper.getReadableDatabase(); } public void close(){ helper.close(); } public long insertarReactivosSQL(String cod_reactivos, String nom_reactivo, String grupo_reactivo,String unidad_reactivo,String esp_quimica){ long estado = 0; try { ContentValues valores=new ContentValues(); valores.put("cod_reactivos",cod_reactivos); valores.put("nom_reactivo",nom_reactivo); valores.put("grupo_reactivo",grupo_reactivo); valores.put("unidad_reactivo",unidad_reactivo); valores.put("esp_quimica",esp_quimica); estado=db.insert("REACTIVOS",null,valores); } catch (Exception e){ estado = 0; } return estado; } public List VerReactivosSQL() { List<String> lista = new ArrayList<String>(); Cursor cur = db2.rawQuery("SELECT * FROM REACTIVOS", null); while (cur.moveToNext()) { lista.add("1."+cur.getString(0) + " | 2." + cur.getString(1)+ " | 3." + cur.getString(2)+ " | 4." + cur.getString(3)+ " | 5." + cur.getString(4) ); } cur.close(); return (lista); } public long eliminarReactivosSQL(String cod_reactivos){ long estado=0; try { estado= db.delete("REACTIVOS","cod_reactivos=?",new String[]{String.valueOf(cod_reactivos)}); } catch (Exception e){ estado = 0; } return estado; } }
2,141
0.613732
0.605325
66
31.439394
30.679245
163
false
false
0
0
0
0
0
0
0.848485
false
false
10
9c6074a11e698bcc7f2240925bbfbff9d4841991
8,435,315,779,395
f7333169a0f52069a990420d0c401eca0395d3a6
/cms/src/main/java/go/gg/cms/core/util/CmsPaginationRenderer.java
abdecc086be2404542ab4f03a222179f1398632f
[]
no_license
haroldjeong/workspace
https://github.com/haroldjeong/workspace
e9defa6cd4a0c49317fbaeb7113c991faa49cc85
c1bc7c7826eb75762cfbda66e125b5376992c25d
refs/heads/master
2022-12-07T09:53:35.919000
2020-08-26T07:34:36
2020-08-26T07:34:36
290,731,672
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2008-2009 the original author or authors. * * 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 go.gg.cms.core.util; import egovframework.rte.ptl.mvc.tags.ui.pagination.AbstractPaginationRenderer; import org.springframework.web.context.ServletContextAware; import javax.servlet.ServletContext; /** * Pagination Renderer * @apiNote 전자정부 프레임워크 제공 기본 페이징 렌더러 -> Cms Template 변경 * @author 개발프레임웍크 실행환경 개발팀 (Copyright (C) by MOPAS All right reserved.) * @since 2009. 03.16 * @version 1.0 */ public class CmsPaginationRenderer extends AbstractPaginationRenderer implements ServletContextAware{ private ServletContext servletContext; public CmsPaginationRenderer() { // no-op } public void initVariables() { firstPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#first\" onclick=\"javascript:{0}({1}); return false;\">«</a></li>"; previousPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#prev\" onclick=\"javascript:{0}({1}); return false;\">‹</a></li>"; currentPageLabel = "<li class=\"footable-page active\"><a href=\"#\">{0}</a></li>"; otherPageLabel = "<li class=\"footable-page\"><a href=\"#\" onclick=\"javascript:{0}({1}); return false;\">{2}</a></li>"; nextPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#next\" onclick=\"javascript:{0}({1}); return false;\">›</a></li>"; lastPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#last\" onclick=\"javascript:{0}({1}); return false;\">»</a></li>"; } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; initVariables(); } }
UTF-8
Java
2,211
java
CmsPaginationRenderer.java
Java
[]
null
[]
/* * Copyright 2008-2009 the original author or authors. * * 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 go.gg.cms.core.util; import egovframework.rte.ptl.mvc.tags.ui.pagination.AbstractPaginationRenderer; import org.springframework.web.context.ServletContextAware; import javax.servlet.ServletContext; /** * Pagination Renderer * @apiNote 전자정부 프레임워크 제공 기본 페이징 렌더러 -> Cms Template 변경 * @author 개발프레임웍크 실행환경 개발팀 (Copyright (C) by MOPAS All right reserved.) * @since 2009. 03.16 * @version 1.0 */ public class CmsPaginationRenderer extends AbstractPaginationRenderer implements ServletContextAware{ private ServletContext servletContext; public CmsPaginationRenderer() { // no-op } public void initVariables() { firstPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#first\" onclick=\"javascript:{0}({1}); return false;\">«</a></li>"; previousPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#prev\" onclick=\"javascript:{0}({1}); return false;\">‹</a></li>"; currentPageLabel = "<li class=\"footable-page active\"><a href=\"#\">{0}</a></li>"; otherPageLabel = "<li class=\"footable-page\"><a href=\"#\" onclick=\"javascript:{0}({1}); return false;\">{2}</a></li>"; nextPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#next\" onclick=\"javascript:{0}({1}); return false;\">›</a></li>"; lastPageLabel = "<li class=\"footable-page-arrow\"><a href=\"#last\" onclick=\"javascript:{0}({1}); return false;\">»</a></li>"; } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; initVariables(); } }
2,211
0.703981
0.688056
52
40.057693
40.714489
134
false
false
0
0
0
0
0
0
1.038462
false
false
10
987d4532d5efd3cf8bc3d3f879c7a55db43cba23
26,706,106,687,267
93c7c359a3f92b0d4c73a67671f62a34ba4690fe
/src/RepositoryRegistry.java
3ddc346731a9b31dd55c4faf7671a9c985ecf066
[ "MIT" ]
permissive
tcK1/EP-DSID-2017_1
https://github.com/tcK1/EP-DSID-2017_1
37f580ad3addde765d3b485a79eadd3cd4d278fb
c865839a2c93fd257d523290830e50ee40b60673
refs/heads/master
2021-01-18T23:05:46.336000
2017-04-22T16:21:16
2017-04-22T16:21:16
87,087,967
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.net.InetAddress; import java.net.UnknownHostException; import java.rmi.registry.Registry; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.HashMap; public class RepositoryRegistry implements Registry{ private HashMap<String, Remote> repos = new HashMap<String, Remote>(); public RepositoryRegistry(){ try{ System.out.println(InetAddress.getLocalHost().getHostName()); } catch(UnknownHostException e){ System.err.println("Unknown hostname."); } } public void bind(String name, Remote repo) throws RemoteException{ if(repo instanceof PartRepository){ repos.put(name, repo); } else throw new RemoteException("RMI service is not of type PartRepository."); } public String[] list(){ return (String[])repos.keySet().toArray(); } public Remote lookup(String name){ return repos.get(name); } public void rebind(String name, Remote repo) throws RemoteException{ bind(name, repo); } public void unbind(String name){ repos.remove(name); } }
UTF-8
Java
1,028
java
RepositoryRegistry.java
Java
[]
null
[]
import java.net.InetAddress; import java.net.UnknownHostException; import java.rmi.registry.Registry; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.HashMap; public class RepositoryRegistry implements Registry{ private HashMap<String, Remote> repos = new HashMap<String, Remote>(); public RepositoryRegistry(){ try{ System.out.println(InetAddress.getLocalHost().getHostName()); } catch(UnknownHostException e){ System.err.println("Unknown hostname."); } } public void bind(String name, Remote repo) throws RemoteException{ if(repo instanceof PartRepository){ repos.put(name, repo); } else throw new RemoteException("RMI service is not of type PartRepository."); } public String[] list(){ return (String[])repos.keySet().toArray(); } public Remote lookup(String name){ return repos.get(name); } public void rebind(String name, Remote repo) throws RemoteException{ bind(name, repo); } public void unbind(String name){ repos.remove(name); } }
1,028
0.73249
0.73249
44
22.363636
22.506657
75
false
false
0
0
0
0
0
0
1.681818
false
false
10
3356a5825522ebdda4917f1c48fd9b9007c951f0
17,695,265,277,892
26d8368b02b735ab0287b2b752cfba412c763ecf
/Exams/Midterm/src/test/java/midtermExam/p1/IndividualFilerTest.java
f5f0097f820b74a48d24d8ec77b1a7dd8e3af776
[]
no_license
Johnspeanut/object_oriented_programming_course
https://github.com/Johnspeanut/object_oriented_programming_course
84a7e4cf6853b030ccf127ad6f56a4fbe97879da
3a2c872ef9c9652bd87defaeb91e87c4ee6cafbf
refs/heads/master
2023-05-09T10:55:08.969000
2021-05-31T06:57:16
2021-05-31T06:57:16
372,411,184
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package midtermExam.p1; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class IndividualFilerTest { IndividualFiler individualFiler; IndividualFiler individualFilerCopy; IndividualFiler individualFilerVary; String taxID = "001"; Name name = new Name("John","Lee"); String phoneNumber = "4512563021"; String address = "255 Terry Ave"; String email = "CS5004@northeastern.edu"; ContactInfo contactInfo = new ContactInfo(name,address,phoneNumber,email); Double lastYearEarnings = 200000.0; Double totalIncomeTaxPaid = 30000.0; Double mortgageInterestPaid = 30000.0; Double studentLoanPaid = 10000.0; Double contributionRetirement = 20000.0; Double contributionHealth = 10000.0; Double charitableDonation = 3000.0; @Before public void setUp() throws Exception { individualFiler = new IndividualFiler(taxID,contactInfo,lastYearEarnings,totalIncomeTaxPaid,mortgageInterestPaid,studentLoanPaid,contributionRetirement,contributionHealth,charitableDonation); individualFilerCopy = new IndividualFiler(taxID,contactInfo,lastYearEarnings,totalIncomeTaxPaid,mortgageInterestPaid,studentLoanPaid,contributionRetirement,contributionHealth,charitableDonation); individualFilerVary = new IndividualFiler(taxID,contactInfo,lastYearEarnings,totalIncomeTaxPaid,mortgageInterestPaid,studentLoanPaid,contributionRetirement,500.0,charitableDonation); } @Test public void getTaxID() { assertTrue(individualFiler.taxID.equals(taxID)); } @Test public void getContactInfo() { assertTrue(individualFiler.contactInfo.equals(contactInfo)); } @Test public void getLastYearEarnings() { assertTrue(individualFiler.lastYearEarnings.equals(lastYearEarnings)); } @Test public void getTotalIncomeTaxPaid() { assertTrue(individualFiler.totalIncomeTaxPaid.equals(totalIncomeTaxPaid)); } @Test public void getMortgageInterestPaid() { assertTrue(individualFiler.mortgageInterestPaid.equals(mortgageInterestPaid)); } @Test public void getStudentLoadPaid() { assertTrue(individualFiler.studentLoadPaid.equals(studentLoanPaid)); } @Test public void getContributionRetirement() { assertTrue(individualFiler.contributionRetirement.equals(contributionRetirement)); } @Test public void getContributionHealth() { assertTrue(individualFiler.contributionHealth.equals(contributionHealth)); } @Test public void getCharitableDonation() { assertTrue(individualFiler.charitableDonation.equals(charitableDonation)); } @Test public void testEquals() { assertTrue(individualFiler.equals(individualFilerCopy)); assertTrue(individualFiler.equals(individualFiler)); assertFalse(individualFiler.equals(individualFilerVary)); assertFalse(individualFiler.equals(null)); assertFalse(individualFiler.equals("")); } @Test public void testHashCode() { assertTrue(individualFiler.hashCode() == individualFilerCopy.hashCode()); assertFalse(individualFiler.hashCode() == individualFilerVary.hashCode()); } @Test public void testToString() { assertTrue(individualFiler.toString().equals(individualFilerCopy.toString())); assertFalse(individualFiler.toString().equals(individualFilerVary.toString())); } @Test public void estimateBasicTaxableIncome() { assertEquals(170000.0,individualFiler.estimateBasicTaxableIncome(),0.0001); } @Test public void estimateDonationDeduction() { assertEquals(charitableDonation,individualFiler.estimateDonationDeduction(),0.0001); } @Test public void estimateMortgagePropertyDeduction() { assertEquals(0.0,individualFiler.estimateMortgagePropertyDeduction(),0.0001); } @Test public void estimateRetireDeduction() { assertEquals(21000.0,individualFiler.estimateRetireDeduction(),0.0001); } @Test public void estimateStudentDeduction() { assertEquals(1500.0,individualFiler.estimateStudentDeduction(),0.0001); } @Test public void calculateTax() { assertEquals(27455.0,individualFiler.calculateTax(),0.0001); } }
UTF-8
Java
4,088
java
IndividualFilerTest.java
Java
[ { "context": ";\n String taxID = \"001\";\n Name name = new Name(\"John\",\"Lee\");\n String phoneNumber = \"4512563021\";\n S", "end": 309, "score": 0.9998630285263062, "start": 305, "tag": "NAME", "value": "John" }, { "context": "ing taxID = \"001\";\n Name name = new Name(\"John\",\"Lee\");\n String phoneNumber = \"4512563021\";\n String ", "end": 315, "score": 0.998989462852478, "start": 312, "tag": "NAME", "value": "Lee" }, { "context": "ring address = \"255 Terry Ave\";\n String email = \"CS5004@northeastern.edu\";\n ContactInfo contactInfo = new ContactInfo(nam", "end": 433, "score": 0.9999006390571594, "start": 410, "tag": "EMAIL", "value": "CS5004@northeastern.edu" } ]
null
[]
package midtermExam.p1; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class IndividualFilerTest { IndividualFiler individualFiler; IndividualFiler individualFilerCopy; IndividualFiler individualFilerVary; String taxID = "001"; Name name = new Name("John","Lee"); String phoneNumber = "4512563021"; String address = "255 Terry Ave"; String email = "<EMAIL>"; ContactInfo contactInfo = new ContactInfo(name,address,phoneNumber,email); Double lastYearEarnings = 200000.0; Double totalIncomeTaxPaid = 30000.0; Double mortgageInterestPaid = 30000.0; Double studentLoanPaid = 10000.0; Double contributionRetirement = 20000.0; Double contributionHealth = 10000.0; Double charitableDonation = 3000.0; @Before public void setUp() throws Exception { individualFiler = new IndividualFiler(taxID,contactInfo,lastYearEarnings,totalIncomeTaxPaid,mortgageInterestPaid,studentLoanPaid,contributionRetirement,contributionHealth,charitableDonation); individualFilerCopy = new IndividualFiler(taxID,contactInfo,lastYearEarnings,totalIncomeTaxPaid,mortgageInterestPaid,studentLoanPaid,contributionRetirement,contributionHealth,charitableDonation); individualFilerVary = new IndividualFiler(taxID,contactInfo,lastYearEarnings,totalIncomeTaxPaid,mortgageInterestPaid,studentLoanPaid,contributionRetirement,500.0,charitableDonation); } @Test public void getTaxID() { assertTrue(individualFiler.taxID.equals(taxID)); } @Test public void getContactInfo() { assertTrue(individualFiler.contactInfo.equals(contactInfo)); } @Test public void getLastYearEarnings() { assertTrue(individualFiler.lastYearEarnings.equals(lastYearEarnings)); } @Test public void getTotalIncomeTaxPaid() { assertTrue(individualFiler.totalIncomeTaxPaid.equals(totalIncomeTaxPaid)); } @Test public void getMortgageInterestPaid() { assertTrue(individualFiler.mortgageInterestPaid.equals(mortgageInterestPaid)); } @Test public void getStudentLoadPaid() { assertTrue(individualFiler.studentLoadPaid.equals(studentLoanPaid)); } @Test public void getContributionRetirement() { assertTrue(individualFiler.contributionRetirement.equals(contributionRetirement)); } @Test public void getContributionHealth() { assertTrue(individualFiler.contributionHealth.equals(contributionHealth)); } @Test public void getCharitableDonation() { assertTrue(individualFiler.charitableDonation.equals(charitableDonation)); } @Test public void testEquals() { assertTrue(individualFiler.equals(individualFilerCopy)); assertTrue(individualFiler.equals(individualFiler)); assertFalse(individualFiler.equals(individualFilerVary)); assertFalse(individualFiler.equals(null)); assertFalse(individualFiler.equals("")); } @Test public void testHashCode() { assertTrue(individualFiler.hashCode() == individualFilerCopy.hashCode()); assertFalse(individualFiler.hashCode() == individualFilerVary.hashCode()); } @Test public void testToString() { assertTrue(individualFiler.toString().equals(individualFilerCopy.toString())); assertFalse(individualFiler.toString().equals(individualFilerVary.toString())); } @Test public void estimateBasicTaxableIncome() { assertEquals(170000.0,individualFiler.estimateBasicTaxableIncome(),0.0001); } @Test public void estimateDonationDeduction() { assertEquals(charitableDonation,individualFiler.estimateDonationDeduction(),0.0001); } @Test public void estimateMortgagePropertyDeduction() { assertEquals(0.0,individualFiler.estimateMortgagePropertyDeduction(),0.0001); } @Test public void estimateRetireDeduction() { assertEquals(21000.0,individualFiler.estimateRetireDeduction(),0.0001); } @Test public void estimateStudentDeduction() { assertEquals(1500.0,individualFiler.estimateStudentDeduction(),0.0001); } @Test public void calculateTax() { assertEquals(27455.0,individualFiler.calculateTax(),0.0001); } }
4,072
0.776663
0.746575
129
30.697674
36.849075
199
false
false
0
0
0
0
0
0
0.674419
false
false
10
a3a876a8a6e4279a86f41367d4c02b7a250d3653
27,839,978,015,848
26398e8e88f2fc01c650275f56c76e23548decbe
/src/main/java/com/shanhh/webhook/integration/microbadger/service/MicrobadgerServiceImpl.java
d46a38659854811a2692f213702922a5a6e7df49
[]
no_license
danshan/webhook-slack
https://github.com/danshan/webhook-slack
40621f3e0a6ded4b748a30ea899beefa3589e26a
f5dc9fe9629cf1fdb19eac5253a2261c03b83fdb
refs/heads/master
2021-01-19T22:26:55.898000
2018-04-26T07:55:51
2018-04-26T07:55:51
83,774,809
1
1
null
false
2018-04-26T07:55:52
2017-03-03T08:15:58
2018-04-26T07:49:05
2018-04-26T07:55:51
1,824
1
1
0
Java
false
null
package com.shanhh.webhook.integration.microbadger.service; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.shanhh.webhook.integration.microbadger.beans.MicrobadgerPayload; import com.shanhh.webhook.repo.entity.SlackAttaColor; import com.shanhh.webhook.repo.entity.SlackAttaPayload; import com.shanhh.webhook.repo.entity.SlackPayload; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @author dan * @since 2017-03-05 23:46 */ @Service @Slf4j public class MicrobadgerServiceImpl implements MicrobadgerService { @Override public SlackPayload exec(MicrobadgerPayload payload) { if (checkSkip(payload)) { return null; } SlackAttaPayload slack = new SlackAttaPayload(); List<SlackAttaPayload.Attachment.Field> fields = Lists.newLinkedList(); if (!CollectionUtils.isEmpty(payload.getNewTags())) { String tags = Joiner.on(" | ").join(payload.getNewTags().stream().map(MicrobadgerPayload.TagBean::getTag).collect(Collectors.toList())); fields.add(SlackAttaPayload.Attachment.Field.builder() .shortField(false) .title("New Tags") .value(tags) .build()); } if (!CollectionUtils.isEmpty(payload.getChangedTags())) { String tags = Joiner.on(" | ").join(payload.getChangedTags().stream().map(MicrobadgerPayload.TagBean::getTag).collect(Collectors.toList())); fields.add(SlackAttaPayload.Attachment.Field.builder() .shortField(false) .title("Changed Tags") .value(tags) .build()); } if (!CollectionUtils.isEmpty(payload.getDeletedTags())) { String tags = Joiner.on(" | ").join(payload.getDeletedTags().stream().map(MicrobadgerPayload.TagBean::getTag).collect(Collectors.toList())); fields.add(SlackAttaPayload.Attachment.Field.builder() .shortField(false) .title("Deleted Tags") .value(tags) .build()); } SlackAttaPayload.Attachment attachment = SlackAttaPayload.Attachment.builder() .title("Microbadger " + payload.getImageName() + " Updated") .text(payload.getText()) .fallback(payload.getText()) .color(SlackAttaColor.good.name()) .fields(fields) .build(); slack.setAttachments(Arrays.asList(attachment)); return slack; } private boolean checkSkip(MicrobadgerPayload payload) { return false; } }
UTF-8
Java
2,860
java
MicrobadgerServiceImpl.java
Java
[ { "context": "mport java.util.stream.Collectors;\n\n/**\n * @author dan\n * @since 2017-03-05 23:46\n */\n@Service\n@Slf4j\npu", "end": 611, "score": 0.9203769564628601, "start": 608, "tag": "USERNAME", "value": "dan" } ]
null
[]
package com.shanhh.webhook.integration.microbadger.service; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.shanhh.webhook.integration.microbadger.beans.MicrobadgerPayload; import com.shanhh.webhook.repo.entity.SlackAttaColor; import com.shanhh.webhook.repo.entity.SlackAttaPayload; import com.shanhh.webhook.repo.entity.SlackPayload; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @author dan * @since 2017-03-05 23:46 */ @Service @Slf4j public class MicrobadgerServiceImpl implements MicrobadgerService { @Override public SlackPayload exec(MicrobadgerPayload payload) { if (checkSkip(payload)) { return null; } SlackAttaPayload slack = new SlackAttaPayload(); List<SlackAttaPayload.Attachment.Field> fields = Lists.newLinkedList(); if (!CollectionUtils.isEmpty(payload.getNewTags())) { String tags = Joiner.on(" | ").join(payload.getNewTags().stream().map(MicrobadgerPayload.TagBean::getTag).collect(Collectors.toList())); fields.add(SlackAttaPayload.Attachment.Field.builder() .shortField(false) .title("New Tags") .value(tags) .build()); } if (!CollectionUtils.isEmpty(payload.getChangedTags())) { String tags = Joiner.on(" | ").join(payload.getChangedTags().stream().map(MicrobadgerPayload.TagBean::getTag).collect(Collectors.toList())); fields.add(SlackAttaPayload.Attachment.Field.builder() .shortField(false) .title("Changed Tags") .value(tags) .build()); } if (!CollectionUtils.isEmpty(payload.getDeletedTags())) { String tags = Joiner.on(" | ").join(payload.getDeletedTags().stream().map(MicrobadgerPayload.TagBean::getTag).collect(Collectors.toList())); fields.add(SlackAttaPayload.Attachment.Field.builder() .shortField(false) .title("Deleted Tags") .value(tags) .build()); } SlackAttaPayload.Attachment attachment = SlackAttaPayload.Attachment.builder() .title("Microbadger " + payload.getImageName() + " Updated") .text(payload.getText()) .fallback(payload.getText()) .color(SlackAttaColor.good.name()) .fields(fields) .build(); slack.setAttachments(Arrays.asList(attachment)); return slack; } private boolean checkSkip(MicrobadgerPayload payload) { return false; } }
2,860
0.631119
0.625874
74
37.648647
32.979286
152
false
false
0
0
0
0
0
0
0.391892
false
false
10
826b978252cc805070ca187cea295d04e6ff9794
24,816,321,042,779
ff6f74d3ea4bc0ccd7053c12884834a064dcae85
/java/src/test/java/edu/numbers/DifferentNumberClassesTest.java
611a94ade50821f1ebca9ca3ae0f6944de0034d4
[]
no_license
maximchukmm/java-and-friends
https://github.com/maximchukmm/java-and-friends
5267add2c3ed2358a3a7265b018cbf37149651e6
80f8b59656d3e973e66abeeaca579d5c9b405463
refs/heads/master
2023-07-19T19:52:35.411000
2023-05-09T06:09:39
2023-05-09T06:09:39
144,025,110
0
0
null
false
2023-07-07T21:57:29
2018-08-08T14:26:27
2021-12-24T16:28:08
2023-07-07T21:57:28
458
0
0
8
Java
false
false
package edu.numbers; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DifferentNumberClassesTest { @Test public void primitiveTypes_WhenFloatBringsIntoLong_ThenRemoveDecimalPartWithoutAnyRounding() { float floatValue = 9.9F; long longValue = (long) floatValue; assertEquals(9L, longValue); } @Test public void integer_WhenDividendLessDivisor_ThenReturnZero() { assertEquals(0, 0 / 60); assertEquals(0, 1 / 60); assertEquals(0, 29 / 60); assertEquals(0, 30 / 60); assertEquals(0, 31 / 60); assertEquals(0, 59 / 60); } @Test public void round_WhenDividendLessThanHalfOfDivisor_ThenReturnZero() { assertEquals(0, Math.round(29 / 60.0)); } @Test public void round_WhenDividendLessThanDivisorButEqualOrGreaterThanHalfOfDivisor_ThenReturnOne() { assertEquals(1, Math.round(30 / 60.0)); assertEquals(1, Math.round(31 / 60.0)); } }
UTF-8
Java
1,008
java
DifferentNumberClassesTest.java
Java
[]
null
[]
package edu.numbers; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DifferentNumberClassesTest { @Test public void primitiveTypes_WhenFloatBringsIntoLong_ThenRemoveDecimalPartWithoutAnyRounding() { float floatValue = 9.9F; long longValue = (long) floatValue; assertEquals(9L, longValue); } @Test public void integer_WhenDividendLessDivisor_ThenReturnZero() { assertEquals(0, 0 / 60); assertEquals(0, 1 / 60); assertEquals(0, 29 / 60); assertEquals(0, 30 / 60); assertEquals(0, 31 / 60); assertEquals(0, 59 / 60); } @Test public void round_WhenDividendLessThanHalfOfDivisor_ThenReturnZero() { assertEquals(0, Math.round(29 / 60.0)); } @Test public void round_WhenDividendLessThanDivisorButEqualOrGreaterThanHalfOfDivisor_ThenReturnOne() { assertEquals(1, Math.round(30 / 60.0)); assertEquals(1, Math.round(31 / 60.0)); } }
1,008
0.660714
0.612103
37
26.243244
26.651308
101
false
false
0
0
0
0
0
0
0.675676
false
false
10
e7397efa0d6a11c770ced10ec835d44c0642818a
20,143,396,646,138
eb25be30fe6050e8d54e74421f7facb5115df759
/commons/storage/kvs/src/main/java/tv/notube/commons/storage/kvs/mybatis/KVStoreDao.java
1656865527460d99e4fe1ebc9258f4337edb12f5
[]
no_license
mox601/NoTube-Beancounter-2.0
https://github.com/mox601/NoTube-Beancounter-2.0
bf05676d1576e6a4f2465b4e256d2ab9a3ef4581
8cda0bc613bd4512ffeaf843d4dd47d51e5b9b76
refs/heads/master
2020-04-11T06:48:27.997000
2012-03-15T10:58:43
2012-03-15T10:58:43
3,727,195
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package tv.notube.commons.storage.kvs.mybatis; import tv.notube.commons.storage.kvs.mybatis.mappers.KVSMapper; import org.apache.ibatis.session.SqlSession; import tv.notube.commons.storage.model.Query; import tv.notube.commons.storage.model.fields.Bytes; import tv.notube.commons.storage.model.fields.StringField; import java.util.List; import java.util.Properties; /** * @author Davide Palmisano ( dpalmisano@gmail.com ) */ public class KVStoreDao extends ConfigurableDao { public KVStoreDao(Properties properties) { super(properties); } public void insertObject(String table, String key, byte[] bytes, StringField[] fields) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); try { mapper.insertObject(table, key, bytes); for (StringField field : fields) { mapper.insertField(table, key, field.getName(), field.getValue()); } session.commit(); } finally { session.close(); } } public void bulkInsertObject( String table, String key, byte[] bytes, StringField[] fields ) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); try { mapper.insertObject(table, key, bytes); for (StringField field : fields) { mapper.insertField(table, key, field.getName(), field.getValue()); } } finally { session.close(); } } public byte[] getObject(String table, String key) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); Bytes bytes; try { bytes = mapper.selectByKey(table, key); } finally { session.close(); } return bytes != null ? bytes.getBytes() : null; } public List<StringField> getFields(String table, String key) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<StringField> fields; try { fields = mapper.selectFieldsByKey(table, key); } finally { session.close(); } return fields; } public List<String> selectByQuery(String table, Query query) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<String> keys; try { keys = mapper.selectByQuery(table, query.compile()); } finally { session.close(); } return keys; } public List<String> selectByTable(String table) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<String> keys; try { keys = mapper.selectByTable(table); } finally { session.close(); } return keys; } public void deleteByKey(String table, String key) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); try { mapper.deleteObject(table, key); mapper.deleteFields(table, key); } finally { session.commit(); session.close(); } } public List<String> selectByQuery(String table, Query query, int limit, int offset) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<String> keys; try { keys = mapper.selectByQueryWithLimit( table, query.compile(), limit, offset ); } finally { session.close(); } return keys; } public void commit() { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); try { session.commit(); } finally { session.close(); } } }
UTF-8
Java
4,576
java
KVStoreDao.java
Java
[ { "context": "List;\nimport java.util.Properties;\n\n/**\n * @author Davide Palmisano ( dpalmisano@gmail.com )\n */\npublic class KVStore", "end": 400, "score": 0.9998913407325745, "start": 384, "tag": "NAME", "value": "Davide Palmisano" }, { "context": "til.Properties;\n\n/**\n * @author Davide Palmisano ( dpalmisano@gmail.com )\n */\npublic class KVStoreDao extends Configurabl", "end": 423, "score": 0.9999260306358337, "start": 403, "tag": "EMAIL", "value": "dpalmisano@gmail.com" } ]
null
[]
package tv.notube.commons.storage.kvs.mybatis; import tv.notube.commons.storage.kvs.mybatis.mappers.KVSMapper; import org.apache.ibatis.session.SqlSession; import tv.notube.commons.storage.model.Query; import tv.notube.commons.storage.model.fields.Bytes; import tv.notube.commons.storage.model.fields.StringField; import java.util.List; import java.util.Properties; /** * @author <NAME> ( <EMAIL> ) */ public class KVStoreDao extends ConfigurableDao { public KVStoreDao(Properties properties) { super(properties); } public void insertObject(String table, String key, byte[] bytes, StringField[] fields) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); try { mapper.insertObject(table, key, bytes); for (StringField field : fields) { mapper.insertField(table, key, field.getName(), field.getValue()); } session.commit(); } finally { session.close(); } } public void bulkInsertObject( String table, String key, byte[] bytes, StringField[] fields ) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); try { mapper.insertObject(table, key, bytes); for (StringField field : fields) { mapper.insertField(table, key, field.getName(), field.getValue()); } } finally { session.close(); } } public byte[] getObject(String table, String key) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); Bytes bytes; try { bytes = mapper.selectByKey(table, key); } finally { session.close(); } return bytes != null ? bytes.getBytes() : null; } public List<StringField> getFields(String table, String key) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<StringField> fields; try { fields = mapper.selectFieldsByKey(table, key); } finally { session.close(); } return fields; } public List<String> selectByQuery(String table, Query query) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<String> keys; try { keys = mapper.selectByQuery(table, query.compile()); } finally { session.close(); } return keys; } public List<String> selectByTable(String table) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<String> keys; try { keys = mapper.selectByTable(table); } finally { session.close(); } return keys; } public void deleteByKey(String table, String key) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); try { mapper.deleteObject(table, key); mapper.deleteFields(table, key); } finally { session.commit(); session.close(); } } public List<String> selectByQuery(String table, Query query, int limit, int offset) { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); KVSMapper mapper = session.getMapper(KVSMapper.class); List<String> keys; try { keys = mapper.selectByQueryWithLimit( table, query.compile(), limit, offset ); } finally { session.close(); } return keys; } public void commit() { SqlSession session = ConnectionFactory.getSession(super.properties).openSession(); try { session.commit(); } finally { session.close(); } } }
4,553
0.593094
0.593094
139
31.928057
26.113102
90
false
false
0
0
0
0
0
0
0.647482
false
false
10
d3d1e04ec58d61a29b72a2c91da300ba0bcfaeed
20,143,396,645,772
0c013c5a7fdbdc9e132217385d831a066fe4db17
/src/com/hrbust/dao/impl/NewsDaoImpl.java
cb1e4cc6ce8b0895629d9785fdda81a6a50366e0
[]
no_license
dalinhuang/campusfan
https://github.com/dalinhuang/campusfan
6df4e8f7e0eba0122d87eb122067e5d259e363ad
a96781340b5b57209dea6d0aa202d204a366cac4
refs/heads/master
2016-08-11T14:04:50.811000
2009-06-05T01:10:03
2009-06-05T01:10:03
46,650,476
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hrbust.dao.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.hrbust.dao.DataConverter; import com.hrbust.dao.INewsDao; import com.hrbust.resource.dbtable.NewsTable; import com.hrbust.util.StringUtil; import com.hrbust.vo.News; import com.hrbust.vo.User; public class NewsDaoImpl extends BaseDao implements INewsDao { /** * 按属性查询新闻实例 * @param id * @return */ private News queryNewsByProperty(String property,String value){ String sql = "SELECT "+NewsTable.ID+","+NewsTable.TITLE+","+NewsTable.USERID +","+NewsTable.SUMMARY+","+NewsTable.BODY+","+NewsTable.CREATETIME+" FROM "+NewsTable.TABLENAME +" WHERE "+property+"=?"; News news = null; Map<String,Object> newsMap = null; String values[]={value}; List<Map<String, Object>> list=this.preparedQuery(sql, values); if(list.size()!=0){ newsMap = list.get(0); news = new News(); //填充news news.setId(DataConverter.toInt( newsMap.get(NewsTable.ID))); news.setTitle(DataConverter.toStr(newsMap.get(NewsTable.TITLE))); news.setSummary(DataConverter.toStr(newsMap.get(NewsTable.SUMMARY))); news.setBody(DataConverter.toStr(newsMap.get(NewsTable.BODY))); news.setCreatetime(StringUtil.getFormatNowDatetime(DataConverter.toStr(newsMap.get(NewsTable.CREATETIME)))); User user = new User(); user.setId(DataConverter.toInt(newsMap.get(NewsTable.USERID))); news.setUser(user); } return news; } /** * 按自定义查询新闻集合 * * @param property 字段名 * @param sign 限制条件 * @param value 字段值 * @param sort 排序字段 * @param dir 升/降序 * @param start 记录起始位置 * @param size 返回记录数 * @return */ private List<News> queryNewsListByCustom(String property,String sign, String value,String sort,String dir,Integer start,Integer size){ log.debug("执行NewsDao:queryNewsListByCustom方法"); String sql="SELECT "+ NewsTable.ID+","+NewsTable.USERID+","+NewsTable.TITLE+","+NewsTable.SUMMARY+","+NewsTable.BODY+"," +NewsTable.CREATETIME+" "+ "FROM "+NewsTable.TABLENAME+" "; if(property!=null&&value!=null){ sql+="WHERE "+property+" "; if(sign.equals("=")){ sql+="= '"+value+"' "; }else if(sign.equals(">")){ sql+="> '"+value+"' "; }else if(sign.equals("<")){ sql+="< '"+value+"' "; }else if(sign.equals("LIKE")){ sql+="LIKE '%"+value+"%' "; } } if(sort!=null){ sql+="ORDER BY "+sort+" "; if(dir!=null){ sql+=dir+" "; } } if(start!=null&&size!=null){ sql+="LIMIT "+start+","+size+" "; } List<News> newsList=new ArrayList<News>(); List<Map<String,Object>> newsMapList=(List<Map<String,Object>>)this.query(sql); for(int i=0;i<newsMapList.size();i++){ Map<String,Object> newsMap=newsMapList.get(i); News news=new News(); news.setId(DataConverter.toInt(newsMap.get(NewsTable.ID))); User owner=new User(); owner.setId(DataConverter.toInt(newsMap.get(NewsTable.USERID))); news.setUser(owner); news.setTitle(DataConverter.toStr(newsMap.get(NewsTable.TITLE))); news.setSummary(DataConverter.toStr(newsMap.get(NewsTable.SUMMARY))); news.setBody(DataConverter.toStr(newsMap.get(NewsTable.BODY))); news.setCreatetime(StringUtil.getFormatNowDatetime(DataConverter.toStr(newsMap.get(NewsTable.CREATETIME)))); newsList.add(news); } return newsList; } /** * 获得所有新闻数量 * @return */ public int queryTotalSize() { log.debug("执行NewsDao:totalSize方法"); int totalSize=0; String sql="SELECT COUNT("+NewsTable.ID+") " + "FROM "+NewsTable.TABLENAME; List<Map<String,Object>> list=this.query(sql); Map<String,Object> newsMap=null; if(list.size()!=0){ newsMap=list.get(0); totalSize=Integer.parseInt(""+newsMap.get("COUNT("+NewsTable.ID+")")); } return totalSize; } public List<News> queryNewsListForSize(String sort, String dir,Integer start, Integer size) { log.debug("执行NewsDao:queryNewsListForSize方法"); return this.queryNewsListByCustom(null, null, null,sort, dir, start, size); } /** * 添加新闻 */ public int saveNews(News news) { log.debug("执行NewsDao:saveNews方法"); String sql = "INSERT INTO "+NewsTable.TABLENAME +"("+NewsTable.USERID+","+NewsTable.TITLE+ ","+NewsTable.SUMMARY+","+NewsTable.BODY+","+NewsTable.CREATETIME +") VALUES (?,?,?,?,?)"; String[] values={news.getUser().getId()+"",news.getTitle(),news.getSummary(),news.getBody(),news.getCreatetime()}; return this.preparedExecute(sql, values); } /** * 删除新闻信息 */ public int deleteNewsById(int id) { log.debug("执行NewsDao:deleteNewsById方法"); String sql = "DELETE FROM "+NewsTable.TABLENAME +" WHERE "+NewsTable.ID+"=?"; String[] values={id+""}; return this.preparedExecute(sql, values); } /** * 查询News信息 */ public News queryNewsById(int id) { log.debug("执行NewsDao:queryNewsById方法"); return this.queryNewsByProperty(NewsTable.ID, ""+id); } /** * 修改新闻 * @param news * @return */ public int updateNews(News news){ log.debug("执行NewsDao:updateNews方法"); String sql = "UPDATE "+NewsTable.TABLENAME+" SET " +NewsTable.TITLE+"=?,"+NewsTable.SUMMARY+"=?,"+NewsTable.BODY+"=?,"+NewsTable.USERID+"=?,"+NewsTable.CREATETIME+"=? WHERE " +NewsTable.ID+"=?"; String[] values={news.getTitle(),news.getSummary(),news.getBody(),news.getUser().getId()+"",news.getCreatetime(),news.getId()+""}; return this.preparedExecute(sql, values); } /** * 查找上一篇新闻 * @param newsid * @return */ public News queryUpNewsById(int newsid){ log.debug("执行NEWSDAO:queryUpNewsByid"); List<News> newsList= this.queryNewsListByCustom(NewsTable.ID, "<", newsid+"", NewsTable.ID, "ASC", 0, 1); if(newsList.size()>0){ return newsList.get(0); }else{ return queryNewsById(newsid); } } /** * 查找下一篇新闻 * @param newsid * @return */ public News queryDownNewsById(int newsid){ log.debug("执行NEWSDAO:queryDownNewsByid"); List<News> newsList= this.queryNewsListByCustom(NewsTable.ID, "<", newsid+"", NewsTable.ID, "ASC", 0, 1); if(newsList.size()>0){ return newsList.get(0); }else{ return queryNewsById(newsid); } } }
UTF-8
Java
6,433
java
NewsDaoImpl.java
Java
[]
null
[]
package com.hrbust.dao.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.hrbust.dao.DataConverter; import com.hrbust.dao.INewsDao; import com.hrbust.resource.dbtable.NewsTable; import com.hrbust.util.StringUtil; import com.hrbust.vo.News; import com.hrbust.vo.User; public class NewsDaoImpl extends BaseDao implements INewsDao { /** * 按属性查询新闻实例 * @param id * @return */ private News queryNewsByProperty(String property,String value){ String sql = "SELECT "+NewsTable.ID+","+NewsTable.TITLE+","+NewsTable.USERID +","+NewsTable.SUMMARY+","+NewsTable.BODY+","+NewsTable.CREATETIME+" FROM "+NewsTable.TABLENAME +" WHERE "+property+"=?"; News news = null; Map<String,Object> newsMap = null; String values[]={value}; List<Map<String, Object>> list=this.preparedQuery(sql, values); if(list.size()!=0){ newsMap = list.get(0); news = new News(); //填充news news.setId(DataConverter.toInt( newsMap.get(NewsTable.ID))); news.setTitle(DataConverter.toStr(newsMap.get(NewsTable.TITLE))); news.setSummary(DataConverter.toStr(newsMap.get(NewsTable.SUMMARY))); news.setBody(DataConverter.toStr(newsMap.get(NewsTable.BODY))); news.setCreatetime(StringUtil.getFormatNowDatetime(DataConverter.toStr(newsMap.get(NewsTable.CREATETIME)))); User user = new User(); user.setId(DataConverter.toInt(newsMap.get(NewsTable.USERID))); news.setUser(user); } return news; } /** * 按自定义查询新闻集合 * * @param property 字段名 * @param sign 限制条件 * @param value 字段值 * @param sort 排序字段 * @param dir 升/降序 * @param start 记录起始位置 * @param size 返回记录数 * @return */ private List<News> queryNewsListByCustom(String property,String sign, String value,String sort,String dir,Integer start,Integer size){ log.debug("执行NewsDao:queryNewsListByCustom方法"); String sql="SELECT "+ NewsTable.ID+","+NewsTable.USERID+","+NewsTable.TITLE+","+NewsTable.SUMMARY+","+NewsTable.BODY+"," +NewsTable.CREATETIME+" "+ "FROM "+NewsTable.TABLENAME+" "; if(property!=null&&value!=null){ sql+="WHERE "+property+" "; if(sign.equals("=")){ sql+="= '"+value+"' "; }else if(sign.equals(">")){ sql+="> '"+value+"' "; }else if(sign.equals("<")){ sql+="< '"+value+"' "; }else if(sign.equals("LIKE")){ sql+="LIKE '%"+value+"%' "; } } if(sort!=null){ sql+="ORDER BY "+sort+" "; if(dir!=null){ sql+=dir+" "; } } if(start!=null&&size!=null){ sql+="LIMIT "+start+","+size+" "; } List<News> newsList=new ArrayList<News>(); List<Map<String,Object>> newsMapList=(List<Map<String,Object>>)this.query(sql); for(int i=0;i<newsMapList.size();i++){ Map<String,Object> newsMap=newsMapList.get(i); News news=new News(); news.setId(DataConverter.toInt(newsMap.get(NewsTable.ID))); User owner=new User(); owner.setId(DataConverter.toInt(newsMap.get(NewsTable.USERID))); news.setUser(owner); news.setTitle(DataConverter.toStr(newsMap.get(NewsTable.TITLE))); news.setSummary(DataConverter.toStr(newsMap.get(NewsTable.SUMMARY))); news.setBody(DataConverter.toStr(newsMap.get(NewsTable.BODY))); news.setCreatetime(StringUtil.getFormatNowDatetime(DataConverter.toStr(newsMap.get(NewsTable.CREATETIME)))); newsList.add(news); } return newsList; } /** * 获得所有新闻数量 * @return */ public int queryTotalSize() { log.debug("执行NewsDao:totalSize方法"); int totalSize=0; String sql="SELECT COUNT("+NewsTable.ID+") " + "FROM "+NewsTable.TABLENAME; List<Map<String,Object>> list=this.query(sql); Map<String,Object> newsMap=null; if(list.size()!=0){ newsMap=list.get(0); totalSize=Integer.parseInt(""+newsMap.get("COUNT("+NewsTable.ID+")")); } return totalSize; } public List<News> queryNewsListForSize(String sort, String dir,Integer start, Integer size) { log.debug("执行NewsDao:queryNewsListForSize方法"); return this.queryNewsListByCustom(null, null, null,sort, dir, start, size); } /** * 添加新闻 */ public int saveNews(News news) { log.debug("执行NewsDao:saveNews方法"); String sql = "INSERT INTO "+NewsTable.TABLENAME +"("+NewsTable.USERID+","+NewsTable.TITLE+ ","+NewsTable.SUMMARY+","+NewsTable.BODY+","+NewsTable.CREATETIME +") VALUES (?,?,?,?,?)"; String[] values={news.getUser().getId()+"",news.getTitle(),news.getSummary(),news.getBody(),news.getCreatetime()}; return this.preparedExecute(sql, values); } /** * 删除新闻信息 */ public int deleteNewsById(int id) { log.debug("执行NewsDao:deleteNewsById方法"); String sql = "DELETE FROM "+NewsTable.TABLENAME +" WHERE "+NewsTable.ID+"=?"; String[] values={id+""}; return this.preparedExecute(sql, values); } /** * 查询News信息 */ public News queryNewsById(int id) { log.debug("执行NewsDao:queryNewsById方法"); return this.queryNewsByProperty(NewsTable.ID, ""+id); } /** * 修改新闻 * @param news * @return */ public int updateNews(News news){ log.debug("执行NewsDao:updateNews方法"); String sql = "UPDATE "+NewsTable.TABLENAME+" SET " +NewsTable.TITLE+"=?,"+NewsTable.SUMMARY+"=?,"+NewsTable.BODY+"=?,"+NewsTable.USERID+"=?,"+NewsTable.CREATETIME+"=? WHERE " +NewsTable.ID+"=?"; String[] values={news.getTitle(),news.getSummary(),news.getBody(),news.getUser().getId()+"",news.getCreatetime(),news.getId()+""}; return this.preparedExecute(sql, values); } /** * 查找上一篇新闻 * @param newsid * @return */ public News queryUpNewsById(int newsid){ log.debug("执行NEWSDAO:queryUpNewsByid"); List<News> newsList= this.queryNewsListByCustom(NewsTable.ID, "<", newsid+"", NewsTable.ID, "ASC", 0, 1); if(newsList.size()>0){ return newsList.get(0); }else{ return queryNewsById(newsid); } } /** * 查找下一篇新闻 * @param newsid * @return */ public News queryDownNewsById(int newsid){ log.debug("执行NEWSDAO:queryDownNewsByid"); List<News> newsList= this.queryNewsListByCustom(NewsTable.ID, "<", newsid+"", NewsTable.ID, "ASC", 0, 1); if(newsList.size()>0){ return newsList.get(0); }else{ return queryNewsById(newsid); } } }
6,433
0.657933
0.655669
240
24.762501
28.845528
135
false
false
0
0
0
0
0
0
2.570833
false
false
10
50eb05183dab6826ac400494e4963bc68ff4b0ad
15,513,421,890,389
250713e8ee2ec893df548024ef89d06f60b16dd5
/0.2.4.2/JFP-Framework-Core/src/main/java/org/isotope/jfp/framework/common/CommonChannelConfig.java
c2200e1ec0ab3c8925c5e9c33d87c80c3bfd8c53
[ "BSD-3-Clause-Clear" ]
permissive
moutainhigh/cnsoft
https://github.com/moutainhigh/cnsoft
5ecda93285476041cde6711b8fa46dc7e7354a7d
b9b921d43ea9b06c881121ab5d98ce18e14df87d
refs/heads/master
2023-07-31T23:20:56.388000
2021-04-30T03:50:46
2021-04-30T03:50:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.isotope.jfp.framework.common; import org.isotope.jfp.framework.biz.common.ISInit; import org.isotope.jfp.framework.cache.ICacheService; import org.isotope.jfp.framework.cache.redis.MyRedisMaster; import org.isotope.jfp.framework.cache.redis.master.JedisMasterUtil; import org.isotope.jfp.framework.cache.redis.master.RedisPoolUtil; import org.isotope.jfp.framework.constants.ISFrameworkConstants; /** * 通用Redis通道队列设置 * * @author fucy * @version 2.4.1 2015/8/15 * @since 2.4.1 */ public class CommonChannelConfig implements ISFrameworkConstants, ISInit { /** * Redis服务器定义 */ protected RedisPoolUtil jedisPool; public void setJedisPool(RedisPoolUtil jedisPool) { this.jedisPool = jedisPool; } public RedisPoolUtil getJedisPool() { return jedisPool; } /** * 缓存定义 */ protected ICacheService catchService; public void setCatchService(ICacheService catchService) { this.catchService = catchService; } public ICacheService getCatchService() { return catchService; } /** * Redis通道定义 */ protected String channelKey; public String getChannelKey() { return channelKey; } public void setChannelKey(String channelKey) { this.channelKey = channelKey; } public boolean doInit() { JedisMasterUtil jedisUtil = new JedisMasterUtil(jedisPool); catchService = new MyRedisMaster(jedisUtil); return true; } }
UTF-8
Java
1,409
java
CommonChannelConfig.java
Java
[ { "context": "orkConstants;\n\n/**\n * 通用Redis通道队列设置\n * \n * @author fucy\n * @version 2.4.1 2015/8/15\n * @since 2.4.1\n */\np", "end": 451, "score": 0.9996778964996338, "start": 447, "tag": "USERNAME", "value": "fucy" } ]
null
[]
package org.isotope.jfp.framework.common; import org.isotope.jfp.framework.biz.common.ISInit; import org.isotope.jfp.framework.cache.ICacheService; import org.isotope.jfp.framework.cache.redis.MyRedisMaster; import org.isotope.jfp.framework.cache.redis.master.JedisMasterUtil; import org.isotope.jfp.framework.cache.redis.master.RedisPoolUtil; import org.isotope.jfp.framework.constants.ISFrameworkConstants; /** * 通用Redis通道队列设置 * * @author fucy * @version 2.4.1 2015/8/15 * @since 2.4.1 */ public class CommonChannelConfig implements ISFrameworkConstants, ISInit { /** * Redis服务器定义 */ protected RedisPoolUtil jedisPool; public void setJedisPool(RedisPoolUtil jedisPool) { this.jedisPool = jedisPool; } public RedisPoolUtil getJedisPool() { return jedisPool; } /** * 缓存定义 */ protected ICacheService catchService; public void setCatchService(ICacheService catchService) { this.catchService = catchService; } public ICacheService getCatchService() { return catchService; } /** * Redis通道定义 */ protected String channelKey; public String getChannelKey() { return channelKey; } public void setChannelKey(String channelKey) { this.channelKey = channelKey; } public boolean doInit() { JedisMasterUtil jedisUtil = new JedisMasterUtil(jedisPool); catchService = new MyRedisMaster(jedisUtil); return true; } }
1,409
0.759327
0.749817
62
21.048388
22.211903
74
false
false
0
0
0
0
0
0
1.032258
false
false
10
1bc5dc6323310d6fa695aae4f6c160fb90ef15ff
15,513,421,889,396
b8e62239883262f00972a2a9eb78b52a398a8d43
/src/main/java/com/zopa/assignment/repository/LenderRepositoryImpl.java
0026c28441e72145e3860a801c84905533106261
[]
no_license
sanketgujarathi/lender-service
https://github.com/sanketgujarathi/lender-service
eb6be46aac56f74533ae01fa4ce21eb95ac473ad
b19b9648770ec2522c648f3f1ac808b3d8b85026
refs/heads/master
2023-04-29T21:38:29.250000
2021-05-24T12:46:17
2021-05-24T12:46:17
369,891,279
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zopa.assignment.repository; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import com.zopa.assignment.domain.Lender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Repository; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.List; @Repository public class LenderRepositoryImpl implements LenderRepository { private String inputFilePath; private static Logger log = LoggerFactory.getLogger(LenderRepositoryImpl.class); public LenderRepositoryImpl(@Value("${lender.file_path}")String inputFilePath) { this.inputFilePath = inputFilePath; } @Override public List<Lender> getAllLenders() { try (FileReader reader = new FileReader(inputFilePath)) { CsvToBean<Lender> csvReader = new CsvToBeanBuilder<Lender>(reader).withType(Lender.class).build(); return csvReader.parse(); } catch (IOException e) { log.error("Unable to read lender data", e); } return Collections.emptyList(); } }
UTF-8
Java
1,189
java
LenderRepositoryImpl.java
Java
[]
null
[]
package com.zopa.assignment.repository; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import com.zopa.assignment.domain.Lender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Repository; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.List; @Repository public class LenderRepositoryImpl implements LenderRepository { private String inputFilePath; private static Logger log = LoggerFactory.getLogger(LenderRepositoryImpl.class); public LenderRepositoryImpl(@Value("${lender.file_path}")String inputFilePath) { this.inputFilePath = inputFilePath; } @Override public List<Lender> getAllLenders() { try (FileReader reader = new FileReader(inputFilePath)) { CsvToBean<Lender> csvReader = new CsvToBeanBuilder<Lender>(reader).withType(Lender.class).build(); return csvReader.parse(); } catch (IOException e) { log.error("Unable to read lender data", e); } return Collections.emptyList(); } }
1,189
0.735913
0.73423
37
31.135136
26.840029
110
false
false
0
0
0
0
0
0
0.540541
false
false
10
8038434b6905f3b82af526b6d2e537c046d9b231
5,677,946,787,079
d0fe0f8b83eb47e9f54a428ca6bd30f589464167
/app/src/main/java/com/example/shows/model/database/entity/User.java
282bc824efcc49e5d328921484ef304a71f9fed3
[]
no_license
Nastya-Lis/ShowsMobile
https://github.com/Nastya-Lis/ShowsMobile
99828e75da7dd30372f4f90daabf3fb0ff013d91
f66b06b511d5781229f37f1f73c4de605dc19871
refs/heads/master
2023-05-15T08:31:59.785000
2021-06-06T06:18:07
2021-06-06T06:18:07
361,262,125
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.shows.model.database.entity; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import java.util.Collection; import java.util.List; import lombok.Data; @Data @Entity(tableName = "user") @ForeignKey(parentColumns = "id", childColumns = "role_id", entity = Role.class) public class User extends CommonEntity{ private String login; private String email; private String password; @ColumnInfo(name = "role_id") private int roleId; public void setRoleId(int roleId) { if(role!=null) this.roleId = role.getId(); } @Ignore private Role role; @Ignore private Collection<Booking> bookings; }
UTF-8
Java
749
java
User.java
Java
[]
null
[]
package com.example.shows.model.database.entity; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.Ignore; import java.util.Collection; import java.util.List; import lombok.Data; @Data @Entity(tableName = "user") @ForeignKey(parentColumns = "id", childColumns = "role_id", entity = Role.class) public class User extends CommonEntity{ private String login; private String email; private String password; @ColumnInfo(name = "role_id") private int roleId; public void setRoleId(int roleId) { if(role!=null) this.roleId = role.getId(); } @Ignore private Role role; @Ignore private Collection<Booking> bookings; }
749
0.703605
0.703605
36
19.805555
18.038261
80
false
false
0
0
0
0
0
0
0.472222
false
false
10
224c8472985f467d4d1f09eed8b6b0ba76b3b234
11,098,195,537,130
50157aa0d6bef718831770a7f67db18f616a5747
/src/main/java/com/phones/ldap/domain/dao/ContactRepoImpl.java
8882ea4cf198cdf1477f9d4ce576a3b2f074d82c
[]
no_license
gevorg96/phones
https://github.com/gevorg96/phones
f87a552e20f9d1249600263040c3e4bb9a75034d
ebab21d5f5b037e062293f56eccd2e2d7f781ef2
refs/heads/master
2020-04-06T10:47:39.797000
2018-11-13T14:28:23
2018-11-13T14:28:23
157,392,068
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 com.phones.ldap.domain.dao; import com.phones.ldap.domain.ContactEntry; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.ldap.NameAlreadyBoundException; import org.springframework.ldap.core.LdapTemplate; import static org.springframework.ldap.query.LdapQueryBuilder.query; import org.springframework.stereotype.Repository; /** * * @author trunov_as */ @Repository public class ContactRepoImpl implements ContactRepo{ private LdapTemplate ldapTemplate; @Autowired public void setLdapTemplate(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; } @Override public void delete(ContactEntry contact) throws EmptyResultDataAccessException{ ldapTemplate.delete(contact); } @Override public void update(ContactEntry contact) throws EmptyResultDataAccessException{ ldapTemplate.update(contact); } @Override public void create(ContactEntry contact) throws NameAlreadyBoundException{ String cn = contact.getGivenName()+" "+contact.getSn(); contact.setCn(cn); ldapTemplate.create(contact); } @Override public List<ContactEntry> find() throws EmptyResultDataAccessException{ return ldapTemplate.findAll(ContactEntry.class); } @Override public ContactEntry find(String containerName) throws EmptyResultDataAccessException{ return ldapTemplate.findOne(query().where("cn").is(containerName), ContactEntry.class); } }
UTF-8
Java
1,808
java
ContactRepoImpl.java
Java
[ { "context": "ramework.stereotype.Repository;\n\n/**\n *\n * @author trunov_as\n */\n@Repository\npublic class ContactRepoImpl impl", "end": 672, "score": 0.9993951916694641, "start": 663, "tag": "USERNAME", "value": "trunov_as" } ]
null
[]
/* * 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 com.phones.ldap.domain.dao; import com.phones.ldap.domain.ContactEntry; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.ldap.NameAlreadyBoundException; import org.springframework.ldap.core.LdapTemplate; import static org.springframework.ldap.query.LdapQueryBuilder.query; import org.springframework.stereotype.Repository; /** * * @author trunov_as */ @Repository public class ContactRepoImpl implements ContactRepo{ private LdapTemplate ldapTemplate; @Autowired public void setLdapTemplate(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; } @Override public void delete(ContactEntry contact) throws EmptyResultDataAccessException{ ldapTemplate.delete(contact); } @Override public void update(ContactEntry contact) throws EmptyResultDataAccessException{ ldapTemplate.update(contact); } @Override public void create(ContactEntry contact) throws NameAlreadyBoundException{ String cn = contact.getGivenName()+" "+contact.getSn(); contact.setCn(cn); ldapTemplate.create(contact); } @Override public List<ContactEntry> find() throws EmptyResultDataAccessException{ return ldapTemplate.findAll(ContactEntry.class); } @Override public ContactEntry find(String containerName) throws EmptyResultDataAccessException{ return ldapTemplate.findOne(query().where("cn").is(containerName), ContactEntry.class); } }
1,808
0.745575
0.745575
61
28.639345
28.806324
95
false
false
0
0
0
0
0
0
0.360656
false
false
10
d0c002ed8c5a9a22c1acf992f6725ce637bd2a51
8,332,236,586,478
f4a4b9818b2f0d1ec604aefcee37aa35ba4eaf3d
/commons/src/main/java/com/reactiveminds/psi/common/imdg/DataGridConfiguration.java
08a81f9b47815a41e3966e7b39c4348d255500fa
[]
no_license
matteobevilacqua/psi-platform
https://github.com/matteobevilacqua/psi-platform
98c325eeea3db2b2c4bd305032f72edccc0fa315
d30fc7129e39e773b07c480d3d26fcb3284df798
refs/heads/master
2023-03-15T15:24:49.375000
2020-09-22T13:07:54
2020-09-22T13:07:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.reactiveminds.psi.common.imdg; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.XmlClientConfigBuilder; import com.hazelcast.core.HazelcastInstance; import com.reactiveminds.psi.client.ClientConfiguration; import com.reactiveminds.psi.common.BaseConfiguration; import com.reactiveminds.psi.common.err.GridOperationNotAllowedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; import javax.annotation.PreDestroy; import java.io.IOException; @Import(BaseConfiguration.class) @Configuration public class DataGridConfiguration { private static final Logger log = LoggerFactory.getLogger(ClientConfiguration.class); @Value("${spring.hazelcast.config:}") String configXml; @Autowired ApplicationContext context; @Value("${psi.grid.client.authEnabled:false}") boolean authEnabled; @Bean public HazelcastInstance hazelcastInstance() throws IOException { if (authEnabled) { Boolean auth = sslClient().get(); if(!auth){ throw new GridOperationNotAllowedException("SSL auth failed! Please install server certificate " + "with `-Djavax.net.ssl.trustStore=<keystore> -Djavax.net.ssl.trustStorePassword=<password>`"); } } Resource config = null; if(StringUtils.hasText(configXml)) { config = context.getResource(configXml); } ClientConfig c = config != null ? new XmlClientConfigBuilder(config.getURL()).build() : new XmlClientConfigBuilder().build(); c.getNetworkConfig().setSmartRouting(true); return getHazelcastInstance(c); } private static HazelcastInstance getHazelcastInstance(ClientConfig clientConfig) { if (StringUtils.hasText(clientConfig.getInstanceName())) { return HazelcastClient .getHazelcastClientByName(clientConfig.getInstanceName()); } return HazelcastClient.newHazelcastClient(clientConfig); } @Autowired HazelcastInstance client; @PreDestroy void shutdown(){ client.shutdown(); } @Bean SslClient sslClient(){ return new SslClient(); } }
UTF-8
Java
2,710
java
DataGridConfiguration.java
Java
[ { "context": "re=<keystore> -Djavax.net.ssl.trustStorePassword=<password>`\");\n }\n }\n Resource con", "end": 1764, "score": 0.9137638211250305, "start": 1756, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.reactiveminds.psi.common.imdg; import com.hazelcast.client.HazelcastClient; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.XmlClientConfigBuilder; import com.hazelcast.core.HazelcastInstance; import com.reactiveminds.psi.client.ClientConfiguration; import com.reactiveminds.psi.common.BaseConfiguration; import com.reactiveminds.psi.common.err.GridOperationNotAllowedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; import javax.annotation.PreDestroy; import java.io.IOException; @Import(BaseConfiguration.class) @Configuration public class DataGridConfiguration { private static final Logger log = LoggerFactory.getLogger(ClientConfiguration.class); @Value("${spring.hazelcast.config:}") String configXml; @Autowired ApplicationContext context; @Value("${psi.grid.client.authEnabled:false}") boolean authEnabled; @Bean public HazelcastInstance hazelcastInstance() throws IOException { if (authEnabled) { Boolean auth = sslClient().get(); if(!auth){ throw new GridOperationNotAllowedException("SSL auth failed! Please install server certificate " + "with `-Djavax.net.ssl.trustStore=<keystore> -Djavax.net.ssl.trustStorePassword=<<PASSWORD>>`"); } } Resource config = null; if(StringUtils.hasText(configXml)) { config = context.getResource(configXml); } ClientConfig c = config != null ? new XmlClientConfigBuilder(config.getURL()).build() : new XmlClientConfigBuilder().build(); c.getNetworkConfig().setSmartRouting(true); return getHazelcastInstance(c); } private static HazelcastInstance getHazelcastInstance(ClientConfig clientConfig) { if (StringUtils.hasText(clientConfig.getInstanceName())) { return HazelcastClient .getHazelcastClientByName(clientConfig.getInstanceName()); } return HazelcastClient.newHazelcastClient(clientConfig); } @Autowired HazelcastInstance client; @PreDestroy void shutdown(){ client.shutdown(); } @Bean SslClient sslClient(){ return new SslClient(); } }
2,712
0.727675
0.726937
73
36.123287
28.501356
133
false
false
0
0
0
0
0
0
0.493151
false
false
10
ae3e7b31d3ffcd5b02772430bf096144be1d385b
21,320,217,696,368
0b4d0c67d74b256e1befbaa1a2565f60a8072d00
/src/main/java/io/lovelacetech/server/command/company/CompanyByNameOrPhoneNumberCommand.java
d0955f405005be52c40503dd2334ca46c000113e
[]
no_license
JaceyPenny/lovelaceassetmanager-server-v2
https://github.com/JaceyPenny/lovelaceassetmanager-server-v2
fddd4e9d72faa1a4e7bea6f982d7454f4a55885e
425cac16cc8303f1cfb84027c319fa74ee784182
refs/heads/master
2020-05-18T15:15:41.003000
2018-04-08T06:21:53
2018-04-08T06:21:53
184,492,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.lovelacetech.server.command.company; import com.google.common.base.Strings; import io.lovelacetech.server.model.api.model.ApiCompanyList; import io.lovelacetech.server.model.api.response.company.CompanyListApiResponse; public class CompanyByNameOrPhoneNumberCommand extends CompanyCommand<CompanyByNameOrPhoneNumberCommand> { private String name; private String phoneNumber; public CompanyByNameOrPhoneNumberCommand setName(String name) { this.name = name; return this; } public CompanyByNameOrPhoneNumberCommand setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; return this; } @Override public boolean checkCommand() { return super.checkCommand() && !Strings.isNullOrEmpty(name) && !Strings.isNullOrEmpty(phoneNumber); } @Override public CompanyListApiResponse execute() { if (!checkCommand()) { return new CompanyListApiResponse().setDefault(); } ApiCompanyList apiCompanyList = null; try { apiCompanyList = new ApiCompanyList( getCompanyRepository().findByNameOrPhoneNumber(name, phoneNumber)); } catch (NullPointerException ignored) { } if (apiCompanyList == null) { return new CompanyListApiResponse().setNotFound(); } else { return new CompanyListApiResponse() .setSuccess() .setResponse(apiCompanyList); } } }
UTF-8
Java
1,409
java
CompanyByNameOrPhoneNumberCommand.java
Java
[]
null
[]
package io.lovelacetech.server.command.company; import com.google.common.base.Strings; import io.lovelacetech.server.model.api.model.ApiCompanyList; import io.lovelacetech.server.model.api.response.company.CompanyListApiResponse; public class CompanyByNameOrPhoneNumberCommand extends CompanyCommand<CompanyByNameOrPhoneNumberCommand> { private String name; private String phoneNumber; public CompanyByNameOrPhoneNumberCommand setName(String name) { this.name = name; return this; } public CompanyByNameOrPhoneNumberCommand setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; return this; } @Override public boolean checkCommand() { return super.checkCommand() && !Strings.isNullOrEmpty(name) && !Strings.isNullOrEmpty(phoneNumber); } @Override public CompanyListApiResponse execute() { if (!checkCommand()) { return new CompanyListApiResponse().setDefault(); } ApiCompanyList apiCompanyList = null; try { apiCompanyList = new ApiCompanyList( getCompanyRepository().findByNameOrPhoneNumber(name, phoneNumber)); } catch (NullPointerException ignored) { } if (apiCompanyList == null) { return new CompanyListApiResponse().setNotFound(); } else { return new CompanyListApiResponse() .setSuccess() .setResponse(apiCompanyList); } } }
1,409
0.721789
0.721789
50
27.18
23.691931
80
false
false
0
0
0
0
0
0
0.34
false
false
10
c26ceca2a3d9f6ed0ffaea9834282565fd60ecc0
24,567,212,997,600
55821b09861478c6db214d808f12f493f54ff82a
/trunk/java.prj/sv65Ecc_ofbiz_component/src/com/siteview/ecc/api/UserEntity.java
94f34196a2656149fb3b2e669c790d306612b253
[]
no_license
SiteView/ECC8.13
https://github.com/SiteView/ECC8.13
ede526a869cf0cb076cd9695dbc16075a1cf9716
bced98372138b09140dc108b33bb63f33ef769fe
refs/heads/master
2016-09-05T13:57:21.282000
2012-06-12T08:54:40
2012-06-12T08:54:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.siteview.ecc.api; import java.util.Enumeration; import java.util.List; import jgl.Array; import jgl.HashMap; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; import com.dragonflow.Properties.HashMapOrdered; public class UserEntity extends EntityBase{ public static Array get()throws Exception { List<GenericValue> list = getAllUser(); Array retlist = new Array(); HashMapOrdered hashMapControl = new HashMapOrdered(false); hashMapControl.put("_nextID", getDelegator().getNextSeqId("SvUser")); hashMapControl.put("_fileEncoding", "UTF-8"); retlist.add(hashMapControl); for (GenericValue val : list) { HashMapOrdered hashMap = new HashMapOrdered(false); hashMap.put("_id", val.get("id")); if (val.get("disabled") !=null && val.getBoolean("disabled") == true)hashMap.put("_disabled", "true"); if (val.getString("group")!=null)hashMap.put("_group", val.getString("group")); if (val.getString("ldapserver")!=null)hashMap.put("_ldapserver", val.getString("ldapserver")); if (val.getString("login")!=null)hashMap.put("_login", val.getString("login")); if (val.getString("password")!=null)hashMap.put("_password", val.getString("password")); if (val.getString("realName")!=null)hashMap.put("_realName", val.getString("realName")); if (val.getString("securityprincipal")!=null)hashMap.put("_securityprincipal", val.getString("securityprincipal")); setUserPermission(val.getString("id"),hashMap); retlist.add(hashMap); } return retlist; } public static void put(Array data)throws Exception { deleteAll(); Enumeration<?> enumeration = data.elements(); if (enumeration.hasMoreElements()){ Object objectFirst = enumeration.nextElement(); if (objectFirst instanceof HashMap){ //put("0",(HashMap) objectFirst); } while(enumeration.hasMoreElements()) { Object object = enumeration.nextElement(); if (object instanceof HashMap){ put((String)((HashMap)object).get("_id"),(HashMap) object); } } } } private static List<String> cols = getDelegator().getModelEntity("SvUser").getAllFieldNames(); public static void put(String id,HashMap hashmap)throws Exception { if (id==null)return; GenericValue val = getDelegator().makeValue("SvUser"); val.set("id", id); val.set("disabled", "true".equals(hashmap.get("_disabled")) ? Boolean.TRUE : Boolean.FALSE); val.set("group", hashmap.get("_group")); val.set("ldapserver", hashmap.get("_ldapserver")); val.set("login", hashmap.get("_login")); val.set("password", hashmap.get("_password")); val.set("realName", hashmap.get("_realName")); val.set("securityprincipal", hashmap.get("_securityprincipal")); val.create(); Enumeration<?> keys = hashmap.keys(); while(keys.hasMoreElements()) { String key = (String)keys.nextElement(); if (isExist(key,cols)) continue; String value = (String)hashmap.get(key); putPermission(id,key,value); } } public static boolean isExist(String skey,List<String> keys) { if (skey == null) return false; if (keys == null) return false; for (String key : keys){ if (skey.equals("_" + key)) return true; } return false; } public static void putPermission(String userId,String key,String value) throws Exception { if (userId==null)return; GenericValue val = getDelegator().makeValue("SvUserPermission"); val.set("userId", userId); val.set("attrName",key); val.set("attrValue", "true".equals(value) ? Boolean.TRUE : Boolean.FALSE); val.create(); } public static List<GenericValue> getPermission(String id)throws Exception { EntityCondition condition = EntityCondition.makeCondition("userId", EntityOperator.EQUALS, id); return getDelegator().findList("SvUserPermission", condition, null,null,null,false); } public static void setUserPermission(String id,HashMap hashMap)throws Exception { List<GenericValue> list = getPermission(id); for (GenericValue val : list) { String key = (String)val.getString("attrName"); if (key == null) continue; String value = "" + val.getBoolean("attrValue"); if (!"true".equals(value)) continue; hashMap.add(key, value); } } public static List<GenericValue> getAllUser()throws Exception { return getDelegator().findList("SvUser", null, null,null,null,false); } public static void deleteAll()throws Exception { getDelegator().removeByAnd("SvUserPermission",UtilMisc.toMap("1","1")); getDelegator().removeByAnd("SvUser",UtilMisc.toMap("1","1")); } }
UTF-8
Java
4,792
java
UserEntity.java
Java
[ { "context": "n\", hashmap.get(\"_login\"));\r\n\t\tval.set(\"password\", hashmap.get(\"_password\"));\r\n\t\tval.set(\"realName\", hashmap.get(\"_realName", "end": 2777, "score": 0.9544013142585754, "start": 2755, "tag": "PASSWORD", "value": "hashmap.get(\"_password" } ]
null
[]
package com.siteview.ecc.api; import java.util.Enumeration; import java.util.List; import jgl.Array; import jgl.HashMap; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; import com.dragonflow.Properties.HashMapOrdered; public class UserEntity extends EntityBase{ public static Array get()throws Exception { List<GenericValue> list = getAllUser(); Array retlist = new Array(); HashMapOrdered hashMapControl = new HashMapOrdered(false); hashMapControl.put("_nextID", getDelegator().getNextSeqId("SvUser")); hashMapControl.put("_fileEncoding", "UTF-8"); retlist.add(hashMapControl); for (GenericValue val : list) { HashMapOrdered hashMap = new HashMapOrdered(false); hashMap.put("_id", val.get("id")); if (val.get("disabled") !=null && val.getBoolean("disabled") == true)hashMap.put("_disabled", "true"); if (val.getString("group")!=null)hashMap.put("_group", val.getString("group")); if (val.getString("ldapserver")!=null)hashMap.put("_ldapserver", val.getString("ldapserver")); if (val.getString("login")!=null)hashMap.put("_login", val.getString("login")); if (val.getString("password")!=null)hashMap.put("_password", val.getString("password")); if (val.getString("realName")!=null)hashMap.put("_realName", val.getString("realName")); if (val.getString("securityprincipal")!=null)hashMap.put("_securityprincipal", val.getString("securityprincipal")); setUserPermission(val.getString("id"),hashMap); retlist.add(hashMap); } return retlist; } public static void put(Array data)throws Exception { deleteAll(); Enumeration<?> enumeration = data.elements(); if (enumeration.hasMoreElements()){ Object objectFirst = enumeration.nextElement(); if (objectFirst instanceof HashMap){ //put("0",(HashMap) objectFirst); } while(enumeration.hasMoreElements()) { Object object = enumeration.nextElement(); if (object instanceof HashMap){ put((String)((HashMap)object).get("_id"),(HashMap) object); } } } } private static List<String> cols = getDelegator().getModelEntity("SvUser").getAllFieldNames(); public static void put(String id,HashMap hashmap)throws Exception { if (id==null)return; GenericValue val = getDelegator().makeValue("SvUser"); val.set("id", id); val.set("disabled", "true".equals(hashmap.get("_disabled")) ? Boolean.TRUE : Boolean.FALSE); val.set("group", hashmap.get("_group")); val.set("ldapserver", hashmap.get("_ldapserver")); val.set("login", hashmap.get("_login")); val.set("password", <PASSWORD>")); val.set("realName", hashmap.get("_realName")); val.set("securityprincipal", hashmap.get("_securityprincipal")); val.create(); Enumeration<?> keys = hashmap.keys(); while(keys.hasMoreElements()) { String key = (String)keys.nextElement(); if (isExist(key,cols)) continue; String value = (String)hashmap.get(key); putPermission(id,key,value); } } public static boolean isExist(String skey,List<String> keys) { if (skey == null) return false; if (keys == null) return false; for (String key : keys){ if (skey.equals("_" + key)) return true; } return false; } public static void putPermission(String userId,String key,String value) throws Exception { if (userId==null)return; GenericValue val = getDelegator().makeValue("SvUserPermission"); val.set("userId", userId); val.set("attrName",key); val.set("attrValue", "true".equals(value) ? Boolean.TRUE : Boolean.FALSE); val.create(); } public static List<GenericValue> getPermission(String id)throws Exception { EntityCondition condition = EntityCondition.makeCondition("userId", EntityOperator.EQUALS, id); return getDelegator().findList("SvUserPermission", condition, null,null,null,false); } public static void setUserPermission(String id,HashMap hashMap)throws Exception { List<GenericValue> list = getPermission(id); for (GenericValue val : list) { String key = (String)val.getString("attrName"); if (key == null) continue; String value = "" + val.getBoolean("attrValue"); if (!"true".equals(value)) continue; hashMap.add(key, value); } } public static List<GenericValue> getAllUser()throws Exception { return getDelegator().findList("SvUser", null, null,null,null,false); } public static void deleteAll()throws Exception { getDelegator().removeByAnd("SvUserPermission",UtilMisc.toMap("1","1")); getDelegator().removeByAnd("SvUser",UtilMisc.toMap("1","1")); } }
4,780
0.679048
0.677796
141
31.985815
29.571404
119
false
false
0
0
0
0
0
0
2.602837
false
false
10
fd4f923291fad215d8400b727d9d40a9da0d29c4
24,567,212,998,620
297c77843daad98db1a570170273f1ad6e15a773
/src/com/selenium/Actions_Keyboard.java
dd6b6cd88a2fe04ebf9045a037c1343e362263d6
[]
no_license
srikanth-05/Selenium_Testing
https://github.com/srikanth-05/Selenium_Testing
580178bda02da4325e3d37b4aa62adb2b09a2cd5
a43f6942b910030ab52990be6ff04ff9ce14e062
refs/heads/master
2023-06-12T10:29:00.464000
2021-07-06T11:28:29
2021-07-06T11:28:29
383,443,123
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.selenium; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class Actions_Keyboard { public static void main(String[] args) throws AWTException, InterruptedException { System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\eclipse-workspace\\Selenium_Testing\\src\\Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://automationpractice.com/index.php"); driver.manage().window().maximize(); WebElement c = driver.findElement(By.xpath("//*[@id=\"block_top_menu\"]/ul/li[1]/a")); Actions z = new Actions (driver); z.moveToElement(c).build().perform(); Thread.sleep(3000); WebElement tshirts = driver.findElement(By.xpath("//*[@id=\\\"block_top_menu\\\"]/ul/li[3]/a")); z.contextClick(tshirts).build().perform(); Thread.sleep(3000); Robot R = new Robot(); R.keyPress(KeyEvent.VK_DOWN); R.keyRelease(KeyEvent.VK_DOWN); } }
UTF-8
Java
1,161
java
Actions_Keyboard.java
Java
[]
null
[]
package com.selenium; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class Actions_Keyboard { public static void main(String[] args) throws AWTException, InterruptedException { System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\eclipse-workspace\\Selenium_Testing\\src\\Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://automationpractice.com/index.php"); driver.manage().window().maximize(); WebElement c = driver.findElement(By.xpath("//*[@id=\"block_top_menu\"]/ul/li[1]/a")); Actions z = new Actions (driver); z.moveToElement(c).build().perform(); Thread.sleep(3000); WebElement tshirts = driver.findElement(By.xpath("//*[@id=\\\"block_top_menu\\\"]/ul/li[3]/a")); z.contextClick(tshirts).build().perform(); Thread.sleep(3000); Robot R = new Robot(); R.keyPress(KeyEvent.VK_DOWN); R.keyRelease(KeyEvent.VK_DOWN); } }
1,161
0.730405
0.721792
33
34.18182
30.387852
136
false
false
0
0
0
0
0
0
1.787879
false
false
10
5abdf95f587fb2af05e0874977f99be3ed85337c
21,320,217,666,791
764aaebebb0ab2764aa0829166bff7cb1e121e18
/contribs/bicycle/src/main/java/org/matsim/contrib/bicycle/BicycleTravelTime.java
cf476907b6fe564ad86d6a106c72fedb14dcaf27
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
muellermichel/matsim
https://github.com/muellermichel/matsim
dabed0f74661e93d64e99181bcfa9d095a849115
a5d811368aeea06b41dd1ee6511b3b26c81dbf00
refs/heads/master
2020-03-25T02:33:06.880000
2019-06-01T22:13:17
2019-06-01T22:13:17
143,295,240
2
1
null
true
2018-08-02T12:59:54
2018-08-02T12:59:54
2018-08-01T21:16:59
2018-08-02T05:06:21
909,763
0
0
0
null
false
null
/* *********************************************************************** * * project: org.matsim.* * * * * *********************************************************************** * * * * copyright : (C) 2008 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.contrib.bicycle; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; import org.matsim.core.router.util.TravelTime; import org.matsim.vehicles.Vehicle; /** * @author dziemke */ class BicycleTravelTime implements TravelTime { @Override public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { // TODO make this speed adjustable double minimumSpeedForDedicatedCyclingInfrastructure = 15.0/3.6; String type = (String) link.getAttributes().getAttribute("type"); String cycleway = (String) link.getAttributes().getAttribute(BicycleLabels.CYCLEWAY); double cyclingInfrastructureSpeed = computeMinimumCyclingInfrastructureSpeed(type, cycleway, minimumSpeedForDedicatedCyclingInfrastructure); double infrastructureSpeed = Math.max(link.getFreespeed(), cyclingInfrastructureSpeed); // This is not yet available, but might be at some point, see https://matsim.atlassian.net/browse/MATSIM-700 // double bicycleVelocity = vehicle.getType().getMaximumVelocity() // ... until then, use this workaround: double vehicleLinkSpeed = Math.min(infrastructureSpeed, BicycleSpeedUtils.getSpeed("bicycle")); double gradientSpeed = computeGradientSpeed(link, vehicleLinkSpeed); String surface = (String) link.getAttributes().getAttribute(BicycleLabels.SURFACE); double surfaceSpeed = vehicleLinkSpeed; if (surface != null) { surfaceSpeed = computeSurfaceSpeed(vehicleLinkSpeed, surface, type); } double effectiveSpeed = Math.min(gradientSpeed, surfaceSpeed); return (link.getLength() / effectiveSpeed); } /** * If there is a dedicated cycling infrastructure, it is unlikely that the speed (before later consideration * of slopes) falls under a certain minimum * @return */ private double computeMinimumCyclingInfrastructureSpeed(String type, String cycleway, double minimumSpeedForDedicatedCyclingInfrastructure) { double cyclingInfrastructureSpeed = 0.; if (type.equals("cycleway")) { cyclingInfrastructureSpeed = minimumSpeedForDedicatedCyclingInfrastructure; // Assume that this speed is always feasible on a dedicated cycleway } if (cycleway != null) { if (cycleway.equals("track") || cycleway.equals("track")) { cyclingInfrastructureSpeed = minimumSpeedForDedicatedCyclingInfrastructure; // Assume that this speed is always feasible on a dedicated cycleway } } return cyclingInfrastructureSpeed; } /** * Based on "Flügel et al. -- Empirical speed models for cycling in the Oslo road network" (not yet published!) * Positive gradients (uphill): Roughly linear decrease in speed with increasing gradient * At 9% gradient, cyclists are 42.7% slower * Negative gradients (downhill): * Not linear; highest speeds at 5% or 6% gradient; at gradients higher than 6% braking */ private double computeGradientSpeed(Link link, double vehicleLinkSpeed) { double gradientSpeedFactor = 1.; Double fromNodeZ = link.getFromNode().getCoord().getZ(); Double toNodeZ = link.getToNode().getCoord().getZ(); if ((fromNodeZ != null) && (toNodeZ != null)) { if (toNodeZ > fromNodeZ) { // No positive speed increase for downhill, only decrease for uphill gradientSpeedFactor = 1 - 5. * ((toNodeZ - fromNodeZ) / link.getLength()); // 50% reducation at 10% up-slope } } if (gradientSpeedFactor < 0.1) { gradientSpeedFactor = 0.1; } return vehicleLinkSpeed * gradientSpeedFactor; } // TODO combine this with comfort private double computeSurfaceSpeed(double vehicleLinkSpeed, String surface, String type) { if (type.equals("cycleway")) { return vehicleLinkSpeed; // Assuming that dedicated cycleways are on good surface like ashalt } double surfaceSpeedFactor; switch (surface) { case "paved": case "asphalt": surfaceSpeedFactor = 1.; break; case "cobblestone": surfaceSpeedFactor = 0.5; break; case "cobblestone (bad)": surfaceSpeedFactor = 0.4; break; case "cobblestone;flattened": case "cobblestone:flattened": case "sett": surfaceSpeedFactor = 0.6; break; case "concrete": surfaceSpeedFactor = 0.9; break; case "concrete:lanes": case "concrete_plates": case "concrete:plates": surfaceSpeedFactor = 0.8; break; case "paving_stones": case "paving_stones:35": case "paving_stones:30": surfaceSpeedFactor = 0.7; break; case "unpaved": surfaceSpeedFactor = 0.5; break; case "compacted": surfaceSpeedFactor = 0.9; break; case "dirt": surfaceSpeedFactor = 0.5; break; case "earth": surfaceSpeedFactor = 0.6; break; case "fine_gravel": case "gravel": case "ground": surfaceSpeedFactor = 0.7; break; case "wood": surfaceSpeedFactor = 0.5; break; case "pebblestone": surfaceSpeedFactor = 0.7; break; case "sand": surfaceSpeedFactor = 0.2; break; case "bricks": case "stone": surfaceSpeedFactor = 0.7; break; case "grass": surfaceSpeedFactor = 0.4; break; case "compressed": surfaceSpeedFactor = 0.7; break; case "asphalt;paving_stones:35": surfaceSpeedFactor = 0.9; break; case "paving_stones:3": surfaceSpeedFactor = 0.8; break; default: surfaceSpeedFactor = 0.5; } return vehicleLinkSpeed * surfaceSpeedFactor; } }
UTF-8
Java
6,576
java
BicycleTravelTime.java
Java
[ { "context": "mport org.matsim.vehicles.Vehicle;\n\n/**\n * @author dziemke\n */\nclass BicycleTravelTime implements TravelTime", "end": 1589, "score": 0.9996232986450195, "start": 1582, "tag": "USERNAME", "value": "dziemke" } ]
null
[]
/* *********************************************************************** * * project: org.matsim.* * * * * *********************************************************************** * * * * copyright : (C) 2008 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.contrib.bicycle; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; import org.matsim.core.router.util.TravelTime; import org.matsim.vehicles.Vehicle; /** * @author dziemke */ class BicycleTravelTime implements TravelTime { @Override public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { // TODO make this speed adjustable double minimumSpeedForDedicatedCyclingInfrastructure = 15.0/3.6; String type = (String) link.getAttributes().getAttribute("type"); String cycleway = (String) link.getAttributes().getAttribute(BicycleLabels.CYCLEWAY); double cyclingInfrastructureSpeed = computeMinimumCyclingInfrastructureSpeed(type, cycleway, minimumSpeedForDedicatedCyclingInfrastructure); double infrastructureSpeed = Math.max(link.getFreespeed(), cyclingInfrastructureSpeed); // This is not yet available, but might be at some point, see https://matsim.atlassian.net/browse/MATSIM-700 // double bicycleVelocity = vehicle.getType().getMaximumVelocity() // ... until then, use this workaround: double vehicleLinkSpeed = Math.min(infrastructureSpeed, BicycleSpeedUtils.getSpeed("bicycle")); double gradientSpeed = computeGradientSpeed(link, vehicleLinkSpeed); String surface = (String) link.getAttributes().getAttribute(BicycleLabels.SURFACE); double surfaceSpeed = vehicleLinkSpeed; if (surface != null) { surfaceSpeed = computeSurfaceSpeed(vehicleLinkSpeed, surface, type); } double effectiveSpeed = Math.min(gradientSpeed, surfaceSpeed); return (link.getLength() / effectiveSpeed); } /** * If there is a dedicated cycling infrastructure, it is unlikely that the speed (before later consideration * of slopes) falls under a certain minimum * @return */ private double computeMinimumCyclingInfrastructureSpeed(String type, String cycleway, double minimumSpeedForDedicatedCyclingInfrastructure) { double cyclingInfrastructureSpeed = 0.; if (type.equals("cycleway")) { cyclingInfrastructureSpeed = minimumSpeedForDedicatedCyclingInfrastructure; // Assume that this speed is always feasible on a dedicated cycleway } if (cycleway != null) { if (cycleway.equals("track") || cycleway.equals("track")) { cyclingInfrastructureSpeed = minimumSpeedForDedicatedCyclingInfrastructure; // Assume that this speed is always feasible on a dedicated cycleway } } return cyclingInfrastructureSpeed; } /** * Based on "Flügel et al. -- Empirical speed models for cycling in the Oslo road network" (not yet published!) * Positive gradients (uphill): Roughly linear decrease in speed with increasing gradient * At 9% gradient, cyclists are 42.7% slower * Negative gradients (downhill): * Not linear; highest speeds at 5% or 6% gradient; at gradients higher than 6% braking */ private double computeGradientSpeed(Link link, double vehicleLinkSpeed) { double gradientSpeedFactor = 1.; Double fromNodeZ = link.getFromNode().getCoord().getZ(); Double toNodeZ = link.getToNode().getCoord().getZ(); if ((fromNodeZ != null) && (toNodeZ != null)) { if (toNodeZ > fromNodeZ) { // No positive speed increase for downhill, only decrease for uphill gradientSpeedFactor = 1 - 5. * ((toNodeZ - fromNodeZ) / link.getLength()); // 50% reducation at 10% up-slope } } if (gradientSpeedFactor < 0.1) { gradientSpeedFactor = 0.1; } return vehicleLinkSpeed * gradientSpeedFactor; } // TODO combine this with comfort private double computeSurfaceSpeed(double vehicleLinkSpeed, String surface, String type) { if (type.equals("cycleway")) { return vehicleLinkSpeed; // Assuming that dedicated cycleways are on good surface like ashalt } double surfaceSpeedFactor; switch (surface) { case "paved": case "asphalt": surfaceSpeedFactor = 1.; break; case "cobblestone": surfaceSpeedFactor = 0.5; break; case "cobblestone (bad)": surfaceSpeedFactor = 0.4; break; case "cobblestone;flattened": case "cobblestone:flattened": case "sett": surfaceSpeedFactor = 0.6; break; case "concrete": surfaceSpeedFactor = 0.9; break; case "concrete:lanes": case "concrete_plates": case "concrete:plates": surfaceSpeedFactor = 0.8; break; case "paving_stones": case "paving_stones:35": case "paving_stones:30": surfaceSpeedFactor = 0.7; break; case "unpaved": surfaceSpeedFactor = 0.5; break; case "compacted": surfaceSpeedFactor = 0.9; break; case "dirt": surfaceSpeedFactor = 0.5; break; case "earth": surfaceSpeedFactor = 0.6; break; case "fine_gravel": case "gravel": case "ground": surfaceSpeedFactor = 0.7; break; case "wood": surfaceSpeedFactor = 0.5; break; case "pebblestone": surfaceSpeedFactor = 0.7; break; case "sand": surfaceSpeedFactor = 0.2; break; case "bricks": case "stone": surfaceSpeedFactor = 0.7; break; case "grass": surfaceSpeedFactor = 0.4; break; case "compressed": surfaceSpeedFactor = 0.7; break; case "asphalt;paving_stones:35": surfaceSpeedFactor = 0.9; break; case "paving_stones:3": surfaceSpeedFactor = 0.8; break; default: surfaceSpeedFactor = 0.5; } return vehicleLinkSpeed * surfaceSpeedFactor; } }
6,576
0.635285
0.622509
142
45.302818
34.157257
148
false
false
0
0
0
0
0
0
2.485915
false
false
10
991e4d93d0f72b713c778667ba95729febeeb6be
3,865,470,578,648
41da1c487e808e988e830e740aecf45a4dd589f9
/src/com/school/dao/DataBaseDao.java
9d007089a170b068bce0008f5a735936e7878532
[]
no_license
RaniaSalem/NewSchool
https://github.com/RaniaSalem/NewSchool
bfc86f56c0d6ba93c76d79a9d6b7c6e956a2fa0d
21444026847ff6864965f8ec4d435b063fcc68c7
refs/heads/master
2021-01-10T16:09:28.981000
2015-12-27T22:14:15
2015-12-27T22:14:15
48,400,819
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.school.dao; import java.sql.Connection; import java.sql.ResultSet; public interface DataBaseDao { public Connection openConnection(); public void closeConnection(Connection conn); public void updateQuery(String sql,Connection conn); public ResultSet excuteQuery(String sql,Connection conn); }
UTF-8
Java
341
java
DataBaseDao.java
Java
[]
null
[]
package com.school.dao; import java.sql.Connection; import java.sql.ResultSet; public interface DataBaseDao { public Connection openConnection(); public void closeConnection(Connection conn); public void updateQuery(String sql,Connection conn); public ResultSet excuteQuery(String sql,Connection conn); }
341
0.739003
0.739003
12
26.416666
21.08498
61
false
false
0
0
0
0
0
0
0.75
false
false
10
88e1dafe91c763494b82854d1f971d874f3b6ead
32,555,852,116,104
6b38bd930c704e243c7c3fc17c62b690980c206e
/EnergyFalcon/src/Fireball.java
1d930113a9b0e30642c233459c73c8e87be9faac
[ "MIT" ]
permissive
dfpaglia/Arcade-Team-2
https://github.com/dfpaglia/Arcade-Team-2
66d55bc055210dd428859fc258a425ce1070798a
495b88583118c2830ba169e1c40c49b8e217a72c
refs/heads/master
2021-01-11T19:47:34.103000
2017-04-17T01:05:03
2017-04-17T01:05:03
79,397,628
0
0
null
false
2017-04-09T18:04:02
2017-01-19T00:08:34
2017-04-09T17:30:18
2017-04-09T18:04:02
141,855
0
0
0
Java
null
null
import java.awt.Graphics2D; import arcadia.Game; public class Fireball { private static final double DEFAULT_SPEED = 5.0; private static final double RADIUS = 15.0; private Vector2D direction; private boolean shouldDelete = false; private boolean shouldDestruct = false; private class FireballCollider extends CircularCollision{ public FireballCollider(double x, double y, double r) { super(x, y, r, CollisionType.ENEMY_HURTBOX_COLLISION); } @Override void onCollide(CollisionType t, CollisionData extraData) { switch(t){ case ENEMY_HITBOX_COLLISION: break; case ENEMY_HURTBOX_COLLISION: break; case HURTBOX_GENERAL: break; case PLAYER_HITBOX_COLLISION: shouldDelete = true; shouldDestruct = true; break; case PLAYER_HURTBOX_COLLISION: break; case WALL_COLLISION: break; default: break; } } @Override CollisionData getCollisionData() { return new CollisionData(Fireball.this); } } private FireballCollider c; public Fireball(double x, double y, Vector2D direction){ this.direction = Vector2D.scale(Vector2D.unitVector(direction), DEFAULT_SPEED); c = new FireballCollider(x, y, RADIUS); } public Fireball(double x, double y, Vector2D direction, double speed){ this.direction = Vector2D.scale(Vector2D.unitVector(direction), speed); c = new FireballCollider(x, y, RADIUS); } public void onTick(){ if(!shouldDelete){ c.setPos(c.getX() + direction.getX(), c.getY() + direction.getY()); //Destroy the fireball if it's out of range if(c.getX() > Game.WIDTH || c.getX() < 0 || c.getY() > Game.HEIGHT || c.getY() < 0 ){ shouldDelete = true; shouldDestruct = true; } } if(shouldDestruct){ this.destruct(); shouldDestruct = false; } } public void draw(Graphics2D g){ if(!shouldDelete){ g.fillOval((int)(c.getX() - RADIUS), (int)(c.getY() - RADIUS), (int)(2*RADIUS), (int)(2*RADIUS)); } } public boolean shouldDelete(){ return shouldDelete; } public void destruct(){ c.destruct(); } }
UTF-8
Java
2,142
java
Fireball.java
Java
[]
null
[]
import java.awt.Graphics2D; import arcadia.Game; public class Fireball { private static final double DEFAULT_SPEED = 5.0; private static final double RADIUS = 15.0; private Vector2D direction; private boolean shouldDelete = false; private boolean shouldDestruct = false; private class FireballCollider extends CircularCollision{ public FireballCollider(double x, double y, double r) { super(x, y, r, CollisionType.ENEMY_HURTBOX_COLLISION); } @Override void onCollide(CollisionType t, CollisionData extraData) { switch(t){ case ENEMY_HITBOX_COLLISION: break; case ENEMY_HURTBOX_COLLISION: break; case HURTBOX_GENERAL: break; case PLAYER_HITBOX_COLLISION: shouldDelete = true; shouldDestruct = true; break; case PLAYER_HURTBOX_COLLISION: break; case WALL_COLLISION: break; default: break; } } @Override CollisionData getCollisionData() { return new CollisionData(Fireball.this); } } private FireballCollider c; public Fireball(double x, double y, Vector2D direction){ this.direction = Vector2D.scale(Vector2D.unitVector(direction), DEFAULT_SPEED); c = new FireballCollider(x, y, RADIUS); } public Fireball(double x, double y, Vector2D direction, double speed){ this.direction = Vector2D.scale(Vector2D.unitVector(direction), speed); c = new FireballCollider(x, y, RADIUS); } public void onTick(){ if(!shouldDelete){ c.setPos(c.getX() + direction.getX(), c.getY() + direction.getY()); //Destroy the fireball if it's out of range if(c.getX() > Game.WIDTH || c.getX() < 0 || c.getY() > Game.HEIGHT || c.getY() < 0 ){ shouldDelete = true; shouldDestruct = true; } } if(shouldDestruct){ this.destruct(); shouldDestruct = false; } } public void draw(Graphics2D g){ if(!shouldDelete){ g.fillOval((int)(c.getX() - RADIUS), (int)(c.getY() - RADIUS), (int)(2*RADIUS), (int)(2*RADIUS)); } } public boolean shouldDelete(){ return shouldDelete; } public void destruct(){ c.destruct(); } }
2,142
0.654062
0.645658
85
23.200001
22.954071
100
false
false
0
0
0
0
0
0
2.694118
false
false
10
cd22361defb8ac231356f90b6dddf3e6d94fc9e9
30,820,685,324,759
f0f1892f604dc3b1e5afd08e8cd772d65b82b17c
/src/main/java/com/ncr/chess/Pawn.java
a7b28e9277644af4db3e5eb46e4265842bb524a5
[]
no_license
tmeedimale/ChessProject
https://github.com/tmeedimale/ChessProject
c8d2980f4425739654da99bfb6555cfaaabe862c
bf0d000c201575799dff2d81b91a41d3e87f6061
refs/heads/master
2023-03-10T13:49:18.021000
2021-02-28T13:35:00
2021-02-28T13:35:00
343,109,203
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ncr.chess; public class Pawn { private ChessBoard chessBoard; private int xCoordinate; private int yCoordinate; private PieceColor pieceColor; public Pawn(PieceColor pieceColor) { this.pieceColor = pieceColor; } public ChessBoard getChessBoard() { return chessBoard; } public void setChessBoard(ChessBoard chessBoard) { this.chessBoard = chessBoard; } public int getXCoordinate() { return xCoordinate; } public void setXCoordinate(int value) { this.xCoordinate = value; } public int getYCoordinate() { return yCoordinate; } public void setYCoordinate(int value) { this.yCoordinate = value; } public PieceColor getPieceColor() { return this.pieceColor; } private void setPieceColor(PieceColor value) { pieceColor = value; } public void move(MovementType movementType, int newX, int newY) { if (movementType == MovementType.MOVE) { int currentXCoordinate = this.xCoordinate; int currentYCoordinate = this.yCoordinate; if (this.pieceColor == PieceColor.BLACK) { //diagonal and any 1 step forward and diagonal towards right if ((newX == (currentXCoordinate - 1) || newX == currentXCoordinate) && (newY == (currentYCoordinate) || newY == (currentYCoordinate - 1))) { this.xCoordinate = newX; this.yCoordinate = newY; } } else if (this.pieceColor == PieceColor.WHITE) { if ((newX == (currentXCoordinate + 1) || newX == currentXCoordinate) && (newY == (currentYCoordinate) || newY == (currentYCoordinate + 1))) { this.xCoordinate = newX; this.yCoordinate = newY; } } } } @Override public String toString() { return getCurrentPositionAsString(); } protected String getCurrentPositionAsString() { String eol = System.lineSeparator(); return String.format("Current X: {1}{0}Current Y: {2}{0}Piece Color: {3}", eol, xCoordinate, yCoordinate, pieceColor); } }
UTF-8
Java
2,270
java
Pawn.java
Java
[]
null
[]
package com.ncr.chess; public class Pawn { private ChessBoard chessBoard; private int xCoordinate; private int yCoordinate; private PieceColor pieceColor; public Pawn(PieceColor pieceColor) { this.pieceColor = pieceColor; } public ChessBoard getChessBoard() { return chessBoard; } public void setChessBoard(ChessBoard chessBoard) { this.chessBoard = chessBoard; } public int getXCoordinate() { return xCoordinate; } public void setXCoordinate(int value) { this.xCoordinate = value; } public int getYCoordinate() { return yCoordinate; } public void setYCoordinate(int value) { this.yCoordinate = value; } public PieceColor getPieceColor() { return this.pieceColor; } private void setPieceColor(PieceColor value) { pieceColor = value; } public void move(MovementType movementType, int newX, int newY) { if (movementType == MovementType.MOVE) { int currentXCoordinate = this.xCoordinate; int currentYCoordinate = this.yCoordinate; if (this.pieceColor == PieceColor.BLACK) { //diagonal and any 1 step forward and diagonal towards right if ((newX == (currentXCoordinate - 1) || newX == currentXCoordinate) && (newY == (currentYCoordinate) || newY == (currentYCoordinate - 1))) { this.xCoordinate = newX; this.yCoordinate = newY; } } else if (this.pieceColor == PieceColor.WHITE) { if ((newX == (currentXCoordinate + 1) || newX == currentXCoordinate) && (newY == (currentYCoordinate) || newY == (currentYCoordinate + 1))) { this.xCoordinate = newX; this.yCoordinate = newY; } } } } @Override public String toString() { return getCurrentPositionAsString(); } protected String getCurrentPositionAsString() { String eol = System.lineSeparator(); return String.format("Current X: {1}{0}Current Y: {2}{0}Piece Color: {3}", eol, xCoordinate, yCoordinate, pieceColor); } }
2,270
0.58326
0.578855
76
28.868422
27.168743
126
false
false
0
0
0
0
0
0
0.486842
false
false
10
3c098da1a859c54d77a47596b761120b820d9b4d
29,076,928,651,074
51830a51638e18ad5c208c65ab9aea9695fcb1ae
/src/main/java/ie/home/graphs_own/GraphMapList.java
90469b7ac0527fd1a8315cbf96890685cc0169e6
[]
no_license
Octtavius/data-structures-examples
https://github.com/Octtavius/data-structures-examples
a188276b221b1df1fd8e79ee28bb4dd64aa8b249
74becec4d9fadbf19a0df8ca17c837f85f62c585
refs/heads/master
2021-06-23T07:18:51.485000
2019-10-28T13:17:19
2019-10-28T13:17:19
211,544,134
0
0
null
false
2021-03-31T21:30:29
2019-09-28T18:24:18
2019-10-28T13:17:34
2021-03-31T21:30:29
77
0
0
2
Java
false
false
package ie.home.graphs_own; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GraphMapList extends Graph{ Map<Integer, List<Integer>> graphMap; public GraphMapList() { graphMap = new HashMap<Integer, List<Integer>>(); } @Override protected void implementAddVertex() { int numV = getNumVertices(); if (graphMap.get(numV) == null) { graphMap.put(numV, new ArrayList<Integer>()); } } @Override protected void implementAddEdge(int from, int to) { List<Integer> nodes = graphMap.get(from); if (!nodes.contains(to)) { nodes.add(to); } } @Override protected List<Integer> getNeighbours(int vertex) { List<Integer> allNeighbours = getIndegreeNeighbours(vertex); for (Integer integer : getOutNeighbours(vertex)) { if (allNeighbours.contains(integer)) { continue; } } return allNeighbours; } @Override protected List<Integer> getIndegreeNeighbours(int vertex) { List<Integer> indegreeNeighbours = new ArrayList<Integer>(); for (Integer node: graphMap.keySet()) { if (node == vertex) { continue; } if (graphMap.get(node).contains(vertex)) { indegreeNeighbours.add(node); } } return indegreeNeighbours; } @Override protected List<Integer> getOutNeighbours(int vertex) { return graphMap.get(vertex); } }
UTF-8
Java
1,366
java
GraphMapList.java
Java
[]
null
[]
package ie.home.graphs_own; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GraphMapList extends Graph{ Map<Integer, List<Integer>> graphMap; public GraphMapList() { graphMap = new HashMap<Integer, List<Integer>>(); } @Override protected void implementAddVertex() { int numV = getNumVertices(); if (graphMap.get(numV) == null) { graphMap.put(numV, new ArrayList<Integer>()); } } @Override protected void implementAddEdge(int from, int to) { List<Integer> nodes = graphMap.get(from); if (!nodes.contains(to)) { nodes.add(to); } } @Override protected List<Integer> getNeighbours(int vertex) { List<Integer> allNeighbours = getIndegreeNeighbours(vertex); for (Integer integer : getOutNeighbours(vertex)) { if (allNeighbours.contains(integer)) { continue; } } return allNeighbours; } @Override protected List<Integer> getIndegreeNeighbours(int vertex) { List<Integer> indegreeNeighbours = new ArrayList<Integer>(); for (Integer node: graphMap.keySet()) { if (node == vertex) { continue; } if (graphMap.get(node).contains(vertex)) { indegreeNeighbours.add(node); } } return indegreeNeighbours; } @Override protected List<Integer> getOutNeighbours(int vertex) { return graphMap.get(vertex); } }
1,366
0.693997
0.693997
66
19.69697
19.494343
62
false
false
0
0
0
0
0
0
1.848485
false
false
10
944e285af26eca002608ea222c998f204cb05316
28,930,899,724,296
11e5eb5d1de8ec8d03615b0ed236eac057bab1e7
/src/main/java/com/demo/java8/pojo/util/CommonUtil.java
755f0e87ad44be975a834287670b7214c3f8e97e
[]
no_license
vljh246v/vljh246v-java8-test-pracitce
https://github.com/vljh246v/vljh246v-java8-test-pracitce
17c68d2d9c36546703badf29f327de7211d330f3
e37eb74b6660a1cb80dfbf75a80e9028c37e83f0
refs/heads/master
2020-07-04T10:10:52.091000
2019-08-16T06:57:40
2019-08-16T06:57:40
202,252,320
0
0
null
false
2019-08-16T06:57:42
2019-08-14T01:46:52
2019-08-14T01:48:14
2019-08-16T06:57:41
12
0
0
0
Java
false
false
package com.demo.java8.pojo.util; import com.demo.java8.pojo.chapter3.functioninterface.BufferReaderProcessor; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; public class CommonUtil { public static <T> List<T> filter (List<T> list, Predicate<T> p){ List<T> result = new ArrayList<>(); for(T e : list) { if (p.test(e)) { result.add(e); } } return result; } public static <T> void forEach(List<T> list, Consumer<T> c){ for(T i : list){ c.accept(i); } } }
UTF-8
Java
679
java
CommonUtil.java
Java
[]
null
[]
package com.demo.java8.pojo.util; import com.demo.java8.pojo.chapter3.functioninterface.BufferReaderProcessor; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; public class CommonUtil { public static <T> List<T> filter (List<T> list, Predicate<T> p){ List<T> result = new ArrayList<>(); for(T e : list) { if (p.test(e)) { result.add(e); } } return result; } public static <T> void forEach(List<T> list, Consumer<T> c){ for(T i : list){ c.accept(i); } } }
679
0.599411
0.594993
28
23.25
20.453125
76
false
false
0
0
0
0
0
0
0.464286
false
false
10
71807012984d90530906c0cb676c16dbe23310ae
5,282,809,777,443
832fdd5af3347b6afdefe92a67c6028d576e6876
/testbot/android/src/TestSimpleClientTest/src/org/alljoyn/bus/samples/simpleclient/test/TestSimpleClient.java
e8207a28d455c8ecd41c7f04432e09f5ff1c9ca1
[ "Apache-2.0" ]
permissive
alljoyn/core-test
https://github.com/alljoyn/core-test
fedcdba7d598010ecc3c856964bfd181295ab9a8
377bec783c8917b4a30350d82dd08fcab27ef6d6
refs/heads/master
2021-09-11T12:36:50.418000
2018-04-06T21:45:26
2018-04-06T21:45:26
112,536,881
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/****************************************************************************** * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ package org.alljoyn.bus.samples.simpleclient.test; import org.alljoyn.bus.samples.simpleclient.*; import android.test.ActivityInstrumentationTestCase2; import android.view.KeyEvent; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; public class TestSimpleClient extends ActivityInstrumentationTestCase2<Client> { private Client clientActivity; private ListView listOfMessages; private ArrayAdapter<String> listAdapter; private EditText textEditor; private final String pingMsg1 = "C L I E N T"; private final String replyMsg1 = "Reply: client"; private final String pingMsg2 = "S U P E R L O N G M E S S A G E"; private final String replyMsg2 = "Reply: superlongmessage"; public TestSimpleClient() { super("org.alljoyn.bus.samples.simpleclient", Client.class); } public void setUp() throws Exception { super.setUp(); clientActivity = this.getActivity(); listOfMessages = (ListView)clientActivity.findViewById(org.alljoyn.bus.samples.simpleclient.R.id.ListView); listAdapter = (ArrayAdapter<String>) listOfMessages.getAdapter(); textEditor = (EditText)clientActivity.findViewById(org.alljoyn.bus.samples.simpleclient.R.id.EditText); } @Override public void tearDown() throws Exception { super.tearDown(); } private void waitDiscoveryComplete() { /* Wait 30 second for discovery complete */ try { Thread.sleep(30000); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } } private void waitReplyBack() { /* Wait 10 second for reply back */ try { Thread.sleep(10000); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } } private void checkListView() { int msgCount = listAdapter.getCount(); assertEquals("Reply not received!", 4, msgCount); assertEquals("1st reply missing!", replyMsg1, listAdapter.getItem(1)); assertEquals("2nd reply missing!", replyMsg2, listAdapter.getItem(3)); } public void testClientPing() { waitDiscoveryComplete(); // text editor should focus after discovery and joinSession complete assertTrue("Discovery or joinSession fail!", textEditor.isInputMethodTarget()); this.sendKeys(pingMsg1); /* Wait 100ms for discovery complete */ try { Thread.sleep(100); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } this.sendKeys(KeyEvent.KEYCODE_ENTER); // Wait till reply back from service waitReplyBack(); this.sendKeys(pingMsg2); /* Wait 100ms for discovery complete */ try { Thread.sleep(100); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } this.sendKeys(KeyEvent.KEYCODE_ENTER); // Wait till reply back from service waitReplyBack(); // Check reply from service checkListView(); } }
UTF-8
Java
4,429
java
TestSimpleClient.java
Java
[]
null
[]
/****************************************************************************** * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ package org.alljoyn.bus.samples.simpleclient.test; import org.alljoyn.bus.samples.simpleclient.*; import android.test.ActivityInstrumentationTestCase2; import android.view.KeyEvent; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; public class TestSimpleClient extends ActivityInstrumentationTestCase2<Client> { private Client clientActivity; private ListView listOfMessages; private ArrayAdapter<String> listAdapter; private EditText textEditor; private final String pingMsg1 = "C L I E N T"; private final String replyMsg1 = "Reply: client"; private final String pingMsg2 = "S U P E R L O N G M E S S A G E"; private final String replyMsg2 = "Reply: superlongmessage"; public TestSimpleClient() { super("org.alljoyn.bus.samples.simpleclient", Client.class); } public void setUp() throws Exception { super.setUp(); clientActivity = this.getActivity(); listOfMessages = (ListView)clientActivity.findViewById(org.alljoyn.bus.samples.simpleclient.R.id.ListView); listAdapter = (ArrayAdapter<String>) listOfMessages.getAdapter(); textEditor = (EditText)clientActivity.findViewById(org.alljoyn.bus.samples.simpleclient.R.id.EditText); } @Override public void tearDown() throws Exception { super.tearDown(); } private void waitDiscoveryComplete() { /* Wait 30 second for discovery complete */ try { Thread.sleep(30000); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } } private void waitReplyBack() { /* Wait 10 second for reply back */ try { Thread.sleep(10000); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } } private void checkListView() { int msgCount = listAdapter.getCount(); assertEquals("Reply not received!", 4, msgCount); assertEquals("1st reply missing!", replyMsg1, listAdapter.getItem(1)); assertEquals("2nd reply missing!", replyMsg2, listAdapter.getItem(3)); } public void testClientPing() { waitDiscoveryComplete(); // text editor should focus after discovery and joinSession complete assertTrue("Discovery or joinSession fail!", textEditor.isInputMethodTarget()); this.sendKeys(pingMsg1); /* Wait 100ms for discovery complete */ try { Thread.sleep(100); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } this.sendKeys(KeyEvent.KEYCODE_ENTER); // Wait till reply back from service waitReplyBack(); this.sendKeys(pingMsg2); /* Wait 100ms for discovery complete */ try { Thread.sleep(100); } catch (InterruptedException e) { assertTrue("sleep timeout!", false); } this.sendKeys(KeyEvent.KEYCODE_ENTER); // Wait till reply back from service waitReplyBack(); // Check reply from service checkListView(); } }
4,429
0.681418
0.670806
144
29.763889
27.086021
109
false
false
0
0
0
0
0
0
1.722222
false
false
10
e15088d0fcf7d5e4cee3a0162e02148aaea85216
9,792,525,453,601
f292322f18e0217c98268b64e93d92853b21cb8c
/app/src/main/java/com/example/siemie/recipes/IngredientsPreference.java
7e6db30a4cdd6c88a07a7afa6b1cabe3964b8725
[]
no_license
Maximvda/Recipes
https://github.com/Maximvda/Recipes
aa41aee658d89c9bcbb9df8d686c4218c744c77b
4ea144128893161dd3110dfcbd7c7a16a43d5cfe
refs/heads/master
2018-11-10T04:18:53.325000
2018-08-22T21:29:50
2018-08-22T21:29:50
143,733,784
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.siemie.recipes; import java.util.ArrayList; public class IngredientsPreference { private ArrayList<Ingredient> ingredientsNegative; private ArrayList<Ingredient> ingredientsPositive; private IngredientList ingredientList; }
UTF-8
Java
260
java
IngredientsPreference.java
Java
[]
null
[]
package com.example.siemie.recipes; import java.util.ArrayList; public class IngredientsPreference { private ArrayList<Ingredient> ingredientsNegative; private ArrayList<Ingredient> ingredientsPositive; private IngredientList ingredientList; }
260
0.807692
0.807692
11
22.636364
21.764328
54
false
false
0
0
0
0
0
0
0.454545
false
false
10
d6ce6097a6ba589687f23bd3007ee0563f395fb9
28,312,424,452,376
4392711786df5d0a4313dee2b840d69316f83860
/Service/src/main/java/com/td/service/command/crud/contractor/FindDriversCommand.java
24e7053e2a901f4c7cf623d8e168b88112bf3ce4
[]
no_license
Zerotul/TransDocs
https://github.com/Zerotul/TransDocs
5aff678b902bf4a88c1c53a82b84888c210caaea
beed3415278dadd815df60bec32d5fae6e2e0e62
refs/heads/master
2018-01-07T18:14:15.060000
2017-03-16T09:09:21
2017-03-16T09:09:21
35,799,120
2
2
null
false
2017-10-11T17:07:19
2015-05-18T05:46:06
2017-03-16T09:09:24
2017-03-16T09:09:22
3,638
2
2
2
CSS
null
null
package com.td.service.command.crud.contractor; import com.td.model.entity.dictionary.company.CarrierModel; import com.td.model.entity.dictionary.company.DriverModel; import com.td.service.command.AbstractProducerCommand; import com.td.service.command.ProducerCommandContext; import com.td.service.command.argument.Argument; import com.td.service.command.crud.qualifier.FindDrivers; import com.td.service.crud.CRUDService; import org.springframework.stereotype.Component; import java.util.*; /** * Created by zerotul. */ @Component @FindDrivers public class FindDriversCommand extends AbstractProducerCommand<UUID, List<DriverModel>> { public static class Arguments{ public static final String CRUD_SERVICE = "crudService"; } @Override protected ProducerCommandContext<UUID, List<DriverModel>> executeInternal(ProducerCommandContext<UUID, List<DriverModel>> context, Map<String, Argument> args) throws Exception { CRUDService<CarrierModel> crudService = getArgumentValue(Arguments.CRUD_SERVICE, args); List<DriverModel> drivers = crudService.getReference(context.getTarget()).getDrivers(); drivers.size(); context.setProduced(Collections.unmodifiableList(drivers)); return context; } @Override protected Set<String> requireArguments() { return Collections.singleton(Arguments.CRUD_SERVICE); } }
UTF-8
Java
1,392
java
FindDriversCommand.java
Java
[ { "context": "Component;\n\nimport java.util.*;\n\n/**\n * Created by zerotul.\n */\n@Component\n@FindDrivers\npublic class FindDri", "end": 520, "score": 0.9996802806854248, "start": 513, "tag": "USERNAME", "value": "zerotul" } ]
null
[]
package com.td.service.command.crud.contractor; import com.td.model.entity.dictionary.company.CarrierModel; import com.td.model.entity.dictionary.company.DriverModel; import com.td.service.command.AbstractProducerCommand; import com.td.service.command.ProducerCommandContext; import com.td.service.command.argument.Argument; import com.td.service.command.crud.qualifier.FindDrivers; import com.td.service.crud.CRUDService; import org.springframework.stereotype.Component; import java.util.*; /** * Created by zerotul. */ @Component @FindDrivers public class FindDriversCommand extends AbstractProducerCommand<UUID, List<DriverModel>> { public static class Arguments{ public static final String CRUD_SERVICE = "crudService"; } @Override protected ProducerCommandContext<UUID, List<DriverModel>> executeInternal(ProducerCommandContext<UUID, List<DriverModel>> context, Map<String, Argument> args) throws Exception { CRUDService<CarrierModel> crudService = getArgumentValue(Arguments.CRUD_SERVICE, args); List<DriverModel> drivers = crudService.getReference(context.getTarget()).getDrivers(); drivers.size(); context.setProduced(Collections.unmodifiableList(drivers)); return context; } @Override protected Set<String> requireArguments() { return Collections.singleton(Arguments.CRUD_SERVICE); } }
1,392
0.766523
0.766523
39
34.692307
37.308933
181
false
false
0
0
0
0
0
0
0.589744
false
false
10
9de1f538934b5e271b94d1f252be421e6ba3b76e
28,312,424,451,365
3d1cb2e58e59db09a536081d7bcf21cd0e9b3d5d
/mall-pojo/src/main/java/com/yunfeng/pojo/vo/SubCategoryVO.java
131cb8dbd58c859b545132f01429ba3814c5f620
[]
no_license
YvantYun/mall
https://github.com/YvantYun/mall
59e2af331cf2fe69c123b3e5bc06063bab4d9871
c2ef65a8dbbb53ea13960a993f18a21a2010b0b5
refs/heads/master
2022-07-24T14:34:20.619000
2020-03-10T13:15:56
2020-03-10T13:15:56
221,631,682
0
0
null
false
2022-06-21T02:14:17
2019-11-14T06:53:41
2020-03-10T13:16:12
2022-06-21T02:14:14
218
0
0
4
Java
false
false
package com.yunfeng.pojo.vo; import lombok.Data; /** * <p> * 三级分类vo * </p> * * @author yunfeng * @since 2019-11-20 */ @Data public class SubCategoryVO { private Integer subId; private String subName; private String subType; private Integer subFatherId; }
UTF-8
Java
290
java
SubCategoryVO.java
Java
[ { "context": ".Data;\n\n/**\n * <p>\n * 三级分类vo\n * </p>\n *\n * @author yunfeng\n * @since 2019-11-20\n */\n@Data\npublic class SubCa", "end": 101, "score": 0.9973490238189697, "start": 94, "tag": "USERNAME", "value": "yunfeng" } ]
null
[]
package com.yunfeng.pojo.vo; import lombok.Data; /** * <p> * 三级分类vo * </p> * * @author yunfeng * @since 2019-11-20 */ @Data public class SubCategoryVO { private Integer subId; private String subName; private String subType; private Integer subFatherId; }
290
0.656028
0.62766
21
12.428572
11.508057
32
false
false
0
0
0
0
0
0
0.285714
false
false
10
36ae5e33ed213789d59425128dc6121ce2167f75
4,887,672,812,085
2c533a20f8e77f447d6c0fcddb0dd479d810f8ea
/src/main/java/com/honghailt/cjtj/repository/LocationRepository.java
da9507d4cbf400ba8698a369130bee2218265500
[]
no_license
wjx656761524/cjti
https://github.com/wjx656761524/cjti
88861e73980f88714e382aa2a5fcad4bbc792043
5615b21c650972ee4ba60befe41bcdf5a391134b
refs/heads/master
2022-12-21T03:15:39.640000
2019-10-15T05:39:37
2019-10-15T05:39:37
215,215,950
0
1
null
false
2022-12-10T06:42:26
2019-10-15T05:42:57
2019-10-15T05:44:33
2022-12-10T06:42:25
2,698
0
1
23
Java
false
false
package com.honghailt.cjtj.repository; import com.honghailt.cjtj.domain.GroupStatus; import com.honghailt.cjtj.domain.Location; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import java.util.List; /** * @Author: WujinXian * @Description: * @Date: Created in 17:36 2019/5/17 * @Modified By */ public interface LocationRepository extends JpaRepository<Location, Long>, JpaSpecificationExecutor<Location> { List<Location> findLocationByGroupId(Long groupId); List<Location>findByCampaignId(Long campaignId); }
UTF-8
Java
613
java
LocationRepository.java
Java
[ { "context": "Executor;\n\nimport java.util.List;\n\n/**\n * @Author: WujinXian\n * @Description:\n * @Date: Created in 17:36 2019/", "end": 314, "score": 0.9880121350288391, "start": 305, "tag": "NAME", "value": "WujinXian" } ]
null
[]
package com.honghailt.cjtj.repository; import com.honghailt.cjtj.domain.GroupStatus; import com.honghailt.cjtj.domain.Location; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import java.util.List; /** * @Author: WujinXian * @Description: * @Date: Created in 17:36 2019/5/17 * @Modified By */ public interface LocationRepository extends JpaRepository<Location, Long>, JpaSpecificationExecutor<Location> { List<Location> findLocationByGroupId(Long groupId); List<Location>findByCampaignId(Long campaignId); }
613
0.796085
0.77814
20
29.65
29.433441
111
false
false
0
0
0
0
0
0
0.5
false
false
10
ec444e0e93485f60713f0d9ae7e6fd72be9b895e
14,723,147,928,328
8adca8f049c8bc9494fedc57aa5aea09e77d3ffa
/hibernate_image_demo/src/main/java/hibernate_image_demo/model/Photo.java
db16d72fe940ec84fb3c793cb6a19d952b05b23e
[]
no_license
dhiraj515151/Core_java_Training
https://github.com/dhiraj515151/Core_java_Training
9406c315f59f7c2f3f4319b18c439cd819c92a11
76fa6738dbd6da0f80bce9f7d7d179d9b7a9bb77
refs/heads/master
2022-12-22T08:32:17.776000
2020-03-14T12:13:17
2020-03-14T12:13:17
232,235,581
0
0
null
false
2022-12-16T15:24:28
2020-01-07T03:34:06
2020-03-14T12:13:28
2022-12-16T15:24:24
4,543
0
0
60
Java
false
false
package hibernate_image_demo.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @Getter @Setter @Entity @Table(name = "PHOTO") public class Photo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String url; @OneToOne(mappedBy = "photo", cascade = CascadeType.ALL ) private Album album; public Photo(String url) { super(); this.url = url; } @Override public String toString() { return "Photo [id=" + id + ", url=" + url + "]"; } }
UTF-8
Java
832
java
Photo.java
Java
[]
null
[]
package hibernate_image_demo.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @Getter @Setter @Entity @Table(name = "PHOTO") public class Photo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String url; @OneToOne(mappedBy = "photo", cascade = CascadeType.ALL ) private Album album; public Photo(String url) { super(); this.url = url; } @Override public String toString() { return "Photo [id=" + id + ", url=" + url + "]"; } }
832
0.729567
0.729567
40
18.85
15.927257
57
false
false
0
0
0
0
0
0
0.575
false
false
10
6142c3272edb7bd3f5f276c2722452eac2724e8e
20,564,303,447,993
ea5e0679a9f76d34fbf72e83d235e3f77b5f51a8
/org/apache/logging/log4j/util/ProviderUtil.java
ae15e94eb2bd6f01e89a47a5d621d20a85eb1ea8
[]
no_license
jipi84/Monitoring
https://github.com/jipi84/Monitoring
d7523e471a38f7ea7a28b69d89997ece69ec1c35
8ccdfd90f67238cdb6b02a98ac36c9733fd66b20
refs/heads/master
2018-02-11T09:42:02.975000
2017-03-16T17:52:29
2017-03-16T17:52:49
39,367,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* */ package org.apache.logging.log4j.util; /* */ /* */ import java.io.IOException; /* */ import java.net.URL; /* */ import java.util.Collection; /* */ import java.util.Enumeration; /* */ import java.util.HashSet; /* */ import java.util.Properties; /* */ import java.util.concurrent.locks.Lock; /* */ import java.util.concurrent.locks.ReentrantLock; /* */ import org.apache.logging.log4j.Logger; /* */ import org.apache.logging.log4j.spi.Provider; /* */ import org.apache.logging.log4j.status.StatusLogger; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public final class ProviderUtil /* */ { /* */ protected static final String PROVIDER_RESOURCE = "META-INF/log4j-provider.properties"; /* */ private static final String API_VERSION = "Log4jAPIVersion"; /* 46 */ private static final String[] COMPATIBLE_API_VERSIONS = { "2.0.0", "2.1.0" }; /* */ /* */ /* */ /* 50 */ private static final Logger LOGGER = StatusLogger.getLogger(); /* */ /* 52 */ protected static final Collection<Provider> PROVIDERS = new HashSet(); /* */ /* */ /* */ /* */ /* */ /* */ /* 59 */ protected static final Lock STARTUP_LOCK = new ReentrantLock(); /* */ /* */ private static volatile ProviderUtil INSTANCE; /* */ /* */ private ProviderUtil() /* */ { /* 65 */ for (LoaderUtil.UrlResource resource : LoaderUtil.findUrlResources("META-INF/log4j-provider.properties")) { /* 66 */ loadProvider(resource.getUrl(), resource.getClassLoader()); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected static void loadProvider(URL url, ClassLoader cl) /* */ { /* */ try /* */ { /* 79 */ Properties props = PropertiesUtil.loadClose(url.openStream(), url); /* 80 */ if (validVersion(props.getProperty("Log4jAPIVersion"))) { /* 81 */ PROVIDERS.add(new Provider(props, url, cl)); /* */ } /* */ } catch (IOException e) { /* 84 */ LOGGER.error("Unable to open {}", new Object[] { url, e }); /* */ } /* */ } /* */ /* */ /* */ /* */ @Deprecated /* */ protected static void loadProviders(Enumeration<URL> urls, ClassLoader cl) /* */ { /* 93 */ if (urls != null) { /* 94 */ while (urls.hasMoreElements()) { /* 95 */ loadProvider((URL)urls.nextElement(), cl); /* */ } /* */ } /* */ } /* */ /* */ public static Iterable<Provider> getProviders() { /* 101 */ lazyInit(); /* 102 */ return PROVIDERS; /* */ } /* */ /* */ public static boolean hasProviders() { /* 106 */ lazyInit(); /* 107 */ return !PROVIDERS.isEmpty(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected static void lazyInit() /* */ { /* 117 */ if (INSTANCE == null) { /* */ try { /* 119 */ STARTUP_LOCK.lockInterruptibly(); /* */ try { /* 121 */ if (INSTANCE == null) { /* 122 */ INSTANCE = new ProviderUtil(); /* */ } /* */ } finally { /* 125 */ STARTUP_LOCK.unlock(); /* */ } /* */ } catch (InterruptedException e) { /* 128 */ LOGGER.fatal("Interrupted before Log4j Providers could be loaded.", e); /* 129 */ Thread.currentThread().interrupt(); /* */ } /* */ } /* */ } /* */ /* */ public static ClassLoader findClassLoader() { /* 135 */ return LoaderUtil.getThreadContextClassLoader(); /* */ } /* */ /* */ private static boolean validVersion(String version) { /* 139 */ for (String v : COMPATIBLE_API_VERSIONS) { /* 140 */ if (version.startsWith(v)) { /* 141 */ return true; /* */ } /* */ } /* 144 */ return false; /* */ } /* */ } /* Location: D:\Monitoring\monitoring.jar!\org\apache\logging\log4j\util\ProviderUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
4,460
java
ProviderUtil.java
Java
[]
null
[]
/* */ package org.apache.logging.log4j.util; /* */ /* */ import java.io.IOException; /* */ import java.net.URL; /* */ import java.util.Collection; /* */ import java.util.Enumeration; /* */ import java.util.HashSet; /* */ import java.util.Properties; /* */ import java.util.concurrent.locks.Lock; /* */ import java.util.concurrent.locks.ReentrantLock; /* */ import org.apache.logging.log4j.Logger; /* */ import org.apache.logging.log4j.spi.Provider; /* */ import org.apache.logging.log4j.status.StatusLogger; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public final class ProviderUtil /* */ { /* */ protected static final String PROVIDER_RESOURCE = "META-INF/log4j-provider.properties"; /* */ private static final String API_VERSION = "Log4jAPIVersion"; /* 46 */ private static final String[] COMPATIBLE_API_VERSIONS = { "2.0.0", "2.1.0" }; /* */ /* */ /* */ /* 50 */ private static final Logger LOGGER = StatusLogger.getLogger(); /* */ /* 52 */ protected static final Collection<Provider> PROVIDERS = new HashSet(); /* */ /* */ /* */ /* */ /* */ /* */ /* 59 */ protected static final Lock STARTUP_LOCK = new ReentrantLock(); /* */ /* */ private static volatile ProviderUtil INSTANCE; /* */ /* */ private ProviderUtil() /* */ { /* 65 */ for (LoaderUtil.UrlResource resource : LoaderUtil.findUrlResources("META-INF/log4j-provider.properties")) { /* 66 */ loadProvider(resource.getUrl(), resource.getClassLoader()); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected static void loadProvider(URL url, ClassLoader cl) /* */ { /* */ try /* */ { /* 79 */ Properties props = PropertiesUtil.loadClose(url.openStream(), url); /* 80 */ if (validVersion(props.getProperty("Log4jAPIVersion"))) { /* 81 */ PROVIDERS.add(new Provider(props, url, cl)); /* */ } /* */ } catch (IOException e) { /* 84 */ LOGGER.error("Unable to open {}", new Object[] { url, e }); /* */ } /* */ } /* */ /* */ /* */ /* */ @Deprecated /* */ protected static void loadProviders(Enumeration<URL> urls, ClassLoader cl) /* */ { /* 93 */ if (urls != null) { /* 94 */ while (urls.hasMoreElements()) { /* 95 */ loadProvider((URL)urls.nextElement(), cl); /* */ } /* */ } /* */ } /* */ /* */ public static Iterable<Provider> getProviders() { /* 101 */ lazyInit(); /* 102 */ return PROVIDERS; /* */ } /* */ /* */ public static boolean hasProviders() { /* 106 */ lazyInit(); /* 107 */ return !PROVIDERS.isEmpty(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected static void lazyInit() /* */ { /* 117 */ if (INSTANCE == null) { /* */ try { /* 119 */ STARTUP_LOCK.lockInterruptibly(); /* */ try { /* 121 */ if (INSTANCE == null) { /* 122 */ INSTANCE = new ProviderUtil(); /* */ } /* */ } finally { /* 125 */ STARTUP_LOCK.unlock(); /* */ } /* */ } catch (InterruptedException e) { /* 128 */ LOGGER.fatal("Interrupted before Log4j Providers could be loaded.", e); /* 129 */ Thread.currentThread().interrupt(); /* */ } /* */ } /* */ } /* */ /* */ public static ClassLoader findClassLoader() { /* 135 */ return LoaderUtil.getThreadContextClassLoader(); /* */ } /* */ /* */ private static boolean validVersion(String version) { /* 139 */ for (String v : COMPATIBLE_API_VERSIONS) { /* 140 */ if (version.startsWith(v)) { /* 141 */ return true; /* */ } /* */ } /* 144 */ return false; /* */ } /* */ } /* Location: D:\Monitoring\monitoring.jar!\org\apache\logging\log4j\util\ProviderUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
4,460
0.458072
0.436323
152
28.348684
24.903566
121
false
false
0
0
0
0
0
0
0.309211
false
false
10
c702676ab3a9b267b498d7a353e0dec604d1eca8
16,020,228,050,527
b4a557174523100183a96ad42cfb7b2a87e6428e
/app/src/main/java/com/mc/books/fragments/gift/myGift/IGiftPresenter.java
2badae277123eceed0623d8c0d72b2f657a59bfe
[]
no_license
atuyen/mcbook_android_test
https://github.com/atuyen/mcbook_android_test
fe9b35ddb02f41933e352188b7ed012b378e550b
befa1156b1474ace15e7f08f2821b44f3ac02296
refs/heads/master
2022-09-09T07:26:23.877000
2020-06-03T08:27:43
2020-06-03T08:27:43
269,031,867
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mc.books.fragments.gift.myGift; import android.view.View; import com.hannesdorfmann.mosby3.mvp.MvpPresenter; import com.hannesdorfmann.mosby3.mvp.MvpView; import com.mc.models.gift.CategoryGift; import java.util.List; public interface IGiftPresenter<V extends MvpView> extends MvpPresenter<V> { void onSearchGift(String keyword, List<CategoryGift> categoryGifts); void onShowDialogDelete(boolean isShow, View view, int position); void onGetCategoryGift(); void onCreateGiftCode(String code); void deleteGift(int id); }
UTF-8
Java
559
java
IGiftPresenter.java
Java
[]
null
[]
package com.mc.books.fragments.gift.myGift; import android.view.View; import com.hannesdorfmann.mosby3.mvp.MvpPresenter; import com.hannesdorfmann.mosby3.mvp.MvpView; import com.mc.models.gift.CategoryGift; import java.util.List; public interface IGiftPresenter<V extends MvpView> extends MvpPresenter<V> { void onSearchGift(String keyword, List<CategoryGift> categoryGifts); void onShowDialogDelete(boolean isShow, View view, int position); void onGetCategoryGift(); void onCreateGiftCode(String code); void deleteGift(int id); }
559
0.781753
0.778175
21
25.619047
25.901785
76
false
false
0
0
0
0
0
0
0.666667
false
false
10
31441e525efda62ff8f788548b366f6ab4b5e43a
26,774,826,126,261
3feec211c81ea942f207d0986dde9428fcbbe23a
/arrays2D/Array2D.java
c308e85588c162a8da66d8b946bb76fbe4241aa1
[ "MIT" ]
permissive
SwettSoquelHS/think-java-notswett
https://github.com/SwettSoquelHS/think-java-notswett
137d6043ad30d8d8eb22de70a8f741c1c467e5f9
0a5e442eb5883f2906149a58731f590e69a21509
refs/heads/master
2021-07-11T11:28:12.883000
2019-03-25T16:13:19
2019-03-25T16:13:19
146,488,891
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Array2D { public static void main(String[] args){ //Normal 1-dimensional array int[] arr1 = {1,2,3,}; //2-Dimensional array int[][] arr2; } public static void print2DArray(int[][] matrix){ } }
UTF-8
Java
263
java
Array2D.java
Java
[]
null
[]
public class Array2D { public static void main(String[] args){ //Normal 1-dimensional array int[] arr1 = {1,2,3,}; //2-Dimensional array int[][] arr2; } public static void print2DArray(int[][] matrix){ } }
263
0.539924
0.505703
16
15.5
17.208282
52
false
false
0
0
0
0
0
0
0.3125
false
false
10
899d75e6e6fe93f4eb6b51e9403b7487e7c21049
28,338,194,237,107
7df444076a31e8cc10d38c31d18a2074423f3b7a
/src/test/java/PageObject/CatalogPO.java
d5c28ba35c2fb80213c9611fdbbb14d4b0863c0e
[]
no_license
AlekseiShabalin/yandexMarketTest
https://github.com/AlekseiShabalin/yandexMarketTest
84d21bb107d6834dd27d28336aba7898be8dd022
3fe8727af7b6ff181023fef8eccb65986b921687
refs/heads/master
2023-03-03T11:20:20.775000
2021-02-17T16:56:59
2021-02-17T16:56:59
339,769,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package PageObject; import org.openqa.selenium.By; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.page; public class CatalogPO { private String buttonBasketSelector = "//a[contains(@href, 'my/cart')]"; public BasketPO goToBasket() { $(By.xpath(buttonBasketSelector)).click(); return page(BasketPO.class); } public void putInBasket(String buttonSelector) { $(By.xpath(buttonSelector)).shouldBe(visible).click(); $(By.xpath("//div[@class='b_2ll3z2LP8N b_39vchGP76M b_17HsszYfH8']//span/span")).shouldBe(appear); } public String getName(String nameProduct) { String resultName = $(By.xpath(nameProduct)).getText(); return resultName; } public String getPrice(String priceProduct) { String resultPrice = $(By.xpath(priceProduct)).getText(); return resultPrice; } }
UTF-8
Java
971
java
CatalogPO.java
Java
[]
null
[]
package PageObject; import org.openqa.selenium.By; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.page; public class CatalogPO { private String buttonBasketSelector = "//a[contains(@href, 'my/cart')]"; public BasketPO goToBasket() { $(By.xpath(buttonBasketSelector)).click(); return page(BasketPO.class); } public void putInBasket(String buttonSelector) { $(By.xpath(buttonSelector)).shouldBe(visible).click(); $(By.xpath("//div[@class='b_2ll3z2LP8N b_39vchGP76M b_17HsszYfH8']//span/span")).shouldBe(appear); } public String getName(String nameProduct) { String resultName = $(By.xpath(nameProduct)).getText(); return resultName; } public String getPrice(String priceProduct) { String resultPrice = $(By.xpath(priceProduct)).getText(); return resultPrice; } }
971
0.680741
0.669413
32
29.34375
27.854095
106
false
false
0
0
0
0
0
0
0.46875
false
false
10
abc4449dd1202ca0e394b17921cf91c5303326e8
25,675,314,564,618
5d58a54ac1733b9464c248c04ae5d99ffb48d4b8
/plugin/src/main/java/com/exadel/aem/toolkit/plugin/sources/ClassSourceImpl.java
170a9b9da9c3ab77dd012897333c65ec095d12bf
[ "Apache-2.0" ]
permissive
exadel-inc/aem-authoring-toolkit
https://github.com/exadel-inc/aem-authoring-toolkit
95af4382eca81fd716ee2f0ee1ccdcdea8a119b6
a25eeb18e2a57d1d5567cd16d3607766053efd2b
refs/heads/master
2021-06-23T08:26:23.435000
2021-06-15T12:27:44
2021-06-15T12:27:44
206,580,735
48
6
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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.exadel.aem.toolkit.plugin.sources; import java.lang.annotation.Annotation; import org.apache.commons.lang3.StringUtils; import com.exadel.aem.toolkit.api.handlers.Source; /** * Implements {@link Source} to expose the metadata that is specific for the underlying Java class */ public class ClassSourceImpl extends SourceImpl { private final Class<?> value; /** * Initializes a class instance storing a reference to the {@code Class} that serves as the metadata source */ ClassSourceImpl(Class<?> value) { this.value = value; } /** * {@inheritDoc} */ @Override public String getName() { return isValid() ? value.getName() : StringUtils.EMPTY; } /** * {@inheritDoc} */ @Override Annotation[] getDeclaredAnnotations() { return value != null ? value.getDeclaredAnnotations() : null; } /** * {@inheritDoc} */ @Override <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { return value != null ? value.getAnnotationsByType(annotationClass) : null; } /** * {@inheritDoc} */ @Override <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) { return value != null ? value.getDeclaredAnnotation(annotationClass) : null; } /** * {@inheritDoc} */ @Override public boolean isValid() { return value != null; } /** * {@inheritDoc} */ @Override public <T> T adaptTo(Class<T> adaptation) { if (Class.class.equals(adaptation)) { return adaptation.cast(value); } return super.adaptTo(adaptation); } }
UTF-8
Java
2,276
java
ClassSourceImpl.java
Java
[]
null
[]
/* * 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.exadel.aem.toolkit.plugin.sources; import java.lang.annotation.Annotation; import org.apache.commons.lang3.StringUtils; import com.exadel.aem.toolkit.api.handlers.Source; /** * Implements {@link Source} to expose the metadata that is specific for the underlying Java class */ public class ClassSourceImpl extends SourceImpl { private final Class<?> value; /** * Initializes a class instance storing a reference to the {@code Class} that serves as the metadata source */ ClassSourceImpl(Class<?> value) { this.value = value; } /** * {@inheritDoc} */ @Override public String getName() { return isValid() ? value.getName() : StringUtils.EMPTY; } /** * {@inheritDoc} */ @Override Annotation[] getDeclaredAnnotations() { return value != null ? value.getDeclaredAnnotations() : null; } /** * {@inheritDoc} */ @Override <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { return value != null ? value.getAnnotationsByType(annotationClass) : null; } /** * {@inheritDoc} */ @Override <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) { return value != null ? value.getDeclaredAnnotation(annotationClass) : null; } /** * {@inheritDoc} */ @Override public boolean isValid() { return value != null; } /** * {@inheritDoc} */ @Override public <T> T adaptTo(Class<T> adaptation) { if (Class.class.equals(adaptation)) { return adaptation.cast(value); } return super.adaptTo(adaptation); } }
2,276
0.645431
0.643234
86
25.465117
27.521534
111
false
false
0
0
0
0
0
0
0.197674
false
false
10
4051c69995850707f319404f1be4b39229fe98e6
20,452,634,283,022
c2f9d69a16986a2690e72718783472fc624ded18
/com/whatsapp/ast.java
7a8fded26196f6a5c764ea967ecb790cef95d48a
[]
no_license
mithileshongit/WhatsApp-Descompilado
https://github.com/mithileshongit/WhatsApp-Descompilado
bc973e1356eb043661a2efc30db22bcc1392d7f3
94a9d0b1c46bb78676ac401572aa11f60e12345e
refs/heads/master
2021-01-16T20:56:27.864000
2015-02-09T04:08:40
2015-02-09T04:08:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whatsapp; import android.os.Handler.Callback; import android.os.Message; import com.whatsapp.contact.c; import com.whatsapp.contact.i; final class ast implements Callback { ast() { } public boolean handleMessage(Message message) { i.b(App.p); App.a(c.BACKGROUND_FULL); return true; } }
UTF-8
Java
341
java
ast.java
Java
[]
null
[]
package com.whatsapp; import android.os.Handler.Callback; import android.os.Message; import com.whatsapp.contact.c; import com.whatsapp.contact.i; final class ast implements Callback { ast() { } public boolean handleMessage(Message message) { i.b(App.p); App.a(c.BACKGROUND_FULL); return true; } }
341
0.671554
0.671554
17
19.058823
15.26037
51
false
false
0
0
0
0
0
0
0.470588
false
false
10
3c1b15fc321e8a70cf7c97173855b1c737272f32
3,951,369,980,498
73009358f8acb8e646c2b304875681ce82cadcab
/src/main/java/com/learn/classloader/Test01.java
c5f943b893cbcf58a6428210c3d5ecdc6b6ca159
[]
no_license
zhueinstein/scala
https://github.com/zhueinstein/scala
c234eb76d60cc71407a570216384d993445a81d2
9561f444f3bebf1841ceedb27c9c3721204920b9
refs/heads/master
2020-09-07T12:28:27.865000
2018-12-19T09:54:25
2018-12-19T10:19:36
94,426,762
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.learn.classloader; /** * @ClassName: UcInfoEnterpriseExample * * @author: 亚信安全NSG WeFon * @date: 2018/7/12 * @Copyright: 2018 */ public class Test01 { public static void main(String[] args) throws Exception{ ClassLoader classLoader = ClassLoader.getSystemClassLoader(); // 主动使用系统类加载器 加载类,并不会初始化这个类 Class<?> clazz = classLoader.loadClass("com.learn.classloader.Cl"); System.out.println("----------------"); Class<?> cla = Class.forName("com.learn.classloader.Cl"); } } class Cl{ static { System.out.println("CL"); } }
UTF-8
Java
610
java
Test01.java
Java
[ { "context": "me: UcInfoEnterpriseExample\n *\n * @author: 亚信安全NSG WeFon\n * @date: 2018/7/12\n * @Copyright: 2018\n */\npubli", "end": 103, "score": 0.9962102770805359, "start": 98, "tag": "NAME", "value": "WeFon" } ]
null
[]
package com.learn.classloader; /** * @ClassName: UcInfoEnterpriseExample * * @author: 亚信安全NSG WeFon * @date: 2018/7/12 * @Copyright: 2018 */ public class Test01 { public static void main(String[] args) throws Exception{ ClassLoader classLoader = ClassLoader.getSystemClassLoader(); // 主动使用系统类加载器 加载类,并不会初始化这个类 Class<?> clazz = classLoader.loadClass("com.learn.classloader.Cl"); System.out.println("----------------"); Class<?> cla = Class.forName("com.learn.classloader.Cl"); } } class Cl{ static { System.out.println("CL"); } }
610
0.676259
0.652878
25
21.24
21.902109
69
false
false
0
0
0
0
0
0
0.88
false
false
10
059becfea1535c66afb63531a7170884a2403af7
24,945,170,109,605
ac96fd546cf6a1426d90534d1b85492ba877d5ea
/ui-notifications/src/main/java/com/bravedroid/ui/notifications/snackbar/SnackbarManager.java
93dcb039543a94324b5881fc90774caae0ddf772
[ "Unlicense" ]
permissive
BraveDroid/UI-playground
https://github.com/BraveDroid/UI-playground
dea6aba06578c4de4d8ad54726908fa62d4f3ffe
9a2663a21f296516b1e9bcf16a65b11be642dba9
refs/heads/master
2020-09-23T03:25:36.218000
2020-03-04T08:02:45
2020-03-04T08:02:45
225,390,289
0
2
Unlicense
false
2020-03-04T08:02:46
2019-12-02T14:12:05
2020-01-28T22:48:20
2020-03-04T08:02:46
750
0
2
0
Java
false
false
package com.bravedroid.ui.notifications.snackbar; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.core.content.ContextCompat; import com.bravedroid.ui.notifications.R; import com.google.android.material.snackbar.Snackbar; import org.jetbrains.annotations.NotNull; public class SnackbarManager { public Snackbar makeSuccessSnackbar(Context context, ViewGroup rootLayout, String text, OnDismissSnackBar onDismissSnackBar) { final Snackbar snackBar = createSnackbar(rootLayout, text); View snackView = inflateSnackView(context); prepareSnackbarLayout(snackBar, snackView, text, R.color.colorSuccess, context); setSnackbarBehaviorOnDismiss(snackBar, snackView, onDismissSnackBar); return snackBar; } public Snackbar makeWarningSnackbar(Context context, ViewGroup rootLayout, String text, OnDismissSnackBar onDismissSnackBar) { final Snackbar snackBar = createSnackbar(rootLayout, text); View snackView = inflateSnackView(context); prepareSnackbarLayout(snackBar, snackView, text, R.color.colorWarning, context); setSnackbarBehaviorOnDismiss(snackBar, snackView, onDismissSnackBar); return snackBar; } public Snackbar makeErrorSnackbar(Context context, ViewGroup rootLayout, String text, OnDismissSnackBar onDismissSnackBar) { final Snackbar snackBar = createSnackbar(rootLayout, text); View snackView = inflateSnackView(context); prepareSnackbarLayout(snackBar, snackView, text, R.color.colorError, context); setSnackbarBehaviorOnDismiss(snackBar, snackView, onDismissSnackBar); return snackBar; } @NotNull private Snackbar createSnackbar(ViewGroup rootLayout, String text) { return Snackbar.make(rootLayout, text, Snackbar.LENGTH_LONG); } private View inflateSnackView(Context context) { return LayoutInflater.from(context).inflate(R.layout.layout_snackbar, null); } private void prepareSnackbarLayout(Snackbar snackBar, View snackView, String text, int color, Context context) { Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackBar.getView(); snackbarLayout.setPadding(0, 0, 0, 0); TextView snackbarText = snackbarLayout.findViewById(R.id.snackbar_text); LinearLayout snackbarLayoutContainer = snackView.findViewById(R.id.linearLayout_snackbar_layout); snackbarLayoutContainer.setBackgroundColor(ContextCompat.getColor(context, color)); snackbarText.setVisibility(View.INVISIBLE); TextView textView = snackView.findViewById(R.id.textView_snackbar_textBody); textView.setText(text); snackbarLayout.addView(snackView, 0); } private void setSnackbarBehaviorOnDismiss(Snackbar snackBar, View snackView, OnDismissSnackBar onDismissSnackBar) { ImageView cancelIcon = snackView.findViewById(R.id.imageView_snackbar_iconCancel); cancelIcon.setOnClickListener(v1 -> { onDismissSnackBar.onDismissSnack(); snackBar.dismiss(); }); } public interface OnDismissSnackBar { void onDismissSnack(); } }
UTF-8
Java
3,345
java
SnackbarManager.java
Java
[]
null
[]
package com.bravedroid.ui.notifications.snackbar; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.core.content.ContextCompat; import com.bravedroid.ui.notifications.R; import com.google.android.material.snackbar.Snackbar; import org.jetbrains.annotations.NotNull; public class SnackbarManager { public Snackbar makeSuccessSnackbar(Context context, ViewGroup rootLayout, String text, OnDismissSnackBar onDismissSnackBar) { final Snackbar snackBar = createSnackbar(rootLayout, text); View snackView = inflateSnackView(context); prepareSnackbarLayout(snackBar, snackView, text, R.color.colorSuccess, context); setSnackbarBehaviorOnDismiss(snackBar, snackView, onDismissSnackBar); return snackBar; } public Snackbar makeWarningSnackbar(Context context, ViewGroup rootLayout, String text, OnDismissSnackBar onDismissSnackBar) { final Snackbar snackBar = createSnackbar(rootLayout, text); View snackView = inflateSnackView(context); prepareSnackbarLayout(snackBar, snackView, text, R.color.colorWarning, context); setSnackbarBehaviorOnDismiss(snackBar, snackView, onDismissSnackBar); return snackBar; } public Snackbar makeErrorSnackbar(Context context, ViewGroup rootLayout, String text, OnDismissSnackBar onDismissSnackBar) { final Snackbar snackBar = createSnackbar(rootLayout, text); View snackView = inflateSnackView(context); prepareSnackbarLayout(snackBar, snackView, text, R.color.colorError, context); setSnackbarBehaviorOnDismiss(snackBar, snackView, onDismissSnackBar); return snackBar; } @NotNull private Snackbar createSnackbar(ViewGroup rootLayout, String text) { return Snackbar.make(rootLayout, text, Snackbar.LENGTH_LONG); } private View inflateSnackView(Context context) { return LayoutInflater.from(context).inflate(R.layout.layout_snackbar, null); } private void prepareSnackbarLayout(Snackbar snackBar, View snackView, String text, int color, Context context) { Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackBar.getView(); snackbarLayout.setPadding(0, 0, 0, 0); TextView snackbarText = snackbarLayout.findViewById(R.id.snackbar_text); LinearLayout snackbarLayoutContainer = snackView.findViewById(R.id.linearLayout_snackbar_layout); snackbarLayoutContainer.setBackgroundColor(ContextCompat.getColor(context, color)); snackbarText.setVisibility(View.INVISIBLE); TextView textView = snackView.findViewById(R.id.textView_snackbar_textBody); textView.setText(text); snackbarLayout.addView(snackView, 0); } private void setSnackbarBehaviorOnDismiss(Snackbar snackBar, View snackView, OnDismissSnackBar onDismissSnackBar) { ImageView cancelIcon = snackView.findViewById(R.id.imageView_snackbar_iconCancel); cancelIcon.setOnClickListener(v1 -> { onDismissSnackBar.onDismissSnack(); snackBar.dismiss(); }); } public interface OnDismissSnackBar { void onDismissSnack(); } }
3,345
0.749776
0.747982
76
43.013157
37.057739
130
false
false
0
0
0
0
0
0
1.157895
false
false
10
e8c2bf57fc70600ae32965619ca16be1b5541e99
6,536,940,245,264
b6e5cb5db466bd323fb11295506b95caff6fc41b
/src/main/java/com/acme/meetyourroommate/controller/TeamsController.java
dbe164207621c9070bb6be80a4d14badaa51d147
[]
no_license
U-Friends-Evo/UF-MYR-REP-SS
https://github.com/U-Friends-Evo/UF-MYR-REP-SS
a4b0248c263597cfd58eb2a556cf4001e8c41bc3
22652b88f49575dda15cc8fb71b50227bcdba921
refs/heads/master
2023-06-10T00:21:41.907000
2021-07-04T00:50:35
2021-07-04T00:50:35
382,733,279
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.acme.meetyourroommate.controller; import com.acme.meetyourroommate.domain.model.Team; import com.acme.meetyourroommate.domain.service.TeamService; import com.acme.meetyourroommate.resource.SaveTeamResource; import com.acme.meetyourroommate.resource.TeamResource; import io.swagger.v3.oas.annotations.Operation; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/api") public class TeamsController { @Autowired private ModelMapper mapper; @Autowired private TeamService teamService; @Operation(summary = "Get teams", description = "Get all teams", tags = {"teams"}) @GetMapping("/teams") public Page<TeamResource> getAllTeams(Pageable pageable){ Page<Team> teamPage = teamService.getAllTeams(pageable); List<TeamResource> resources = teamPage.getContent() .stream() .map(this::convertToResource) .collect(Collectors.toList()); return new PageImpl<>(resources,pageable,resources.size()); } @Operation(summary = "Get a team by Name", description = "Get team by Name", tags = {"teams"}) @GetMapping("/teams/find-name/{teamName}") public TeamResource getTeamByName(@PathVariable String teamName){ Team team = teamService.getTeamByName(teamName); return convertToResource(team); } @Operation(summary = "Get Student's teams", description = "Get team by Student Id", tags = {"teams"}) @GetMapping("/students/{studentId}/team") public TeamResource getTeamByStudentId(@PathVariable Long studentId){ return convertToResource(teamService.getTeamByStudentId(studentId)); } @Operation(summary = "Get a team by id", description = "Get an existing team", tags = {"teams"}) @GetMapping("/teams/{teamId}") public TeamResource getTeamById(@PathVariable Long teamId){ return convertToResource(teamService.getTeamById(teamId)); } @Operation(summary = "Create a team", description = "Create a new Team", tags = {"teams"}) @PostMapping("/teams") public TeamResource createTeam(@Valid @RequestBody SaveTeamResource resource){ Team team = convertToEntity(resource); return convertToResource(teamService.createTeam(team)); } @Operation(summary = "Update a team", description = "Update an existing team", tags = {"teams"}) @PutMapping("/teams/{teamId}") public TeamResource updateTeam(@RequestBody SaveTeamResource teamRequest,@PathVariable Long teamId){ Team team = convertToEntity(teamRequest); return convertToResource(teamService.updateTeam(team,teamId)); } @Operation(summary = "Delete a team", description = "Delete an existing team", tags = {"teams"}) @DeleteMapping("/teams/{teamId}") public ResponseEntity<?> deleteTeam(@PathVariable Long teamId){ return teamService.deleteTeam(teamId); } private Team convertToEntity (SaveTeamResource resource){ return mapper.map(resource, Team.class);} private TeamResource convertToResource(Team entity){return mapper.map(entity,TeamResource.class);} }
UTF-8
Java
3,492
java
TeamsController.java
Java
[]
null
[]
package com.acme.meetyourroommate.controller; import com.acme.meetyourroommate.domain.model.Team; import com.acme.meetyourroommate.domain.service.TeamService; import com.acme.meetyourroommate.resource.SaveTeamResource; import com.acme.meetyourroommate.resource.TeamResource; import io.swagger.v3.oas.annotations.Operation; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/api") public class TeamsController { @Autowired private ModelMapper mapper; @Autowired private TeamService teamService; @Operation(summary = "Get teams", description = "Get all teams", tags = {"teams"}) @GetMapping("/teams") public Page<TeamResource> getAllTeams(Pageable pageable){ Page<Team> teamPage = teamService.getAllTeams(pageable); List<TeamResource> resources = teamPage.getContent() .stream() .map(this::convertToResource) .collect(Collectors.toList()); return new PageImpl<>(resources,pageable,resources.size()); } @Operation(summary = "Get a team by Name", description = "Get team by Name", tags = {"teams"}) @GetMapping("/teams/find-name/{teamName}") public TeamResource getTeamByName(@PathVariable String teamName){ Team team = teamService.getTeamByName(teamName); return convertToResource(team); } @Operation(summary = "Get Student's teams", description = "Get team by Student Id", tags = {"teams"}) @GetMapping("/students/{studentId}/team") public TeamResource getTeamByStudentId(@PathVariable Long studentId){ return convertToResource(teamService.getTeamByStudentId(studentId)); } @Operation(summary = "Get a team by id", description = "Get an existing team", tags = {"teams"}) @GetMapping("/teams/{teamId}") public TeamResource getTeamById(@PathVariable Long teamId){ return convertToResource(teamService.getTeamById(teamId)); } @Operation(summary = "Create a team", description = "Create a new Team", tags = {"teams"}) @PostMapping("/teams") public TeamResource createTeam(@Valid @RequestBody SaveTeamResource resource){ Team team = convertToEntity(resource); return convertToResource(teamService.createTeam(team)); } @Operation(summary = "Update a team", description = "Update an existing team", tags = {"teams"}) @PutMapping("/teams/{teamId}") public TeamResource updateTeam(@RequestBody SaveTeamResource teamRequest,@PathVariable Long teamId){ Team team = convertToEntity(teamRequest); return convertToResource(teamService.updateTeam(team,teamId)); } @Operation(summary = "Delete a team", description = "Delete an existing team", tags = {"teams"}) @DeleteMapping("/teams/{teamId}") public ResponseEntity<?> deleteTeam(@PathVariable Long teamId){ return teamService.deleteTeam(teamId); } private Team convertToEntity (SaveTeamResource resource){ return mapper.map(resource, Team.class);} private TeamResource convertToResource(Team entity){return mapper.map(entity,TeamResource.class);} }
3,492
0.72709
0.726804
84
40.57143
32.003082
105
false
false
0
0
0
0
0
0
0.619048
false
false
10
3388a4e5f4a9d354f03b26aa39a115ccdb5caee1
21,723,944,631,212
f2a4ee2eb536e3817ac5bbf6504ade75f0376cf7
/ace-web/src/main/java/com/quikj/ace/web/client/view/desktop/DesktopChatPanel.java
71a2cdd7f04acd6d26d7056785c60a3de50e9dea
[]
no_license
aceoperator/ace
https://github.com/aceoperator/ace
3ef2ce7d489c0625a2cba83d24f535c09871b062
08f7c98896b3cc71793cdea3d1e44c910f0fdb74
refs/heads/master
2020-04-06T04:27:51.734000
2018-06-30T12:25:53
2018-06-30T12:25:53
82,558,405
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.quikj.ace.web.client.view.desktop; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.ContextMenuEvent; import com.google.gwt.event.dom.client.ContextMenuHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitEvent; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.RichTextArea; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.StackLayoutPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.quikj.ace.messages.vo.app.ResponseMessage; import com.quikj.ace.messages.vo.talk.CallPartyElement; import com.quikj.ace.messages.vo.talk.CannedMessageElement; import com.quikj.ace.messages.vo.talk.DisconnectReasonElement; import com.quikj.ace.web.client.ApplicationController; import com.quikj.ace.web.client.ClientProperties; import com.quikj.ace.web.client.Images; import com.quikj.ace.web.client.presenter.ChatSessionPresenter; import com.quikj.ace.web.client.presenter.EmoticonPresenter; import com.quikj.ace.web.client.presenter.MessageBoxPresenter; import com.quikj.ace.web.client.view.ChatPanel; import com.quikj.ace.web.client.view.EmoticonUtils; import com.quikj.ace.web.client.view.FormRenderer; import com.quikj.ace.web.client.view.FormRenderer.FormListener; import com.quikj.ace.web.client.view.HtmlUtils; import com.quikj.ace.web.client.view.ViewUtils; /** * @author amit * */ public class DesktopChatPanel extends StackLayoutPanel implements ChatPanel, FormListener { private static final double VISITOR_TITLE_SIZE = 30.0; private static final double TITLE_SIZE = 45.0; private static final int DATA_ENTRY_PANEL_SIZE = 100; private HTMLPanel transcriptPanel; private RichTextArea chatEditTextArea; private ChatSessionPresenter presenter; private Button discButton; private Button sendButton; private ListBox cannedMessageListBox; private ScrollPanel transcriptScrollPanel; private Button btnBold; private Button btnItalics; private Button btnUnderline; private HorizontalPanel commandPanel; private PopupPanel emoticonPallette; private boolean adjusted = false; private Button btnEmoticon; private VerticalPanel dataEntryPanel; private VerticalPanel chatPanel; private boolean operator; private FlexTable chatInfoDetailTable; private HTML chatPanelHeaderLabel; private ListBox contactList; private HorizontalPanel chatPanelHeaderControls; private Button conferenceButton; private Button transferButton; private String me; private Widget typing; private String typingFrom; private List<HandlerRegistration> eventHandlers = new ArrayList<HandlerRegistration>(); private HTML controlSeparator; private boolean hideAvatar; private FormPanel fileShareFormPanel; private FileUpload fileShare; private Hidden sessionField; private Button shareButton; private FormRenderer formRenderer = new FormRenderer(); public DesktopChatPanel() { super(Unit.PX); setSize("100%", "97%"); } private void init(String me, CallPartyElement otherParty, CannedMessageElement[] cannedMessages, boolean operator, boolean showOtherPartyInfo, boolean hideAvatar) { this.operator = operator; this.me = me; this.hideAvatar = hideAvatar; initTranscriptArea(otherParty, operator); initChatEditArea(cannedMessages); if (showOtherPartyInfo) { initChatInfoArea(otherParty); } } private void initChatInfoArea(CallPartyElement otherParty) { chatInfoDetailTable = new FlexTable(); add(chatInfoDetailTable, ApplicationController.getMessages().DesktopChatPanel_chatSessionInformation(), false, VISITOR_TITLE_SIZE); chatInfoDetailTable.setWidth("100%"); chatInfoDetailTable.setCellPadding(10); setOtherPartyDetails(0, otherParty); } private void initTranscriptArea(CallPartyElement otherParty, boolean operator) { chatPanel = new VerticalPanel(); chatPanel.setSize("100%", "100%"); HorizontalPanel chatPanelHeader = new HorizontalPanel(); add(chatPanel, chatPanelHeader, TITLE_SIZE); chatPanelHeader.setWidth("100%"); chatPanelHeader.setSpacing(2); chatPanelHeaderLabel = new HTML(); chatPanelHeaderLabel.setStyleName("gwt-StackLayoutPanelHeader"); chatPanelHeaderLabel.setWidth("100%"); chatPanelHeader.add(chatPanelHeaderLabel); chatPanelHeader.setCellHorizontalAlignment(chatPanelHeaderLabel, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeader.setCellVerticalAlignment(chatPanelHeaderLabel, HasVerticalAlignment.ALIGN_MIDDLE); chatPanelHeaderLabel.setHTML(otherParty == null ? ApplicationController.getMessages().DesktopChatPanel_private() : formatOtherParties(ViewUtils.formatName(otherParty), otherParty.getAvatar()).toString()); chatPanelHeaderControls = new HorizontalPanel(); chatPanelHeader.add(chatPanelHeaderControls); chatPanelHeaderControls.setSpacing(4); chatPanelHeader.setCellHorizontalAlignment(chatPanelHeaderControls, HasHorizontalAlignment.ALIGN_RIGHT); chatPanelHeader.setCellVerticalAlignment(chatPanelHeaderControls, HasVerticalAlignment.ALIGN_MIDDLE); if (operator) { contactList = new ListBox(); chatPanelHeaderControls.add(contactList); chatPanelHeaderControls.setCellHorizontalAlignment(contactList, HasHorizontalAlignment.ALIGN_RIGHT); chatPanelHeaderControls.setCellVerticalAlignment(contactList, HasVerticalAlignment.ALIGN_MIDDLE); contactList.setEnabled(false); contactList.addItem(ApplicationController.getMessages().DesktopChatPanel_selectContact()); contactList.addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { contactList.clear(); contactList.addItem(ApplicationController.getMessages().DesktopChatPanel_selectContact()); List<String> contacts = presenter.getContactsList(); for (String contact : contacts) { contactList.addItem(contact); } } }); conferenceButton = new Button(ApplicationController.getMessages().DesktopChatPanel_add()); chatPanelHeaderControls.add(conferenceButton); chatPanelHeaderControls.setCellHorizontalAlignment(conferenceButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(conferenceButton, HasVerticalAlignment.ALIGN_MIDDLE); conferenceButton.setEnabled(false); conferenceButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index = contactList.getSelectedIndex(); if (index == 0) { return; } presenter.addToConference(contactList.getItemText(index)); contactList.setSelectedIndex(0); } }); transferButton = new Button(ApplicationController.getMessages().DesktopChatPanel_transfer()); chatPanelHeaderControls.add(transferButton); chatPanelHeaderControls.setCellHorizontalAlignment(transferButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(transferButton, HasVerticalAlignment.ALIGN_MIDDLE); transferButton.setEnabled(false); transferButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index = contactList.getSelectedIndex(); if (index == 0) { return; } presenter.transferTo(contactList.getItemText(index)); contactList.setSelectedIndex(0); } }); controlSeparator = new HTML("&nbsp;|&nbsp"); chatPanelHeaderControls.add(controlSeparator); } discButton = new Button(ApplicationController.getMessages().DesktopChatPanel_disconnect()); chatPanelHeaderControls.add(discButton); chatPanelHeaderControls.setCellHorizontalAlignment(discButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(discButton, HasVerticalAlignment.ALIGN_MIDDLE); discButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.userDisconnected(DisconnectReasonElement.NORMAL_DISCONNECT, null); } }); if (operator) { Button closeButton = new Button(ApplicationController.getMessages().DesktopChatPanel_close()); chatPanelHeaderControls.add(closeButton); chatPanelHeaderControls.setCellHorizontalAlignment(closeButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(closeButton, HasVerticalAlignment.ALIGN_MIDDLE); closeButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.chatClosed(); } }); } transcriptScrollPanel = new ScrollPanel(); transcriptScrollPanel.setTouchScrollingDisabled(false); transcriptScrollPanel.setAlwaysShowScrollBars(true); chatPanel.add(transcriptScrollPanel); transcriptScrollPanel.setWidth("98%"); transcriptPanel = new HTMLPanel(""); transcriptScrollPanel.setWidget(transcriptPanel); transcriptPanel.setSize("100%", "100%"); if (ClientProperties.getInstance().getBooleanValue(ClientProperties.SUPPRESS_COPY_PASTE, ChatPanel.DEFAULT_SUPPRESS_COPYPASTE)) { eventHandlers.add(RootPanel.get().addDomHandler(new ContextMenuHandler() { @Override public void onContextMenu(ContextMenuEvent event) { event.preventDefault(); event.stopPropagation(); } }, ContextMenuEvent.getType())); eventHandlers.add(RootPanel.get().addDomHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (event.isControlKeyDown()) { event.preventDefault(); event.stopPropagation(); } } }, KeyDownEvent.getType())); } } @Override public void dispose() { for (HandlerRegistration handler : eventHandlers) { handler.removeHandler(); } eventHandlers.clear(); } private void initChatEditArea(CannedMessageElement[] cannedMessages) { dataEntryPanel = new VerticalPanel(); dataEntryPanel.setSpacing(3); chatPanel.add(dataEntryPanel); chatPanel.setCellVerticalAlignment(dataEntryPanel, HasVerticalAlignment.ALIGN_BOTTOM); dataEntryPanel.setWidth("100%"); dataEntryPanel.setHeight(DATA_ENTRY_PANEL_SIZE + "px"); HorizontalPanel controlPanel = new HorizontalPanel(); dataEntryPanel.add(controlPanel); controlPanel.setWidth("100%"); commandPanel = new HorizontalPanel(); commandPanel.setSpacing(5); controlPanel.add(commandPanel); btnBold = new Button("B"); commandPanel.add(btnBold); btnBold.setTitle(ApplicationController.getMessages().DesktopChatPanel_boldType()); commandPanel.setCellVerticalAlignment(btnBold, HasVerticalAlignment.ALIGN_MIDDLE); btnBold.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { chatEditTextArea.getFormatter().toggleBold(); if (chatEditTextArea.getFormatter().isBold()) { btnBold.setHTML("<b>B</b>"); } else { btnBold.setHTML("B"); } } }); btnItalics = new Button("I"); commandPanel.add(btnItalics); btnItalics.setTitle(ApplicationController.getMessages().DesktopChatPanel_italicsType()); commandPanel.setCellVerticalAlignment(btnItalics, HasVerticalAlignment.ALIGN_MIDDLE); btnItalics.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { chatEditTextArea.getFormatter().toggleItalic(); if (chatEditTextArea.getFormatter().isItalic()) { btnItalics.setHTML("<i>I</i>"); } else { btnItalics.setHTML("I"); } } }); btnUnderline = new Button("U"); commandPanel.add(btnUnderline); btnUnderline.setTitle(ApplicationController.getMessages().DesktopChatPanel_underlineType()); commandPanel.setCellVerticalAlignment(btnUnderline, HasVerticalAlignment.ALIGN_MIDDLE); btnUnderline.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { chatEditTextArea.getFormatter().toggleUnderline(); if (chatEditTextArea.getFormatter().isUnderlined()) { btnUnderline.setHTML("<u>U</u>"); } else { btnUnderline.setHTML("U"); } } }); btnEmoticon = new Button(); Image img = new Image(EmoticonUtils.getEmoticons().get(0).url); btnEmoticon.setHTML(img.toString()); commandPanel.add(btnEmoticon); commandPanel.setCellVerticalAlignment(btnEmoticon, HasVerticalAlignment.ALIGN_MIDDLE); btnEmoticon.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (emoticonPallette == null) { emoticonPallette = new EmoticonPresenter().createView(DesktopChatPanel.this); } emoticonPallette.show(); emoticonPallette.setPopupPosition(btnEmoticon.getAbsoluteLeft() + btnEmoticon.getOffsetWidth(), btnEmoticon.getAbsoluteTop() + btnEmoticon.getOffsetWidth()); } }); btnEmoticon.setEnabled(false); if (operator) { initCannedMessages(cannedMessages, commandPanel); } if (operator || ClientProperties.getInstance().getBooleanValue(ClientProperties.DISPLAY_FILE_SHARE, false)) { initFileShareArea(commandPanel); } HorizontalPanel editPanel = new HorizontalPanel(); dataEntryPanel.add(editPanel); editPanel.setSize("100%", "100%"); editPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); chatEditTextArea = new RichTextArea(); editPanel.add(chatEditTextArea); chatEditTextArea.setSize("98%", "55px"); chatEditTextArea.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER && !event.getNativeEvent().getShiftKey()) { processEnteredText(); } else { presenter.typing(); } } }); chatEditTextArea.setEnabled(false); sendButton = new Button(ApplicationController.getMessages().DesktopChatPanel_send()); editPanel.add(sendButton); editPanel.setCellHorizontalAlignment(sendButton, HasHorizontalAlignment.ALIGN_LEFT); sendButton.setSize("100%", "100%"); sendButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { processEnteredText(); chatEditTextArea.setFocus(true); } }); sendButton.setEnabled(false); } private void initFileShareArea(HorizontalPanel commandButtonsPanel) { fileShareFormPanel = new FormPanel(); fileShareFormPanel.setEncoding(FormPanel.ENCODING_MULTIPART); fileShareFormPanel.setMethod(FormPanel.METHOD_POST); fileShareFormPanel.setAction(fileSharingUrl()); commandButtonsPanel.add(fileShareFormPanel); commandButtonsPanel.setCellHorizontalAlignment(fileShareFormPanel, HasHorizontalAlignment.ALIGN_RIGHT); commandButtonsPanel.setCellVerticalAlignment(fileShareFormPanel, HasVerticalAlignment.ALIGN_MIDDLE); HorizontalPanel fileSharePanel = new HorizontalPanel(); fileSharePanel.setSpacing(2); fileShareFormPanel.setWidget(fileSharePanel); sessionField = new Hidden("session"); fileSharePanel.add(sessionField); fileShare = new FileUpload(); fileSharePanel.add(fileShare); fileShare.setName("file"); fileSharePanel.setCellHorizontalAlignment(fileShare, HasHorizontalAlignment.ALIGN_RIGHT); fileSharePanel.setCellVerticalAlignment(fileShare, HasVerticalAlignment.ALIGN_MIDDLE); shareButton = new Button(ApplicationController.getMessages().DesktopChatPanel_share()); fileSharePanel.add(shareButton); fileSharePanel.setCellHorizontalAlignment(shareButton, HasHorizontalAlignment.ALIGN_LEFT); fileSharePanel.setCellVerticalAlignment(shareButton, HasVerticalAlignment.ALIGN_MIDDLE); shareButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { fileShareFormPanel.submit(); } }); shareButton.setEnabled(false); fileShareFormPanel.addSubmitHandler(new FormPanel.SubmitHandler() { public void onSubmit(SubmitEvent event) { if (fileShare.getFilename().trim().length() == 0) { MessageBoxPresenter.getInstance().show( ApplicationController.getMessages().DesktopChatPanel_fileTransferStatus(), ApplicationController.getMessages().DesktopChatPanel_noFileName(), MessageBoxPresenter.Severity.WARN, true); event.cancel(); return; } sessionField.setValue(Long.toString(presenter.getSessionId())); MessageBoxPresenter.getInstance().show( ApplicationController.getMessages().DesktopChatPanel_fileTransferStatus(), ApplicationController.getMessages().DesktopChatPanel_fileTransferInProgress() + " ...", MessageBoxPresenter.Severity.INFO, true); } }); fileShareFormPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { MessageBoxPresenter.getInstance().hide(); String results = event.getResults(); int index = results.indexOf(","); if (index < 0) { // Should not happen return; } int status = Integer.parseInt(results.substring(0, index)); String param = ApplicationController.getMessages().DesktopChatPanel_noReasonGiven(); if (index + 1 < results.length()) { param = results.substring(index + 1); } switch (status) { case ResponseMessage.OK: presenter.notifyFileSharing(param); appendToConveration(null, ApplicationController.getInstance().timestamp(), ApplicationController.getMessages().DesktopChatPanel_fileShared(fileShare.getFilename())); break; case ResponseMessage.NO_CONTENT: appendToConveration(null, ApplicationController.getInstance().timestamp(), ApplicationController.getMessages().DesktopChatPanel_fileNoData()); break; case ResponseMessage.NOT_ACCEPTABLE: appendToConveration(null, ApplicationController.getInstance().timestamp(), ApplicationController.getMessages().DesktopChatPanel_fileTooBig()); break; default: appendToConveration(null, ApplicationController.getInstance().timestamp(), param); break; } } }); } public String fileSharingUrl() { return GWT.getModuleBaseURL() + "../fileSharing"; } private void initCannedMessages(CannedMessageElement[] cannedMessages, HorizontalPanel commandButtonsPanel) { if (cannedMessages != null && cannedMessages.length > 0) { cannedMessageListBox = new ListBox(); commandButtonsPanel.add(cannedMessageListBox); cannedMessageListBox.setVisibleItemCount(1); cannedMessageListBox.setWidth("200px"); cannedMessageListBox.addItem(""); for (int i = 0; i < cannedMessages.length; i++) { cannedMessageListBox.addItem(cannedMessages[i].getDescription()); } commandButtonsPanel.setCellHorizontalAlignment(cannedMessageListBox, HasHorizontalAlignment.ALIGN_RIGHT); commandButtonsPanel.setCellVerticalAlignment(cannedMessageListBox, HasVerticalAlignment.ALIGN_MIDDLE); cannedMessageListBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { if (cannedMessageListBox.getSelectedIndex() > 0) { presenter.cannedMessageSelected(cannedMessageListBox.getSelectedIndex() - 1); cannedMessageListBox.setSelectedIndex(-1); } } }); } } @Override public void appendToConveration(String from, long timeStamp, String message) { if (!adjusted) { adjustScrollHeight(); } boolean userTyping = false; if (typing != null) { userTyping = true; transcriptPanel.remove(typing); } Widget widget = ChatPanel.Util.formatChat(from, timeStamp, message, me, ClientProperties.getInstance().getBooleanValue(ClientProperties.CONVERSATION_SMALL_SPACE, false)); transcriptPanel.add(widget); if (userTyping) { transcriptPanel.add(typing); } transcriptScrollPanel.setVerticalScrollPosition(transcriptPanel.getOffsetHeight()); } @Override public void appendToConveration(String from, long timeStamp, long formId, String formDef) { if (!adjusted) { adjustScrollHeight(); } boolean userTyping = false; if (typing != null) { userTyping = true; transcriptPanel.remove(typing); } transcriptPanel.add(ChatPanel.Util.formatChat(from, timeStamp, "", me, true)); Widget widget = formRenderer.renderForm(formId, formDef, this); transcriptPanel.add(widget); if (userTyping) { transcriptPanel.add(typing); } } @Override public void setPresenter(ChatSessionPresenter presenter) { this.presenter = presenter; } @Override public ChatSessionPresenter getPresenter() { return presenter; } @Override public void makeReadOnly() { discButton.removeFromParent(); chatEditTextArea.removeFromParent(); sendButton.removeFromParent(); if (operator) { if (cannedMessageListBox != null) { cannedMessageListBox.removeFromParent(); } controlSeparator.removeFromParent(); contactList.removeFromParent(); conferenceButton.removeFromParent(); transferButton.removeFromParent(); } commandPanel.removeFromParent(); dataEntryPanel.setHeight(discButton.getOffsetHeight() + 20 + "px"); adjustScrollHeight(); } private void processEnteredText() { String text = chatEditTextArea.getHTML(); chatEditTextArea.setHTML(""); text = HtmlUtils.scrubTags(text); if (text.length() == 0) { return; } text = EmoticonUtils.replaceEmoticonText(text); appendToConveration(null, ApplicationController.getInstance().timestamp(), text); presenter.sendTextMessage(text); } @Override public void emoticonSelected(String url) { chatEditTextArea.getFormatter().insertHTML("&nbsp;" + EmoticonUtils.getEmoticonTag(url) + "&nbsp;"); chatEditTextArea.setFocus(true); presenter.typing(); } @Override public void onResize() { super.onResize(); adjustScrollHeight(); } private void adjustScrollHeight() { int pheight = getOffsetHeight(); int dheight = dataEntryPanel.getOffsetHeight(); int sessionInfoHeaderSize = chatInfoDetailTable != null ? (int) VISITOR_TITLE_SIZE : 0; int height = pheight - dheight - sessionInfoHeaderSize - 30; if (operator) { height -= 15; } if (height >= 0) { transcriptScrollPanel.setHeight(height + "px"); adjusted = true; } transcriptScrollPanel.scrollToBottom(); } @Override public void attach(String me, CallPartyElement otherParty, CannedMessageElement[] cannedMessages, boolean operator, boolean showOtherPartyInfo, boolean hideAvatar) { init(me, otherParty, cannedMessages, operator, showOtherPartyInfo, hideAvatar); } @Override public String getTranscript() { return transcriptPanel.toString(); } @Override public void chatEnabled() { chatEditingSetEnabled(true); } @Override public void chatDisabled() { chatEditingSetEnabled(false); } private void chatEditingSetEnabled(boolean enabled) { chatEditTextArea.setEnabled(enabled); sendButton.setEnabled(enabled); btnEmoticon.setEnabled(enabled); if (shareButton != null) { shareButton.setEnabled(enabled); } if (operator) { transferButton.setEnabled(enabled); conferenceButton.setEnabled(enabled); contactList.setEnabled(enabled); } if (enabled) { Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { chatEditTextArea.setFocus(true); } }); } } @Override public void setOtherPartyInfo(List<CallPartyElement> otherParties) { if (chatInfoDetailTable != null) { chatInfoDetailTable.clear(); int row = 0; for (CallPartyElement cp : otherParties) { setOtherPartyDetails(row, cp); row++; } } String parties; String avatar = null; if (otherParties.size() == 1) { CallPartyElement userInfo = otherParties.get(0); parties = ViewUtils.formatName(userInfo); avatar = userInfo.getAvatar(); } else { parties = ApplicationController.getMessages() .DesktopChatPanel_numUsersInConference(otherParties.size() + 1 + ""); } StringBuilder builder = formatOtherParties(parties, avatar); chatPanelHeaderLabel.setHTML(builder.toString()); chatPanelHeaderLabel.setStyleName("gwt-StackLayoutPanelHeader"); chatPanelHeaderLabel.setWidth("100%"); } private StringBuilder formatOtherParties(String parties, String avatar) { StringBuilder builder = new StringBuilder(); if (avatar != null && !hideAvatar) { builder.append("<img src='"); builder.append(avatar); builder.append("' width='"); builder.append(Images.TINY_IMG_WIDTH); builder.append("' + height='"); builder.append(Images.TINY_IMG_HEIGHT); builder.append("' border='0' align='center'>&nbsp;"); } builder.append(parties); return builder; } private void setOtherPartyDetails(int row, CallPartyElement cp) { String image; if (cp.getAvatar() != null) { image = cp.getAvatar(); } else { image = Images.USER_MEDIUM; } Image img = new Image(image); chatInfoDetailTable.setWidget(row, 0, img); img.setSize(Images.MEDIUM_IMG_WIDTH, Images.MEDIUM_IMG_WIDTH); String userInfo = ViewUtils.formatUserInfo(cp); chatInfoDetailTable.setWidget(row, 1, new HTML(userInfo)); } @Override public void transferSetEnabled(boolean enabled) { if (transferButton != null) { transferButton.setEnabled(enabled); } } @Override public void showTyping(String from, long timestamp) { boolean render = false; if (typing == null) { render = true; } else if (!typingFrom.equals(from)) { hideTyping(); render = true; } if (render) { typing = ChatPanel.Util.formatChat(from, timestamp, ChatPanel.TYPING, me, ClientProperties.getInstance().getBooleanValue(ClientProperties.CONVERSATION_SMALL_SPACE, false)); typingFrom = from; transcriptPanel.add(typing); transcriptScrollPanel.setVerticalScrollPosition(transcriptPanel.getOffsetHeight()); } } @Override public void hideTyping() { if (typing != null) { transcriptPanel.remove(typing); typing = null; typingFrom = null; } } @Override public void onLoad() { super.onLoad(); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { adjustScrollHeight(); } }); } @Override public boolean formSubmitted(long formId, Map<String, String> result) { presenter.submitForm(formId, result); return true; } }
UTF-8
Java
28,332
java
DesktopChatPanel.java
Java
[ { "context": ".ace.web.client.view.ViewUtils;\r\n\r\n/**\r\n * @author amit\r\n * \r\n */\r\npublic class DesktopChatPanel extends ", "end": 3040, "score": 0.9094216823577881, "start": 3036, "tag": "USERNAME", "value": "amit" } ]
null
[]
/** * */ package com.quikj.ace.web.client.view.desktop; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.ContextMenuEvent; import com.google.gwt.event.dom.client.ContextMenuHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitEvent; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.RichTextArea; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.StackLayoutPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.quikj.ace.messages.vo.app.ResponseMessage; import com.quikj.ace.messages.vo.talk.CallPartyElement; import com.quikj.ace.messages.vo.talk.CannedMessageElement; import com.quikj.ace.messages.vo.talk.DisconnectReasonElement; import com.quikj.ace.web.client.ApplicationController; import com.quikj.ace.web.client.ClientProperties; import com.quikj.ace.web.client.Images; import com.quikj.ace.web.client.presenter.ChatSessionPresenter; import com.quikj.ace.web.client.presenter.EmoticonPresenter; import com.quikj.ace.web.client.presenter.MessageBoxPresenter; import com.quikj.ace.web.client.view.ChatPanel; import com.quikj.ace.web.client.view.EmoticonUtils; import com.quikj.ace.web.client.view.FormRenderer; import com.quikj.ace.web.client.view.FormRenderer.FormListener; import com.quikj.ace.web.client.view.HtmlUtils; import com.quikj.ace.web.client.view.ViewUtils; /** * @author amit * */ public class DesktopChatPanel extends StackLayoutPanel implements ChatPanel, FormListener { private static final double VISITOR_TITLE_SIZE = 30.0; private static final double TITLE_SIZE = 45.0; private static final int DATA_ENTRY_PANEL_SIZE = 100; private HTMLPanel transcriptPanel; private RichTextArea chatEditTextArea; private ChatSessionPresenter presenter; private Button discButton; private Button sendButton; private ListBox cannedMessageListBox; private ScrollPanel transcriptScrollPanel; private Button btnBold; private Button btnItalics; private Button btnUnderline; private HorizontalPanel commandPanel; private PopupPanel emoticonPallette; private boolean adjusted = false; private Button btnEmoticon; private VerticalPanel dataEntryPanel; private VerticalPanel chatPanel; private boolean operator; private FlexTable chatInfoDetailTable; private HTML chatPanelHeaderLabel; private ListBox contactList; private HorizontalPanel chatPanelHeaderControls; private Button conferenceButton; private Button transferButton; private String me; private Widget typing; private String typingFrom; private List<HandlerRegistration> eventHandlers = new ArrayList<HandlerRegistration>(); private HTML controlSeparator; private boolean hideAvatar; private FormPanel fileShareFormPanel; private FileUpload fileShare; private Hidden sessionField; private Button shareButton; private FormRenderer formRenderer = new FormRenderer(); public DesktopChatPanel() { super(Unit.PX); setSize("100%", "97%"); } private void init(String me, CallPartyElement otherParty, CannedMessageElement[] cannedMessages, boolean operator, boolean showOtherPartyInfo, boolean hideAvatar) { this.operator = operator; this.me = me; this.hideAvatar = hideAvatar; initTranscriptArea(otherParty, operator); initChatEditArea(cannedMessages); if (showOtherPartyInfo) { initChatInfoArea(otherParty); } } private void initChatInfoArea(CallPartyElement otherParty) { chatInfoDetailTable = new FlexTable(); add(chatInfoDetailTable, ApplicationController.getMessages().DesktopChatPanel_chatSessionInformation(), false, VISITOR_TITLE_SIZE); chatInfoDetailTable.setWidth("100%"); chatInfoDetailTable.setCellPadding(10); setOtherPartyDetails(0, otherParty); } private void initTranscriptArea(CallPartyElement otherParty, boolean operator) { chatPanel = new VerticalPanel(); chatPanel.setSize("100%", "100%"); HorizontalPanel chatPanelHeader = new HorizontalPanel(); add(chatPanel, chatPanelHeader, TITLE_SIZE); chatPanelHeader.setWidth("100%"); chatPanelHeader.setSpacing(2); chatPanelHeaderLabel = new HTML(); chatPanelHeaderLabel.setStyleName("gwt-StackLayoutPanelHeader"); chatPanelHeaderLabel.setWidth("100%"); chatPanelHeader.add(chatPanelHeaderLabel); chatPanelHeader.setCellHorizontalAlignment(chatPanelHeaderLabel, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeader.setCellVerticalAlignment(chatPanelHeaderLabel, HasVerticalAlignment.ALIGN_MIDDLE); chatPanelHeaderLabel.setHTML(otherParty == null ? ApplicationController.getMessages().DesktopChatPanel_private() : formatOtherParties(ViewUtils.formatName(otherParty), otherParty.getAvatar()).toString()); chatPanelHeaderControls = new HorizontalPanel(); chatPanelHeader.add(chatPanelHeaderControls); chatPanelHeaderControls.setSpacing(4); chatPanelHeader.setCellHorizontalAlignment(chatPanelHeaderControls, HasHorizontalAlignment.ALIGN_RIGHT); chatPanelHeader.setCellVerticalAlignment(chatPanelHeaderControls, HasVerticalAlignment.ALIGN_MIDDLE); if (operator) { contactList = new ListBox(); chatPanelHeaderControls.add(contactList); chatPanelHeaderControls.setCellHorizontalAlignment(contactList, HasHorizontalAlignment.ALIGN_RIGHT); chatPanelHeaderControls.setCellVerticalAlignment(contactList, HasVerticalAlignment.ALIGN_MIDDLE); contactList.setEnabled(false); contactList.addItem(ApplicationController.getMessages().DesktopChatPanel_selectContact()); contactList.addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { contactList.clear(); contactList.addItem(ApplicationController.getMessages().DesktopChatPanel_selectContact()); List<String> contacts = presenter.getContactsList(); for (String contact : contacts) { contactList.addItem(contact); } } }); conferenceButton = new Button(ApplicationController.getMessages().DesktopChatPanel_add()); chatPanelHeaderControls.add(conferenceButton); chatPanelHeaderControls.setCellHorizontalAlignment(conferenceButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(conferenceButton, HasVerticalAlignment.ALIGN_MIDDLE); conferenceButton.setEnabled(false); conferenceButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index = contactList.getSelectedIndex(); if (index == 0) { return; } presenter.addToConference(contactList.getItemText(index)); contactList.setSelectedIndex(0); } }); transferButton = new Button(ApplicationController.getMessages().DesktopChatPanel_transfer()); chatPanelHeaderControls.add(transferButton); chatPanelHeaderControls.setCellHorizontalAlignment(transferButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(transferButton, HasVerticalAlignment.ALIGN_MIDDLE); transferButton.setEnabled(false); transferButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index = contactList.getSelectedIndex(); if (index == 0) { return; } presenter.transferTo(contactList.getItemText(index)); contactList.setSelectedIndex(0); } }); controlSeparator = new HTML("&nbsp;|&nbsp"); chatPanelHeaderControls.add(controlSeparator); } discButton = new Button(ApplicationController.getMessages().DesktopChatPanel_disconnect()); chatPanelHeaderControls.add(discButton); chatPanelHeaderControls.setCellHorizontalAlignment(discButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(discButton, HasVerticalAlignment.ALIGN_MIDDLE); discButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.userDisconnected(DisconnectReasonElement.NORMAL_DISCONNECT, null); } }); if (operator) { Button closeButton = new Button(ApplicationController.getMessages().DesktopChatPanel_close()); chatPanelHeaderControls.add(closeButton); chatPanelHeaderControls.setCellHorizontalAlignment(closeButton, HasHorizontalAlignment.ALIGN_LEFT); chatPanelHeaderControls.setCellVerticalAlignment(closeButton, HasVerticalAlignment.ALIGN_MIDDLE); closeButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.chatClosed(); } }); } transcriptScrollPanel = new ScrollPanel(); transcriptScrollPanel.setTouchScrollingDisabled(false); transcriptScrollPanel.setAlwaysShowScrollBars(true); chatPanel.add(transcriptScrollPanel); transcriptScrollPanel.setWidth("98%"); transcriptPanel = new HTMLPanel(""); transcriptScrollPanel.setWidget(transcriptPanel); transcriptPanel.setSize("100%", "100%"); if (ClientProperties.getInstance().getBooleanValue(ClientProperties.SUPPRESS_COPY_PASTE, ChatPanel.DEFAULT_SUPPRESS_COPYPASTE)) { eventHandlers.add(RootPanel.get().addDomHandler(new ContextMenuHandler() { @Override public void onContextMenu(ContextMenuEvent event) { event.preventDefault(); event.stopPropagation(); } }, ContextMenuEvent.getType())); eventHandlers.add(RootPanel.get().addDomHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (event.isControlKeyDown()) { event.preventDefault(); event.stopPropagation(); } } }, KeyDownEvent.getType())); } } @Override public void dispose() { for (HandlerRegistration handler : eventHandlers) { handler.removeHandler(); } eventHandlers.clear(); } private void initChatEditArea(CannedMessageElement[] cannedMessages) { dataEntryPanel = new VerticalPanel(); dataEntryPanel.setSpacing(3); chatPanel.add(dataEntryPanel); chatPanel.setCellVerticalAlignment(dataEntryPanel, HasVerticalAlignment.ALIGN_BOTTOM); dataEntryPanel.setWidth("100%"); dataEntryPanel.setHeight(DATA_ENTRY_PANEL_SIZE + "px"); HorizontalPanel controlPanel = new HorizontalPanel(); dataEntryPanel.add(controlPanel); controlPanel.setWidth("100%"); commandPanel = new HorizontalPanel(); commandPanel.setSpacing(5); controlPanel.add(commandPanel); btnBold = new Button("B"); commandPanel.add(btnBold); btnBold.setTitle(ApplicationController.getMessages().DesktopChatPanel_boldType()); commandPanel.setCellVerticalAlignment(btnBold, HasVerticalAlignment.ALIGN_MIDDLE); btnBold.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { chatEditTextArea.getFormatter().toggleBold(); if (chatEditTextArea.getFormatter().isBold()) { btnBold.setHTML("<b>B</b>"); } else { btnBold.setHTML("B"); } } }); btnItalics = new Button("I"); commandPanel.add(btnItalics); btnItalics.setTitle(ApplicationController.getMessages().DesktopChatPanel_italicsType()); commandPanel.setCellVerticalAlignment(btnItalics, HasVerticalAlignment.ALIGN_MIDDLE); btnItalics.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { chatEditTextArea.getFormatter().toggleItalic(); if (chatEditTextArea.getFormatter().isItalic()) { btnItalics.setHTML("<i>I</i>"); } else { btnItalics.setHTML("I"); } } }); btnUnderline = new Button("U"); commandPanel.add(btnUnderline); btnUnderline.setTitle(ApplicationController.getMessages().DesktopChatPanel_underlineType()); commandPanel.setCellVerticalAlignment(btnUnderline, HasVerticalAlignment.ALIGN_MIDDLE); btnUnderline.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { chatEditTextArea.getFormatter().toggleUnderline(); if (chatEditTextArea.getFormatter().isUnderlined()) { btnUnderline.setHTML("<u>U</u>"); } else { btnUnderline.setHTML("U"); } } }); btnEmoticon = new Button(); Image img = new Image(EmoticonUtils.getEmoticons().get(0).url); btnEmoticon.setHTML(img.toString()); commandPanel.add(btnEmoticon); commandPanel.setCellVerticalAlignment(btnEmoticon, HasVerticalAlignment.ALIGN_MIDDLE); btnEmoticon.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (emoticonPallette == null) { emoticonPallette = new EmoticonPresenter().createView(DesktopChatPanel.this); } emoticonPallette.show(); emoticonPallette.setPopupPosition(btnEmoticon.getAbsoluteLeft() + btnEmoticon.getOffsetWidth(), btnEmoticon.getAbsoluteTop() + btnEmoticon.getOffsetWidth()); } }); btnEmoticon.setEnabled(false); if (operator) { initCannedMessages(cannedMessages, commandPanel); } if (operator || ClientProperties.getInstance().getBooleanValue(ClientProperties.DISPLAY_FILE_SHARE, false)) { initFileShareArea(commandPanel); } HorizontalPanel editPanel = new HorizontalPanel(); dataEntryPanel.add(editPanel); editPanel.setSize("100%", "100%"); editPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT); chatEditTextArea = new RichTextArea(); editPanel.add(chatEditTextArea); chatEditTextArea.setSize("98%", "55px"); chatEditTextArea.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER && !event.getNativeEvent().getShiftKey()) { processEnteredText(); } else { presenter.typing(); } } }); chatEditTextArea.setEnabled(false); sendButton = new Button(ApplicationController.getMessages().DesktopChatPanel_send()); editPanel.add(sendButton); editPanel.setCellHorizontalAlignment(sendButton, HasHorizontalAlignment.ALIGN_LEFT); sendButton.setSize("100%", "100%"); sendButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { processEnteredText(); chatEditTextArea.setFocus(true); } }); sendButton.setEnabled(false); } private void initFileShareArea(HorizontalPanel commandButtonsPanel) { fileShareFormPanel = new FormPanel(); fileShareFormPanel.setEncoding(FormPanel.ENCODING_MULTIPART); fileShareFormPanel.setMethod(FormPanel.METHOD_POST); fileShareFormPanel.setAction(fileSharingUrl()); commandButtonsPanel.add(fileShareFormPanel); commandButtonsPanel.setCellHorizontalAlignment(fileShareFormPanel, HasHorizontalAlignment.ALIGN_RIGHT); commandButtonsPanel.setCellVerticalAlignment(fileShareFormPanel, HasVerticalAlignment.ALIGN_MIDDLE); HorizontalPanel fileSharePanel = new HorizontalPanel(); fileSharePanel.setSpacing(2); fileShareFormPanel.setWidget(fileSharePanel); sessionField = new Hidden("session"); fileSharePanel.add(sessionField); fileShare = new FileUpload(); fileSharePanel.add(fileShare); fileShare.setName("file"); fileSharePanel.setCellHorizontalAlignment(fileShare, HasHorizontalAlignment.ALIGN_RIGHT); fileSharePanel.setCellVerticalAlignment(fileShare, HasVerticalAlignment.ALIGN_MIDDLE); shareButton = new Button(ApplicationController.getMessages().DesktopChatPanel_share()); fileSharePanel.add(shareButton); fileSharePanel.setCellHorizontalAlignment(shareButton, HasHorizontalAlignment.ALIGN_LEFT); fileSharePanel.setCellVerticalAlignment(shareButton, HasVerticalAlignment.ALIGN_MIDDLE); shareButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { fileShareFormPanel.submit(); } }); shareButton.setEnabled(false); fileShareFormPanel.addSubmitHandler(new FormPanel.SubmitHandler() { public void onSubmit(SubmitEvent event) { if (fileShare.getFilename().trim().length() == 0) { MessageBoxPresenter.getInstance().show( ApplicationController.getMessages().DesktopChatPanel_fileTransferStatus(), ApplicationController.getMessages().DesktopChatPanel_noFileName(), MessageBoxPresenter.Severity.WARN, true); event.cancel(); return; } sessionField.setValue(Long.toString(presenter.getSessionId())); MessageBoxPresenter.getInstance().show( ApplicationController.getMessages().DesktopChatPanel_fileTransferStatus(), ApplicationController.getMessages().DesktopChatPanel_fileTransferInProgress() + " ...", MessageBoxPresenter.Severity.INFO, true); } }); fileShareFormPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { MessageBoxPresenter.getInstance().hide(); String results = event.getResults(); int index = results.indexOf(","); if (index < 0) { // Should not happen return; } int status = Integer.parseInt(results.substring(0, index)); String param = ApplicationController.getMessages().DesktopChatPanel_noReasonGiven(); if (index + 1 < results.length()) { param = results.substring(index + 1); } switch (status) { case ResponseMessage.OK: presenter.notifyFileSharing(param); appendToConveration(null, ApplicationController.getInstance().timestamp(), ApplicationController.getMessages().DesktopChatPanel_fileShared(fileShare.getFilename())); break; case ResponseMessage.NO_CONTENT: appendToConveration(null, ApplicationController.getInstance().timestamp(), ApplicationController.getMessages().DesktopChatPanel_fileNoData()); break; case ResponseMessage.NOT_ACCEPTABLE: appendToConveration(null, ApplicationController.getInstance().timestamp(), ApplicationController.getMessages().DesktopChatPanel_fileTooBig()); break; default: appendToConveration(null, ApplicationController.getInstance().timestamp(), param); break; } } }); } public String fileSharingUrl() { return GWT.getModuleBaseURL() + "../fileSharing"; } private void initCannedMessages(CannedMessageElement[] cannedMessages, HorizontalPanel commandButtonsPanel) { if (cannedMessages != null && cannedMessages.length > 0) { cannedMessageListBox = new ListBox(); commandButtonsPanel.add(cannedMessageListBox); cannedMessageListBox.setVisibleItemCount(1); cannedMessageListBox.setWidth("200px"); cannedMessageListBox.addItem(""); for (int i = 0; i < cannedMessages.length; i++) { cannedMessageListBox.addItem(cannedMessages[i].getDescription()); } commandButtonsPanel.setCellHorizontalAlignment(cannedMessageListBox, HasHorizontalAlignment.ALIGN_RIGHT); commandButtonsPanel.setCellVerticalAlignment(cannedMessageListBox, HasVerticalAlignment.ALIGN_MIDDLE); cannedMessageListBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { if (cannedMessageListBox.getSelectedIndex() > 0) { presenter.cannedMessageSelected(cannedMessageListBox.getSelectedIndex() - 1); cannedMessageListBox.setSelectedIndex(-1); } } }); } } @Override public void appendToConveration(String from, long timeStamp, String message) { if (!adjusted) { adjustScrollHeight(); } boolean userTyping = false; if (typing != null) { userTyping = true; transcriptPanel.remove(typing); } Widget widget = ChatPanel.Util.formatChat(from, timeStamp, message, me, ClientProperties.getInstance().getBooleanValue(ClientProperties.CONVERSATION_SMALL_SPACE, false)); transcriptPanel.add(widget); if (userTyping) { transcriptPanel.add(typing); } transcriptScrollPanel.setVerticalScrollPosition(transcriptPanel.getOffsetHeight()); } @Override public void appendToConveration(String from, long timeStamp, long formId, String formDef) { if (!adjusted) { adjustScrollHeight(); } boolean userTyping = false; if (typing != null) { userTyping = true; transcriptPanel.remove(typing); } transcriptPanel.add(ChatPanel.Util.formatChat(from, timeStamp, "", me, true)); Widget widget = formRenderer.renderForm(formId, formDef, this); transcriptPanel.add(widget); if (userTyping) { transcriptPanel.add(typing); } } @Override public void setPresenter(ChatSessionPresenter presenter) { this.presenter = presenter; } @Override public ChatSessionPresenter getPresenter() { return presenter; } @Override public void makeReadOnly() { discButton.removeFromParent(); chatEditTextArea.removeFromParent(); sendButton.removeFromParent(); if (operator) { if (cannedMessageListBox != null) { cannedMessageListBox.removeFromParent(); } controlSeparator.removeFromParent(); contactList.removeFromParent(); conferenceButton.removeFromParent(); transferButton.removeFromParent(); } commandPanel.removeFromParent(); dataEntryPanel.setHeight(discButton.getOffsetHeight() + 20 + "px"); adjustScrollHeight(); } private void processEnteredText() { String text = chatEditTextArea.getHTML(); chatEditTextArea.setHTML(""); text = HtmlUtils.scrubTags(text); if (text.length() == 0) { return; } text = EmoticonUtils.replaceEmoticonText(text); appendToConveration(null, ApplicationController.getInstance().timestamp(), text); presenter.sendTextMessage(text); } @Override public void emoticonSelected(String url) { chatEditTextArea.getFormatter().insertHTML("&nbsp;" + EmoticonUtils.getEmoticonTag(url) + "&nbsp;"); chatEditTextArea.setFocus(true); presenter.typing(); } @Override public void onResize() { super.onResize(); adjustScrollHeight(); } private void adjustScrollHeight() { int pheight = getOffsetHeight(); int dheight = dataEntryPanel.getOffsetHeight(); int sessionInfoHeaderSize = chatInfoDetailTable != null ? (int) VISITOR_TITLE_SIZE : 0; int height = pheight - dheight - sessionInfoHeaderSize - 30; if (operator) { height -= 15; } if (height >= 0) { transcriptScrollPanel.setHeight(height + "px"); adjusted = true; } transcriptScrollPanel.scrollToBottom(); } @Override public void attach(String me, CallPartyElement otherParty, CannedMessageElement[] cannedMessages, boolean operator, boolean showOtherPartyInfo, boolean hideAvatar) { init(me, otherParty, cannedMessages, operator, showOtherPartyInfo, hideAvatar); } @Override public String getTranscript() { return transcriptPanel.toString(); } @Override public void chatEnabled() { chatEditingSetEnabled(true); } @Override public void chatDisabled() { chatEditingSetEnabled(false); } private void chatEditingSetEnabled(boolean enabled) { chatEditTextArea.setEnabled(enabled); sendButton.setEnabled(enabled); btnEmoticon.setEnabled(enabled); if (shareButton != null) { shareButton.setEnabled(enabled); } if (operator) { transferButton.setEnabled(enabled); conferenceButton.setEnabled(enabled); contactList.setEnabled(enabled); } if (enabled) { Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { chatEditTextArea.setFocus(true); } }); } } @Override public void setOtherPartyInfo(List<CallPartyElement> otherParties) { if (chatInfoDetailTable != null) { chatInfoDetailTable.clear(); int row = 0; for (CallPartyElement cp : otherParties) { setOtherPartyDetails(row, cp); row++; } } String parties; String avatar = null; if (otherParties.size() == 1) { CallPartyElement userInfo = otherParties.get(0); parties = ViewUtils.formatName(userInfo); avatar = userInfo.getAvatar(); } else { parties = ApplicationController.getMessages() .DesktopChatPanel_numUsersInConference(otherParties.size() + 1 + ""); } StringBuilder builder = formatOtherParties(parties, avatar); chatPanelHeaderLabel.setHTML(builder.toString()); chatPanelHeaderLabel.setStyleName("gwt-StackLayoutPanelHeader"); chatPanelHeaderLabel.setWidth("100%"); } private StringBuilder formatOtherParties(String parties, String avatar) { StringBuilder builder = new StringBuilder(); if (avatar != null && !hideAvatar) { builder.append("<img src='"); builder.append(avatar); builder.append("' width='"); builder.append(Images.TINY_IMG_WIDTH); builder.append("' + height='"); builder.append(Images.TINY_IMG_HEIGHT); builder.append("' border='0' align='center'>&nbsp;"); } builder.append(parties); return builder; } private void setOtherPartyDetails(int row, CallPartyElement cp) { String image; if (cp.getAvatar() != null) { image = cp.getAvatar(); } else { image = Images.USER_MEDIUM; } Image img = new Image(image); chatInfoDetailTable.setWidget(row, 0, img); img.setSize(Images.MEDIUM_IMG_WIDTH, Images.MEDIUM_IMG_WIDTH); String userInfo = ViewUtils.formatUserInfo(cp); chatInfoDetailTable.setWidget(row, 1, new HTML(userInfo)); } @Override public void transferSetEnabled(boolean enabled) { if (transferButton != null) { transferButton.setEnabled(enabled); } } @Override public void showTyping(String from, long timestamp) { boolean render = false; if (typing == null) { render = true; } else if (!typingFrom.equals(from)) { hideTyping(); render = true; } if (render) { typing = ChatPanel.Util.formatChat(from, timestamp, ChatPanel.TYPING, me, ClientProperties.getInstance().getBooleanValue(ClientProperties.CONVERSATION_SMALL_SPACE, false)); typingFrom = from; transcriptPanel.add(typing); transcriptScrollPanel.setVerticalScrollPosition(transcriptPanel.getOffsetHeight()); } } @Override public void hideTyping() { if (typing != null) { transcriptPanel.remove(typing); typing = null; typingFrom = null; } } @Override public void onLoad() { super.onLoad(); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { adjustScrollHeight(); } }); } @Override public boolean formSubmitted(long formId, Map<String, String> result) { presenter.submitForm(formId, result); return true; } }
28,332
0.735635
0.731929
853
31.214537
28.222897
116
false
false
0
0
0
0
0
0
2.614302
false
false
10
b74a5419a195f8b3753d40f66ffb72ee9206dfe7
30,554,397,344,365
93c1f8260b3e657de83cd2e1d6f1008890b5b3b1
/common/src/main/java/by/smirnov/message/util/MessageJSONParser.java
e2dc2dca69e7d77c876afd85243426240d7ba58f
[]
no_license
dzmt/support
https://github.com/dzmt/support
7ac9dc30148b8fe737cbd60aba8f7d5d9540fc34
87d7895b01a57a49fd4793cdb27fa1b19893cafc
refs/heads/master
2020-03-31T21:31:47.504000
2018-10-30T05:48:26
2018-10-30T05:48:26
152,584,023
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.smirnov.message.util; import by.smirnov.message.Message; public interface MessageJSONParser { String parseMessage(Message message); Message parseString(String message); }
UTF-8
Java
194
java
MessageJSONParser.java
Java
[]
null
[]
package by.smirnov.message.util; import by.smirnov.message.Message; public interface MessageJSONParser { String parseMessage(Message message); Message parseString(String message); }
194
0.778351
0.778351
10
18.4
18.364096
41
false
false
0
0
0
0
0
0
0.4
false
false
10
86c7127043b6f4f0795b6762c04075ceed0041cd
26,585,847,562,289
751bf5bdd7a36cb9653e9b5ef2e3291587851418
/src/main/java/io/xhao/scanner/impl/ScanUtil.java
b2ff51ba8511fef4252563f6eeee2a57c94b3899
[ "MIT" ]
permissive
XHao/annotation-scanner
https://github.com/XHao/annotation-scanner
19eb8399b5b5150501ec7535370ef41dd4f036e6
f17127701102d97b7fdbe32009b12dee99d97d39
refs/heads/master
2015-08-11T19:04:12.315000
2015-05-12T05:47:39
2015-05-12T05:47:39
20,156,522
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.xhao.scanner.impl; import java.io.File; import java.util.ArrayList; import org.apache.log4j.Logger; public class ScanUtil { private static Logger logger = Logger.getLogger(ScanUtil.class); public static ArrayList<String> readClassPath(String[] paths) throws IllegalArgumentException { ArrayList<String> classList = new ArrayList<String>(); for (int i = 0, length = paths.length; i < length; i++) { File root = new File(paths[i]); if (root.isDirectory()) { try { classList.addAll(getFileList(root, ".class")); } catch (Exception e) { logger.error(e.getMessage()); } } } return classList; } public static ArrayList<String> readDir(File f, String regex) throws Exception { return getFileList(f, regex); } private static ArrayList<String> getFileList(File dir, String regex) throws Exception { ArrayList<String> fileList = new ArrayList<String>(); File[] fs = dir.listFiles(); for (int i = 0; i < fs.length; i++) { if (fs[i].isDirectory()) { fileList.addAll(getFileList(fs[i], regex)); } else if (fs[i].isFile() && fs[i].getName().endsWith(regex)) { fileList.add(fs[i].getAbsolutePath()); } } return fileList; } }
UTF-8
Java
1,214
java
ScanUtil.java
Java
[]
null
[]
package io.xhao.scanner.impl; import java.io.File; import java.util.ArrayList; import org.apache.log4j.Logger; public class ScanUtil { private static Logger logger = Logger.getLogger(ScanUtil.class); public static ArrayList<String> readClassPath(String[] paths) throws IllegalArgumentException { ArrayList<String> classList = new ArrayList<String>(); for (int i = 0, length = paths.length; i < length; i++) { File root = new File(paths[i]); if (root.isDirectory()) { try { classList.addAll(getFileList(root, ".class")); } catch (Exception e) { logger.error(e.getMessage()); } } } return classList; } public static ArrayList<String> readDir(File f, String regex) throws Exception { return getFileList(f, regex); } private static ArrayList<String> getFileList(File dir, String regex) throws Exception { ArrayList<String> fileList = new ArrayList<String>(); File[] fs = dir.listFiles(); for (int i = 0; i < fs.length; i++) { if (fs[i].isDirectory()) { fileList.addAll(getFileList(fs[i], regex)); } else if (fs[i].isFile() && fs[i].getName().endsWith(regex)) { fileList.add(fs[i].getAbsolutePath()); } } return fileList; } }
1,214
0.668863
0.666392
48
24.291666
22.108595
69
false
false
0
0
0
0
0
0
2.291667
false
false
10
4de28cf901ef6c57cf36c3af685e697f23a50a4e
15,083,925,186,297
641e77f33ad8fa499cc36b661e3c24917bc47f96
/issue/src/server/essp/issue/report/action/AcIssueReport.java
cf4b6a650f0d11e593c7f4beb602bfa3f3be024d
[]
no_license
stonethink/essp
https://github.com/stonethink/essp
43203bba6d95438eca7e47a071beba32dc7c2db1
10267cd3af60fc06631a7ff4b7fd855f7143f271
refs/heads/master
2021-04-12T10:07:27.792000
2018-04-22T03:18:02
2018-04-22T03:18:02
126,622,326
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package server.essp.issue.report.action; import server.framework.action.AbstractBusinessAction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import c2s.dto.TransactionData; import server.framework.common.BusinessException; public class AcIssueReport extends AbstractBusinessAction { /** * 根据输入projId查询生成报表 * Call:LgIssueReport.report() * ForwardId:result * @param request HttpServletRequest * @param response HttpServletResponse * @param data TransactionData * @throws BusinessException */ public void executeAct(HttpServletRequest request, HttpServletResponse response, TransactionData data) throws BusinessException { } /** @link dependency */ /*# server.essp.issue.report.logic.LgIssueReport lnkLgIssueReport; */ /** @link dependency */ /*# server.essp.issue.report.viewbean.VbIssueReportList lnkVbIssueReportList; */ }
GB18030
Java
1,042
java
AcIssueReport.java
Java
[]
null
[]
package server.essp.issue.report.action; import server.framework.action.AbstractBusinessAction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import c2s.dto.TransactionData; import server.framework.common.BusinessException; public class AcIssueReport extends AbstractBusinessAction { /** * 根据输入projId查询生成报表 * Call:LgIssueReport.report() * ForwardId:result * @param request HttpServletRequest * @param response HttpServletResponse * @param data TransactionData * @throws BusinessException */ public void executeAct(HttpServletRequest request, HttpServletResponse response, TransactionData data) throws BusinessException { } /** @link dependency */ /*# server.essp.issue.report.logic.LgIssueReport lnkLgIssueReport; */ /** @link dependency */ /*# server.essp.issue.report.viewbean.VbIssueReportList lnkVbIssueReportList; */ }
1,042
0.69863
0.697652
29
34.241379
24.107025
85
false
false
0
0
0
0
0
0
0.344828
false
false
10
7bbd0a0fb1b2026236f16e6ba8aeed6c9ece2c58
4,286,377,417,808
24388a40be7ca8fa2f4ecb2d0fedf0efeb33fa19
/web/src/main/java/is/service/CardServiceImpl.java
6887bb0bed53b042427feab8e9923273bb9e7c7a
[]
no_license
mohammadrezaaliabadi/is
https://github.com/mohammadrezaaliabadi/is
d15c55e41ad6319a4b6237d3dd372ba638db3c8d
9ac0df7568436e7a4f20a83f5721ca012cfee034
refs/heads/master
2022-11-28T08:58:14.319000
2020-08-05T16:59:19
2020-08-05T16:59:19
282,042,672
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package is.service; import is.domain.Account; import is.domain.Card; import is.domain.Customer; import is.repository.AccountRepository; import is.repository.CardRepository; import is.web.mapper.CardMapper; import is.web.model.CardDto; import javassist.NotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class CardServiceImpl implements CardService { @Autowired private CardRepository repository; @Autowired private CardMapper mapper; @Autowired private AccountRepository accountRepository; @Override public CardDto saveCard(CardDto cardDto) throws NotFoundException { Account byId = accountRepository.findById(cardDto.getAccountId()); if (byId==null){ throw new NotFoundException("Customer Not Found for FK"); } return mapper.cardToCardDto(repository.save(mapper.cardDtoToCard(cardDto))); } @Override public CardDto findById(int id) { return mapper.cardToCardDto(repository.findById(id)); } @Override public CardDto updateCard(int id, CardDto cardDto) { return mapper.cardToCardDto(repository.update(id,mapper.cardDtoToCard(cardDto))); } @Override public void deleteCard(int id) { repository.delete(id); } @Override public List<CardDto> findAll() { return repository.findAll().stream().map(mapper::cardToCardDto).collect(Collectors.toList()); } @Override public CardDto findCardNumber(String cardNumber) { return mapper.cardToCardDto(repository.findCardNumber(cardNumber)); } }
UTF-8
Java
1,719
java
CardServiceImpl.java
Java
[]
null
[]
package is.service; import is.domain.Account; import is.domain.Card; import is.domain.Customer; import is.repository.AccountRepository; import is.repository.CardRepository; import is.web.mapper.CardMapper; import is.web.model.CardDto; import javassist.NotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class CardServiceImpl implements CardService { @Autowired private CardRepository repository; @Autowired private CardMapper mapper; @Autowired private AccountRepository accountRepository; @Override public CardDto saveCard(CardDto cardDto) throws NotFoundException { Account byId = accountRepository.findById(cardDto.getAccountId()); if (byId==null){ throw new NotFoundException("Customer Not Found for FK"); } return mapper.cardToCardDto(repository.save(mapper.cardDtoToCard(cardDto))); } @Override public CardDto findById(int id) { return mapper.cardToCardDto(repository.findById(id)); } @Override public CardDto updateCard(int id, CardDto cardDto) { return mapper.cardToCardDto(repository.update(id,mapper.cardDtoToCard(cardDto))); } @Override public void deleteCard(int id) { repository.delete(id); } @Override public List<CardDto> findAll() { return repository.findAll().stream().map(mapper::cardToCardDto).collect(Collectors.toList()); } @Override public CardDto findCardNumber(String cardNumber) { return mapper.cardToCardDto(repository.findCardNumber(cardNumber)); } }
1,719
0.728912
0.728912
58
28.637932
25.845495
101
false
false
0
0
0
0
0
0
0.448276
false
false
10
2872439e34f74b3b10657ed684261cd4aeb6225f
12,799,002,607,300
53e4e6bf14cd9e1c62b40cc855576d61429bef2b
/demo/src/main/java/cn/cj/dlna/dms/ContentDirectoryCommand.java
d2478e211ebc4a7f26cba723d93f48ac15bb4c71
[]
no_license
woodyhi/dlna-android
https://github.com/woodyhi/dlna-android
6dbb6ef1d191e176e33bd350d251a993c7b97bbe
7e23804486f2cd3a34b90c2ef48adde4ce80eb3f
refs/heads/master
2020-03-19T07:48:27.696000
2018-07-20T07:11:34
2018-07-20T07:11:34
136,149,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.cj.dlna.dms; import org.fourthline.cling.UpnpService; import org.fourthline.cling.android.AndroidUpnpService; import org.fourthline.cling.controlpoint.ActionCallback; import org.fourthline.cling.model.action.ActionInvocation; import org.fourthline.cling.model.message.UpnpResponse; import org.fourthline.cling.model.meta.Device; import org.fourthline.cling.model.meta.Service; import org.fourthline.cling.model.types.UDAServiceType; import org.fourthline.cling.support.contentdirectory.callback.Browse; import org.fourthline.cling.support.model.BrowseFlag; import org.fourthline.cling.support.model.DIDLContent; import org.fourthline.cling.support.model.SortCriterion; /** * Created by June on 2017/3/7. */ public class ContentDirectoryCommand { AndroidUpnpService upnpService; public ContentDirectoryCommand(AndroidUpnpService upnpService){ this.upnpService = upnpService; } public void browse(Device device, String directoryId) { Service service = device.findService(new UDAServiceType("ContentDirectory")); ActionCallback actionCallback = new Browse(service, directoryId, BrowseFlag.DIRECT_CHILDREN, "*", 0, null, new SortCriterion(true, "dc:title")) { @Override public void received(ActionInvocation actionInvocation, DIDLContent didlContent) { System.out.println("=======contentDirectory=====success===" + didlContent.getContainers().get(0).getTitle()); } @Override public void updateStatus(Status status) { } @Override public void failure(ActionInvocation actionInvocation, UpnpResponse upnpResponse, String s) { System.out.println("======contentDirectory======fail===" + s); } }; upnpService.getControlPoint().execute(actionCallback); } public interface Callback{ void onSuccess(); void onFail(); } }
UTF-8
Java
1,791
java
ContentDirectoryCommand.java
Java
[ { "context": "ng.support.model.SortCriterion;\n\n/**\n * Created by June on 2017/3/7.\n */\n\npublic class ContentDirectoryCo", "end": 704, "score": 0.9451736211776733, "start": 700, "tag": "NAME", "value": "June" } ]
null
[]
package cn.cj.dlna.dms; import org.fourthline.cling.UpnpService; import org.fourthline.cling.android.AndroidUpnpService; import org.fourthline.cling.controlpoint.ActionCallback; import org.fourthline.cling.model.action.ActionInvocation; import org.fourthline.cling.model.message.UpnpResponse; import org.fourthline.cling.model.meta.Device; import org.fourthline.cling.model.meta.Service; import org.fourthline.cling.model.types.UDAServiceType; import org.fourthline.cling.support.contentdirectory.callback.Browse; import org.fourthline.cling.support.model.BrowseFlag; import org.fourthline.cling.support.model.DIDLContent; import org.fourthline.cling.support.model.SortCriterion; /** * Created by June on 2017/3/7. */ public class ContentDirectoryCommand { AndroidUpnpService upnpService; public ContentDirectoryCommand(AndroidUpnpService upnpService){ this.upnpService = upnpService; } public void browse(Device device, String directoryId) { Service service = device.findService(new UDAServiceType("ContentDirectory")); ActionCallback actionCallback = new Browse(service, directoryId, BrowseFlag.DIRECT_CHILDREN, "*", 0, null, new SortCriterion(true, "dc:title")) { @Override public void received(ActionInvocation actionInvocation, DIDLContent didlContent) { System.out.println("=======contentDirectory=====success===" + didlContent.getContainers().get(0).getTitle()); } @Override public void updateStatus(Status status) { } @Override public void failure(ActionInvocation actionInvocation, UpnpResponse upnpResponse, String s) { System.out.println("======contentDirectory======fail===" + s); } }; upnpService.getControlPoint().execute(actionCallback); } public interface Callback{ void onSuccess(); void onFail(); } }
1,791
0.772753
0.768286
54
32.166668
30.728048
113
false
false
0
0
0
0
0
0
1.722222
false
false
10
3b4a2551ea01884570767e44afb6ab26387cc89b
29,996,051,649,919
b23e379d0b191dcf1044a3ad7c3b682059a86a2e
/sampu/JavaSource/portal/entidades/GthEducacionEmpleado.java
8ea2adaa914fc6bd6aef1e5c58e041a0f4afbe73
[]
no_license
hhslouis/erp
https://github.com/hhslouis/erp
bc0291474a8df1a4d24b3fc1de7a420af56b1a4f
ab2615d2072cf1e93962e88fc3a8908d98e51432
refs/heads/master
2020-04-06T07:03:23.312000
2016-08-23T06:10:50
2016-08-23T06:10:50
42,479,772
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package portal.entidades; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Jimes */ @Entity @Table(name = "gth_educacion_empleado", catalog = "sampu", schema = "public") @NamedQueries({ @NamedQuery(name = "GthEducacionEmpleado.findAll", query = "SELECT g FROM GthEducacionEmpleado g"), @NamedQuery(name = "GthEducacionEmpleado.findByIdeGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.ideGtede = :ideGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByAnioGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.anioGtede = :anioGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByAnioGradoGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.anioGradoGtede = :anioGradoGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByActivoGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.activoGtede = :activoGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByUsuarioIngre", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.usuarioIngre = :usuarioIngre"), @NamedQuery(name = "GthEducacionEmpleado.findByFechaIngre", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.fechaIngre = :fechaIngre"), @NamedQuery(name = "GthEducacionEmpleado.findByUsuarioActua", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.usuarioActua = :usuarioActua"), @NamedQuery(name = "GthEducacionEmpleado.findByFechaActua", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.fechaActua = :fechaActua"), @NamedQuery(name = "GthEducacionEmpleado.findByHoraIngre", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.horaIngre = :horaIngre"), @NamedQuery(name = "GthEducacionEmpleado.findByHoraActua", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.horaActua = :horaActua")}) public class GthEducacionEmpleado implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "ide_gtede", nullable = false) private Integer ideGtede; @Column(name = "anio_gtede") private Integer anioGtede; @Column(name = "anio_grado_gtede") private Integer anioGradoGtede; @Column(name = "activo_gtede") private Boolean activoGtede; @Size(max = 50) @Column(name = "usuario_ingre", length = 50) private String usuarioIngre; @Column(name = "fecha_ingre") @Temporal(TemporalType.DATE) private Date fechaIngre; @Size(max = 50) @Column(name = "usuario_actua", length = 50) private String usuarioActua; @Column(name = "fecha_actua") @Temporal(TemporalType.DATE) private Date fechaActua; @Column(name = "hora_ingre") @Temporal(TemporalType.TIME) private Date horaIngre; @Column(name = "hora_actua") @Temporal(TemporalType.TIME) private Date horaActua; @JoinColumn(name = "ide_gtttp", referencedColumnName = "ide_gtttp") @ManyToOne private GthTipoTituloProfesional ideGtttp; @JoinColumn(name = "ide_gttes", referencedColumnName = "ide_gttes") @ManyToOne private GthTipoEspecialidad ideGttes; @JoinColumn(name = "ide_gtted", referencedColumnName = "ide_gtted") @ManyToOne private GthTipoEducacion ideGtted; @JoinColumn(name = "ide_gtemp", referencedColumnName = "ide_gtemp") @ManyToOne private GthEmpleado ideGtemp; @JoinColumn(name = "ide_gtana", referencedColumnName = "ide_gtana") @ManyToOne private GthAnioAprobado ideGtana; @JoinColumn(name = "ide_geins", referencedColumnName = "ide_geins") @ManyToOne private GenInstitucion ideGeins; @JoinColumn(name = "ide_gedip", referencedColumnName = "ide_gedip") @ManyToOne private GenDivisionPolitica ideGedip; public GthEducacionEmpleado() { } public GthEducacionEmpleado(Integer ideGtede) { this.ideGtede = ideGtede; } public Integer getIdeGtede() { return ideGtede; } public void setIdeGtede(Integer ideGtede) { this.ideGtede = ideGtede; } public Integer getAnioGtede() { return anioGtede; } public void setAnioGtede(Integer anioGtede) { this.anioGtede = anioGtede; } public Integer getAnioGradoGtede() { return anioGradoGtede; } public void setAnioGradoGtede(Integer anioGradoGtede) { this.anioGradoGtede = anioGradoGtede; } public Boolean getActivoGtede() { return activoGtede; } public void setActivoGtede(Boolean activoGtede) { this.activoGtede = activoGtede; } public String getUsuarioIngre() { return usuarioIngre; } public void setUsuarioIngre(String usuarioIngre) { this.usuarioIngre = usuarioIngre; } public Date getFechaIngre() { return fechaIngre; } public void setFechaIngre(Date fechaIngre) { this.fechaIngre = fechaIngre; } public String getUsuarioActua() { return usuarioActua; } public void setUsuarioActua(String usuarioActua) { this.usuarioActua = usuarioActua; } public Date getFechaActua() { return fechaActua; } public void setFechaActua(Date fechaActua) { this.fechaActua = fechaActua; } public Date getHoraIngre() { return horaIngre; } public void setHoraIngre(Date horaIngre) { this.horaIngre = horaIngre; } public Date getHoraActua() { return horaActua; } public void setHoraActua(Date horaActua) { this.horaActua = horaActua; } public GthTipoTituloProfesional getIdeGtttp() { return ideGtttp; } public void setIdeGtttp(GthTipoTituloProfesional ideGtttp) { this.ideGtttp = ideGtttp; } public GthTipoEspecialidad getIdeGttes() { return ideGttes; } public void setIdeGttes(GthTipoEspecialidad ideGttes) { this.ideGttes = ideGttes; } public GthTipoEducacion getIdeGtted() { return ideGtted; } public void setIdeGtted(GthTipoEducacion ideGtted) { this.ideGtted = ideGtted; } public GthEmpleado getIdeGtemp() { return ideGtemp; } public void setIdeGtemp(GthEmpleado ideGtemp) { this.ideGtemp = ideGtemp; } public GthAnioAprobado getIdeGtana() { return ideGtana; } public void setIdeGtana(GthAnioAprobado ideGtana) { this.ideGtana = ideGtana; } public GenInstitucion getIdeGeins() { return ideGeins; } public void setIdeGeins(GenInstitucion ideGeins) { this.ideGeins = ideGeins; } public GenDivisionPolitica getIdeGedip() { return ideGedip; } public void setIdeGedip(GenDivisionPolitica ideGedip) { this.ideGedip = ideGedip; } @Override public int hashCode() { int hash = 0; hash += (ideGtede != null ? ideGtede.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof GthEducacionEmpleado)) { return false; } GthEducacionEmpleado other = (GthEducacionEmpleado) object; if ((this.ideGtede == null && other.ideGtede != null) || (this.ideGtede != null && !this.ideGtede.equals(other.ideGtede))) { return false; } return true; } @Override public String toString() { return "portal.entidades.GthEducacionEmpleado[ ideGtede=" + ideGtede + " ]"; } }
UTF-8
Java
8,383
java
GthEducacionEmpleado.java
Java
[ { "context": "alidation.constraints.Size;\r\n\r\n/**\r\n *\r\n * @author Jimes\r\n */\r\n@Entity\r\n@Table(name = \"gth_educacion_emple", "end": 696, "score": 0.7338130474090576, "start": 691, "tag": "NAME", "value": "Jimes" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package portal.entidades; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Jimes */ @Entity @Table(name = "gth_educacion_empleado", catalog = "sampu", schema = "public") @NamedQueries({ @NamedQuery(name = "GthEducacionEmpleado.findAll", query = "SELECT g FROM GthEducacionEmpleado g"), @NamedQuery(name = "GthEducacionEmpleado.findByIdeGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.ideGtede = :ideGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByAnioGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.anioGtede = :anioGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByAnioGradoGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.anioGradoGtede = :anioGradoGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByActivoGtede", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.activoGtede = :activoGtede"), @NamedQuery(name = "GthEducacionEmpleado.findByUsuarioIngre", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.usuarioIngre = :usuarioIngre"), @NamedQuery(name = "GthEducacionEmpleado.findByFechaIngre", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.fechaIngre = :fechaIngre"), @NamedQuery(name = "GthEducacionEmpleado.findByUsuarioActua", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.usuarioActua = :usuarioActua"), @NamedQuery(name = "GthEducacionEmpleado.findByFechaActua", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.fechaActua = :fechaActua"), @NamedQuery(name = "GthEducacionEmpleado.findByHoraIngre", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.horaIngre = :horaIngre"), @NamedQuery(name = "GthEducacionEmpleado.findByHoraActua", query = "SELECT g FROM GthEducacionEmpleado g WHERE g.horaActua = :horaActua")}) public class GthEducacionEmpleado implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "ide_gtede", nullable = false) private Integer ideGtede; @Column(name = "anio_gtede") private Integer anioGtede; @Column(name = "anio_grado_gtede") private Integer anioGradoGtede; @Column(name = "activo_gtede") private Boolean activoGtede; @Size(max = 50) @Column(name = "usuario_ingre", length = 50) private String usuarioIngre; @Column(name = "fecha_ingre") @Temporal(TemporalType.DATE) private Date fechaIngre; @Size(max = 50) @Column(name = "usuario_actua", length = 50) private String usuarioActua; @Column(name = "fecha_actua") @Temporal(TemporalType.DATE) private Date fechaActua; @Column(name = "hora_ingre") @Temporal(TemporalType.TIME) private Date horaIngre; @Column(name = "hora_actua") @Temporal(TemporalType.TIME) private Date horaActua; @JoinColumn(name = "ide_gtttp", referencedColumnName = "ide_gtttp") @ManyToOne private GthTipoTituloProfesional ideGtttp; @JoinColumn(name = "ide_gttes", referencedColumnName = "ide_gttes") @ManyToOne private GthTipoEspecialidad ideGttes; @JoinColumn(name = "ide_gtted", referencedColumnName = "ide_gtted") @ManyToOne private GthTipoEducacion ideGtted; @JoinColumn(name = "ide_gtemp", referencedColumnName = "ide_gtemp") @ManyToOne private GthEmpleado ideGtemp; @JoinColumn(name = "ide_gtana", referencedColumnName = "ide_gtana") @ManyToOne private GthAnioAprobado ideGtana; @JoinColumn(name = "ide_geins", referencedColumnName = "ide_geins") @ManyToOne private GenInstitucion ideGeins; @JoinColumn(name = "ide_gedip", referencedColumnName = "ide_gedip") @ManyToOne private GenDivisionPolitica ideGedip; public GthEducacionEmpleado() { } public GthEducacionEmpleado(Integer ideGtede) { this.ideGtede = ideGtede; } public Integer getIdeGtede() { return ideGtede; } public void setIdeGtede(Integer ideGtede) { this.ideGtede = ideGtede; } public Integer getAnioGtede() { return anioGtede; } public void setAnioGtede(Integer anioGtede) { this.anioGtede = anioGtede; } public Integer getAnioGradoGtede() { return anioGradoGtede; } public void setAnioGradoGtede(Integer anioGradoGtede) { this.anioGradoGtede = anioGradoGtede; } public Boolean getActivoGtede() { return activoGtede; } public void setActivoGtede(Boolean activoGtede) { this.activoGtede = activoGtede; } public String getUsuarioIngre() { return usuarioIngre; } public void setUsuarioIngre(String usuarioIngre) { this.usuarioIngre = usuarioIngre; } public Date getFechaIngre() { return fechaIngre; } public void setFechaIngre(Date fechaIngre) { this.fechaIngre = fechaIngre; } public String getUsuarioActua() { return usuarioActua; } public void setUsuarioActua(String usuarioActua) { this.usuarioActua = usuarioActua; } public Date getFechaActua() { return fechaActua; } public void setFechaActua(Date fechaActua) { this.fechaActua = fechaActua; } public Date getHoraIngre() { return horaIngre; } public void setHoraIngre(Date horaIngre) { this.horaIngre = horaIngre; } public Date getHoraActua() { return horaActua; } public void setHoraActua(Date horaActua) { this.horaActua = horaActua; } public GthTipoTituloProfesional getIdeGtttp() { return ideGtttp; } public void setIdeGtttp(GthTipoTituloProfesional ideGtttp) { this.ideGtttp = ideGtttp; } public GthTipoEspecialidad getIdeGttes() { return ideGttes; } public void setIdeGttes(GthTipoEspecialidad ideGttes) { this.ideGttes = ideGttes; } public GthTipoEducacion getIdeGtted() { return ideGtted; } public void setIdeGtted(GthTipoEducacion ideGtted) { this.ideGtted = ideGtted; } public GthEmpleado getIdeGtemp() { return ideGtemp; } public void setIdeGtemp(GthEmpleado ideGtemp) { this.ideGtemp = ideGtemp; } public GthAnioAprobado getIdeGtana() { return ideGtana; } public void setIdeGtana(GthAnioAprobado ideGtana) { this.ideGtana = ideGtana; } public GenInstitucion getIdeGeins() { return ideGeins; } public void setIdeGeins(GenInstitucion ideGeins) { this.ideGeins = ideGeins; } public GenDivisionPolitica getIdeGedip() { return ideGedip; } public void setIdeGedip(GenDivisionPolitica ideGedip) { this.ideGedip = ideGedip; } @Override public int hashCode() { int hash = 0; hash += (ideGtede != null ? ideGtede.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof GthEducacionEmpleado)) { return false; } GthEducacionEmpleado other = (GthEducacionEmpleado) object; if ((this.ideGtede == null && other.ideGtede != null) || (this.ideGtede != null && !this.ideGtede.equals(other.ideGtede))) { return false; } return true; } @Override public String toString() { return "portal.entidades.GthEducacionEmpleado[ ideGtede=" + ideGtede + " ]"; } }
8,383
0.66444
0.663128
262
29.996183
31.765301
157
false
false
0
0
0
0
0
0
0.435115
false
false
10
4cf21da65016f7bd7c6e0de8d54f195e374811e2
23,613,730,199,225
a39222979ed147d8d233dc8be619a216a8b52e8e
/JxvaFramework/WebRoot/WEB-INF/classes/com/jxva/entity/Path.java
5d7f082c096112f0112dc89e49fedc145d405cf0
[]
no_license
jxva/jxvaframework
https://github.com/jxva/jxvaframework
ae532cbaa027540f907b00ea745b8236c17ba555
d56b3a5eafe78dedb55a8feca215de562bac045c
refs/heads/master
2020-06-05T01:23:57.433000
2012-04-17T08:20:39
2012-04-17T08:20:39
1,904,195
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright @ 2006-2010 by The Jxva Framework Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jxva.entity; /** * 在如下环境下进行了测试 * <pre> * Test Environment * Windows Linux Unix * Tomcat6.0.10 * Resin3.1.1 * Jboss4.0.0/5.0.0 * WebLogic9.1 * WebSphere6.1 * WasCE1.1 * Apusic4.0.3 * JFox3 * Jetty6.1.3 * </pre> * @author The Jxva Framework Foundation * @since 1.0 * @version 2008-11-26 14:14:23 PM by Jxva * */ public abstract class Path{ public static final String CLASS_PATH; //if this path include "WEB-INF" will return "WEB-INF"'s absolute path,otherwise return "classes"'s parent path public static final String WEB_INF_PATH; public static final String APP_PATH; public static final String ROOT_PATH; static{ String currentPath=getPath(Path.class); if(currentPath.indexOf(".jar!/")>-1||currentPath.indexOf("classes")>-1){ String classPath=currentPath.replaceAll("/./","/"); //weblogic //if this class be included .jar file,will replace "/lib/*.!/" to "/classes/" classPath=classPath.replaceAll("/lib/([^\'']+)!/","/classes/"); //jar classPath=classPath.split("/classes/")[0]+"/classes/"; //if os is not windows system if(classPath.indexOf(':')<0){ classPath='/'+classPath; } CLASS_PATH=classPath; }else{ CLASS_PATH=Path.class.getClassLoader().getResource(".").getPath().substring(1); } WEB_INF_PATH=CLASS_PATH.substring(0,CLASS_PATH.substring(0,CLASS_PATH.lastIndexOf('/')).lastIndexOf('/')+1); APP_PATH=WEB_INF_PATH.substring(0,WEB_INF_PATH.substring(0,WEB_INF_PATH.lastIndexOf('/')).lastIndexOf('/')+1); ROOT_PATH=CLASS_PATH.substring(0,CLASS_PATH.indexOf('/')+1); } /** * 获取参数cls的目录路径 * @param cls * @return */ public static String getPath(Class<?> cls){ String t=getAbsoluteFile(cls); return t.substring(0,t.lastIndexOf('/')+1).replaceAll("(file:/)|(file:)|(wsjar:)|(jar:)|(zip:)",""); // t=t.replaceAll("file:/", ""); //windows // t=t.replaceAll("file:", ""); //linux,unix // t=t.replaceAll("wsjar:",""); //websphere wsjar: has to at jar: before // t=t.replaceAll("jar:",""); //tomcat,jboss,resin,wasce,apusic // t=t.replaceAll("zip:",""); //weblogic } /** * 获取参数cls的文件路径 * @param cls * @return */ public static String getAbsoluteFile(Class<?> cls){ return cls.getResource(cls.getSimpleName() + ".class").toString().replaceAll("%20", " "); } }
UTF-8
Java
3,013
java
Path.java
Java
[]
null
[]
/* * Copyright @ 2006-2010 by The Jxva Framework Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jxva.entity; /** * 在如下环境下进行了测试 * <pre> * Test Environment * Windows Linux Unix * Tomcat6.0.10 * Resin3.1.1 * Jboss4.0.0/5.0.0 * WebLogic9.1 * WebSphere6.1 * WasCE1.1 * Apusic4.0.3 * JFox3 * Jetty6.1.3 * </pre> * @author The Jxva Framework Foundation * @since 1.0 * @version 2008-11-26 14:14:23 PM by Jxva * */ public abstract class Path{ public static final String CLASS_PATH; //if this path include "WEB-INF" will return "WEB-INF"'s absolute path,otherwise return "classes"'s parent path public static final String WEB_INF_PATH; public static final String APP_PATH; public static final String ROOT_PATH; static{ String currentPath=getPath(Path.class); if(currentPath.indexOf(".jar!/")>-1||currentPath.indexOf("classes")>-1){ String classPath=currentPath.replaceAll("/./","/"); //weblogic //if this class be included .jar file,will replace "/lib/*.!/" to "/classes/" classPath=classPath.replaceAll("/lib/([^\'']+)!/","/classes/"); //jar classPath=classPath.split("/classes/")[0]+"/classes/"; //if os is not windows system if(classPath.indexOf(':')<0){ classPath='/'+classPath; } CLASS_PATH=classPath; }else{ CLASS_PATH=Path.class.getClassLoader().getResource(".").getPath().substring(1); } WEB_INF_PATH=CLASS_PATH.substring(0,CLASS_PATH.substring(0,CLASS_PATH.lastIndexOf('/')).lastIndexOf('/')+1); APP_PATH=WEB_INF_PATH.substring(0,WEB_INF_PATH.substring(0,WEB_INF_PATH.lastIndexOf('/')).lastIndexOf('/')+1); ROOT_PATH=CLASS_PATH.substring(0,CLASS_PATH.indexOf('/')+1); } /** * 获取参数cls的目录路径 * @param cls * @return */ public static String getPath(Class<?> cls){ String t=getAbsoluteFile(cls); return t.substring(0,t.lastIndexOf('/')+1).replaceAll("(file:/)|(file:)|(wsjar:)|(jar:)|(zip:)",""); // t=t.replaceAll("file:/", ""); //windows // t=t.replaceAll("file:", ""); //linux,unix // t=t.replaceAll("wsjar:",""); //websphere wsjar: has to at jar: before // t=t.replaceAll("jar:",""); //tomcat,jboss,resin,wasce,apusic // t=t.replaceAll("zip:",""); //weblogic } /** * 获取参数cls的文件路径 * @param cls * @return */ public static String getAbsoluteFile(Class<?> cls){ return cls.getResource(cls.getSimpleName() + ".class").toString().replaceAll("%20", " "); } }
3,013
0.65956
0.635533
98
29.163265
29.843706
112
false
false
0
0
0
0
0
0
1.663265
false
false
10
02d7883fa80dbfb2f74cc3fe2909980167e99536
25,297,357,425,854
301412742fdaf35d10b38b37283968932404bd94
/bank-client-selfservice/src/main/java/controller/CustomerAddPayeeController.java
0e06433c24020e4cbc22ac4599879d00b837566b
[]
no_license
skarlet-witcher/CS5721-Project
https://github.com/skarlet-witcher/CS5721-Project
6a7c46739e420869fb1a4dc719214501d7a17a33
46db460a5d5a011745f45ec57461f07c4bffd199
refs/heads/master
2021-10-27T18:33:38.576000
2019-04-18T16:26:32
2019-04-18T16:26:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controller; import model.UserModel; import model.UserPayeeModel; import service.impl.CustomerPayeeService; import util.JTextFieldLimit; import view.CustomerAddPayeeView; import view.CustomerMainView; import javax.swing.*; import java.awt.event.ActionEvent; import static javax.swing.WindowConstants.EXIT_ON_CLOSE; public class CustomerAddPayeeController implements BaseController { private CustomerAddPayeeView view; private CustomerMainView customerMainView; private UserModel userModel; public CustomerAddPayeeController(CustomerAddPayeeView view, CustomerMainView customerMainView, UserModel userModel) { this.view = view; this.customerMainView = customerMainView; this.userModel = userModel; } @Override public void initialize() { this.view.initComponents(); initFields(); run(); } public void run() { this.view.setDefaultCloseOperation(EXIT_ON_CLOSE); this.view.setVisible(true); this.view.pack(); // resize } private void initFields() { this.view.tf_IBAN.setDocument(new JTextFieldLimit(34)); this.view. pf_pin.setDocument(new JTextFieldLimit(6)); } public void btn_backActionPerformed(ActionEvent e) { this.view.dispose(); new CustomerMainView(userModel); } public void btn_addActionPerformed(ActionEvent e) { // payee name validator if(this.view.tf_payeeName.getText().trim().length() <= 0) { JOptionPane.showMessageDialog(null, "Please input your payee name", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_payeeName.grabFocus(); return; } if(!this.view.tf_payeeName.getText().trim().matches("^[a-zA-Z]+$")) { JOptionPane.showMessageDialog(null, "Payee name should only contain letters", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_payeeName.grabFocus(); return; } // IBAN validator if(this.view.tf_IBAN.getText().trim().length() <= 0) { JOptionPane.showMessageDialog(null, "Please input your payee's IBAN", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_IBAN.grabFocus(); return; } if(!this.view.tf_IBAN.getText().trim().matches("^[0-9A-Z]+$")) { JOptionPane.showMessageDialog(null, "IBAN should only contain capital letters and digits", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_IBAN.grabFocus(); return; } // pin validator if(this.view.pf_pin.getPassword().length <=0) { JOptionPane.showMessageDialog(null, "Please input your PIN", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.pf_pin.grabFocus(); return; } // add payee service UserPayeeModel userPayeeModel = new UserPayeeModel(); userPayeeModel.setUserId(this.userModel.getId()); userPayeeModel.setIban(this.view.tf_IBAN.getText().trim()); userPayeeModel.setName(this.view.tf_payeeName.getText().trim()); String pin = new String(this.view.pf_pin.getPassword()); try { CustomerPayeeService.getInstance().addPayee(userPayeeModel, pin); JOptionPane.showMessageDialog(null, "add payee successful", "Info Message", JOptionPane.INFORMATION_MESSAGE); } catch (Exception E) { JOptionPane.showMessageDialog(null, "Fail to add payee, due to " + E.getMessage() + "please contact with admin", "Error Message", JOptionPane.ERROR_MESSAGE); return; } this.view.dispose(); new CustomerMainView(userModel); } }
UTF-8
Java
3,991
java
CustomerAddPayeeController.java
Java
[]
null
[]
package controller; import model.UserModel; import model.UserPayeeModel; import service.impl.CustomerPayeeService; import util.JTextFieldLimit; import view.CustomerAddPayeeView; import view.CustomerMainView; import javax.swing.*; import java.awt.event.ActionEvent; import static javax.swing.WindowConstants.EXIT_ON_CLOSE; public class CustomerAddPayeeController implements BaseController { private CustomerAddPayeeView view; private CustomerMainView customerMainView; private UserModel userModel; public CustomerAddPayeeController(CustomerAddPayeeView view, CustomerMainView customerMainView, UserModel userModel) { this.view = view; this.customerMainView = customerMainView; this.userModel = userModel; } @Override public void initialize() { this.view.initComponents(); initFields(); run(); } public void run() { this.view.setDefaultCloseOperation(EXIT_ON_CLOSE); this.view.setVisible(true); this.view.pack(); // resize } private void initFields() { this.view.tf_IBAN.setDocument(new JTextFieldLimit(34)); this.view. pf_pin.setDocument(new JTextFieldLimit(6)); } public void btn_backActionPerformed(ActionEvent e) { this.view.dispose(); new CustomerMainView(userModel); } public void btn_addActionPerformed(ActionEvent e) { // payee name validator if(this.view.tf_payeeName.getText().trim().length() <= 0) { JOptionPane.showMessageDialog(null, "Please input your payee name", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_payeeName.grabFocus(); return; } if(!this.view.tf_payeeName.getText().trim().matches("^[a-zA-Z]+$")) { JOptionPane.showMessageDialog(null, "Payee name should only contain letters", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_payeeName.grabFocus(); return; } // IBAN validator if(this.view.tf_IBAN.getText().trim().length() <= 0) { JOptionPane.showMessageDialog(null, "Please input your payee's IBAN", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_IBAN.grabFocus(); return; } if(!this.view.tf_IBAN.getText().trim().matches("^[0-9A-Z]+$")) { JOptionPane.showMessageDialog(null, "IBAN should only contain capital letters and digits", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.tf_IBAN.grabFocus(); return; } // pin validator if(this.view.pf_pin.getPassword().length <=0) { JOptionPane.showMessageDialog(null, "Please input your PIN", "Error Message", JOptionPane.ERROR_MESSAGE); this.view.pf_pin.grabFocus(); return; } // add payee service UserPayeeModel userPayeeModel = new UserPayeeModel(); userPayeeModel.setUserId(this.userModel.getId()); userPayeeModel.setIban(this.view.tf_IBAN.getText().trim()); userPayeeModel.setName(this.view.tf_payeeName.getText().trim()); String pin = new String(this.view.pf_pin.getPassword()); try { CustomerPayeeService.getInstance().addPayee(userPayeeModel, pin); JOptionPane.showMessageDialog(null, "add payee successful", "Info Message", JOptionPane.INFORMATION_MESSAGE); } catch (Exception E) { JOptionPane.showMessageDialog(null, "Fail to add payee, due to " + E.getMessage() + "please contact with admin", "Error Message", JOptionPane.ERROR_MESSAGE); return; } this.view.dispose(); new CustomerMainView(userModel); } }
3,991
0.610874
0.60887
107
36.299065
24.740982
122
false
false
0
0
0
0
0
0
0.719626
false
false
10
f2c1b8b93930c0ae2a18c2a3395213aab59ecd20
25,237,227,892,744
de66fcd4c3528e265b6db9bb0968fde4dedc795c
/backend/src/main/java/com/stu/luanvan/controller/URlController.java
60d6807fe2cc8caf66390021dad2019ab4932add
[]
no_license
ndhuy3011/luanvantotnghiep
https://github.com/ndhuy3011/luanvantotnghiep
5cbe367a6177b3d92e267983f619da7ba7e75d99
84c57d9831fce934bdf590e2e2808a5eeded29ef
refs/heads/master
2023-07-30T15:36:27.069000
2021-09-22T15:51:25
2021-09-22T15:51:25
409,262,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stu.luanvan.controller; public class URlController { public final static String ADMIN = "/api/admin"; public final static String CATEGORY_ADMIN = ADMIN + "/category"; public final static String COLOR_ADMIN = ADMIN + "/color"; public final static String COUPON_ADMIN = ADMIN + "/coupon"; public final static String DETAILS_PRODUCT_ADMIN = ADMIN + "/detailsproduct"; public final static String FILE_ADMIN = ADMIN + "/file"; public final static String PRODUCT_ADMIN = ADMIN + "/product"; public final static String SIZE_ADMIN = ADMIN + "/size"; public final static String INVOICE_ADMIN = ADMIN + "/invoice"; public final static String REVIEW_ADMIN = ADMIN + "/review"; public final static String REPORT_ADMIN = ADMIN + "/report"; public final static String SUPPLIER_ADMIN = ADMIN + "/supplier"; public final static String INFOWEBSITE_ADMIN = ADMIN + "/infoweb"; public final static String BANNER_ADMIN = ADMIN + "/banner"; }
UTF-8
Java
991
java
URlController.java
Java
[]
null
[]
package com.stu.luanvan.controller; public class URlController { public final static String ADMIN = "/api/admin"; public final static String CATEGORY_ADMIN = ADMIN + "/category"; public final static String COLOR_ADMIN = ADMIN + "/color"; public final static String COUPON_ADMIN = ADMIN + "/coupon"; public final static String DETAILS_PRODUCT_ADMIN = ADMIN + "/detailsproduct"; public final static String FILE_ADMIN = ADMIN + "/file"; public final static String PRODUCT_ADMIN = ADMIN + "/product"; public final static String SIZE_ADMIN = ADMIN + "/size"; public final static String INVOICE_ADMIN = ADMIN + "/invoice"; public final static String REVIEW_ADMIN = ADMIN + "/review"; public final static String REPORT_ADMIN = ADMIN + "/report"; public final static String SUPPLIER_ADMIN = ADMIN + "/supplier"; public final static String INFOWEBSITE_ADMIN = ADMIN + "/infoweb"; public final static String BANNER_ADMIN = ADMIN + "/banner"; }
991
0.705348
0.705348
18
54.055557
22.319578
81
false
false
0
0
0
0
0
0
0.833333
false
false
10
ca652167ddb73318bc88e6aa5ed5fc200b43baaa
25,666,724,611,387
84be7356cffc267844db8d8e7384a0b1739db26c
/CoFHCore/src/main/java/cofh/lib/util/comparison/ComparableItemStackValidatedNBT.java
10305e0aeb9e30454d8724d1c3543ab4a0bc31e8
[]
no_license
KingLemming/1.13-pre
https://github.com/KingLemming/1.13-pre
bc851d425658cc191d1a5abb09d3ca2aa43a1535
3badbe2e158f1fb8756ceb80a0a6cee4d105a172
refs/heads/master
2020-04-20T10:56:17.220000
2019-06-22T07:58:44
2019-06-22T07:58:44
168,802,634
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cofh.lib.util.comparison; import cofh.lib.util.oredict.OreDictHelper; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; import java.util.List; /** * This is an implementation of a ComparableItemStackNBT - where the oreName/Id is constrained to an allowed subset, specified by the validator. * * @author King Lemming */ public class ComparableItemStackValidatedNBT extends ComparableItemStackNBT { private final OreValidator validator; public ComparableItemStackValidatedNBT(ItemStack stack) { super(stack); this.validator = DEFAULT_VALIDATOR; this.oreID = getOreID(stack); this.oreName = OreDictHelper.getOreName(oreID); } public ComparableItemStackValidatedNBT(ItemStack stack, @Nonnull OreValidator validator) { super(stack); this.validator = validator; this.oreID = getOreID(stack); this.oreName = OreDictHelper.getOreName(oreID); } public int getOreID(ItemStack stack) { List<Integer> ids = OreDictHelper.getAllOreIDs(stack); if (!ids.isEmpty()) { for (Integer id : ids) { if (id != -1 && validator.validate(OreDictHelper.getOreName(id))) { return id; } } } return -1; } public int getOreID(String oreName) { if (!validator.validate(oreName)) { return -1; } return OreDictHelper.getOreID(oreName); } }
UTF-8
Java
1,312
java
ComparableItemStackValidatedNBT.java
Java
[ { "context": " subset, specified by the validator.\n *\n * @author King Lemming\n */\npublic class ComparableItemStackValidatedNBT ", "end": 349, "score": 0.9998576045036316, "start": 337, "tag": "NAME", "value": "King Lemming" } ]
null
[]
package cofh.lib.util.comparison; import cofh.lib.util.oredict.OreDictHelper; import net.minecraft.item.ItemStack; import javax.annotation.Nonnull; import java.util.List; /** * This is an implementation of a ComparableItemStackNBT - where the oreName/Id is constrained to an allowed subset, specified by the validator. * * @author <NAME> */ public class ComparableItemStackValidatedNBT extends ComparableItemStackNBT { private final OreValidator validator; public ComparableItemStackValidatedNBT(ItemStack stack) { super(stack); this.validator = DEFAULT_VALIDATOR; this.oreID = getOreID(stack); this.oreName = OreDictHelper.getOreName(oreID); } public ComparableItemStackValidatedNBT(ItemStack stack, @Nonnull OreValidator validator) { super(stack); this.validator = validator; this.oreID = getOreID(stack); this.oreName = OreDictHelper.getOreName(oreID); } public int getOreID(ItemStack stack) { List<Integer> ids = OreDictHelper.getAllOreIDs(stack); if (!ids.isEmpty()) { for (Integer id : ids) { if (id != -1 && validator.validate(OreDictHelper.getOreName(id))) { return id; } } } return -1; } public int getOreID(String oreName) { if (!validator.validate(oreName)) { return -1; } return OreDictHelper.getOreID(oreName); } }
1,306
0.734756
0.732469
55
22.854546
27.885101
144
false
false
0
0
0
0
0
0
1.490909
false
false
10
6c8427630c6c27c195fa86dae3fdf7aed011e0cb
21,414,707,005,350
2cbe972eed176600f56174f93cde736b703db916
/core/implementations/swordSkills/JellyfishStingImplementations.java
7fece13e752ad8d82f8de669ab6805f9c456d494
[]
no_license
beanowonotanuwu/HydraClass
https://github.com/beanowonotanuwu/HydraClass
2b45cc94b990242df12fb188f3d8c4e40f8ae67e
16fdcb54c3be64dc9b77a0d43689e41a2c0a5d44
refs/heads/master
2022-12-05T09:37:19.109000
2020-09-02T15:17:55
2020-09-02T15:17:55
291,409,431
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hydra.hunter.core.implementations.swordSkills; import hydra.hunter.core.implementations.SkillImplementations; import hydra.hunter.core.vaults.swordSkillsVault.JellyfishStingVault; public interface JellyfishStingImplementations extends SkillImplementations, JellyfishStingVault { }
UTF-8
Java
316
java
JellyfishStingImplementations.java
Java
[]
null
[]
package hydra.hunter.core.implementations.swordSkills; import hydra.hunter.core.implementations.SkillImplementations; import hydra.hunter.core.vaults.swordSkillsVault.JellyfishStingVault; public interface JellyfishStingImplementations extends SkillImplementations, JellyfishStingVault { }
316
0.810127
0.810127
9
33.111111
26.358404
69
false
false
0
0
0
0
0
0
0.444444
false
false
10
206688d71da115b2928db70b1d5da96b9cc5f327
16,750,372,488,074
4402f51f35b8b76898a00a6f83345fcbb05a3699
/src/main/java/com/jcoroutine/core/instrument/JCoroutineTransformer.java
c68b8531595915674234b597419c252d043fca1f
[]
no_license
Kweii/JCoroutine
https://github.com/Kweii/JCoroutine
9edbb8bc0cccd112284c615c635da3ab6439c8e0
a00f3dfbb4796d3a09f00d5c0a1d74c4be86289a
refs/heads/master
2020-04-05T15:00:42.181000
2018-11-12T10:31:02
2018-11-12T10:31:02
156,948,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jcoroutine.core.instrument; import com.jcoroutine.common.tool.JCoroutineTools; import com.jcoroutine.core.callSite.CallSiteAnalyzer; import org.apache.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; import java.security.ProtectionDomain; /** * @author: guiliehua * @description: * @date:2018-09-10 */ public final class JCoroutineTransformer implements ClassFileTransformer { private static Logger logger = Logger.getLogger(JCoroutineTransformer.class); static { CallSiteAnalyzer.preAnalyze(); CallSiteAnalyzer.analyze(); } public static void premain(String options, Instrumentation ins) throws UnmodifiableClassException { ins.addTransformer(new JCoroutineTransformer()); } public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (JCoroutineTools.refersJCoroutinePackage(className)){ return doTransform(classfileBuffer); } return null; } private byte[] doTransform(byte[] classfileBuffer){ ClassReader cr = new ClassReader(classfileBuffer); ClassNode cn = new ClassNode(); cr.accept(cn, 0); for (Object obj : cn.methods) { MethodNode md = (MethodNode) obj; if ("<init>".endsWith(md.name) || "<clinit>".equals(md.name)) { continue; } InsnList insns = md.instructions; InsnList il = new InsnList(); il.add(new FieldInsnNode(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")); il.add(new LdcInsnNode("Enter method-> " + cn.name+"."+md.name)); il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V")); insns.insert(il); InsnList end = new InsnList(); end.add(new FieldInsnNode(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")); end.add(new LdcInsnNode("Leave method->" + cn.name+"."+md.name)); end.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V")); insns.insert(insns.getLast(), end); md.maxStack += 6; } ClassWriter cw = new ClassWriter(0); cn.accept(cw); return cw.toByteArray(); } }
UTF-8
Java
2,942
java
JCoroutineTransformer.java
Java
[ { "context": "ava.security.ProtectionDomain;\r\n\r\n/**\r\n * @author: guiliehua\r\n * @description:\r\n * @date:2018-09-10\r\n */\r\npubl", "end": 612, "score": 0.994574248790741, "start": 603, "tag": "USERNAME", "value": "guiliehua" } ]
null
[]
package com.jcoroutine.core.instrument; import com.jcoroutine.common.tool.JCoroutineTools; import com.jcoroutine.core.callSite.CallSiteAnalyzer; import org.apache.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; import java.security.ProtectionDomain; /** * @author: guiliehua * @description: * @date:2018-09-10 */ public final class JCoroutineTransformer implements ClassFileTransformer { private static Logger logger = Logger.getLogger(JCoroutineTransformer.class); static { CallSiteAnalyzer.preAnalyze(); CallSiteAnalyzer.analyze(); } public static void premain(String options, Instrumentation ins) throws UnmodifiableClassException { ins.addTransformer(new JCoroutineTransformer()); } public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (JCoroutineTools.refersJCoroutinePackage(className)){ return doTransform(classfileBuffer); } return null; } private byte[] doTransform(byte[] classfileBuffer){ ClassReader cr = new ClassReader(classfileBuffer); ClassNode cn = new ClassNode(); cr.accept(cn, 0); for (Object obj : cn.methods) { MethodNode md = (MethodNode) obj; if ("<init>".endsWith(md.name) || "<clinit>".equals(md.name)) { continue; } InsnList insns = md.instructions; InsnList il = new InsnList(); il.add(new FieldInsnNode(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")); il.add(new LdcInsnNode("Enter method-> " + cn.name+"."+md.name)); il.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V")); insns.insert(il); InsnList end = new InsnList(); end.add(new FieldInsnNode(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")); end.add(new LdcInsnNode("Leave method->" + cn.name+"."+md.name)); end.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V")); insns.insert(insns.getLast(), end); md.maxStack += 6; } ClassWriter cw = new ClassWriter(0); cn.accept(cw); return cw.toByteArray(); } }
2,942
0.635622
0.631543
84
33.023811
32.088783
191
false
false
0
0
0
0
0
0
0.761905
false
false
10
e3e55e6fa5d2f6bfc7d25d79dcff988ea2f78145
25,580,825,251,947
3c8d465e076222003e10ca8b100a10be592fe6d9
/src/main/java/exercise/AtlassianExercise.java
d54732eefe79f07590cafdafbabcad0d9c51c781
[]
no_license
amitavabasu/atlassian-exercise
https://github.com/amitavabasu/atlassian-exercise
39160b8b855b76126b82190ca5cfdb4463c242cb
7c881a5fd81332650a1ff066f0146d39bba4c0f6
refs/heads/master
2021-01-20T20:53:37.120000
2016-08-19T22:21:51
2016-08-19T22:21:51
65,860,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exercise; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Phaser; import org.springframework.http.ResponseEntity; import org.springframework.util.concurrent.ListenableFutureCallback; import org.springframework.web.client.AsyncRestTemplate; import exercise.model.Issue; import exercise.model.IssueType; public class AtlassianExercise { private String HOST = null; //Used for calling REST API Asynchronously private AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); //Used for storing the final result <issue type>:<total estimate> as key value. Needs concurrent hash map as will be modified //and read concurrently within multiple rest call processing at different times. private Map<String, Integer> totalEstimateByIssueType = new ConcurrentHashMap<String, Integer>(); //will be using to keep track of total number of anync. request/thread started and ended in calling sequence to traverse rest api data. private Phaser phaser = new Phaser(); //Issue type listener - will execute on call back of issue type rest request. private ListenableFutureCallback<ResponseEntity<IssueType>> issueTypeListner = new ListenableFutureCallback<ResponseEntity<IssueType>>() { @Override public void onSuccess(ResponseEntity<IssueType> entity) { IssueType issueType = entity.getBody(); String[] issues = issueType.getIssues(); if(issues!=null && issues.length > 0){ //register total number of calls to be made asynchronously to get all issue details phaser.bulkRegister(issues.length); for(String issueUri:issues){ asyncRestTemplate.getForEntity(HOST+issueUri, Issue.class).addCallback(issueListner); } } //unregister as one rest issue type call completed processed successfully phaser.arriveAndDeregister(); } @Override public void onFailure(Throwable t) { System.out.println("Exception calling rest service: " +t.getLocalizedMessage()); //unregister as one rest call completed but failed (due to any reason, not trying to track errors) phaser.arriveAndDeregister(); } }; //Issue listener - will execute on call back of issue details...? rest request. private ListenableFutureCallback<ResponseEntity<Issue>> issueListner = new ListenableFutureCallback<ResponseEntity<Issue>>() { @Override public void onSuccess(ResponseEntity<Issue> entity) { Issue issue = entity.getBody(); incrementTotalEstimate(issue.getIssuetype(), issue.getEstimate()); //unregister as one rest issue details call completed - processed successfully phaser.arriveAndDeregister(); } @Override public void onFailure(Throwable t) { System.out.println("Exception calling rest service: " +t.getLocalizedMessage()); //unregister as one rest call completed but failed (NO ERROR tracking at this point) phaser.arriveAndDeregister(); } }; /* * Method to read update store totalEstimateByIssueType Synchronously by blocking threads who want to increment totalEstimate-By-IssueType at the same time. * */ public void incrementTotalEstimate(String issueType, Integer estimate){ synchronized(totalEstimateByIssueType){ Integer currentTotalEstimate = totalEstimateByIssueType.get(issueType); //Calculate and store total estimate if(estimate==null){ totalEstimateByIssueType.put(issueType, estimate); }else{ totalEstimateByIssueType.put(issueType, currentTotalEstimate+estimate); } } } /* * Method to print final result from the map - totalEstimateByIssueType * */ private void printResult(){ if(totalEstimateByIssueType.size()==0){ System.out.println("No result to print"); }else{ Set<String> keys = totalEstimateByIssueType.keySet(); for(String key:keys){ Integer totalEstimate = totalEstimateByIssueType.get(key); System.out.println(key.substring(key.lastIndexOf('/')+1)+":"+totalEstimate); } } } //TEST METHOD public Map<String, Integer> testMethod(String host, List<String> issueTypes){ HOST = host; phaser.bulkRegister(issueTypes.size()+1); for(String issueType:issueTypes){ totalEstimateByIssueType.put("/issuetypes/"+issueType, 0); asyncRestTemplate.getForEntity(HOST+"/issuetypes/"+issueType, IssueType.class).addCallback(issueTypeListner); } phaser.arriveAndAwaitAdvance(); printResult(); return totalEstimateByIssueType; } //MAIN // public static void main(String[] args){ // // Process provided input for correctness and invoke test method on an instance // if(args.length == 0) // System.exit(0); // String host = args[0].trim(); // List<String> issueTypes = new ArrayList<String>(); // for(int i=1; i<args.length; i++){ // issueTypes.add(args[i]); // } // if(issueTypes.size()==0) // System.exit(0); // new AtlassianExercise().testMethod(host, issueTypes); // } }
UTF-8
Java
4,976
java
AtlassianExercise.java
Java
[]
null
[]
package exercise; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Phaser; import org.springframework.http.ResponseEntity; import org.springframework.util.concurrent.ListenableFutureCallback; import org.springframework.web.client.AsyncRestTemplate; import exercise.model.Issue; import exercise.model.IssueType; public class AtlassianExercise { private String HOST = null; //Used for calling REST API Asynchronously private AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); //Used for storing the final result <issue type>:<total estimate> as key value. Needs concurrent hash map as will be modified //and read concurrently within multiple rest call processing at different times. private Map<String, Integer> totalEstimateByIssueType = new ConcurrentHashMap<String, Integer>(); //will be using to keep track of total number of anync. request/thread started and ended in calling sequence to traverse rest api data. private Phaser phaser = new Phaser(); //Issue type listener - will execute on call back of issue type rest request. private ListenableFutureCallback<ResponseEntity<IssueType>> issueTypeListner = new ListenableFutureCallback<ResponseEntity<IssueType>>() { @Override public void onSuccess(ResponseEntity<IssueType> entity) { IssueType issueType = entity.getBody(); String[] issues = issueType.getIssues(); if(issues!=null && issues.length > 0){ //register total number of calls to be made asynchronously to get all issue details phaser.bulkRegister(issues.length); for(String issueUri:issues){ asyncRestTemplate.getForEntity(HOST+issueUri, Issue.class).addCallback(issueListner); } } //unregister as one rest issue type call completed processed successfully phaser.arriveAndDeregister(); } @Override public void onFailure(Throwable t) { System.out.println("Exception calling rest service: " +t.getLocalizedMessage()); //unregister as one rest call completed but failed (due to any reason, not trying to track errors) phaser.arriveAndDeregister(); } }; //Issue listener - will execute on call back of issue details...? rest request. private ListenableFutureCallback<ResponseEntity<Issue>> issueListner = new ListenableFutureCallback<ResponseEntity<Issue>>() { @Override public void onSuccess(ResponseEntity<Issue> entity) { Issue issue = entity.getBody(); incrementTotalEstimate(issue.getIssuetype(), issue.getEstimate()); //unregister as one rest issue details call completed - processed successfully phaser.arriveAndDeregister(); } @Override public void onFailure(Throwable t) { System.out.println("Exception calling rest service: " +t.getLocalizedMessage()); //unregister as one rest call completed but failed (NO ERROR tracking at this point) phaser.arriveAndDeregister(); } }; /* * Method to read update store totalEstimateByIssueType Synchronously by blocking threads who want to increment totalEstimate-By-IssueType at the same time. * */ public void incrementTotalEstimate(String issueType, Integer estimate){ synchronized(totalEstimateByIssueType){ Integer currentTotalEstimate = totalEstimateByIssueType.get(issueType); //Calculate and store total estimate if(estimate==null){ totalEstimateByIssueType.put(issueType, estimate); }else{ totalEstimateByIssueType.put(issueType, currentTotalEstimate+estimate); } } } /* * Method to print final result from the map - totalEstimateByIssueType * */ private void printResult(){ if(totalEstimateByIssueType.size()==0){ System.out.println("No result to print"); }else{ Set<String> keys = totalEstimateByIssueType.keySet(); for(String key:keys){ Integer totalEstimate = totalEstimateByIssueType.get(key); System.out.println(key.substring(key.lastIndexOf('/')+1)+":"+totalEstimate); } } } //TEST METHOD public Map<String, Integer> testMethod(String host, List<String> issueTypes){ HOST = host; phaser.bulkRegister(issueTypes.size()+1); for(String issueType:issueTypes){ totalEstimateByIssueType.put("/issuetypes/"+issueType, 0); asyncRestTemplate.getForEntity(HOST+"/issuetypes/"+issueType, IssueType.class).addCallback(issueTypeListner); } phaser.arriveAndAwaitAdvance(); printResult(); return totalEstimateByIssueType; } //MAIN // public static void main(String[] args){ // // Process provided input for correctness and invoke test method on an instance // if(args.length == 0) // System.exit(0); // String host = args[0].trim(); // List<String> issueTypes = new ArrayList<String>(); // for(int i=1; i<args.length; i++){ // issueTypes.add(args[i]); // } // if(issueTypes.size()==0) // System.exit(0); // new AtlassianExercise().testMethod(host, issueTypes); // } }
4,976
0.738947
0.736736
130
37.276924
35.303524
159
false
false
0
0
0
0
0
0
2.1
false
false
10
8e86cf97488ec457ad9e6d4531c2bec3bd02f4b9
17,042,430,266,248
a1820d9b2e33d02ef89fdd2070491a5065c0cf89
/enode-common/src/main/java/com/kunlv/ddd/j/enode/common/serializing/IJsonSerializer.java
792ac7d24c333471a969050940dd7e7655d30506
[]
no_license
bellmit/JGEnode
https://github.com/bellmit/JGEnode
5b9ea789532ad91f688a7a154a4600dbed192e07
1dbf2740996ebc032e78ad37acbb9fe5306f765d
refs/heads/master
2022-02-17T07:10:14.414000
2019-09-13T19:32:45
2019-09-13T19:32:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kunlv.ddd.j.enode.common.serializing; public interface IJsonSerializer { String serialize(Object obj); <T> T deserialize(String aSerialization, final Class<T> aType); }
UTF-8
Java
191
java
IJsonSerializer.java
Java
[]
null
[]
package com.kunlv.ddd.j.enode.common.serializing; public interface IJsonSerializer { String serialize(Object obj); <T> T deserialize(String aSerialization, final Class<T> aType); }
191
0.753927
0.753927
7
26.285715
24.78314
67
false
false
0
0
0
0
0
0
0.571429
false
false
10
8ecdb6d15f454225aab583eaf8c85315186bc2db
17,042,430,266,252
556643d73371ba9b09111cc65ec422f248e14248
/src/classes/ContaController.java
5d839aa16d54c0ab0a3d087535264cd8e15a8612
[]
no_license
samaratg/projeto-conta-corrente
https://github.com/samaratg/projeto-conta-corrente
d7c7d74f3e55fd29802bc5b04087f572e36003f0
513209326a2bb5df3699e1542433f6a7ef4735ee
refs/heads/main
2023-03-22T06:39:41.812000
2021-03-18T16:37:51
2021-03-18T16:37:51
349,145,455
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package classes; import java.util.ArrayList; import java.util.List; import exception.NumeroContaException; import exception.SaldoInsuficienteException; public class ContaController { public List<Conta> lista = new ArrayList<>(); // private void preencherLista() { // Pessoa p1 = new Pessoa("Faris","f@mail.com","065"); // Pessoa p2 = new Pessoa("Faradh","fh@mail.com","015"); // Pessoa p3 = new Pessoa("Samara","s@mail.com","035"); // Pessoa p4 = new Pessoa("Empresa","emp@mail.com","015"); // Conta c1 = new Conta(90,-12.0,"pf", p1); // Conta c4 = new Conta(93,1000.0,"pf",p2); // Conta c2 = new Conta(91,120.0,"pf",p3); // Conta c3 = new Conta(92,3000.0,"pj",p4); // // adicionar(c1); // adicionar(c2); // adicionar(c3); // adicionar(c4); // } // public ContaController() { // //TODO Remover em caso de sistema em produção // this.preencherLista(); // } public void adicionar(Conta conta) { this.lista.add(conta); } public boolean existeNumero(int numero) { for (Conta conta : lista) { if (numero == conta.getNumero()) { return true; } } return false; } public void remove(int numero) { if (existeNumero(numero)) { for (Conta conta : lista) { System.out.println("CONTA REMOVIDA: "); lista.remove(conta); System.out.println(conta); break; } } else { System.out.println("Número de conta não encontrada"); } } public void listarContas() { for (Conta conta : lista) { System.out.println(conta); } } public List<Conta> listaContasTipo(String tipo) { List<Conta> listaTipos = new ArrayList<>(); for (Conta conta : lista) { if (conta.getTipo().equals(tipo.toLowerCase()) || conta.getTipo().equals(tipo.toUpperCase())) { listaTipos.add(conta); } } return listaTipos; } public List<Conta> listaSaldoNegativo() { List<Conta> listaNeg = new ArrayList<>(); for (Conta conta : lista) { if (conta.getSaldo() < 0.0) { listaNeg.add(conta); } } return listaNeg; } public List<Conta> listaClientesInvest() { List<Conta> listaInvest = new ArrayList<>(); for (Conta conta : lista) { if (conta.getSaldo() > 2000.00) { listaInvest.add(conta); } } return listaInvest; } public List<Conta> filtrar(int codigo, String nome, String cpf_cnpj) { List<Conta> listAux = new ArrayList<Conta>(); for (Conta conta : this.lista) { if (codigo != 0 && nome != null && cpf_cnpj != null) { if (codigo == conta.getNumero() && nome.equals(conta.getPessoa().getNome()) && cpf_cnpj.equals(conta.getPessoa().getCpf_cnpj())) {//contains listAux.add(conta); } }else { if ((codigo == conta.getNumero()) || (nome != null && nome.equals(conta.getPessoa().getNome())) || (cpf_cnpj != null && cpf_cnpj.equals(conta.getPessoa().getCpf_cnpj()))) { listAux.add(conta); } } } return listAux; } public List<Conta> filtrarPorNumero(int numero){ return filtrar(numero, null, null); } public List<Conta> filtrarPorNome(String nome){ return filtrar(0, nome, null); } public List<Conta> filtrarPorCpfCnpj(String cpfCnpj){ return filtrar(0, null, cpfCnpj); } public void deposito(int numero, double valor) { if (valor < 0) { throw new IllegalArgumentException("Não posso depositar um valor negativo!"); } if (!existeNumero(numero)) { throw new NumeroContaException("Número de conta não encontrada!"); } for (Conta conta : lista) { if (conta.getNumero() == numero) { conta.setSaldo(conta.getSaldo() + valor); System.out.println("Depósito realizado com sucesso!"); } } } public void saque(int numero, double valor) { if (valor < 0) { throw new IllegalArgumentException("Não posso sacar um valor negativo!"); } if (!existeNumero(numero)) { throw new NumeroContaException("Número de conta não encontrada!"); } Conta conta2 = filtrarPorNumero(numero).get(0); if (valor < conta2.getSaldo()) { for (Conta conta : lista) { if (conta.getNumero() == numero) { conta.setSaldo(conta.getSaldo() - valor); } } } else { throw new SaldoInsuficienteException("Saldo Insuficiente, tente um valor menor que " + conta2.getSaldo()); } } public void transferir(int origem, int destino, double valor) { if (valor < 0) { throw new IllegalArgumentException("Não posso sacar um valor negativo!"); } if (!existeNumero(origem)) { throw new NumeroContaException("Número de conta não encontrada!"); } if (!existeNumero(destino)) { throw new NumeroContaException("Número de conta não encontrada!"); } Conta contaOrigem = filtrarPorNumero(origem).get(0); if (valor < contaOrigem.getSaldo()) { for (Conta conta : lista) { if (conta.getNumero() == origem) { conta.setSaldo(conta.getSaldo() - valor); } if (conta.getNumero() == destino) { conta.setSaldo(conta.getSaldo() + valor); } } } else { throw new SaldoInsuficienteException( "Saldo Insuficiente, tente um valor menor que " + contaOrigem.getSaldo()); } } public boolean existeCpfCnpj(String cpf_cnpj) { for (Conta c : lista) { if (cpf_cnpj.equals(c.getPessoa().getCpf_cnpj())) { System.out.println("CPF/CNPJ já cadastrado!"); return true; } } return false; } public void imprimeLista(List<Conta> contas) { for (Conta conta : contas) { System.out.println(conta); } } }
ISO-8859-1
Java
5,397
java
ContaController.java
Java
[ { "context": "id preencherLista() {\n//\t\tPessoa p1 = new Pessoa(\"Faris\",\"f@mail.com\",\"065\");\n//\t\tPessoa p2 = new Pessoa(", "end": 303, "score": 0.9998564124107361, "start": 298, "tag": "NAME", "value": "Faris" }, { "context": "cherLista() {\n//\t\tPessoa p1 = new Pessoa(\"Faris\",\"f@mail.com\",\"065\");\n//\t\tPessoa p2 = new Pessoa(\"Faradh\",\"fh@", "end": 316, "score": 0.999921441078186, "start": 306, "tag": "EMAIL", "value": "f@mail.com" }, { "context": ",\"f@mail.com\",\"065\");\n//\t\tPessoa p2 = new Pessoa(\"Faradh\",\"fh@mail.com\",\"015\");\n//\t\tPessoa p3 = new Pessoa", "end": 360, "score": 0.9998429417610168, "start": 354, "tag": "NAME", "value": "Faradh" }, { "context": "com\",\"065\");\n//\t\tPessoa p2 = new Pessoa(\"Faradh\",\"fh@mail.com\",\"015\");\n//\t\tPessoa p3 = new Pessoa(\"Samara\",\"s@m", "end": 374, "score": 0.9999245405197144, "start": 363, "tag": "EMAIL", "value": "fh@mail.com" }, { "context": "\"fh@mail.com\",\"015\");\n//\t\tPessoa p3 = new Pessoa(\"Samara\",\"s@mail.com\",\"035\");\n//\t\tPessoa p4 = new Pessoa(", "end": 418, "score": 0.9998360872268677, "start": 412, "tag": "NAME", "value": "Samara" }, { "context": "com\",\"015\");\n//\t\tPessoa p3 = new Pessoa(\"Samara\",\"s@mail.com\",\"035\");\n//\t\tPessoa p4 = new Pessoa(\"Empresa\",\"em", "end": 431, "score": 0.9999213218688965, "start": 421, "tag": "EMAIL", "value": "s@mail.com" }, { "context": "om\",\"035\");\n//\t\tPessoa p4 = new Pessoa(\"Empresa\",\"emp@mail.com\",\"015\");\n//\t\tConta c1 = new Conta(90,-12.0,\"pf\", ", "end": 491, "score": 0.9999247789382935, "start": 479, "tag": "EMAIL", "value": "emp@mail.com" } ]
null
[]
package classes; import java.util.ArrayList; import java.util.List; import exception.NumeroContaException; import exception.SaldoInsuficienteException; public class ContaController { public List<Conta> lista = new ArrayList<>(); // private void preencherLista() { // Pessoa p1 = new Pessoa("Faris","<EMAIL>","065"); // Pessoa p2 = new Pessoa("Faradh","<EMAIL>","015"); // Pessoa p3 = new Pessoa("Samara","<EMAIL>","035"); // Pessoa p4 = new Pessoa("Empresa","<EMAIL>","015"); // Conta c1 = new Conta(90,-12.0,"pf", p1); // Conta c4 = new Conta(93,1000.0,"pf",p2); // Conta c2 = new Conta(91,120.0,"pf",p3); // Conta c3 = new Conta(92,3000.0,"pj",p4); // // adicionar(c1); // adicionar(c2); // adicionar(c3); // adicionar(c4); // } // public ContaController() { // //TODO Remover em caso de sistema em produção // this.preencherLista(); // } public void adicionar(Conta conta) { this.lista.add(conta); } public boolean existeNumero(int numero) { for (Conta conta : lista) { if (numero == conta.getNumero()) { return true; } } return false; } public void remove(int numero) { if (existeNumero(numero)) { for (Conta conta : lista) { System.out.println("CONTA REMOVIDA: "); lista.remove(conta); System.out.println(conta); break; } } else { System.out.println("Número de conta não encontrada"); } } public void listarContas() { for (Conta conta : lista) { System.out.println(conta); } } public List<Conta> listaContasTipo(String tipo) { List<Conta> listaTipos = new ArrayList<>(); for (Conta conta : lista) { if (conta.getTipo().equals(tipo.toLowerCase()) || conta.getTipo().equals(tipo.toUpperCase())) { listaTipos.add(conta); } } return listaTipos; } public List<Conta> listaSaldoNegativo() { List<Conta> listaNeg = new ArrayList<>(); for (Conta conta : lista) { if (conta.getSaldo() < 0.0) { listaNeg.add(conta); } } return listaNeg; } public List<Conta> listaClientesInvest() { List<Conta> listaInvest = new ArrayList<>(); for (Conta conta : lista) { if (conta.getSaldo() > 2000.00) { listaInvest.add(conta); } } return listaInvest; } public List<Conta> filtrar(int codigo, String nome, String cpf_cnpj) { List<Conta> listAux = new ArrayList<Conta>(); for (Conta conta : this.lista) { if (codigo != 0 && nome != null && cpf_cnpj != null) { if (codigo == conta.getNumero() && nome.equals(conta.getPessoa().getNome()) && cpf_cnpj.equals(conta.getPessoa().getCpf_cnpj())) {//contains listAux.add(conta); } }else { if ((codigo == conta.getNumero()) || (nome != null && nome.equals(conta.getPessoa().getNome())) || (cpf_cnpj != null && cpf_cnpj.equals(conta.getPessoa().getCpf_cnpj()))) { listAux.add(conta); } } } return listAux; } public List<Conta> filtrarPorNumero(int numero){ return filtrar(numero, null, null); } public List<Conta> filtrarPorNome(String nome){ return filtrar(0, nome, null); } public List<Conta> filtrarPorCpfCnpj(String cpfCnpj){ return filtrar(0, null, cpfCnpj); } public void deposito(int numero, double valor) { if (valor < 0) { throw new IllegalArgumentException("Não posso depositar um valor negativo!"); } if (!existeNumero(numero)) { throw new NumeroContaException("Número de conta não encontrada!"); } for (Conta conta : lista) { if (conta.getNumero() == numero) { conta.setSaldo(conta.getSaldo() + valor); System.out.println("Depósito realizado com sucesso!"); } } } public void saque(int numero, double valor) { if (valor < 0) { throw new IllegalArgumentException("Não posso sacar um valor negativo!"); } if (!existeNumero(numero)) { throw new NumeroContaException("Número de conta não encontrada!"); } Conta conta2 = filtrarPorNumero(numero).get(0); if (valor < conta2.getSaldo()) { for (Conta conta : lista) { if (conta.getNumero() == numero) { conta.setSaldo(conta.getSaldo() - valor); } } } else { throw new SaldoInsuficienteException("Saldo Insuficiente, tente um valor menor que " + conta2.getSaldo()); } } public void transferir(int origem, int destino, double valor) { if (valor < 0) { throw new IllegalArgumentException("Não posso sacar um valor negativo!"); } if (!existeNumero(origem)) { throw new NumeroContaException("Número de conta não encontrada!"); } if (!existeNumero(destino)) { throw new NumeroContaException("Número de conta não encontrada!"); } Conta contaOrigem = filtrarPorNumero(origem).get(0); if (valor < contaOrigem.getSaldo()) { for (Conta conta : lista) { if (conta.getNumero() == origem) { conta.setSaldo(conta.getSaldo() - valor); } if (conta.getNumero() == destino) { conta.setSaldo(conta.getSaldo() + valor); } } } else { throw new SaldoInsuficienteException( "Saldo Insuficiente, tente um valor menor que " + contaOrigem.getSaldo()); } } public boolean existeCpfCnpj(String cpf_cnpj) { for (Conta c : lista) { if (cpf_cnpj.equals(c.getPessoa().getCpf_cnpj())) { System.out.println("CPF/CNPJ já cadastrado!"); return true; } } return false; } public void imprimeLista(List<Conta> contas) { for (Conta conta : contas) { System.out.println(conta); } } }
5,382
0.645167
0.631784
207
24.990337
23.222925
109
false
false
0
0
0
0
0
0
2.628019
false
false
10
74fdc0a1df613cfb73ba2add13eae2bd634a956a
11,450,382,863,168
b8e323eca953d88446aca904fae0bd3f73b8803a
/GuoLeetCode/src/NumberOfBoomeranges.java
ba258b8d0781cccdca5fa57ab32480127a064901
[]
no_license
guowenyu999/leetcode
https://github.com/guowenyu999/leetcode
88a44d9886815159bc8ff679021a0e1edd3ccc43
09ddb985f40ba125097c4f1995cf7fbdea591ff8
refs/heads/master
2021-01-12T06:23:58.109000
2017-06-03T08:20:47
2017-06-03T08:20:47
77,353,377
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.HashMap; import java.util.Map; public class NumberOfBoomeranges { public static int numberOfBoomerangs(int[][] points) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int sum = 0; for (int i = 0; i < points.length; i++) { for (int j = 0; j < points.length; j++) { if (i == j) { continue; } int dis = getdistance(points[i], points[j]); if (map.containsKey(dis)) { map.put(dis, map.get(dis) + 1); } else { map.put(dis, 1); } } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() > 1) { sum += entry.getValue() * (entry.getValue() - 1); } } map.clear(); } return sum; } public static int getdistance(int a[], int b[]) { int x = a[0] - b[0]; int y = a[1] - b[1]; int sum = x * x + y * y; return sum; } public static void main(String[] args) { int[][] num = new int[3][2]; num[0][0] = 0; num[0][1] = 0; num[1][0] = 1; num[1][1] = 0; num[2][0] = 2; num[2][1] = 0; System.out.println(numberOfBoomerangs(num)); } }
UTF-8
Java
1,128
java
NumberOfBoomeranges.java
Java
[]
null
[]
import java.util.HashMap; import java.util.Map; public class NumberOfBoomeranges { public static int numberOfBoomerangs(int[][] points) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int sum = 0; for (int i = 0; i < points.length; i++) { for (int j = 0; j < points.length; j++) { if (i == j) { continue; } int dis = getdistance(points[i], points[j]); if (map.containsKey(dis)) { map.put(dis, map.get(dis) + 1); } else { map.put(dis, 1); } } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() > 1) { sum += entry.getValue() * (entry.getValue() - 1); } } map.clear(); } return sum; } public static int getdistance(int a[], int b[]) { int x = a[0] - b[0]; int y = a[1] - b[1]; int sum = x * x + y * y; return sum; } public static void main(String[] args) { int[][] num = new int[3][2]; num[0][0] = 0; num[0][1] = 0; num[1][0] = 1; num[1][1] = 0; num[2][0] = 2; num[2][1] = 0; System.out.println(numberOfBoomerangs(num)); } }
1,128
0.52305
0.495567
49
21.020409
17.910765
62
false
false
0
0
0
0
0
0
2.877551
false
false
10
c878e00d364f8a4cb707789d41670fe93267a09e
21,509,196,246,608
1d8bd0efb0903dd91288b653856144c9a92e729e
/OldExams/SimulazioneEsame-Favoliere-TaglianiMichele-0000978601/test/favoliere/controller/test/MyControllerTest.java
8463d0a65b17c91c085d62b7c1db452d9b3e12bc
[]
no_license
taglioIsCoding/LearnJava
https://github.com/taglioIsCoding/LearnJava
7c3026f2dea2a54ea6c5ad0965038f77d8004b65
3b34d8e2e01cf018106579c7b53668862bcfb776
refs/heads/main
2023-07-11T05:00:17.010000
2021-08-17T10:42:28
2021-08-17T10:42:28
343,448,023
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package favoliere.controller.test; import static org.junit.jupiter.api.Assertions.*; import java.util.Optional; import org.junit.jupiter.api.*; import favoliere.controller.Controller; import favoliere.controller.MyController; import favoliere.model.FasciaEta; import favoliere.model.Favola; import favoliere.model.Impressionabilita; public class MyControllerTest { private Controller controller; @BeforeEach public void genController() { //test del costruttore testa anche il metodo load controller = new MyController(new PersonaggiLoaderMock(), "Personaggi.txt", new ScenariLoaderMock(), "Scenari.txt", new AzioniLoaderMock(), "Azioni.txt", new ConclusioniLoaderMock(), "Conclusioni.txt","Favola.txt"); } @Test public void testGetImpressionabilita() { assertArrayEquals(controller.getLivelliImpressionabilita(),Impressionabilita.values()); } @Test public void testGetFasceEta() { assertArrayEquals(controller.getFasceEta(), FasciaEta.values()); } @Test public void testGetOutputFileName() { assertEquals(controller.getOutputFileName(), "Favola.txt"); } @Test public void testGeneraFavola() { Optional<Favola> favola = controller.generaFavola(FasciaEta.GRANDE,Impressionabilita.PERNULLA_IMPRESSIONABILE); assertTrue(favola.isPresent()); Optional<Favola> favolaEmpty = controller.generaFavola(FasciaEta.PICCOLISSIMO,Impressionabilita.MOLTO_IMPRESSIONABILE); assertFalse(favolaEmpty.isPresent()); } }
UTF-8
Java
1,456
java
MyControllerTest.java
Java
[]
null
[]
package favoliere.controller.test; import static org.junit.jupiter.api.Assertions.*; import java.util.Optional; import org.junit.jupiter.api.*; import favoliere.controller.Controller; import favoliere.controller.MyController; import favoliere.model.FasciaEta; import favoliere.model.Favola; import favoliere.model.Impressionabilita; public class MyControllerTest { private Controller controller; @BeforeEach public void genController() { //test del costruttore testa anche il metodo load controller = new MyController(new PersonaggiLoaderMock(), "Personaggi.txt", new ScenariLoaderMock(), "Scenari.txt", new AzioniLoaderMock(), "Azioni.txt", new ConclusioniLoaderMock(), "Conclusioni.txt","Favola.txt"); } @Test public void testGetImpressionabilita() { assertArrayEquals(controller.getLivelliImpressionabilita(),Impressionabilita.values()); } @Test public void testGetFasceEta() { assertArrayEquals(controller.getFasceEta(), FasciaEta.values()); } @Test public void testGetOutputFileName() { assertEquals(controller.getOutputFileName(), "Favola.txt"); } @Test public void testGeneraFavola() { Optional<Favola> favola = controller.generaFavola(FasciaEta.GRANDE,Impressionabilita.PERNULLA_IMPRESSIONABILE); assertTrue(favola.isPresent()); Optional<Favola> favolaEmpty = controller.generaFavola(FasciaEta.PICCOLISSIMO,Impressionabilita.MOLTO_IMPRESSIONABILE); assertFalse(favolaEmpty.isPresent()); } }
1,456
0.783654
0.783654
48
29.333334
32.933857
121
false
false
0
0
0
0
0
0
1.604167
false
false
10
79418102528fc07ad3a3c162c70c719c2d5eba72
25,769,838,009
de6e0405e658df217250c49744af318a724b9828
/dmc-dao/src/main/java/com/cmos/dmc/dao/myAttetion/VisitTop10Dao.java
cef6fdf911d52d85c4feced99c07b006933921a4
[]
no_license
dmcaqsars/dmc_parent
https://github.com/dmcaqsars/dmc_parent
47999438e7ba3d092576791d8efbede6f68d681a
efcaf14745f0f8dac7378081add2930026ffda86
refs/heads/master
2018-10-22T11:21:34.276000
2018-06-26T07:28:47
2018-06-26T07:28:47
138,607,932
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cmos.dmc.dao.myAttetion; import java.util.List; import java.util.Map; public interface VisitTop10Dao { List queryTop10ztDetail(Map<String,Object> map); List queryTop10rptDetail(Map<String,Object> map); List queryTop10idxDetail(Map<String,Object> map); List queryTop10mrptDetail(Map<String,Object> map); }
UTF-8
Java
336
java
VisitTop10Dao.java
Java
[]
null
[]
package com.cmos.dmc.dao.myAttetion; import java.util.List; import java.util.Map; public interface VisitTop10Dao { List queryTop10ztDetail(Map<String,Object> map); List queryTop10rptDetail(Map<String,Object> map); List queryTop10idxDetail(Map<String,Object> map); List queryTop10mrptDetail(Map<String,Object> map); }
336
0.764881
0.735119
12
27
21.863211
54
false
false
0
0
0
0
0
0
0.916667
false
false
10
4ebe8e248ff0d7209670d1e20dca2b35d44c2222
6,459,630,829,781
056fe6f8c30a54b07fec80e66ede1ac5fcd3ad1d
/src/com/ns/neo/dao/jpa/NameQueryInvoke.java
843eeed2adc3f3e1a7594b7a062e6409da41cec0
[]
no_license
githubQQ/wzcx
https://github.com/githubQQ/wzcx
c6930bb6f1ba894d045030a745b8ff9588fda262
947f470276e097447d8ef06cdde6d91e430ffbcd
refs/heads/master
2019-01-02T01:56:41.077000
2015-06-24T01:19:21
2015-06-24T01:19:21
37,698,048
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ns.neo.dao.jpa; import java.util.List; import javax.persistence.TypedQuery; /** * Created by zzm on 15/2/9. */ public interface NameQueryInvoke { public List excuteQuery(TypedQuery typedQuery); }
UTF-8
Java
217
java
NameQueryInvoke.java
Java
[ { "context": "t javax.persistence.TypedQuery;\n\n/**\n * Created by zzm on 15/2/9.\n */\npublic interface NameQueryInvoke {", "end": 112, "score": 0.999634861946106, "start": 109, "tag": "USERNAME", "value": "zzm" } ]
null
[]
package com.ns.neo.dao.jpa; import java.util.List; import javax.persistence.TypedQuery; /** * Created by zzm on 15/2/9. */ public interface NameQueryInvoke { public List excuteQuery(TypedQuery typedQuery); }
217
0.737327
0.718894
12
17.083334
17.240738
51
false
false
0
0
0
0
0
0
0.333333
false
false
10
c28862ed8ca35fe4c3d797dec692fbee47f1bca1
17,360,257,845,344
68c3a929801c13770ceae9497184206630611da2
/wr/src/main/java/wordroot/wr/service/UserService.java
4b4fb218f20a3dea38204d92587d9946974ec5c7
[]
no_license
StephenCurryMVP/wordRoot
https://github.com/StephenCurryMVP/wordRoot
7722d3e9567dd0e26ec31669a58335ca3598f0f5
359d46cb5713af6ad7bab30c2a6829e580d5a482
refs/heads/master
2022-11-23T23:54:55.133000
2020-08-01T13:36:15
2020-08-01T13:36:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wordroot.wr.service; import org.apache.shiro.crypto.hash.SimpleHash; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.util.HtmlUtils; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import wordroot.wr.Mapper.UserMapper; import wordroot.wr.bean.User; import java.util.Date; import java.util.List; /** * @auctor wuliang * @date 2020/7/21 */ @Service public class UserService { @Autowired UserMapper userMapper; public boolean isExist(int id){ User user = userMapper.getId(id); return null != user; } public User findUserId(int id){ return userMapper.getId(id); } public User findUserName(String name){ return userMapper.getUserName(name); } public int signup(User user){ String userName = user.getUsername(); String userEmail = user.getEmail(); String userPassword = user.getPassword(); Date date = new java.sql.Date(new java.util.Date().getTime()); user.setGmt_create(date); user.setGmt_modified(date); /** * 这里做处理,防止XSS攻击 */ userName = HtmlUtils.htmlEscape(userName); user.setUsername(userName); userEmail = HtmlUtils.htmlEscape(userEmail); user.setEmail(userEmail); user.setEnabled(true); if(userName.equals("") || userPassword.equals("")){ return 0; } /** * 这里简单做下处理,默认生成16位盐 */ String salt = new SecureRandomNumberGenerator().nextBytes().toString(); int times = 2; String encodeedPasssword = new SimpleHash("md5",userPassword,salt,times).toString(); user.setSalt(salt); user.setSalt(encodeedPasssword); userMapper.insert(user); return 1; } /** * 更新用户状态 * */ public void updateUserStatus(User user){ User userID = userMapper.update(user); userID.setEnabled(userID.isEnabled()); userMapper.insert(userID); } /** * 编辑用户信息 */ public void editUser(User user){ User userID = userMapper.getId(user.getId()); userID.setUsername(user.getUsername()); userID.setPassword(user.getPassword()); userID.setEmail(user.getEmail()); userID.setGmt_modified(user.getGmt_modified()); userMapper.insert(user); } /** * 根据ID删除用户 */ public void deteleById(int id){ userMapper.delete(id); } }
UTF-8
Java
2,644
java
UserService.java
Java
[ { "context": ".util.Date;\nimport java.util.List;\n\n/**\n * @auctor wuliang\n * @date 2020/7/21\n */\n\n@Service\npublic class Use", "end": 433, "score": 0.999607264995575, "start": 426, "tag": "USERNAME", "value": "wuliang" }, { "context": "Id(user.getId());\n userID.setUsername(user.getUsername());\n userID.setPassword(user.getPassword()", "end": 2259, "score": 0.4305579960346222, "start": 2248, "tag": "USERNAME", "value": "getUsername" }, { "context": "e(user.getUsername());\n userID.setPassword(user.getPassword());\n userID.setEmail(user.getE", "end": 2295, "score": 0.871597945690155, "start": 2291, "tag": "PASSWORD", "value": "user" }, { "context": "r.getUsername());\n userID.setPassword(user.getPassword());\n userID.setEmail(user.getEmail());\n ", "end": 2307, "score": 0.9445275068283081, "start": 2296, "tag": "PASSWORD", "value": "getPassword" } ]
null
[]
package wordroot.wr.service; import org.apache.shiro.crypto.hash.SimpleHash; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.util.HtmlUtils; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import wordroot.wr.Mapper.UserMapper; import wordroot.wr.bean.User; import java.util.Date; import java.util.List; /** * @auctor wuliang * @date 2020/7/21 */ @Service public class UserService { @Autowired UserMapper userMapper; public boolean isExist(int id){ User user = userMapper.getId(id); return null != user; } public User findUserId(int id){ return userMapper.getId(id); } public User findUserName(String name){ return userMapper.getUserName(name); } public int signup(User user){ String userName = user.getUsername(); String userEmail = user.getEmail(); String userPassword = user.getPassword(); Date date = new java.sql.Date(new java.util.Date().getTime()); user.setGmt_create(date); user.setGmt_modified(date); /** * 这里做处理,防止XSS攻击 */ userName = HtmlUtils.htmlEscape(userName); user.setUsername(userName); userEmail = HtmlUtils.htmlEscape(userEmail); user.setEmail(userEmail); user.setEnabled(true); if(userName.equals("") || userPassword.equals("")){ return 0; } /** * 这里简单做下处理,默认生成16位盐 */ String salt = new SecureRandomNumberGenerator().nextBytes().toString(); int times = 2; String encodeedPasssword = new SimpleHash("md5",userPassword,salt,times).toString(); user.setSalt(salt); user.setSalt(encodeedPasssword); userMapper.insert(user); return 1; } /** * 更新用户状态 * */ public void updateUserStatus(User user){ User userID = userMapper.update(user); userID.setEnabled(userID.isEnabled()); userMapper.insert(userID); } /** * 编辑用户信息 */ public void editUser(User user){ User userID = userMapper.getId(user.getId()); userID.setUsername(user.getUsername()); userID.setPassword(<PASSWORD>.<PASSWORD>()); userID.setEmail(user.getEmail()); userID.setGmt_modified(user.getGmt_modified()); userMapper.insert(user); } /** * 根据ID删除用户 */ public void deteleById(int id){ userMapper.delete(id); } }
2,649
0.623534
0.618452
107
22.906542
20.822136
92
false
false
0
0
0
0
0
0
0.457944
false
false
10
f2079660b13ae8baaf70027e028d5f234c862a9a
29,901,562,381,212
9fc7f217c1ad1173086cbcee297c2e26da9da2fd
/src/main/java/br/com/byron/luderia/controller/CreditCardController.java
d378a57d53c4cf2167aaa4fbb3368c91a13d7164
[]
no_license
byron-codes/Luderia
https://github.com/byron-codes/Luderia
ec5f1c0fa2d619f81ea43811eb59cbbb2f2fbc8e
7f148fc855a86c3570d9b8b3bc7004b6784dc930
refs/heads/master
2022-11-16T16:47:25.791000
2020-07-11T16:56:21
2020-07-11T16:56:21
236,067,682
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.byron.luderia.controller; import br.com.byron.luderia.domain.filter.CreditCardFilter; import br.com.byron.luderia.domain.mapper.ICreditCardMapper; import br.com.byron.luderia.domain.request.CreditCardRequest; import br.com.byron.luderia.domain.response.CreditCardResponse; import br.com.byron.luderia.facade.Facade; import br.com.byron.luderia.domain.model.CreditCard; import br.com.byron.luderia.repository.ICreditCardRepository; import br.com.byron.luderia.repository.specification.CreditCardSpecification; import br.com.byron.luderia.strategy.ExecuteStrategy; import io.swagger.annotations.Api; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/credit-card") @Api(value = "Credit Card") @ApiResponses({ @ApiResponse(code = 201, message = "Created", response = CreditCardResponse.class), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 400, message = "Bad request") }) public class CreditCardController extends GenericController<CreditCard, CreditCardFilter, CreditCardRequest, CreditCardResponse> { @Autowired public CreditCardController(ExecuteStrategy<CreditCard> strategy, ICreditCardMapper mapper, ICreditCardRepository repository) { super(new Facade<CreditCard, CreditCardFilter>(strategy, repository), mapper, new CreditCardSpecification()); } }
UTF-8
Java
1,576
java
CreditCardController.java
Java
[]
null
[]
package br.com.byron.luderia.controller; import br.com.byron.luderia.domain.filter.CreditCardFilter; import br.com.byron.luderia.domain.mapper.ICreditCardMapper; import br.com.byron.luderia.domain.request.CreditCardRequest; import br.com.byron.luderia.domain.response.CreditCardResponse; import br.com.byron.luderia.facade.Facade; import br.com.byron.luderia.domain.model.CreditCard; import br.com.byron.luderia.repository.ICreditCardRepository; import br.com.byron.luderia.repository.specification.CreditCardSpecification; import br.com.byron.luderia.strategy.ExecuteStrategy; import io.swagger.annotations.Api; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/credit-card") @Api(value = "Credit Card") @ApiResponses({ @ApiResponse(code = 201, message = "Created", response = CreditCardResponse.class), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 400, message = "Bad request") }) public class CreditCardController extends GenericController<CreditCard, CreditCardFilter, CreditCardRequest, CreditCardResponse> { @Autowired public CreditCardController(ExecuteStrategy<CreditCard> strategy, ICreditCardMapper mapper, ICreditCardRepository repository) { super(new Facade<CreditCard, CreditCardFilter>(strategy, repository), mapper, new CreditCardSpecification()); } }
1,576
0.824873
0.819162
32
48.25
35.04818
130
false
false
0
0
0
0
0
0
1.28125
false
false
10
ffdf0247f50a888fb85e95412f85e61ebba88336
16,681,652,986,781
baab6f1a00fa6979c38f1d8cf553bdf2099ddc81
/PrototypeNavigator/app/src/main/java/se/jolo/prototypenavigator/utils/Cipher.java
23f4d4d7070380a97cc6daf638b17ea0fefcce45
[]
no_license
PrototypeNavigator/PrototypeNavigator
https://github.com/PrototypeNavigator/PrototypeNavigator
6736df3e7f8c2b9677e0be1582484cff23899d31
63dd2de592d6a40cf8ff6beca29a0b7518f40222
refs/heads/master
2021-01-10T16:08:06.585000
2016-04-11T11:27:06
2016-04-11T11:27:06
51,075,105
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.jolo.prototypenavigator.utils; import java.util.ArrayList; import java.util.Collections; /* The Cipher class decodes the encrypted xml file. */ public final class Cipher { private Cipher() {} public static byte[] decrypt(byte[] data, byte[] key) { /* Create a table with the given key */ Table table = new Table(key, data); /* Sort the columns by the order of the corresponding key characters */ table.sortColumnsByKey(); /* Write data into the table, row-by-row */ table.write(data, false); /* Restore the order of the columns to match the key */ table.restoreColumns(); /* Read back the data, column-by-column */ byte[] decryptedData = table.read(true); /* Trim trailing zeros in encryptedData */ return table.trim(decryptedData); } private static class Table { byte[] key; ArrayList<Column> columns; ArrayList<Column> savedColumns; int numRows; public Table(byte[] key, byte[] data) { this.key = key; this.columns = new ArrayList<Column>(); this.savedColumns = new ArrayList<Column>(); int numCols = key.length; numRows = (int) Math.ceil((float) data.length / (float) numCols); // Pre-allocate table wth numColums Columns holding numRows bytes for (int i = 0; i < numCols; i++) { columns.add(new Column(key[i], numRows)); } } /** * Rearrange columns by sorting them by their key characters */ public void sortColumnsByKey() { savedColumns.clear(); for (int i = 0; i < columns.size(); i++) { savedColumns.add(columns.get(i)); } Collections.sort(columns); } /** * Rearrange columns to their original order given by the order of the key characters in the key */ public void restoreColumns() { columns.clear(); for (int i = 0; i < savedColumns.size(); i++) { columns.add(savedColumns.get(i)); } savedColumns.clear(); } /** * Read data from table, column by column or row by row */ public byte[] read(boolean columnByColumn) { int numCols = columns.size(); byte[] tableData = new byte[numRows * numCols]; int tableDataPos = 0; if (columnByColumn) { for (int c = 0; c < numCols; c++) { System.arraycopy(columns.get(c).getBytes(), 0, tableData, tableDataPos, numRows); tableDataPos += numRows; } } else { for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { tableDataPos = r * numCols + c; tableData[tableDataPos] = columns.get(c).getBytes()[r]; } } } return tableData; } /** * Write data to table, column by column or row by row */ public void write(byte[] data, boolean columnByColumn) { int numCols = columns.size(); byte[] tableData = new byte[numRows * numCols]; System.arraycopy(data, 0, tableData, 0, data.length); int tableDataPos = 0; // Write to table if (columnByColumn) { for (int c = 0; c < numCols; c++) { System.arraycopy(tableData, tableDataPos, columns.get(c).getBytes(), 0, numRows); tableDataPos += numRows; } } else { for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { tableDataPos = r * numCols + c; columns.get(c).getBytes()[r] = tableData[tableDataPos]; } } } } public byte[] trim(byte[] data) { int lastNonZeroByte = data.length - 1; while (data[lastNonZeroByte] == 0) { lastNonZeroByte--; } // If zeros where found, trim data if (lastNonZeroByte != data.length - 1) { byte[] trimmedData = new byte[lastNonZeroByte + 1]; System.arraycopy(data, 0, trimmedData, 0, lastNonZeroByte + 1); return trimmedData; } else { return data; } } private class Column implements Comparable<Column> { public Column(byte keyChar, int size) { this.keyChar = keyChar; this.data = new byte[size]; } public byte[] getBytes() { return data; } public int compareTo(Column column) { if (keyChar < column.keyChar) return -1; else if (keyChar > column.keyChar) return 1; else return 0; } byte keyChar; byte[] data; } } }
UTF-8
Java
5,247
java
Cipher.java
Java
[]
null
[]
package se.jolo.prototypenavigator.utils; import java.util.ArrayList; import java.util.Collections; /* The Cipher class decodes the encrypted xml file. */ public final class Cipher { private Cipher() {} public static byte[] decrypt(byte[] data, byte[] key) { /* Create a table with the given key */ Table table = new Table(key, data); /* Sort the columns by the order of the corresponding key characters */ table.sortColumnsByKey(); /* Write data into the table, row-by-row */ table.write(data, false); /* Restore the order of the columns to match the key */ table.restoreColumns(); /* Read back the data, column-by-column */ byte[] decryptedData = table.read(true); /* Trim trailing zeros in encryptedData */ return table.trim(decryptedData); } private static class Table { byte[] key; ArrayList<Column> columns; ArrayList<Column> savedColumns; int numRows; public Table(byte[] key, byte[] data) { this.key = key; this.columns = new ArrayList<Column>(); this.savedColumns = new ArrayList<Column>(); int numCols = key.length; numRows = (int) Math.ceil((float) data.length / (float) numCols); // Pre-allocate table wth numColums Columns holding numRows bytes for (int i = 0; i < numCols; i++) { columns.add(new Column(key[i], numRows)); } } /** * Rearrange columns by sorting them by their key characters */ public void sortColumnsByKey() { savedColumns.clear(); for (int i = 0; i < columns.size(); i++) { savedColumns.add(columns.get(i)); } Collections.sort(columns); } /** * Rearrange columns to their original order given by the order of the key characters in the key */ public void restoreColumns() { columns.clear(); for (int i = 0; i < savedColumns.size(); i++) { columns.add(savedColumns.get(i)); } savedColumns.clear(); } /** * Read data from table, column by column or row by row */ public byte[] read(boolean columnByColumn) { int numCols = columns.size(); byte[] tableData = new byte[numRows * numCols]; int tableDataPos = 0; if (columnByColumn) { for (int c = 0; c < numCols; c++) { System.arraycopy(columns.get(c).getBytes(), 0, tableData, tableDataPos, numRows); tableDataPos += numRows; } } else { for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { tableDataPos = r * numCols + c; tableData[tableDataPos] = columns.get(c).getBytes()[r]; } } } return tableData; } /** * Write data to table, column by column or row by row */ public void write(byte[] data, boolean columnByColumn) { int numCols = columns.size(); byte[] tableData = new byte[numRows * numCols]; System.arraycopy(data, 0, tableData, 0, data.length); int tableDataPos = 0; // Write to table if (columnByColumn) { for (int c = 0; c < numCols; c++) { System.arraycopy(tableData, tableDataPos, columns.get(c).getBytes(), 0, numRows); tableDataPos += numRows; } } else { for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { tableDataPos = r * numCols + c; columns.get(c).getBytes()[r] = tableData[tableDataPos]; } } } } public byte[] trim(byte[] data) { int lastNonZeroByte = data.length - 1; while (data[lastNonZeroByte] == 0) { lastNonZeroByte--; } // If zeros where found, trim data if (lastNonZeroByte != data.length - 1) { byte[] trimmedData = new byte[lastNonZeroByte + 1]; System.arraycopy(data, 0, trimmedData, 0, lastNonZeroByte + 1); return trimmedData; } else { return data; } } private class Column implements Comparable<Column> { public Column(byte keyChar, int size) { this.keyChar = keyChar; this.data = new byte[size]; } public byte[] getBytes() { return data; } public int compareTo(Column column) { if (keyChar < column.keyChar) return -1; else if (keyChar > column.keyChar) return 1; else return 0; } byte keyChar; byte[] data; } } }
5,247
0.489423
0.484658
170
29.870588
24.197613
104
false
false
0
0
0
0
0
0
0.664706
false
false
10
ed20b802e2c123e3ca7d41db6f70ad9eae1b2c12
38,156,489,477,628
2cf3ec06632124e03afb49c2f0199d6d145e668c
/src/main/java/object/ways/WayDetailDto.java
324ca5a7b0b10ea5fdad48bbc0dfbb76eae0d6fe
[]
no_license
hoangnp2G/Vaccine2
https://github.com/hoangnp2G/Vaccine2
a7084a280b76f31b2dace0a3bb99a8961c3a24e4
f48f222ea9cbeb476cd4eda01188b9db9f00f188
refs/heads/master
2023-05-22T21:50:10.052000
2021-06-04T10:19:28
2021-06-04T10:19:28
372,352,646
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package object.ways; import com.google.gson.annotations.SerializedName; public class WayDetailDto{ @SerializedName("type4") private String type4; @SerializedName("type3") private String type3; @SerializedName("type2") private String type2; @SerializedName("way_id2") private int wayId2; @SerializedName("way_id1") private int wayId1; @SerializedName("way_id4") private int wayId4; @SerializedName("way_id3") private int wayId3; @SerializedName("type1") private String type1; @SerializedName("name4") private String name4; @SerializedName("name3") private String name3; @SerializedName("id2") private int id2; @SerializedName("id1") private int id1; @SerializedName("id4") private int id4; @SerializedName("id3") private int id3; @SerializedName("name2") private String name2; @SerializedName("name1") private String name1; public void setType4(String type4){ this.type4 = type4; } public String getType4(){ return type4; } public void setType3(String type3){ this.type3 = type3; } public String getType3(){ return type3; } public void setType2(String type2){ this.type2 = type2; } public String getType2(){ return type2; } public void setWayId2(int wayId2){ this.wayId2 = wayId2; } public int getWayId2(){ return wayId2; } public void setWayId1(int wayId1){ this.wayId1 = wayId1; } public int getWayId1(){ return wayId1; } public void setWayId4(int wayId4){ this.wayId4 = wayId4; } public int getWayId4(){ return wayId4; } public void setWayId3(int wayId3){ this.wayId3 = wayId3; } public int getWayId3(){ return wayId3; } public void setType1(String type1){ this.type1 = type1; } public String getType1(){ return type1; } public void setName4(String name4){ this.name4 = name4; } public String getName4(){ return name4; } public void setName3(String name3){ this.name3 = name3; } public String getName3(){ return name3; } public void setId2(int id2){ this.id2 = id2; } public int getId2(){ return id2; } public void setId1(int id1){ this.id1 = id1; } public int getId1(){ return id1; } public void setId4(int id4){ this.id4 = id4; } public int getId4(){ return id4; } public void setId3(int id3){ this.id3 = id3; } public int getId3(){ return id3; } public void setName2(String name2){ this.name2 = name2; } public String getName2(){ return name2; } public void setName1(String name1){ this.name1 = name1; } public String getName1(){ return name1; } }
UTF-8
Java
2,562
java
WayDetailDto.java
Java
[]
null
[]
package object.ways; import com.google.gson.annotations.SerializedName; public class WayDetailDto{ @SerializedName("type4") private String type4; @SerializedName("type3") private String type3; @SerializedName("type2") private String type2; @SerializedName("way_id2") private int wayId2; @SerializedName("way_id1") private int wayId1; @SerializedName("way_id4") private int wayId4; @SerializedName("way_id3") private int wayId3; @SerializedName("type1") private String type1; @SerializedName("name4") private String name4; @SerializedName("name3") private String name3; @SerializedName("id2") private int id2; @SerializedName("id1") private int id1; @SerializedName("id4") private int id4; @SerializedName("id3") private int id3; @SerializedName("name2") private String name2; @SerializedName("name1") private String name1; public void setType4(String type4){ this.type4 = type4; } public String getType4(){ return type4; } public void setType3(String type3){ this.type3 = type3; } public String getType3(){ return type3; } public void setType2(String type2){ this.type2 = type2; } public String getType2(){ return type2; } public void setWayId2(int wayId2){ this.wayId2 = wayId2; } public int getWayId2(){ return wayId2; } public void setWayId1(int wayId1){ this.wayId1 = wayId1; } public int getWayId1(){ return wayId1; } public void setWayId4(int wayId4){ this.wayId4 = wayId4; } public int getWayId4(){ return wayId4; } public void setWayId3(int wayId3){ this.wayId3 = wayId3; } public int getWayId3(){ return wayId3; } public void setType1(String type1){ this.type1 = type1; } public String getType1(){ return type1; } public void setName4(String name4){ this.name4 = name4; } public String getName4(){ return name4; } public void setName3(String name3){ this.name3 = name3; } public String getName3(){ return name3; } public void setId2(int id2){ this.id2 = id2; } public int getId2(){ return id2; } public void setId1(int id1){ this.id1 = id1; } public int getId1(){ return id1; } public void setId4(int id4){ this.id4 = id4; } public int getId4(){ return id4; } public void setId3(int id3){ this.id3 = id3; } public int getId3(){ return id3; } public void setName2(String name2){ this.name2 = name2; } public String getName2(){ return name2; } public void setName1(String name1){ this.name1 = name1; } public String getName1(){ return name1; } }
2,562
0.685402
0.635441
182
13.082417
12.319859
50
false
false
0
0
0
0
0
0
1.153846
false
false
10
e63d330d3206494ec2f50514f43698792e783687
34,780,645,196,900
26749f30330e1bf3aaab2d1e526b89848e5ea5b1
/src/girard/sc/be/io/msg/BETimeTckMsg.java
06adb6252cae6865b91c745ebeaf61aec1dc8d1f
[]
no_license
impsbro/ExNet
https://github.com/impsbro/ExNet
fbd398230598528bae270a1eca472130afba1ccc
8d76fd386766222fd4fe29bbfe86616c4426c545
refs/heads/master
2021-01-19T04:22:13.920000
2016-06-10T18:07:24
2016-06-10T18:07:24
60,866,731
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package girard.sc.be.io.msg; /* Lets subjects and observers know that another time tick has passed. Subjects respond back so the server knows when to move time foward again. Author: Dudley Girard Started: 1-1-2001 Modified: 4-26-2001 Modified: 5-18-2001 */ import girard.sc.awt.ErrorDialog; import girard.sc.be.awt.BENetworkActionClientWindow; import girard.sc.be.awt.BENetworkActionExperimenterWindow; import girard.sc.be.awt.BENetworkActionObserverWindow; import girard.sc.be.obj.BEEdge; import girard.sc.be.obj.BEEdgeResource; import girard.sc.be.obj.BENetwork; import girard.sc.be.obj.BENode; import girard.sc.be.obj.BENodeExchange; import girard.sc.be.obj.BEOfferOutputObject; import girard.sc.expt.awt.ClientWindow; import girard.sc.expt.awt.ExperimenterWindow; import girard.sc.expt.awt.ObserverWindow; import girard.sc.expt.io.ExptServerConnection; import girard.sc.expt.io.msg.ExptErrorMsg; import girard.sc.expt.io.msg.ExptMessage; import girard.sc.expt.io.obj.ExptComptroller; import java.util.Enumeration; import java.util.Vector; public class BETimeTckMsg extends ExptMessage { public BETimeTckMsg (Object args[]) { super(args); } public void getClientResponse(ClientWindow cw) { if ((!cw.getExpApp().getExptRunning()) || (cw.getExpApp().getExptStopping())) return; if (cw instanceof BENetworkActionClientWindow) { BENetworkActionClientWindow nacw = (BENetworkActionClientWindow)cw; BENetwork ben = (BENetwork)nacw.getExpApp().getActiveAction(); ben.getActivePeriod().setCurrentTime(ben.getActivePeriod().getCurrentTime() - 1); nacw.setTimeLabel(ben.getActivePeriod().getCurrentTime()); BETimeTckMsg tmp = new BETimeTckMsg(null); cw.getSML().sendMessage(tmp); } else { new ErrorDialog("Wrong Client Window. - BERoundWindowMsg"); } } public ExptMessage getExptServerConnectionResponse(ExptServerConnection esc) { Object[] args = this.getArgs(); // System.err.println("ESR: Time Tck Message"); ExptComptroller ec = esc.getExptIndex(); int index = esc.getUserNum(); if (ec != null) { synchronized(ec) { if (index == ExptComptroller.EXPERIMENTER) { if (!ec.allRegistered()) { Object[] err_args = new Object[2]; err_args[0] = new String("Least one user not registered."); err_args[1] = new String("BETimeTckMsg"); return new ExptErrorMsg(err_args); } ec.sendToAllUsers(new BETimeTckMsg(args)); ec.sendToAllObservers(new BETimeTckMsg(args)); return null; } else { if (!ec.allRegistered()) return null; Object[] out_args = new Object[1]; out_args[0] = new Integer(index); ec.addServerMessage(new BETimeTckMsg(out_args)); return null; } } } else { Object[] err_args = new Object[2]; err_args[0] = new String("No experiment."); err_args[1] = new String("BETimeTckMsg"); return new ExptErrorMsg(err_args); } } public void getExperimenterResponse(ExperimenterWindow ew) { Integer index = (Integer)this.getArgs()[0]; BENetworkActionExperimenterWindow naew = (BENetworkActionExperimenterWindow)ew; boolean[] tick = (boolean[])naew.getNetwork().getExtraData("TimeReady"); Boolean rr = (Boolean)naew.getNetwork().getExtraData("RoundRunning"); if ((!rr.booleanValue()) || (!ew.getExpApp().getExptRunning()) || (ew.getExpApp().getExptStopping())) return; tick[index.intValue()] = true; boolean flag = true; for (int x=0;x<ew.getExpApp().getNumUsers();x++) { if (!tick[x]) flag = false; } if (flag) { for (int x=0;x<ew.getExpApp().getNumUsers();x++) { tick[x] = false; } BENetwork ben = (BENetwork)ew.getExpApp().getActiveAction().getAction(); ben.getActivePeriod().setCurrentTime(ben.getActivePeriod().getCurrentTime() - 1); naew.setTimeLabel(ben.getActivePeriod().getCurrentTime()); if (ben.getActivePeriod().getCurrentTime() > 0) { BETimeTckMsg tmp = new BETimeTckMsg(null); ew.getSML().sendMessage(tmp); } else { /* Update exchanges for Simultaneous method */ String exchType = (String)ben.getExtraData("ExchangeMethod"); if (exchType.equals("Simultaneous")) { computeExchanges(naew,ben); naew.repaint(); } ben.setExtraData("RoundRunning",new Boolean(false)); BEStopRoundMsg tmp = new BEStopRoundMsg(null); ew.getSML().sendMessage(tmp); } } } public void getObserverResponse(ObserverWindow ow) { if (!ow.getExpApp().getJoined()) return; if (!(ow instanceof BENetworkActionObserverWindow)) { new ErrorDialog("Wrong Observer Window. - BETimeTckMsg"); return; } BENetworkActionObserverWindow naow = (BENetworkActionObserverWindow)ow; Boolean rr = (Boolean)naow.getNetwork().getExtraData("RoundRunning"); if ((!rr.booleanValue()) || (!ow.getExpApp().getExptRunning()) || (ow.getExpApp().getExptStopping())) return; BENetwork ben = naow.getNetwork(); ben.getActivePeriod().setCurrentTime(ben.getActivePeriod().getCurrentTime() - 1); naow.setTimeLabel(ben.getActivePeriod().getCurrentTime()); } private void computeExchanges(BENetworkActionExperimenterWindow naew, BENetwork ben) { // Create a random list of the nodes to cycle through. Vector nodes = new Vector(); Enumeration enm = ben.getNodeList().elements(); while (enm.hasMoreElements()) { BENode n = (BENode)enm.nextElement(); int loc = (int)(Math.floor(Math.random()*nodes.size())); nodes.insertElementAt(new Integer(n.getID()),loc); } boolean flag = true; while (flag) { int numPE = 0; enm = nodes.elements(); while (enm.hasMoreElements()) { Integer n = (Integer)enm.nextElement(); Vector potentialExchanges = new Vector(); Enumeration enum2 = ben.getEdgeList().elements(); while (enum2.hasMoreElements()) { BEEdge edge = (BEEdge)enum2.nextElement(); BEEdgeResource beer = (BEEdgeResource)edge.getExptData("BEEdgeResource"); if ((edge.getActive()) && (beer.getN1Keep().getResource() == beer.getN2Give().getResource()) && (beer.getN1Keep().getResource() > 0)) { if (edge.getNode1() == n.intValue()) { if (potentialExchanges.size() == 0) { potentialExchanges.addElement(edge); } else { BEEdge tmpE = (BEEdge)potentialExchanges.elementAt(0); BEEdgeResource tmpB = (BEEdgeResource)tmpE.getExptData("BEEdgeResource"); if (beer.getN1Keep().getResource() > tmpB.getN1Keep().getResource()) { potentialExchanges.removeAllElements(); potentialExchanges.addElement(edge); } else if (beer.getN1Keep().getResource() == tmpB.getN1Keep().getResource()) { potentialExchanges.addElement(edge); } } } if (edge.getNode2() == n.intValue()) { if (potentialExchanges.size() == 0) { potentialExchanges.addElement(edge); } else { BEEdge tmpE = (BEEdge)potentialExchanges.elementAt(0); BEEdgeResource tmpB = (BEEdgeResource)tmpE.getExptData("BEEdgeResource"); if (beer.getN2Keep().getResource() > tmpB.getN2Keep().getResource()) { potentialExchanges.removeAllElements(); potentialExchanges.addElement(edge); } else if (beer.getN2Keep().getResource() == tmpB.getN2Keep().getResource()) { potentialExchanges.addElement(edge); } } } } } numPE = numPE + potentialExchanges.size(); if (potentialExchanges.size() > 0) { int index = (int)Math.floor(Math.random()*potentialExchanges.size()); BEEdge edge = (BEEdge)potentialExchanges.elementAt(index); BEEdgeResource beer = (BEEdgeResource)edge.getExptData("BEEdgeResource"); int tt = naew.getNetwork().getActivePeriod().getTime() - naew.getNetwork().getActivePeriod().getCurrentTime(); beer.completeExchange(tt,naew.getPresentTime(),beer.getN1Keep().getIntResource(),beer.getN2Keep().getIntResource()); int cr = naew.getNetwork().getActivePeriod().getCurrentRound() + 1; int cp = naew.getNetwork().getCurrentPeriod() + 1; BEOfferOutputObject data = new BEOfferOutputObject(naew.getExpApp().getExptOutputID(),naew.getExpApp().getActionIndex(),cp,cr,edge.getNode1(),edge.getNode2(),beer.getN1Keep().getIntResource(),beer.getN2Keep().getIntResource(),"Complete",tt, naew.getPresentTime()); Vector outData = (Vector)naew.getNetwork().getExtraData("Data"); outData.addElement(data); // Store the arguments for the CompleteOffer message we are going to send out. Object[] out_args = new Object[4]; out_args[0] = new Integer(edge.getNode1()); out_args[1] = new Integer(edge.getNode2()); out_args[2] = new Integer(beer.getN1Keep().getIntResource()); out_args[3] = new Integer(beer.getN2Keep().getIntResource()); // update active settings for edges. BENode n1 = (BENode)ben.getNode(edge.getNode1()); BENode n2 = (BENode)ben.getNode(edge.getNode2()); BENodeExchange exch1 = (BENodeExchange)n1.getExptData("BENodeExchange"); BENodeExchange exch2 = (BENodeExchange)n2.getExptData("BENodeExchange"); exch1.updateNetwork(edge); exch2.updateNetwork(edge); // Let the subjects know what happened. BECompleteOfferMsg tmp = new BECompleteOfferMsg(out_args); naew.getSML().sendMessage(tmp); } enum2 = ben.getEdgeList().elements(); flag = false; while (enum2.hasMoreElements()) { BEEdge tmpEdge = (BEEdge)enum2.nextElement(); BENode n1 = (BENode)ben.getNode(tmpEdge.getNode1()); BENode n2 = (BENode)ben.getNode(tmpEdge.getNode2()); BENodeExchange exch1 = (BENodeExchange)n1.getExptData("BENodeExchange"); BENodeExchange exch2 = (BENodeExchange)n2.getExptData("BENodeExchange"); if ((exch1.isEdgeActive(tmpEdge)) && (exch2.isEdgeActive(tmpEdge))) { tmpEdge.setActive(true); } else { tmpEdge.setActive(false); } if (tmpEdge.getActive()) flag = true; } if (!flag) break; } if (numPE == 0) flag = false; } } }
UTF-8
Java
13,589
java
BETimeTckMsg.java
Java
[ { "context": "knows when to \n move time foward again.\n\nAuthor: Dudley Girard\nStarted: 1-1-2001\nModified: 4-26-2001\nModified: 5", "end": 204, "score": 0.9998857975006104, "start": 191, "tag": "NAME", "value": "Dudley Girard" } ]
null
[]
package girard.sc.be.io.msg; /* Lets subjects and observers know that another time tick has passed. Subjects respond back so the server knows when to move time foward again. Author: <NAME> Started: 1-1-2001 Modified: 4-26-2001 Modified: 5-18-2001 */ import girard.sc.awt.ErrorDialog; import girard.sc.be.awt.BENetworkActionClientWindow; import girard.sc.be.awt.BENetworkActionExperimenterWindow; import girard.sc.be.awt.BENetworkActionObserverWindow; import girard.sc.be.obj.BEEdge; import girard.sc.be.obj.BEEdgeResource; import girard.sc.be.obj.BENetwork; import girard.sc.be.obj.BENode; import girard.sc.be.obj.BENodeExchange; import girard.sc.be.obj.BEOfferOutputObject; import girard.sc.expt.awt.ClientWindow; import girard.sc.expt.awt.ExperimenterWindow; import girard.sc.expt.awt.ObserverWindow; import girard.sc.expt.io.ExptServerConnection; import girard.sc.expt.io.msg.ExptErrorMsg; import girard.sc.expt.io.msg.ExptMessage; import girard.sc.expt.io.obj.ExptComptroller; import java.util.Enumeration; import java.util.Vector; public class BETimeTckMsg extends ExptMessage { public BETimeTckMsg (Object args[]) { super(args); } public void getClientResponse(ClientWindow cw) { if ((!cw.getExpApp().getExptRunning()) || (cw.getExpApp().getExptStopping())) return; if (cw instanceof BENetworkActionClientWindow) { BENetworkActionClientWindow nacw = (BENetworkActionClientWindow)cw; BENetwork ben = (BENetwork)nacw.getExpApp().getActiveAction(); ben.getActivePeriod().setCurrentTime(ben.getActivePeriod().getCurrentTime() - 1); nacw.setTimeLabel(ben.getActivePeriod().getCurrentTime()); BETimeTckMsg tmp = new BETimeTckMsg(null); cw.getSML().sendMessage(tmp); } else { new ErrorDialog("Wrong Client Window. - BERoundWindowMsg"); } } public ExptMessage getExptServerConnectionResponse(ExptServerConnection esc) { Object[] args = this.getArgs(); // System.err.println("ESR: Time Tck Message"); ExptComptroller ec = esc.getExptIndex(); int index = esc.getUserNum(); if (ec != null) { synchronized(ec) { if (index == ExptComptroller.EXPERIMENTER) { if (!ec.allRegistered()) { Object[] err_args = new Object[2]; err_args[0] = new String("Least one user not registered."); err_args[1] = new String("BETimeTckMsg"); return new ExptErrorMsg(err_args); } ec.sendToAllUsers(new BETimeTckMsg(args)); ec.sendToAllObservers(new BETimeTckMsg(args)); return null; } else { if (!ec.allRegistered()) return null; Object[] out_args = new Object[1]; out_args[0] = new Integer(index); ec.addServerMessage(new BETimeTckMsg(out_args)); return null; } } } else { Object[] err_args = new Object[2]; err_args[0] = new String("No experiment."); err_args[1] = new String("BETimeTckMsg"); return new ExptErrorMsg(err_args); } } public void getExperimenterResponse(ExperimenterWindow ew) { Integer index = (Integer)this.getArgs()[0]; BENetworkActionExperimenterWindow naew = (BENetworkActionExperimenterWindow)ew; boolean[] tick = (boolean[])naew.getNetwork().getExtraData("TimeReady"); Boolean rr = (Boolean)naew.getNetwork().getExtraData("RoundRunning"); if ((!rr.booleanValue()) || (!ew.getExpApp().getExptRunning()) || (ew.getExpApp().getExptStopping())) return; tick[index.intValue()] = true; boolean flag = true; for (int x=0;x<ew.getExpApp().getNumUsers();x++) { if (!tick[x]) flag = false; } if (flag) { for (int x=0;x<ew.getExpApp().getNumUsers();x++) { tick[x] = false; } BENetwork ben = (BENetwork)ew.getExpApp().getActiveAction().getAction(); ben.getActivePeriod().setCurrentTime(ben.getActivePeriod().getCurrentTime() - 1); naew.setTimeLabel(ben.getActivePeriod().getCurrentTime()); if (ben.getActivePeriod().getCurrentTime() > 0) { BETimeTckMsg tmp = new BETimeTckMsg(null); ew.getSML().sendMessage(tmp); } else { /* Update exchanges for Simultaneous method */ String exchType = (String)ben.getExtraData("ExchangeMethod"); if (exchType.equals("Simultaneous")) { computeExchanges(naew,ben); naew.repaint(); } ben.setExtraData("RoundRunning",new Boolean(false)); BEStopRoundMsg tmp = new BEStopRoundMsg(null); ew.getSML().sendMessage(tmp); } } } public void getObserverResponse(ObserverWindow ow) { if (!ow.getExpApp().getJoined()) return; if (!(ow instanceof BENetworkActionObserverWindow)) { new ErrorDialog("Wrong Observer Window. - BETimeTckMsg"); return; } BENetworkActionObserverWindow naow = (BENetworkActionObserverWindow)ow; Boolean rr = (Boolean)naow.getNetwork().getExtraData("RoundRunning"); if ((!rr.booleanValue()) || (!ow.getExpApp().getExptRunning()) || (ow.getExpApp().getExptStopping())) return; BENetwork ben = naow.getNetwork(); ben.getActivePeriod().setCurrentTime(ben.getActivePeriod().getCurrentTime() - 1); naow.setTimeLabel(ben.getActivePeriod().getCurrentTime()); } private void computeExchanges(BENetworkActionExperimenterWindow naew, BENetwork ben) { // Create a random list of the nodes to cycle through. Vector nodes = new Vector(); Enumeration enm = ben.getNodeList().elements(); while (enm.hasMoreElements()) { BENode n = (BENode)enm.nextElement(); int loc = (int)(Math.floor(Math.random()*nodes.size())); nodes.insertElementAt(new Integer(n.getID()),loc); } boolean flag = true; while (flag) { int numPE = 0; enm = nodes.elements(); while (enm.hasMoreElements()) { Integer n = (Integer)enm.nextElement(); Vector potentialExchanges = new Vector(); Enumeration enum2 = ben.getEdgeList().elements(); while (enum2.hasMoreElements()) { BEEdge edge = (BEEdge)enum2.nextElement(); BEEdgeResource beer = (BEEdgeResource)edge.getExptData("BEEdgeResource"); if ((edge.getActive()) && (beer.getN1Keep().getResource() == beer.getN2Give().getResource()) && (beer.getN1Keep().getResource() > 0)) { if (edge.getNode1() == n.intValue()) { if (potentialExchanges.size() == 0) { potentialExchanges.addElement(edge); } else { BEEdge tmpE = (BEEdge)potentialExchanges.elementAt(0); BEEdgeResource tmpB = (BEEdgeResource)tmpE.getExptData("BEEdgeResource"); if (beer.getN1Keep().getResource() > tmpB.getN1Keep().getResource()) { potentialExchanges.removeAllElements(); potentialExchanges.addElement(edge); } else if (beer.getN1Keep().getResource() == tmpB.getN1Keep().getResource()) { potentialExchanges.addElement(edge); } } } if (edge.getNode2() == n.intValue()) { if (potentialExchanges.size() == 0) { potentialExchanges.addElement(edge); } else { BEEdge tmpE = (BEEdge)potentialExchanges.elementAt(0); BEEdgeResource tmpB = (BEEdgeResource)tmpE.getExptData("BEEdgeResource"); if (beer.getN2Keep().getResource() > tmpB.getN2Keep().getResource()) { potentialExchanges.removeAllElements(); potentialExchanges.addElement(edge); } else if (beer.getN2Keep().getResource() == tmpB.getN2Keep().getResource()) { potentialExchanges.addElement(edge); } } } } } numPE = numPE + potentialExchanges.size(); if (potentialExchanges.size() > 0) { int index = (int)Math.floor(Math.random()*potentialExchanges.size()); BEEdge edge = (BEEdge)potentialExchanges.elementAt(index); BEEdgeResource beer = (BEEdgeResource)edge.getExptData("BEEdgeResource"); int tt = naew.getNetwork().getActivePeriod().getTime() - naew.getNetwork().getActivePeriod().getCurrentTime(); beer.completeExchange(tt,naew.getPresentTime(),beer.getN1Keep().getIntResource(),beer.getN2Keep().getIntResource()); int cr = naew.getNetwork().getActivePeriod().getCurrentRound() + 1; int cp = naew.getNetwork().getCurrentPeriod() + 1; BEOfferOutputObject data = new BEOfferOutputObject(naew.getExpApp().getExptOutputID(),naew.getExpApp().getActionIndex(),cp,cr,edge.getNode1(),edge.getNode2(),beer.getN1Keep().getIntResource(),beer.getN2Keep().getIntResource(),"Complete",tt, naew.getPresentTime()); Vector outData = (Vector)naew.getNetwork().getExtraData("Data"); outData.addElement(data); // Store the arguments for the CompleteOffer message we are going to send out. Object[] out_args = new Object[4]; out_args[0] = new Integer(edge.getNode1()); out_args[1] = new Integer(edge.getNode2()); out_args[2] = new Integer(beer.getN1Keep().getIntResource()); out_args[3] = new Integer(beer.getN2Keep().getIntResource()); // update active settings for edges. BENode n1 = (BENode)ben.getNode(edge.getNode1()); BENode n2 = (BENode)ben.getNode(edge.getNode2()); BENodeExchange exch1 = (BENodeExchange)n1.getExptData("BENodeExchange"); BENodeExchange exch2 = (BENodeExchange)n2.getExptData("BENodeExchange"); exch1.updateNetwork(edge); exch2.updateNetwork(edge); // Let the subjects know what happened. BECompleteOfferMsg tmp = new BECompleteOfferMsg(out_args); naew.getSML().sendMessage(tmp); } enum2 = ben.getEdgeList().elements(); flag = false; while (enum2.hasMoreElements()) { BEEdge tmpEdge = (BEEdge)enum2.nextElement(); BENode n1 = (BENode)ben.getNode(tmpEdge.getNode1()); BENode n2 = (BENode)ben.getNode(tmpEdge.getNode2()); BENodeExchange exch1 = (BENodeExchange)n1.getExptData("BENodeExchange"); BENodeExchange exch2 = (BENodeExchange)n2.getExptData("BENodeExchange"); if ((exch1.isEdgeActive(tmpEdge)) && (exch2.isEdgeActive(tmpEdge))) { tmpEdge.setActive(true); } else { tmpEdge.setActive(false); } if (tmpEdge.getActive()) flag = true; } if (!flag) break; } if (numPE == 0) flag = false; } } }
13,582
0.503716
0.496431
325
40.815384
32.55825
284
false
false
0
0
0
0
0
0
0.523077
false
false
10
74c2114f42467df4b018cb62dae61a6a9ba81150
1,357,209,732,554
13a0a332cdcf9fb5b258b61dc906cdec286a2140
/src/main/java/cn/edu/buaa/network/nexmark/Query5.java
a67b46f7b4eaf3b3ead8728ced86e1cc080b6d6a
[]
no_license
HalfCoke/nexmark-datastream
https://github.com/HalfCoke/nexmark-datastream
fd284c0853088717a75c55a0ae12dd9aebd60aaa
9b43243451b583c00b219cf29e7e0e71f7b4ef47
refs/heads/master
2023-08-15T12:22:48.675000
2021-10-18T07:22:48
2021-10-18T07:22:48
418,388,554
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.edu.buaa.network.nexmark; import cn.edu.buaa.network.nexmark.sources.BidSourceFunction; import org.apache.beam.sdk.nexmark.model.Bid; import org.apache.flink.api.common.state.*; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.KeyedStream; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.co.KeyedCoProcessFunction; import org.apache.flink.streaming.api.functions.sink.DiscardingSink; import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor; import org.apache.flink.streaming.api.functions.windowing.RichAllWindowFunction; import org.apache.flink.streaming.api.functions.windowing.RichWindowFunction; import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.streaming.runtime.operators.util.AssignerWithPeriodicWatermarksAdapter; import org.apache.flink.util.Collector; import static org.apache.flink.api.common.typeinfo.BasicTypeInfo.LONG_TYPE_INFO; /** * Query 5, 'Hot Items'. Which auctions have seen the most bids in the last hour (updated every * minute). In CQL syntax: * * <pre>{@code * SELECT Rstream(auction) * FROM (SELECT B1.auction, count(*) AS num * FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B1 * GROUP BY B1.auction) * WHERE num >= ALL (SELECT count(*) * FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B2 * GROUP BY B2.auction); * }</pre> * * <p>To make things a bit more dynamic and easier to test we use much shorter windows, and we'll * also preserve the bid counts. */ public class Query5 { public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.disableOperatorChaining(); env.getConfig().setAutoWatermarkInterval(1000); final int srcRate = params.getInt("srcRate", 100000); DataStream<Bid> bidOneSource = env.addSource(new BidSourceFunction(srcRate)) .name("BidOneSource") .uid("BidOneSource") .setParallelism(params.getInt("BidOneSource", 1)) .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarksAdapter.Strategy<>(new TimestampExtractor(Time.seconds(0)))); DataStream<Bid> bidTwoSource = env.addSource(new BidSourceFunction(srcRate)) .name("BidTwoSource") .uid("BidTwoSource") .setParallelism(params.getInt("BidTwoSource", 1)) .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarksAdapter.Strategy<>(new TimestampExtractor(Time.seconds(0)))); // SELECT B1.auction, count(*) AS num // FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B1 // GROUP BY B1.auction DataStream<Tuple3<Long, Long, Long>> bidOneWindowed = bidOneSource.keyBy((KeySelector<Bid, Long>) value -> value.auction) .window(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(2))) .apply(new CountBidsWithTime()) .name("BidOneSlidingWindow") .uid("BidOneSlidingWindow") .setParallelism(params.getInt("BidOneSlidingWindow", 1)); // ALL (SELECT B2.auction, count(*) AS num // FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B2 // GROUP BY B2.auction) DataStream<Tuple2<Long, Long>> bidTwoWindowed = bidTwoSource.windowAll(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(2))) .apply(new MaxCountWithAllKeyWindow()) .name("BidTwoSlidingWindow") .uid("BidTwoSlidingWindow") .setParallelism(params.getInt("BidTwoSlidingWindow", 1)); KeyedStream<Tuple3<Long, Long, Long>, Long> keyedBidOneWindowed = bidOneWindowed.keyBy((KeySelector<Tuple3<Long, Long, Long>, Long>) value -> value.f2); KeyedStream<Tuple2<Long, Long>, Long> keyedBidTwoWindowed = bidTwoWindowed.keyBy((KeySelector<Tuple2<Long, Long>, Long>) value -> value.f1); SingleOutputStreamOperator<Tuple2<Long, Long>> process = keyedBidOneWindowed.connect(keyedBidTwoWindowed) .process(new OneAndTwoConnectProcess()) .name("ConnectProcess") .uid("ConnectProcess") .setParallelism(params.getInt("ConnectProcess", 1)); process.addSink(new DiscardingSink<>()) .name("DiscardingSink") .uid("DiscardingSink") .setParallelism(params.getInt("DiscardingSink", 1)); env.execute("Nexmark Query5"); } public static final class OneAndTwoConnectProcess extends KeyedCoProcessFunction<Long, Tuple3<Long, Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> { ValueState<Long> maxCount; ListState<Tuple3<Long, Long, Long>> bidOneList; @Override public void open(Configuration parameters) throws Exception { ValueStateDescriptor<Long> maxCountDescriptor = new ValueStateDescriptor<>("MaxCount", LONG_TYPE_INFO); ListStateDescriptor<Tuple3<Long, Long, Long>> bidOneListDescriptor = new ListStateDescriptor<>("BidOneList", TypeInformation.of(new TypeHint<Tuple3<Long, Long, Long>>() { })); maxCount = getRuntimeContext().getState(maxCountDescriptor); bidOneList = getRuntimeContext().getListState(bidOneListDescriptor); } @Override public void processElement1(Tuple3<Long, Long, Long> value, Context ctx, Collector<Tuple2<Long, Long>> out) throws Exception { Long count = maxCount.value(); if (count == null) { bidOneList.add(value); } else if (value.f1 >= count) { out.collect(new Tuple2<>(value.f0, value.f1)); } } @Override public void processElement2(Tuple2<Long, Long> value, Context ctx, Collector<Tuple2<Long, Long>> out) throws Exception { maxCount.update(value.f0); Iterable<Tuple3<Long, Long, Long>> bidOnes = bidOneList.get(); for (Tuple3<Long, Long, Long> bid : bidOnes) { if (bid.f1 >= value.f0) { out.collect(new Tuple2<>(bid.f0, bid.f1)); } } bidOneList.clear(); } } public static final class MaxCountWithAllKeyWindow extends RichAllWindowFunction<Bid, Tuple2<Long, Long>, TimeWindow> { MapState<Long, Long> keyedCount; @Override public void open(Configuration parameters) throws Exception { MapStateDescriptor<Long, Long> keyedCountDescriptor = new MapStateDescriptor<>("KeyedCount", LONG_TYPE_INFO, LONG_TYPE_INFO); keyedCount = getRuntimeContext().getMapState(keyedCountDescriptor); } @Override public void apply(TimeWindow window, Iterable<Bid> values, Collector<Tuple2<Long, Long>> out) throws Exception { for (Bid v : values) { Long acc = keyedCount.get(v.auction); Long count = acc == null ? 0L : acc; keyedCount.put(v.auction, count + 1); } Long maxCount = 0L; for (Long value : keyedCount.values()) { maxCount = Math.max(maxCount, value); } keyedCount.clear(); out.collect(new Tuple2<>(maxCount, window.getEnd())); } } public static final class TimestampExtractor extends BoundedOutOfOrdernessTimestampExtractor<Bid> { private long maxTimestamp = Long.MIN_VALUE; public TimestampExtractor(Time maxOutOfOrderness) { super(maxOutOfOrderness); } @Override public long extractTimestamp(Bid element) { maxTimestamp = Math.max(maxTimestamp, element.dateTime.getMillis()); return element.dateTime.getMillis(); } } public static final class CountBidsWithTime extends RichWindowFunction<Bid, Tuple3<Long, Long, Long>, Long, TimeWindow> { @Override public void apply(Long aLong, TimeWindow window, Iterable<Bid> input, Collector<Tuple3<Long, Long, Long>> out) throws Exception { Long count = 0L; for (Bid in : input) { count++; } out.collect(new Tuple3<>(aLong, count, window.getEnd())); } } }
UTF-8
Java
8,161
java
Query5.java
Java
[]
null
[]
package cn.edu.buaa.network.nexmark; import cn.edu.buaa.network.nexmark.sources.BidSourceFunction; import org.apache.beam.sdk.nexmark.model.Bid; import org.apache.flink.api.common.state.*; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.KeyedStream; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.co.KeyedCoProcessFunction; import org.apache.flink.streaming.api.functions.sink.DiscardingSink; import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor; import org.apache.flink.streaming.api.functions.windowing.RichAllWindowFunction; import org.apache.flink.streaming.api.functions.windowing.RichWindowFunction; import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.streaming.runtime.operators.util.AssignerWithPeriodicWatermarksAdapter; import org.apache.flink.util.Collector; import static org.apache.flink.api.common.typeinfo.BasicTypeInfo.LONG_TYPE_INFO; /** * Query 5, 'Hot Items'. Which auctions have seen the most bids in the last hour (updated every * minute). In CQL syntax: * * <pre>{@code * SELECT Rstream(auction) * FROM (SELECT B1.auction, count(*) AS num * FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B1 * GROUP BY B1.auction) * WHERE num >= ALL (SELECT count(*) * FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B2 * GROUP BY B2.auction); * }</pre> * * <p>To make things a bit more dynamic and easier to test we use much shorter windows, and we'll * also preserve the bid counts. */ public class Query5 { public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.disableOperatorChaining(); env.getConfig().setAutoWatermarkInterval(1000); final int srcRate = params.getInt("srcRate", 100000); DataStream<Bid> bidOneSource = env.addSource(new BidSourceFunction(srcRate)) .name("BidOneSource") .uid("BidOneSource") .setParallelism(params.getInt("BidOneSource", 1)) .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarksAdapter.Strategy<>(new TimestampExtractor(Time.seconds(0)))); DataStream<Bid> bidTwoSource = env.addSource(new BidSourceFunction(srcRate)) .name("BidTwoSource") .uid("BidTwoSource") .setParallelism(params.getInt("BidTwoSource", 1)) .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarksAdapter.Strategy<>(new TimestampExtractor(Time.seconds(0)))); // SELECT B1.auction, count(*) AS num // FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B1 // GROUP BY B1.auction DataStream<Tuple3<Long, Long, Long>> bidOneWindowed = bidOneSource.keyBy((KeySelector<Bid, Long>) value -> value.auction) .window(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(2))) .apply(new CountBidsWithTime()) .name("BidOneSlidingWindow") .uid("BidOneSlidingWindow") .setParallelism(params.getInt("BidOneSlidingWindow", 1)); // ALL (SELECT B2.auction, count(*) AS num // FROM Bid [RANGE 60 MINUTE SLIDE 1 MINUTE] B2 // GROUP BY B2.auction) DataStream<Tuple2<Long, Long>> bidTwoWindowed = bidTwoSource.windowAll(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(2))) .apply(new MaxCountWithAllKeyWindow()) .name("BidTwoSlidingWindow") .uid("BidTwoSlidingWindow") .setParallelism(params.getInt("BidTwoSlidingWindow", 1)); KeyedStream<Tuple3<Long, Long, Long>, Long> keyedBidOneWindowed = bidOneWindowed.keyBy((KeySelector<Tuple3<Long, Long, Long>, Long>) value -> value.f2); KeyedStream<Tuple2<Long, Long>, Long> keyedBidTwoWindowed = bidTwoWindowed.keyBy((KeySelector<Tuple2<Long, Long>, Long>) value -> value.f1); SingleOutputStreamOperator<Tuple2<Long, Long>> process = keyedBidOneWindowed.connect(keyedBidTwoWindowed) .process(new OneAndTwoConnectProcess()) .name("ConnectProcess") .uid("ConnectProcess") .setParallelism(params.getInt("ConnectProcess", 1)); process.addSink(new DiscardingSink<>()) .name("DiscardingSink") .uid("DiscardingSink") .setParallelism(params.getInt("DiscardingSink", 1)); env.execute("Nexmark Query5"); } public static final class OneAndTwoConnectProcess extends KeyedCoProcessFunction<Long, Tuple3<Long, Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> { ValueState<Long> maxCount; ListState<Tuple3<Long, Long, Long>> bidOneList; @Override public void open(Configuration parameters) throws Exception { ValueStateDescriptor<Long> maxCountDescriptor = new ValueStateDescriptor<>("MaxCount", LONG_TYPE_INFO); ListStateDescriptor<Tuple3<Long, Long, Long>> bidOneListDescriptor = new ListStateDescriptor<>("BidOneList", TypeInformation.of(new TypeHint<Tuple3<Long, Long, Long>>() { })); maxCount = getRuntimeContext().getState(maxCountDescriptor); bidOneList = getRuntimeContext().getListState(bidOneListDescriptor); } @Override public void processElement1(Tuple3<Long, Long, Long> value, Context ctx, Collector<Tuple2<Long, Long>> out) throws Exception { Long count = maxCount.value(); if (count == null) { bidOneList.add(value); } else if (value.f1 >= count) { out.collect(new Tuple2<>(value.f0, value.f1)); } } @Override public void processElement2(Tuple2<Long, Long> value, Context ctx, Collector<Tuple2<Long, Long>> out) throws Exception { maxCount.update(value.f0); Iterable<Tuple3<Long, Long, Long>> bidOnes = bidOneList.get(); for (Tuple3<Long, Long, Long> bid : bidOnes) { if (bid.f1 >= value.f0) { out.collect(new Tuple2<>(bid.f0, bid.f1)); } } bidOneList.clear(); } } public static final class MaxCountWithAllKeyWindow extends RichAllWindowFunction<Bid, Tuple2<Long, Long>, TimeWindow> { MapState<Long, Long> keyedCount; @Override public void open(Configuration parameters) throws Exception { MapStateDescriptor<Long, Long> keyedCountDescriptor = new MapStateDescriptor<>("KeyedCount", LONG_TYPE_INFO, LONG_TYPE_INFO); keyedCount = getRuntimeContext().getMapState(keyedCountDescriptor); } @Override public void apply(TimeWindow window, Iterable<Bid> values, Collector<Tuple2<Long, Long>> out) throws Exception { for (Bid v : values) { Long acc = keyedCount.get(v.auction); Long count = acc == null ? 0L : acc; keyedCount.put(v.auction, count + 1); } Long maxCount = 0L; for (Long value : keyedCount.values()) { maxCount = Math.max(maxCount, value); } keyedCount.clear(); out.collect(new Tuple2<>(maxCount, window.getEnd())); } } public static final class TimestampExtractor extends BoundedOutOfOrdernessTimestampExtractor<Bid> { private long maxTimestamp = Long.MIN_VALUE; public TimestampExtractor(Time maxOutOfOrderness) { super(maxOutOfOrderness); } @Override public long extractTimestamp(Bid element) { maxTimestamp = Math.max(maxTimestamp, element.dateTime.getMillis()); return element.dateTime.getMillis(); } } public static final class CountBidsWithTime extends RichWindowFunction<Bid, Tuple3<Long, Long, Long>, Long, TimeWindow> { @Override public void apply(Long aLong, TimeWindow window, Iterable<Bid> input, Collector<Tuple3<Long, Long, Long>> out) throws Exception { Long count = 0L; for (Bid in : input) { count++; } out.collect(new Tuple3<>(aLong, count, window.getEnd())); } } }
8,161
0.745252
0.733611
203
39.201969
38.458904
173
false
false
0
0
0
0
0
0
2.374384
false
false
10
4536931ac923acb320709722b92107ca3115c047
36,842,229,486,166
9702a51962cda6e1922d671dbec8acf21d9e84ec
/src/main/com/topcoder/web/aolicq/dao/AolicqDAOUtil.java
6e03e9304aa729a0e686f3414d540201f5b3fe8e
[]
no_license
topcoder-platform/tc-website
https://github.com/topcoder-platform/tc-website
ccf111d95a4d7e033d3cf2f6dcf19364babb8a08
15ab92adf0e60afb1777b3d548b5ba3c3f6c12f7
refs/heads/dev
2023-08-23T13:41:21.308000
2023-04-04T01:28:38
2023-04-04T01:28:38
83,655,110
3
19
null
false
2023-04-04T01:32:16
2017-03-02T08:43:01
2023-01-31T16:48:18
2023-04-04T01:32:15
504,085
2
14
19
Java
false
false
package com.topcoder.web.aolicq.dao; import com.topcoder.web.aolicq.dao.hibernate.AolicqDAOFactoryHibernate; /** * @author dok * @version $Revision$ Date: 2005/01/01 00:00:00 * Create Date: Jul 17, 2006 */ public class AolicqDAOUtil { public static AolicqDAOFactory getFactory() { return new AolicqDAOFactoryHibernate(); } }
UTF-8
Java
356
java
AolicqDAOUtil.java
Java
[ { "context": "bernate.AolicqDAOFactoryHibernate;\n\n/**\n * @author dok\n * @version $Revision$ Date: 2005/01/01 00:00:00\n", "end": 129, "score": 0.995752215385437, "start": 126, "tag": "USERNAME", "value": "dok" } ]
null
[]
package com.topcoder.web.aolicq.dao; import com.topcoder.web.aolicq.dao.hibernate.AolicqDAOFactoryHibernate; /** * @author dok * @version $Revision$ Date: 2005/01/01 00:00:00 * Create Date: Jul 17, 2006 */ public class AolicqDAOUtil { public static AolicqDAOFactory getFactory() { return new AolicqDAOFactoryHibernate(); } }
356
0.702247
0.646067
14
24.428572
22.81827
71
false
false
0
0
0
0
0
0
0.285714
false
false
10
84efb210e1304675c42f96bf0d374559b1b26c52
35,244,501,675,778
caeee03c16513be8a47e25f925ee02c0d6da3ae2
/CookyApp/src/main/java/de/cookyapp/enums/Role.java
237e532d46b94ddbcfbe2d9dc0bd7660fb1394a7
[]
no_license
dschaufelberger/Cooky
https://github.com/dschaufelberger/Cooky
f5527e1dab34e108ac87d3cf9306647c776935ec
dab9ad5df7d46347e9861426be0fbee3e4f2ee97
refs/heads/master
2021-01-18T03:10:10.958000
2016-06-07T12:37:55
2016-06-07T12:37:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.cookyapp.enums; /** * Created by Dominik Schaufelberger on 14.05.2016. */ public enum Role { COOKY_USER, COOKY_ADMIN }
UTF-8
Java
141
java
Role.java
Java
[ { "context": "package de.cookyapp.enums;\n\n/**\n * Created by Dominik Schaufelberger on 14.05.2016.\n */\npublic enum Role {\n COOKY_U", "end": 68, "score": 0.9998708963394165, "start": 46, "tag": "NAME", "value": "Dominik Schaufelberger" } ]
null
[]
package de.cookyapp.enums; /** * Created by <NAME> on 14.05.2016. */ public enum Role { COOKY_USER, COOKY_ADMIN }
125
0.673759
0.617021
9
14.666667
15.398413
51
false
false
0
0
0
0
0
0
0.222222
false
false
10
7a4292ada907cde6728f4b445b67534e324fa3ed
35,244,501,675,600
1f2011841ddc728d338b6bb3b7be35a84b565315
/app/src/main/java/com/example/kitchen_assistant/models/HistoryEntry.java
173c23a884e7ed619c62a835113587ebbc581c9c
[]
no_license
truonghh99/Kitchen-Assistant
https://github.com/truonghh99/Kitchen-Assistant
16eddaad7c9f8984dd60fd0455bcb93969803582
b60e2c5b399e189bf4007fab8b917456dbe4bc88
refs/heads/master
2022-12-01T16:08:39.139000
2020-08-13T19:52:43
2020-08-13T19:52:43
278,228,540
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.kitchen_assistant.models; import android.util.Log; import com.example.kitchen_assistant.storage.CurrentHistoryEntries; import com.parse.ParseClassName; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseUser; import java.util.Date; import java.util.Map; @ParseClassName("HistoryEntry") public class HistoryEntry extends ParseObject { private static final String TAG = "HistoryEntry"; // Parse key public static final String KEY_RECIPE_ID = "recipeId"; public static final String KEY_USER_ID = "userId"; public static final String KEY_CREATED_AT = "createdAt"; public static final String KEY_CALORIES = "cumulativeCalories"; public static final String KEY_CARBS = "cumulativeCarbs"; public static final String KEY_PROTEIN = "cumulativeProtein"; public static final String KEY_FAT = "cumulativeFat"; // Local storage private String recipeId; private String userId; private Date timestamp; private float cumulativeCalories; private float cumulativeProtein; private float cumulativeCarbs; private float cumulativeFat; private static float lastCalories = 0; private static float lastProtein = 0; private static float lastCarbs = 0; private static float lastFat = 0; public static void addEntryFromRecipe(Recipe recipe) { HistoryEntry entry = new HistoryEntry(); entry.setRecipeId(recipe.getCode()); entry.setUserId(ParseUser.getCurrentUser().getObjectId()); entry.setTimestamp(new Date()); entry.setCumulativeCalories(lastCalories + recipe.getNutrition().getCalories()); entry.setCumulativeCarbs(lastCarbs + recipe.getNutrition().getCarbs()); entry.setCumulativeProtein(lastProtein + recipe.getNutrition().getProtein()); entry.setCumulativeFat(lastFat + recipe.getNutrition().getFat()); updateLatestEntry(entry); CurrentHistoryEntries.addEntry(entry); } public static void updateLatestEntry(HistoryEntry entry) { lastCalories = entry.getCumulativeCalories(); lastProtein = entry.getCumulativeProtein(); lastCarbs = entry.getCumulativeCarbs(); lastFat = entry.getCumulativeFat(); } public void fetchInfo() { try { fetch(); } catch (ParseException e) { Log.e(TAG, "Cannot fetch history entry"); e.printStackTrace(); } recipeId = getString(KEY_RECIPE_ID); userId = getString(KEY_USER_ID); timestamp = getCreatedAt(); cumulativeCalories = getNumber(KEY_CALORIES).floatValue(); cumulativeCarbs = getNumber(KEY_CARBS).floatValue(); cumulativeProtein = getNumber(KEY_PROTEIN).floatValue(); cumulativeFat = getNumber(KEY_FAT).floatValue(); } public void saveInfo() { put(KEY_RECIPE_ID, recipeId); put(KEY_USER_ID, userId); put(KEY_CALORIES, cumulativeCalories); put(KEY_CARBS, cumulativeCarbs); put(KEY_PROTEIN, cumulativeProtein); put(KEY_FAT, cumulativeFat); } public String getRecipeId() { return recipeId; } public void setRecipeId(String recipeId) { this.recipeId = recipeId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public float getCumulativeCalories() { return cumulativeCalories; } public void setCumulativeCalories(float cumulativeCalories) { this.cumulativeCalories = cumulativeCalories; } public float getCumulativeProtein() { return cumulativeProtein; } public void setCumulativeProtein(float cumulativeProtein) { this.cumulativeProtein = cumulativeProtein; } public float getCumulativeCarbs() { return cumulativeCarbs; } public void setCumulativeCarbs(float cumulativeCarbs) { this.cumulativeCarbs = cumulativeCarbs; } public float getCumulativeFat() { return cumulativeFat; } public void setCumulativeFat(float cumulativeFat) { this.cumulativeFat = cumulativeFat; } }
UTF-8
Java
4,357
java
HistoryEntry.java
Java
[]
null
[]
package com.example.kitchen_assistant.models; import android.util.Log; import com.example.kitchen_assistant.storage.CurrentHistoryEntries; import com.parse.ParseClassName; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseUser; import java.util.Date; import java.util.Map; @ParseClassName("HistoryEntry") public class HistoryEntry extends ParseObject { private static final String TAG = "HistoryEntry"; // Parse key public static final String KEY_RECIPE_ID = "recipeId"; public static final String KEY_USER_ID = "userId"; public static final String KEY_CREATED_AT = "createdAt"; public static final String KEY_CALORIES = "cumulativeCalories"; public static final String KEY_CARBS = "cumulativeCarbs"; public static final String KEY_PROTEIN = "cumulativeProtein"; public static final String KEY_FAT = "cumulativeFat"; // Local storage private String recipeId; private String userId; private Date timestamp; private float cumulativeCalories; private float cumulativeProtein; private float cumulativeCarbs; private float cumulativeFat; private static float lastCalories = 0; private static float lastProtein = 0; private static float lastCarbs = 0; private static float lastFat = 0; public static void addEntryFromRecipe(Recipe recipe) { HistoryEntry entry = new HistoryEntry(); entry.setRecipeId(recipe.getCode()); entry.setUserId(ParseUser.getCurrentUser().getObjectId()); entry.setTimestamp(new Date()); entry.setCumulativeCalories(lastCalories + recipe.getNutrition().getCalories()); entry.setCumulativeCarbs(lastCarbs + recipe.getNutrition().getCarbs()); entry.setCumulativeProtein(lastProtein + recipe.getNutrition().getProtein()); entry.setCumulativeFat(lastFat + recipe.getNutrition().getFat()); updateLatestEntry(entry); CurrentHistoryEntries.addEntry(entry); } public static void updateLatestEntry(HistoryEntry entry) { lastCalories = entry.getCumulativeCalories(); lastProtein = entry.getCumulativeProtein(); lastCarbs = entry.getCumulativeCarbs(); lastFat = entry.getCumulativeFat(); } public void fetchInfo() { try { fetch(); } catch (ParseException e) { Log.e(TAG, "Cannot fetch history entry"); e.printStackTrace(); } recipeId = getString(KEY_RECIPE_ID); userId = getString(KEY_USER_ID); timestamp = getCreatedAt(); cumulativeCalories = getNumber(KEY_CALORIES).floatValue(); cumulativeCarbs = getNumber(KEY_CARBS).floatValue(); cumulativeProtein = getNumber(KEY_PROTEIN).floatValue(); cumulativeFat = getNumber(KEY_FAT).floatValue(); } public void saveInfo() { put(KEY_RECIPE_ID, recipeId); put(KEY_USER_ID, userId); put(KEY_CALORIES, cumulativeCalories); put(KEY_CARBS, cumulativeCarbs); put(KEY_PROTEIN, cumulativeProtein); put(KEY_FAT, cumulativeFat); } public String getRecipeId() { return recipeId; } public void setRecipeId(String recipeId) { this.recipeId = recipeId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public float getCumulativeCalories() { return cumulativeCalories; } public void setCumulativeCalories(float cumulativeCalories) { this.cumulativeCalories = cumulativeCalories; } public float getCumulativeProtein() { return cumulativeProtein; } public void setCumulativeProtein(float cumulativeProtein) { this.cumulativeProtein = cumulativeProtein; } public float getCumulativeCarbs() { return cumulativeCarbs; } public void setCumulativeCarbs(float cumulativeCarbs) { this.cumulativeCarbs = cumulativeCarbs; } public float getCumulativeFat() { return cumulativeFat; } public void setCumulativeFat(float cumulativeFat) { this.cumulativeFat = cumulativeFat; } }
4,357
0.680285
0.679367
143
29.468531
22.936155
88
false
false
0
0
0
0
0
0
0.552448
false
false
10
02b774a07a719a23ba0329cea80ce51958692af3
33,956,011,492,581
a4a51084cfb715c7076c810520542af38a854868
/src/main/java/androidx/core/g/v.java
0577ba14a069378a0960d7e9c1db6b0d19c83ff3
[]
no_license
BharathPalanivelu/repotest
https://github.com/BharathPalanivelu/repotest
ddaf56a94eb52867408e0e769f35bef2d815da72
f78ae38738d2ba6c9b9b4049f3092188fabb5b59
refs/heads/master
2020-09-30T18:55:04.802000
2019-12-02T10:52:08
2019-12-02T10:52:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package androidx.core.g; import android.view.VelocityTracker; @Deprecated public final class v { @Deprecated public static float a(VelocityTracker velocityTracker, int i) { return velocityTracker.getXVelocity(i); } }
UTF-8
Java
239
java
v.java
Java
[]
null
[]
package androidx.core.g; import android.view.VelocityTracker; @Deprecated public final class v { @Deprecated public static float a(VelocityTracker velocityTracker, int i) { return velocityTracker.getXVelocity(i); } }
239
0.732218
0.732218
11
20.727272
20.670977
67
false
false
0
0
0
0
0
0
0.363636
false
false
10
6db800b99fcbcb862a53a1ada7b215174fbe25a9
25,451,976,257,212
9b33a32530197dbeabd9f253ee3fd3d11c764507
/app/models/MaisAntigoNaoAssistido.java
8d46cfc6d80ba0880b8ebebff7a25485f5cde548
[]
no_license
leticiamaia/si1-lab2-parte3
https://github.com/leticiamaia/si1-lab2-parte3
9d4a4c1d6d978fb9e2a0fdbd5d0fa9bd5c0c732b
5d82ebcdf712f031dd90b2d59673d4e6ae3c9eb2
refs/heads/master
2021-01-24T05:15:13.775000
2015-02-13T23:56:42
2015-02-13T23:56:42
30,425,987
0
0
null
true
2015-02-06T18:10:30
2015-02-06T18:10:30
2014-12-06T00:12:05
2014-12-06T00:12:05
1,660
0
0
0
null
null
null
package models; import javax.persistence.Entity; import java.util.List; /** * Created by Leticia on 2/13/2015. */ @Entity(name="MaisAntigoNaoAssistido") public class MaisAntigoNaoAssistido extends IndicadorDeProximoEp{ public MaisAntigoNaoAssistido(Serie serie) {super.serie = serie;} public MaisAntigoNaoAssistido() {} @Override protected Episodio proximoEpisodio(int temporada, Serie serie) { List<Episodio> episodios = serie.getEpisodios(temporada); for (int i = 0; i < episodios.size(); i++) { if (!episodios.get(i).isAssistido()) { return episodios.get(i); } } return null; } }
UTF-8
Java
681
java
MaisAntigoNaoAssistido.java
Java
[ { "context": ".Entity;\nimport java.util.List;\n\n/**\n * Created by Leticia on 2/13/2015.\n */\n@Entity(name=\"MaisAntigoNaoAssi", "end": 99, "score": 0.9993034601211548, "start": 92, "tag": "NAME", "value": "Leticia" } ]
null
[]
package models; import javax.persistence.Entity; import java.util.List; /** * Created by Leticia on 2/13/2015. */ @Entity(name="MaisAntigoNaoAssistido") public class MaisAntigoNaoAssistido extends IndicadorDeProximoEp{ public MaisAntigoNaoAssistido(Serie serie) {super.serie = serie;} public MaisAntigoNaoAssistido() {} @Override protected Episodio proximoEpisodio(int temporada, Serie serie) { List<Episodio> episodios = serie.getEpisodios(temporada); for (int i = 0; i < episodios.size(); i++) { if (!episodios.get(i).isAssistido()) { return episodios.get(i); } } return null; } }
681
0.651982
0.640235
25
26.24
23.777771
69
false
false
0
0
0
0
0
0
0.4
false
false
10
b2d3e8a46e2a4cce42bdf0a462608ea556456403
37,503,654,456,997
fe1b9ef5832d8e43171a751b90dec8dfb67bd153
/CoursePricing/src/test/java/com/example/course/service/PriceServiceImplTest.java
fa35bbf821dca0b9b529b2e30b0e19eb9b47c0e5
[]
no_license
vrajeshjayswal/UpworkTest
https://github.com/vrajeshjayswal/UpworkTest
1f65ceb9300a6a181bd893f4c732ad85a03fd32f
63ee0ac813df2cedab747436649a16b43c31d6e2
refs/heads/master
2022-11-13T00:44:22.963000
2020-07-11T09:53:26
2020-07-11T09:53:26
278,294,778
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.course.service; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.math.BigDecimal; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import com.example.course.entity.Country; import com.example.course.entity.Course; import com.example.course.entity.PaymentStrategy; import com.example.course.entity.Price; import com.example.course.pojo.PriceBreakup; import com.example.course.repository.PriceRepository; import exception.PriceNotFoundException; /** * Unit testing for PriceServiceImpl class * * @author vrajesh * */ @SpringBootTest public class PriceServiceImplTest { private static final BigDecimal BASE_PRICE = BigDecimal.ONE; private static final BigDecimal WHOLE_PRICE = BigDecimal.valueOf(1.45); private static final BigDecimal OTHER_CHARGES = BigDecimal.valueOf(0.25); private static final BigDecimal TAXES = BigDecimal.valueOf(0.15); private static final BigDecimal CONVERSION_FEES = BigDecimal.valueOf(0.05); private static final Long COURSE_ID = 3L; private static final Long COUNTRY_ID = 2L; private static final Long INVALID_COURSE_ID = 1L; @Mock private PriceRepository priceRepository; @InjectMocks private PriceServiceImpl priceService; @BeforeEach void setMockOutput() { Course course = new Course(); course.setPaymentStrategy(PaymentStrategy.MONTHLY_SUBSCRIPTION); Country country = new Country(); country.setConversionFees(CONVERSION_FEES); Price price = new Price(); price.setBasePrice(BASE_PRICE); price.setOtherCharges(OTHER_CHARGES); price.setTaxes(TAXES); price.setCountry(country); price.setCourse(course); Optional<Price> priceOptional = Optional.of(price); when(priceRepository.findByCourse_CourseIdAndCountry_CountryId(COURSE_ID, COUNTRY_ID)) .thenReturn(priceOptional); } @DisplayName("PriceService - getCourseBasePrice - valid scenario") @Test void testGetCourseBasePrice() throws PriceNotFoundException { PriceBreakup priceBreakup = priceService.getCourseBasePrice(COURSE_ID, COUNTRY_ID); assertNotNull(priceBreakup); assertEquals(BASE_PRICE, priceBreakup.getBasePrice()); assertNull(priceBreakup.getTotalPrice()); } @DisplayName("PriceService - getCourseBasePrice - Price not found scenario") @Test void testGetCourseBasePriceRecordNotFound() { assertThrows(PriceNotFoundException.class, () -> priceService.getCourseBasePrice(INVALID_COURSE_ID, COUNTRY_ID)); } @DisplayName("PriceService - getCourseWholePrice - valid scenario") @Test void testGetCourseWholePrice() throws PriceNotFoundException { PriceBreakup priceBreakup = priceService.getCourseWholePrice(COURSE_ID, COUNTRY_ID); assertNotNull(priceBreakup); assertEquals(WHOLE_PRICE, priceBreakup.getTotalPrice()); assertNull(priceBreakup.getBasePrice()); } @DisplayName("PriceService - getCourseWholePrice - Price not found scenario") @Test void testGetCourseWholePriceRecordNotFound() { assertThrows(PriceNotFoundException.class, () -> priceService.getCourseWholePrice(INVALID_COURSE_ID, COUNTRY_ID)); } @DisplayName("PriceService - getCoursePriceBreakup - valid scenario") @Test void getCoursePriceBreakup() throws PriceNotFoundException { PriceBreakup priceBreakup; priceBreakup = priceService.getCoursePriceBreakup(COURSE_ID, COUNTRY_ID); assertNotNull(priceBreakup); assertEquals(BASE_PRICE, priceBreakup.getBasePrice()); assertEquals(WHOLE_PRICE, priceBreakup.getTotalPrice()); assertEquals(CONVERSION_FEES, priceBreakup.getConversionFees()); assertEquals(OTHER_CHARGES, priceBreakup.getOtherCharges()); assertEquals(TAXES, priceBreakup.getTaxes()); assertEquals(COUNTRY_ID, priceBreakup.getCountryId()); assertEquals(COURSE_ID, priceBreakup.getCourseId()); assertEquals(PaymentStrategy.MONTHLY_SUBSCRIPTION.name(), priceBreakup.getPaymentStrategy()); } @DisplayName("PriceService - getCoursePriceBreakup - Price not found scenario") @Test void getCoursePriceBreakupRecordNotFound() { assertThrows(PriceNotFoundException.class, () -> priceService.getCoursePriceBreakup(INVALID_COURSE_ID, COUNTRY_ID)); } }
UTF-8
Java
4,475
java
PriceServiceImplTest.java
Java
[ { "context": " testing for PriceServiceImpl class\n * \n * @author vrajesh\n *\n */\n@SpringBootTest\npublic class PriceServiceI", "end": 951, "score": 0.9873467683792114, "start": 944, "tag": "USERNAME", "value": "vrajesh" } ]
null
[]
package com.example.course.service; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import java.math.BigDecimal; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import com.example.course.entity.Country; import com.example.course.entity.Course; import com.example.course.entity.PaymentStrategy; import com.example.course.entity.Price; import com.example.course.pojo.PriceBreakup; import com.example.course.repository.PriceRepository; import exception.PriceNotFoundException; /** * Unit testing for PriceServiceImpl class * * @author vrajesh * */ @SpringBootTest public class PriceServiceImplTest { private static final BigDecimal BASE_PRICE = BigDecimal.ONE; private static final BigDecimal WHOLE_PRICE = BigDecimal.valueOf(1.45); private static final BigDecimal OTHER_CHARGES = BigDecimal.valueOf(0.25); private static final BigDecimal TAXES = BigDecimal.valueOf(0.15); private static final BigDecimal CONVERSION_FEES = BigDecimal.valueOf(0.05); private static final Long COURSE_ID = 3L; private static final Long COUNTRY_ID = 2L; private static final Long INVALID_COURSE_ID = 1L; @Mock private PriceRepository priceRepository; @InjectMocks private PriceServiceImpl priceService; @BeforeEach void setMockOutput() { Course course = new Course(); course.setPaymentStrategy(PaymentStrategy.MONTHLY_SUBSCRIPTION); Country country = new Country(); country.setConversionFees(CONVERSION_FEES); Price price = new Price(); price.setBasePrice(BASE_PRICE); price.setOtherCharges(OTHER_CHARGES); price.setTaxes(TAXES); price.setCountry(country); price.setCourse(course); Optional<Price> priceOptional = Optional.of(price); when(priceRepository.findByCourse_CourseIdAndCountry_CountryId(COURSE_ID, COUNTRY_ID)) .thenReturn(priceOptional); } @DisplayName("PriceService - getCourseBasePrice - valid scenario") @Test void testGetCourseBasePrice() throws PriceNotFoundException { PriceBreakup priceBreakup = priceService.getCourseBasePrice(COURSE_ID, COUNTRY_ID); assertNotNull(priceBreakup); assertEquals(BASE_PRICE, priceBreakup.getBasePrice()); assertNull(priceBreakup.getTotalPrice()); } @DisplayName("PriceService - getCourseBasePrice - Price not found scenario") @Test void testGetCourseBasePriceRecordNotFound() { assertThrows(PriceNotFoundException.class, () -> priceService.getCourseBasePrice(INVALID_COURSE_ID, COUNTRY_ID)); } @DisplayName("PriceService - getCourseWholePrice - valid scenario") @Test void testGetCourseWholePrice() throws PriceNotFoundException { PriceBreakup priceBreakup = priceService.getCourseWholePrice(COURSE_ID, COUNTRY_ID); assertNotNull(priceBreakup); assertEquals(WHOLE_PRICE, priceBreakup.getTotalPrice()); assertNull(priceBreakup.getBasePrice()); } @DisplayName("PriceService - getCourseWholePrice - Price not found scenario") @Test void testGetCourseWholePriceRecordNotFound() { assertThrows(PriceNotFoundException.class, () -> priceService.getCourseWholePrice(INVALID_COURSE_ID, COUNTRY_ID)); } @DisplayName("PriceService - getCoursePriceBreakup - valid scenario") @Test void getCoursePriceBreakup() throws PriceNotFoundException { PriceBreakup priceBreakup; priceBreakup = priceService.getCoursePriceBreakup(COURSE_ID, COUNTRY_ID); assertNotNull(priceBreakup); assertEquals(BASE_PRICE, priceBreakup.getBasePrice()); assertEquals(WHOLE_PRICE, priceBreakup.getTotalPrice()); assertEquals(CONVERSION_FEES, priceBreakup.getConversionFees()); assertEquals(OTHER_CHARGES, priceBreakup.getOtherCharges()); assertEquals(TAXES, priceBreakup.getTaxes()); assertEquals(COUNTRY_ID, priceBreakup.getCountryId()); assertEquals(COURSE_ID, priceBreakup.getCourseId()); assertEquals(PaymentStrategy.MONTHLY_SUBSCRIPTION.name(), priceBreakup.getPaymentStrategy()); } @DisplayName("PriceService - getCoursePriceBreakup - Price not found scenario") @Test void getCoursePriceBreakupRecordNotFound() { assertThrows(PriceNotFoundException.class, () -> priceService.getCoursePriceBreakup(INVALID_COURSE_ID, COUNTRY_ID)); } }
4,475
0.795754
0.792402
126
34.523811
26.638889
95
false
false
0
0
0
0
0
0
1.650794
false
false
10
8f37e187a8c5f5c2b430748544c58b55b1f86515
37,503,654,456,290
69fde681f0eb27ac5b416cd00628fc2458bacb05
/src/main/java/matrix/MatrixTask.java
1d52730c38bd96e7ec29c670134c5d4d97f6eab6
[]
no_license
wzhang12/operatefile
https://github.com/wzhang12/operatefile
b1426159b1a73c03933330c61a92792954a46394
dcc574f9c1daa419d1222a19f8dc4bc124689aa1
refs/heads/master
2021-01-01T19:01:33.384000
2016-01-06T11:07:32
2016-01-06T11:07:32
33,345,257
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package matrix; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; public class MatrixTask implements Runnable { private static final AtomicInteger counter = new AtomicInteger(); private static final int FOUNDED_WORDS_BUF_SIZE = 1024; private final PageReader in; private final String[] words; private final Map<String, Map<String, AtomicInteger>> out; public MatrixTask( PageReader reader, String[] inputWords, Map<String, Map<String, AtomicInteger>> output ) { in = reader; words = inputWords; out = output; } public void run() { String[] founded = new String[FOUNDED_WORDS_BUF_SIZE]; int wordsFound; String[] lines; while ((lines = in.readPage()) != null) { for (String line : lines) { wordsFound = 0; for (String word : words) { // String.contains() -> 主要性能瓶颈,但是似乎没有更快的方法了 if (line.contains(word)) founded[wordsFound++] = word; } for (int ptr1 = 0; ptr1 < wordsFound - 1; ptr1++) { for (int ptr2 = ptr1 + 1; ptr2 < wordsFound; ptr2++) { // counter -> 主要内存瓶颈(对于测试数据,约消耗300M内存) out .computeIfAbsent(founded[ptr1], e -> new ConcurrentHashMap<>()) .computeIfAbsent(founded[ptr2], e -> new AtomicInteger()) .incrementAndGet(); } } // 每4k行左右报告一次进度 int count = counter.incrementAndGet(); if ((count & 0xFFF) == 0) echo(count + " lines compared"); } } } // t0:运行开始时间 private static final long t0 = System.currentTimeMillis(); // t1:上次调用echo的时间 private static long t1 = t0; public synchronized static void echo(String msg) { long now = System.currentTimeMillis(); System.out.println("time " + (now - t0) + " (+" + (now - t1) + "): " + msg); t1 = now; } }
UTF-8
Java
1,906
java
MatrixTask.java
Java
[]
null
[]
package matrix; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; public class MatrixTask implements Runnable { private static final AtomicInteger counter = new AtomicInteger(); private static final int FOUNDED_WORDS_BUF_SIZE = 1024; private final PageReader in; private final String[] words; private final Map<String, Map<String, AtomicInteger>> out; public MatrixTask( PageReader reader, String[] inputWords, Map<String, Map<String, AtomicInteger>> output ) { in = reader; words = inputWords; out = output; } public void run() { String[] founded = new String[FOUNDED_WORDS_BUF_SIZE]; int wordsFound; String[] lines; while ((lines = in.readPage()) != null) { for (String line : lines) { wordsFound = 0; for (String word : words) { // String.contains() -> 主要性能瓶颈,但是似乎没有更快的方法了 if (line.contains(word)) founded[wordsFound++] = word; } for (int ptr1 = 0; ptr1 < wordsFound - 1; ptr1++) { for (int ptr2 = ptr1 + 1; ptr2 < wordsFound; ptr2++) { // counter -> 主要内存瓶颈(对于测试数据,约消耗300M内存) out .computeIfAbsent(founded[ptr1], e -> new ConcurrentHashMap<>()) .computeIfAbsent(founded[ptr2], e -> new AtomicInteger()) .incrementAndGet(); } } // 每4k行左右报告一次进度 int count = counter.incrementAndGet(); if ((count & 0xFFF) == 0) echo(count + " lines compared"); } } } // t0:运行开始时间 private static final long t0 = System.currentTimeMillis(); // t1:上次调用echo的时间 private static long t1 = t0; public synchronized static void echo(String msg) { long now = System.currentTimeMillis(); System.out.println("time " + (now - t0) + " (+" + (now - t1) + "): " + msg); t1 = now; } }
1,906
0.649606
0.632171
66
25.939394
22.140652
78
false
false
0
0
0
0
0
0
2.833333
false
false
10
14d1b92948a4d606a38cd2d84f1df10c685df071
12,678,743,510,330
d9e374943344e25299a58de161cdee1ce3108d59
/src/main/java/com/allforfunmc/CamoStuff/CamoBlock.java
8e7213cbdda3ff42e3e40709c8c09f0af80c69bf
[ "MIT" ]
permissive
AllForFun/modpack
https://github.com/AllForFun/modpack
1869bf595536c716252a59d8e8889cd56c7021f3
0befd4db4175438e6125901dbad92d1c87332370
refs/heads/master
2021-01-23T11:48:16.496000
2015-03-01T18:56:49
2015-03-01T18:56:49
21,941,773
1
0
null
false
2014-10-14T16:11:32
2014-07-17T12:53:10
2014-10-10T11:43:06
2014-10-14T13:00:59
8,028
4
5
16
Java
null
null
package com.allforfunmc.CamoStuff; import com.allforfunmc.allforfuncore.Core; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class CamoBlock extends Block implements ITileEntityProvider { public CamoBlock(Material mat){ super(mat); setBlockName("camo_block"); setCreativeTab(Core.AllForFunBlocks); this.setHardness(6f); this.setHarvestLevel("pickaxe", 3); this.setBlockTextureName("sleshymod:camo_block"); } @Override public boolean isOpaqueCube(){ return false; } /* @Override @SideOnly(Side.CLIENT) public IIcon getIcon(IBlockAccess block, int x, int y, int z, int side){ return this.getTileEntity(block, x,y,z); }*/ @Override public TileEntity createTileEntity(World world, int metadata){ return ((ITileEntityProvider) this).createNewTileEntity(world, metadata); } public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_){ return new CamoBlockEntity(); } protected CamoBlockEntity getTileEntity(IBlockAccess blockAccess, int x, int y, int z) { CamoBlockEntity camoBlockEntity; TileEntity TE = blockAccess.getTileEntity(x, y, z); if (TE instanceof CamoBlockEntity) camoBlockEntity = (CamoBlockEntity) TE; else camoBlockEntity = null; return camoBlockEntity; } }
UTF-8
Java
1,560
java
CamoBlock.java
Java
[]
null
[]
package com.allforfunmc.CamoStuff; import com.allforfunmc.allforfuncore.Core; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class CamoBlock extends Block implements ITileEntityProvider { public CamoBlock(Material mat){ super(mat); setBlockName("camo_block"); setCreativeTab(Core.AllForFunBlocks); this.setHardness(6f); this.setHarvestLevel("pickaxe", 3); this.setBlockTextureName("sleshymod:camo_block"); } @Override public boolean isOpaqueCube(){ return false; } /* @Override @SideOnly(Side.CLIENT) public IIcon getIcon(IBlockAccess block, int x, int y, int z, int side){ return this.getTileEntity(block, x,y,z); }*/ @Override public TileEntity createTileEntity(World world, int metadata){ return ((ITileEntityProvider) this).createNewTileEntity(world, metadata); } public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_){ return new CamoBlockEntity(); } protected CamoBlockEntity getTileEntity(IBlockAccess blockAccess, int x, int y, int z) { CamoBlockEntity camoBlockEntity; TileEntity TE = blockAccess.getTileEntity(x, y, z); if (TE instanceof CamoBlockEntity) camoBlockEntity = (CamoBlockEntity) TE; else camoBlockEntity = null; return camoBlockEntity; } }
1,560
0.774359
0.764103
56
26.857143
23.309584
87
false
false
0
0
0
0
0
0
1.696429
false
false
10
6958c51e18d5e40190cec64534931e58a7d446a4
39,402,029,993,667
19dd636fb3fb6485571f021d20aaf8443a06c2d4
/src/org/twak/tweed/gen/SolverState.java
50c901d2bd060d99bdd928e03a269949266e93b2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
twak/chordatlas
https://github.com/twak/chordatlas
b15e939d345e32ef459a0b1d22500a16eee4abee
9f5603b03a8e50570e00edad3f74ecb44b33df91
refs/heads/stable
2022-03-01T05:46:09.474000
2022-02-13T19:13:29
2022-02-13T19:13:29
93,035,129
99
28
Apache-2.0
false
2020-11-16T20:30:46
2017-06-01T08:33:28
2020-11-09T08:04:50
2020-11-16T20:30:45
41,672
65
17
3
Java
false
false
package org.twak.tweed.gen; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import org.twak.tweed.gen.FeatureCache.MFPoint; import org.twak.tweed.gen.FeatureCache.MegaFeatures; import org.twak.utils.CloneSerializable; import org.twak.utils.DumbCluster1D; import org.twak.utils.DumbCluster1D.Cluster; import org.twak.utils.Line; import org.twak.utils.PaintThing; import org.twak.utils.PaintThing.ICanPaint; import org.twak.utils.PanMouseAdaptor; import org.twak.utils.collections.MultiMap; import org.twak.utils.geom.HalfMesh2; import org.twak.utils.geom.HalfMesh2.HalfEdge; import org.twak.utils.geom.HalfMesh2.HalfFace; import org.twak.utils.ui.Plot; import org.twak.utils.ui.Rainbow; import org.twak.viewTrace.SuperLine; import org.twak.viewTrace.facades.MiniFacade; import org.twak.viewTrace.facades.MiniFacadePainter; import com.thoughtworks.xstream.XStream; public class SolverState implements Serializable { HalfMesh2 mesh; MultiMap<MegaFeatures, MFPoint> minis; List<Prof> globalProfs; Map<SuperEdge, double[]> profFit; List<Line> footprint; public StringBuilder dbgInfo = new StringBuilder(); public SolverState( HalfMesh2 mesh, MultiMap<MegaFeatures, MFPoint> minis, List<Prof> globalProfs, Map<SuperEdge, double[]> profFit, List<Line> footprint ) { this.mesh = mesh; this.minis = minis; this.globalProfs = globalProfs; this.profFit = profFit; this.footprint = footprint; } public SolverState copy( boolean removeMegaFacades ) { SolverState out = (SolverState) CloneSerializable.xClone( this ); if (removeMegaFacades) { for (HalfFace f : out.mesh) for (HalfEdge e : f) { SuperEdge se = (SuperEdge)e; if (se.profLine != null) se.profLine.mega = null; if (e.over != null && ((SuperEdge)e.over).profLine != null) ((SuperEdge)e.over).profLine.mega = null; } } return out; } public void debugSolverResult() { new Plot( mesh ).add ( miniPainter() ).add (new ICanPaint() { @Override public void paint( Graphics2D g, PanMouseAdaptor ma ) { Set<HalfEdge> seen = new HashSet<>(); Color tWhite = new Color(255,255,255,150); if (!seen.isEmpty()) for (HalfFace f : mesh) { for (HalfEdge e : f) { int i = ((SuperEdge)e).profI; // if (i == -1) // continue; Point2d loc = e.line().fromPPram( 0.5 ); String s = ""+i; int offset = e.start.x < e.end.x ? -10 : 10; seen.add(e); Rectangle2D b = g.getFontMetrics().getStringBounds( s, g ); b = new Rectangle2D.Double(0,0, b.getWidth()+ 4, b.getHeight() ); g.setColor(tWhite); g.fillRect(ma.toX( loc.x ) - (int) ( b.getWidth()/2), offset+ ma.toY(loc.y ) - (int)(b.getHeight()/2), (int)(b.getWidth()), (int)(b.getHeight())); g.setColor(Color.gray); g.drawString( s, ma.toX( loc.x ) - (int) ( b.getWidth()/2)+2, offset+ma.toY(loc.y ) + (int)(b.getHeight()/2) - 3); } } }} ); } public ICanPaint miniPainter() { return new ICanPaint() { @Override public void paint( Graphics2D g, PanMouseAdaptor ma ) { // for ( MegaFeatures f : SS.minis.keySet() ) { // // for ( MFPoint mfp : SS.minis.get( f ) ) { // Line l = mfp.image.mega.megafacade; // // spreadImages( g, ma, l, mfp, Listz.from( mfp.left, mfp.right ) ); // // } // } // if (SS.minis == null) int brake = 100; for ( HalfFace f : mesh ) { for ( HalfEdge e : f ) { if ( e.over != null ) continue; if (brake-- < 0) break; SuperEdge se = (SuperEdge) e; if ( se.toRegularize == null ) continue; List<MiniFacade> mfs = new ArrayList( se.toRegularize ); // while (mfs .size() < 2) // mfs.add(null); spreadImages( g, ma, se.line(), se.line().fromPPram( 0.5 ), mfs ); } } int i = 0; if ( minis != null ) for ( MegaFeatures f : minis.keySet() ) { // PaintThing.paint (f.megafacade, g, ma); DumbCluster1D<MFPoint> res = GurobiSkelSolver.clusterMinis( f, minis ); Vector2d dir = f.megafacade.dir(); Vector2d out = new Vector2d( dir ); out.set( -out.y, out.x ); out.scale( ma.toZoom( 2 ) / out.length() ); for ( Cluster<MFPoint> c : res ) { g.setColor( Rainbow.getColour( i++ ) ); for ( MFPoint mfp : c.things ) { Point2d pt = new Point2d( mfp ); pt.add( out ); g.setStroke( new BasicStroke( 0.2f ) ); PaintThing.paint( pt, g, ma ); g.setStroke( new BasicStroke( 0.2f ) ); for ( HalfEdge e : GurobiSkelSolver.findNear( f.megafacade, mfp, mesh ) ) g.drawLine( ma.toX( pt.x ), ma.toY( pt.y ), ma.toX( e.end.x ), ma.toY( e.end.y ) ); if ( mfp.selectedEdge != null ) { g.setStroke( new BasicStroke( 2f ) ); g.drawLine( ma.toX( pt.x ), ma.toY( pt.y ), ma.toX( mfp.selectedEdge.end.x ), ma.toY( mfp.selectedEdge.end.y ) ); } } } } g.setStroke( new BasicStroke( 1 ) ); } private void spreadImages( Graphics2D g, PanMouseAdaptor ma, Line sel, Point2d cen, List<MiniFacade> mfs ) { Vector2d perp = sel.dir(); perp.set( -perp.y, perp.x ); perp.normalize(); MiniFacadePainter mfPainter = new MiniFacadePainter(); for ( int i = 0; i < mfs.size(); i++ ) { MiniFacade mf = mfs.get( i ); Vector2d p2 = new Vector2d( perp ); p2.scale( ( i + 1 ) * 10 ); p2.add( cen ); if ( mf == null ) { g.setColor( Color.black ); g.fillRect( ma.toX( p2.x - 1 ), ma.toY( p2.y - 3 ), ma.toZoom( 2 ), ma.toZoom( 6 ) ); continue; } double w = mf.width * 0.1; double h = mf.height * 0.1; mfPainter.paintImage( g, ma, mf, p2.x - w, p2.y - h, p2.x + w, p2.y + h ); } } }; } public void save( File location, boolean clean ) { try { if ( clean ) cleanMegas(); System.out.print( "writing state to " + location +" ..." ); location.getAbsoluteFile().getParentFile().mkdirs(); new XStream().toXML( this, new FileOutputStream( location ) ); System.out.println( "done!" ); } catch ( FileNotFoundException e ) { e.printStackTrace(); } } private void cleanMegas() { for ( HalfFace f : mesh ) { for ( HalfEdge e : f ) { SuperEdge se = (SuperEdge) e; if ( se.profLine != null ) ( (SuperLine) se.profLine ).mega = null; } } } }
UTF-8
Java
6,900
java
SolverState.java
Java
[]
null
[]
package org.twak.tweed.gen; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.vecmath.Point2d; import javax.vecmath.Vector2d; import org.twak.tweed.gen.FeatureCache.MFPoint; import org.twak.tweed.gen.FeatureCache.MegaFeatures; import org.twak.utils.CloneSerializable; import org.twak.utils.DumbCluster1D; import org.twak.utils.DumbCluster1D.Cluster; import org.twak.utils.Line; import org.twak.utils.PaintThing; import org.twak.utils.PaintThing.ICanPaint; import org.twak.utils.PanMouseAdaptor; import org.twak.utils.collections.MultiMap; import org.twak.utils.geom.HalfMesh2; import org.twak.utils.geom.HalfMesh2.HalfEdge; import org.twak.utils.geom.HalfMesh2.HalfFace; import org.twak.utils.ui.Plot; import org.twak.utils.ui.Rainbow; import org.twak.viewTrace.SuperLine; import org.twak.viewTrace.facades.MiniFacade; import org.twak.viewTrace.facades.MiniFacadePainter; import com.thoughtworks.xstream.XStream; public class SolverState implements Serializable { HalfMesh2 mesh; MultiMap<MegaFeatures, MFPoint> minis; List<Prof> globalProfs; Map<SuperEdge, double[]> profFit; List<Line> footprint; public StringBuilder dbgInfo = new StringBuilder(); public SolverState( HalfMesh2 mesh, MultiMap<MegaFeatures, MFPoint> minis, List<Prof> globalProfs, Map<SuperEdge, double[]> profFit, List<Line> footprint ) { this.mesh = mesh; this.minis = minis; this.globalProfs = globalProfs; this.profFit = profFit; this.footprint = footprint; } public SolverState copy( boolean removeMegaFacades ) { SolverState out = (SolverState) CloneSerializable.xClone( this ); if (removeMegaFacades) { for (HalfFace f : out.mesh) for (HalfEdge e : f) { SuperEdge se = (SuperEdge)e; if (se.profLine != null) se.profLine.mega = null; if (e.over != null && ((SuperEdge)e.over).profLine != null) ((SuperEdge)e.over).profLine.mega = null; } } return out; } public void debugSolverResult() { new Plot( mesh ).add ( miniPainter() ).add (new ICanPaint() { @Override public void paint( Graphics2D g, PanMouseAdaptor ma ) { Set<HalfEdge> seen = new HashSet<>(); Color tWhite = new Color(255,255,255,150); if (!seen.isEmpty()) for (HalfFace f : mesh) { for (HalfEdge e : f) { int i = ((SuperEdge)e).profI; // if (i == -1) // continue; Point2d loc = e.line().fromPPram( 0.5 ); String s = ""+i; int offset = e.start.x < e.end.x ? -10 : 10; seen.add(e); Rectangle2D b = g.getFontMetrics().getStringBounds( s, g ); b = new Rectangle2D.Double(0,0, b.getWidth()+ 4, b.getHeight() ); g.setColor(tWhite); g.fillRect(ma.toX( loc.x ) - (int) ( b.getWidth()/2), offset+ ma.toY(loc.y ) - (int)(b.getHeight()/2), (int)(b.getWidth()), (int)(b.getHeight())); g.setColor(Color.gray); g.drawString( s, ma.toX( loc.x ) - (int) ( b.getWidth()/2)+2, offset+ma.toY(loc.y ) + (int)(b.getHeight()/2) - 3); } } }} ); } public ICanPaint miniPainter() { return new ICanPaint() { @Override public void paint( Graphics2D g, PanMouseAdaptor ma ) { // for ( MegaFeatures f : SS.minis.keySet() ) { // // for ( MFPoint mfp : SS.minis.get( f ) ) { // Line l = mfp.image.mega.megafacade; // // spreadImages( g, ma, l, mfp, Listz.from( mfp.left, mfp.right ) ); // // } // } // if (SS.minis == null) int brake = 100; for ( HalfFace f : mesh ) { for ( HalfEdge e : f ) { if ( e.over != null ) continue; if (brake-- < 0) break; SuperEdge se = (SuperEdge) e; if ( se.toRegularize == null ) continue; List<MiniFacade> mfs = new ArrayList( se.toRegularize ); // while (mfs .size() < 2) // mfs.add(null); spreadImages( g, ma, se.line(), se.line().fromPPram( 0.5 ), mfs ); } } int i = 0; if ( minis != null ) for ( MegaFeatures f : minis.keySet() ) { // PaintThing.paint (f.megafacade, g, ma); DumbCluster1D<MFPoint> res = GurobiSkelSolver.clusterMinis( f, minis ); Vector2d dir = f.megafacade.dir(); Vector2d out = new Vector2d( dir ); out.set( -out.y, out.x ); out.scale( ma.toZoom( 2 ) / out.length() ); for ( Cluster<MFPoint> c : res ) { g.setColor( Rainbow.getColour( i++ ) ); for ( MFPoint mfp : c.things ) { Point2d pt = new Point2d( mfp ); pt.add( out ); g.setStroke( new BasicStroke( 0.2f ) ); PaintThing.paint( pt, g, ma ); g.setStroke( new BasicStroke( 0.2f ) ); for ( HalfEdge e : GurobiSkelSolver.findNear( f.megafacade, mfp, mesh ) ) g.drawLine( ma.toX( pt.x ), ma.toY( pt.y ), ma.toX( e.end.x ), ma.toY( e.end.y ) ); if ( mfp.selectedEdge != null ) { g.setStroke( new BasicStroke( 2f ) ); g.drawLine( ma.toX( pt.x ), ma.toY( pt.y ), ma.toX( mfp.selectedEdge.end.x ), ma.toY( mfp.selectedEdge.end.y ) ); } } } } g.setStroke( new BasicStroke( 1 ) ); } private void spreadImages( Graphics2D g, PanMouseAdaptor ma, Line sel, Point2d cen, List<MiniFacade> mfs ) { Vector2d perp = sel.dir(); perp.set( -perp.y, perp.x ); perp.normalize(); MiniFacadePainter mfPainter = new MiniFacadePainter(); for ( int i = 0; i < mfs.size(); i++ ) { MiniFacade mf = mfs.get( i ); Vector2d p2 = new Vector2d( perp ); p2.scale( ( i + 1 ) * 10 ); p2.add( cen ); if ( mf == null ) { g.setColor( Color.black ); g.fillRect( ma.toX( p2.x - 1 ), ma.toY( p2.y - 3 ), ma.toZoom( 2 ), ma.toZoom( 6 ) ); continue; } double w = mf.width * 0.1; double h = mf.height * 0.1; mfPainter.paintImage( g, ma, mf, p2.x - w, p2.y - h, p2.x + w, p2.y + h ); } } }; } public void save( File location, boolean clean ) { try { if ( clean ) cleanMegas(); System.out.print( "writing state to " + location +" ..." ); location.getAbsoluteFile().getParentFile().mkdirs(); new XStream().toXML( this, new FileOutputStream( location ) ); System.out.println( "done!" ); } catch ( FileNotFoundException e ) { e.printStackTrace(); } } private void cleanMegas() { for ( HalfFace f : mesh ) { for ( HalfEdge e : f ) { SuperEdge se = (SuperEdge) e; if ( se.profLine != null ) ( (SuperLine) se.profLine ).mega = null; } } } }
6,900
0.602029
0.588841
255
26.062746
23.703314
122
false
false
0
0
0
0
0
0
3.913725
false
false
10