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
sequence
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
sequence
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
eede5bebcbf67b70986c23cce62fd56bdb906265
3,521,873,210,651
cbf98f589fbab4a4030d288cafa442e4e9987370
/src/tecno/controller/ProdutoController.java
eb8dfca42cb152af247c0a87dde513572129b202
[]
no_license
joaoe5/tecnoroca
https://github.com/joaoe5/tecnoroca
e393b9d459a505437a3b84d4954819c15bfb2ff3
ae3653c075039bdcb886c14d154a62cc32c02514
refs/heads/master
2020-04-11T06:28:56.925000
2018-12-13T04:06:28
2018-12-13T04:06:28
161,581,759
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tecno.controller; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import tecno.dao.DAO; import tecno.modelo.Produto; import tecno.modelo.Usuario; @ViewScoped @ManagedBean public class ProdutoController { private Produto produto = new Produto(); private Integer idUsuario; public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } public void gravar(Produto produto) { FacesContext context = FacesContext.getCurrentInstance(); Usuario usuario = (Usuario) context.getExternalContext().getSessionMap().get("usuariologado"); usuario = new DAO<Usuario>(Usuario.class).buscaPorId(usuario.getId()); this.produto.setUsuario(usuario); DAO<Produto> dao = new DAO<Produto>(Produto.class); if(produto.getId() == null){ dao.adiciona(produto); } else{ dao.atualiza(produto); } this.produto = new Produto(); } public void carregar(Produto produto){ this.produto = produto; } // public void remover(Produto produto){ // new DAO<Produto>(Produto.class).remove(produto); // } public void remover(Produto produto){ try { new DAO<Produto>(Produto.class).remove(produto); } catch (Exception e) { e.printStackTrace(); FacesContext.getCurrentInstance().addMessage("produto", new FacesMessage("O produto não pode ser removido pois está vinculado a uma produção!")); } } public List<Produto> getProdutos(){ FacesContext context = FacesContext.getCurrentInstance(); Usuario usuario = (Usuario) context.getExternalContext().getSessionMap().get("usuariologado"); usuario = new DAO<Usuario>(Usuario.class).buscaPorId(usuario.getId()); this.produto.setUsuario(usuario); idUsuario = usuario.getId(); return new DAO<Produto>(Produto.class).listaPorUsuario(idUsuario); } public List<Produto> getTodosProdutos(){ return new DAO<Produto>(Produto.class).listaTodos(); } }
ISO-8859-1
Java
2,062
java
ProdutoController.java
Java
[]
null
[]
package tecno.controller; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import tecno.dao.DAO; import tecno.modelo.Produto; import tecno.modelo.Usuario; @ViewScoped @ManagedBean public class ProdutoController { private Produto produto = new Produto(); private Integer idUsuario; public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } public void gravar(Produto produto) { FacesContext context = FacesContext.getCurrentInstance(); Usuario usuario = (Usuario) context.getExternalContext().getSessionMap().get("usuariologado"); usuario = new DAO<Usuario>(Usuario.class).buscaPorId(usuario.getId()); this.produto.setUsuario(usuario); DAO<Produto> dao = new DAO<Produto>(Produto.class); if(produto.getId() == null){ dao.adiciona(produto); } else{ dao.atualiza(produto); } this.produto = new Produto(); } public void carregar(Produto produto){ this.produto = produto; } // public void remover(Produto produto){ // new DAO<Produto>(Produto.class).remove(produto); // } public void remover(Produto produto){ try { new DAO<Produto>(Produto.class).remove(produto); } catch (Exception e) { e.printStackTrace(); FacesContext.getCurrentInstance().addMessage("produto", new FacesMessage("O produto não pode ser removido pois está vinculado a uma produção!")); } } public List<Produto> getProdutos(){ FacesContext context = FacesContext.getCurrentInstance(); Usuario usuario = (Usuario) context.getExternalContext().getSessionMap().get("usuariologado"); usuario = new DAO<Usuario>(Usuario.class).buscaPorId(usuario.getId()); this.produto.setUsuario(usuario); idUsuario = usuario.getId(); return new DAO<Produto>(Produto.class).listaPorUsuario(idUsuario); } public List<Produto> getTodosProdutos(){ return new DAO<Produto>(Produto.class).listaTodos(); } }
2,062
0.732264
0.732264
82
24.097561
24.512123
96
false
false
0
0
0
0
0
0
1.682927
false
false
4
b19eb762732ec3ace8f405cf7859125f44d7a92a
9,912,784,550,568
a119edd785b152cda3aaee2128d1b9fd5f65fdd4
/exam_2020_march/ChristmasTournament.java
c4e302dca2661e2ad6bdb955d44195f76e033f6c
[]
no_license
m-d-asenov/SoftUni-Programming-Basics-with-Java-and-CPP
https://github.com/m-d-asenov/SoftUni-Programming-Basics-with-Java-and-CPP
9460c00ab0ed713c8a8930ff1fd70a663cb92054
cdfd5417d6b808bfefe8e03872670d53f6543ed2
refs/heads/master
2022-11-28T01:44:03.358000
2020-07-21T20:24:30
2020-07-21T20:24:30
276,233,442
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class ChristmasTournament{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); double totalMoney = 0.0; int winDays = 0; for(int i = 0; i < n; i++){ int wins = 0; int losses = 0; double dayMoney = 0.0; String input = sc.nextLine(); while(!input.equals("Finish")){ String result = sc.nextLine(); if(result.equals("win")){ dayMoney += 20; wins++; }else{ losses++; } //if(sc.hasNext()) input = sc.nextLine(); } if(wins > losses){ dayMoney += dayMoney * 0.1; totalMoney += dayMoney; winDays++; }else{ totalMoney += dayMoney; } } if(winDays > n - winDays){ totalMoney += totalMoney * 0.2; System.out.printf("You won the tournament! Total raised money: %.2f", totalMoney); }else{ System.out.printf("You lost the tournament! Total raised money: %.2f", totalMoney); } } }
UTF-8
Java
1,077
java
ChristmasTournament.java
Java
[]
null
[]
import java.util.Scanner; public class ChristmasTournament{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.nextLine()); double totalMoney = 0.0; int winDays = 0; for(int i = 0; i < n; i++){ int wins = 0; int losses = 0; double dayMoney = 0.0; String input = sc.nextLine(); while(!input.equals("Finish")){ String result = sc.nextLine(); if(result.equals("win")){ dayMoney += 20; wins++; }else{ losses++; } //if(sc.hasNext()) input = sc.nextLine(); } if(wins > losses){ dayMoney += dayMoney * 0.1; totalMoney += dayMoney; winDays++; }else{ totalMoney += dayMoney; } } if(winDays > n - winDays){ totalMoney += totalMoney * 0.2; System.out.printf("You won the tournament! Total raised money: %.2f", totalMoney); }else{ System.out.printf("You lost the tournament! Total raised money: %.2f", totalMoney); } } }
1,077
0.545961
0.531105
54
17.981482
18.396347
86
false
false
0
0
0
0
0
0
3.166667
false
false
4
adec17ff0f3b0a94d5c903371cb77dba167030fb
5,334,349,408,526
e8c0e98e7519fbc176d235a3bdfa04e3343b7541
/src/main/java/com/hm/manage/file/service/IFileService.java
a3f0a474e6ce6cfcfb0fbaa0e0dface307fb3488
[]
no_license
dreamhm/clown-service
https://github.com/dreamhm/clown-service
05ba146699879137c6ca6961cd6a328b0f6fbfe1
4fe42fa6b5a0aba96abbde71ea5c6e321333e0f9
refs/heads/master
2022-06-21T10:30:24.539000
2020-06-20T16:02:32
2020-06-20T16:02:32
241,352,481
1
0
null
false
2022-06-21T02:50:07
2020-02-18T12:12:59
2020-06-20T16:03:41
2022-06-21T02:50:07
113
0
0
2
Java
false
false
package com.hm.manage.file.service; import com.hm.common.entity.ClownResult; import com.hm.manage.file.model.FileBo; /** * @创建人 【郝苗】 * @创建时间 * @描述: */ public interface IFileService { /** *@描述 新增、修改文件信息 *@参数 fileBo *@返回值 clownResult *@创建人 haomiao *@创建时间 2020/2/16 */ public ClownResult addFileInfo(FileBo fileBo); /** *@描述 获取文件信息 *@参数 id *@返回值 file *@创建人 haomiao *@创建时间 2020/2/16 */ public ClownResult getFileInfo(Long id); /** *@描述 删除文件信息 *@参数 id *@返回值 file *@创建人 haomiao *@创建时间 2020/2/16 */ public ClownResult deleteFileInfo(Long id); }
UTF-8
Java
812
java
IFileService.java
Java
[ { "context": "rt com.hm.manage.file.model.FileBo;\n\n/**\n * @创建人 【郝苗】\n * @创建时间\n * @描述:\n */\npublic interface IFileServi", "end": 134, "score": 0.9449413418769836, "start": 132, "tag": "NAME", "value": "郝苗" }, { "context": " *@参数 fileBo\n *@返回值 clownResult\n *@创建人 haomiao\n *@创建时间 2020/2/16\n */\n public ClownRes", "end": 275, "score": 0.9995400309562683, "start": 268, "tag": "USERNAME", "value": "haomiao" }, { "context": "@描述 获取文件信息\n *@参数 id\n *@返回值 file\n *@创建人 haomiao\n *@创建时间 2020/2/16\n */\n public ClownRes", "end": 430, "score": 0.9992819428443909, "start": 423, "tag": "USERNAME", "value": "haomiao" }, { "context": "@描述 删除文件信息\n *@参数 id\n *@返回值 file\n *@创建人 haomiao\n *@创建时间 2020/2/16\n */\n public ClownRes", "end": 579, "score": 0.9994000792503357, "start": 572, "tag": "USERNAME", "value": "haomiao" } ]
null
[]
package com.hm.manage.file.service; import com.hm.common.entity.ClownResult; import com.hm.manage.file.model.FileBo; /** * @创建人 【郝苗】 * @创建时间 * @描述: */ public interface IFileService { /** *@描述 新增、修改文件信息 *@参数 fileBo *@返回值 clownResult *@创建人 haomiao *@创建时间 2020/2/16 */ public ClownResult addFileInfo(FileBo fileBo); /** *@描述 获取文件信息 *@参数 id *@返回值 file *@创建人 haomiao *@创建时间 2020/2/16 */ public ClownResult getFileInfo(Long id); /** *@描述 删除文件信息 *@参数 id *@返回值 file *@创建人 haomiao *@创建时间 2020/2/16 */ public ClownResult deleteFileInfo(Long id); }
812
0.571212
0.539394
38
16.368422
13.559656
50
false
false
0
0
0
0
0
0
0.157895
false
false
4
efdec9d4d88e71bd3989a4221e0373b0a122f3f4
17,394,617,576,949
b4d706c1a971a37bdae4193904681d31e632124e
/code/com/jivesoftware/os/tasmo/tasmo-id/src/main/java/com/jivesoftware/os/tasmo/id/BaseView.java
0679a74270ce42f4c1e0dc42c76437d5b42b481b
[ "Apache-2.0" ]
permissive
jnthnclt/tasmo
https://github.com/jnthnclt/tasmo
d64ba798bc4b6e26e13293db59e9a5116422f9a0
86d02eb95d1ffb58440349ff4d10f8db31439c93
refs/heads/master
2020-12-29T00:42:33.790000
2014-04-17T15:54:33
2014-04-17T15:54:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jivesoftware.os.tasmo.id; /** * Base implementation for all views. * * @param <E> event type that the view is rooted on */ public interface BaseView<E extends BaseEvent> { Ref<E> viewBase(); }
UTF-8
Java
215
java
BaseView.java
Java
[]
null
[]
package com.jivesoftware.os.tasmo.id; /** * Base implementation for all views. * * @param <E> event type that the view is rooted on */ public interface BaseView<E extends BaseEvent> { Ref<E> viewBase(); }
215
0.688372
0.688372
11
18.545454
19.924236
51
false
false
0
0
0
0
0
0
0.181818
false
false
4
55ba89ca95230a184d9c6a8700239cc51f9cd110
27,668,179,365,275
7da25f7c726ebba8805fc0a370607e0533c9b80c
/src/main/java/hudson/plugins/cobertura/targets/CoverageTreeElement.java
40b85719ddd378dbbfc9b5978e00eed647f31fe0
[ "MIT" ]
permissive
jenkinsci/cobertura-plugin
https://github.com/jenkinsci/cobertura-plugin
7d6846cd48397b1b14f06533d255ca40b6ae620f
343d1c46ac566b32a82f0c6dc0635e6ca4cc8d76
refs/heads/master
2023-08-30T11:10:00.297000
2023-08-23T13:32:03
2023-08-23T13:32:03
1,163,504
91
123
MIT
false
2023-09-04T17:59:44
2010-12-13T05:31:02
2023-08-23T06:50:49
2023-09-04T17:59:40
705
109
130
62
Java
false
false
package hudson.plugins.cobertura.targets; import java.io.Serializable; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import hudson.plugins.cobertura.Ratio; @ExportedBean public class CoverageTreeElement implements Serializable { /** * Generated */ private static final long serialVersionUID = 498666415572813346L; private Ratio ratio; private CoverageMetric metric; public CoverageTreeElement(CoverageMetric metric, Ratio ratio) { this.metric = metric; this.ratio = ratio; } @Exported public String getName() { return metric.getName(); } @Exported public float getRatio() { return ratio.getPercentageFloat(); } @Exported public float getNumerator() { return ratio.numerator; } @Exported public float getDenominator() { return ratio.denominator; } }
UTF-8
Java
937
java
CoverageTreeElement.java
Java
[]
null
[]
package hudson.plugins.cobertura.targets; import java.io.Serializable; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import hudson.plugins.cobertura.Ratio; @ExportedBean public class CoverageTreeElement implements Serializable { /** * Generated */ private static final long serialVersionUID = 498666415572813346L; private Ratio ratio; private CoverageMetric metric; public CoverageTreeElement(CoverageMetric metric, Ratio ratio) { this.metric = metric; this.ratio = ratio; } @Exported public String getName() { return metric.getName(); } @Exported public float getRatio() { return ratio.getPercentageFloat(); } @Exported public float getNumerator() { return ratio.numerator; } @Exported public float getDenominator() { return ratio.denominator; } }
937
0.680896
0.661686
46
19.369566
19.178066
69
false
false
0
0
0
0
0
0
0.326087
false
false
4
b774add4bd9dc0154c06fb027da6fd8fec5a4aeb
32,384,053,457,021
1cebfcd79a9a6eb096ff7a37c957b886bcb032a7
/BeansIntro/src/com/jp/person/BadPerson.java
dfcdf0a04176961f0739eef937bcad99eb5d6c78
[]
no_license
2004javausf/Day3Jordan
https://github.com/2004javausf/Day3Jordan
aaa00d5c88f53d76f864214fe5eb972a7da26251
e8a44796a562ed91b72a8dd5bcc3dcdd84f43cf1
refs/heads/master
2022-04-16T22:52:45.911000
2020-04-15T21:39:16
2020-04-15T21:39:16
256,041,725
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jp.person; public class BadPerson { String name; String bad_deed; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBad_deed() { return bad_deed; } public void setBad_deed(String bad_deed) { this.bad_deed = bad_deed; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "BadPerson [name=" + name + ", bad_deed=" + bad_deed + ", age=" + age + "]"; } }
UTF-8
Java
551
java
BadPerson.java
Java
[]
null
[]
package com.jp.person; public class BadPerson { String name; String bad_deed; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBad_deed() { return bad_deed; } public void setBad_deed(String bad_deed) { this.bad_deed = bad_deed; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "BadPerson [name=" + name + ", bad_deed=" + bad_deed + ", age=" + age + "]"; } }
551
0.631579
0.631579
32
16.21875
17.11128
85
false
false
0
0
0
0
0
0
1.5
false
false
4
ffbd915cc2255243306d4a8d3dd3a2858cb2a148
13,460,427,554,574
4323f9512a9b253143b32f4604837aecafa51570
/sneakLifeUT/src/main/java/com/sneaklife/ut/log/AccessLogAn.java
9dfc768feb430a733f12deb23b02623d50e6705b
[]
no_license
XiFYuW/sneakLife-admin
https://github.com/XiFYuW/sneakLife-admin
2f3fba3996859ed5e455d9daafdda0dc639a91fd
31a3f803a8bfcc687ac82c02c8aaba1e1e01cece
refs/heads/master
2022-02-22T18:49:43.481000
2022-02-04T02:44:03
2022-02-04T02:44:03
190,953,239
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sneaklife.ut.log; import java.lang.annotation.*; /** * @author https://github.com/XiFYuW * @date 2019/12/8 11:52 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface AccessLogAn { String value() default ""; }
UTF-8
Java
274
java
AccessLogAn.java
Java
[ { "context": ".annotation.*;\n\n/**\n * @author https://github.com/XiFYuW\n * @date 2019/12/8 11:52\n */\n@Retention(Retention", "end": 103, "score": 0.99955153465271, "start": 97, "tag": "USERNAME", "value": "XiFYuW" } ]
null
[]
package com.sneaklife.ut.log; import java.lang.annotation.*; /** * @author https://github.com/XiFYuW * @date 2019/12/8 11:52 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface AccessLogAn { String value() default ""; }
274
0.718978
0.678832
14
18.571428
13.988334
36
false
false
0
0
0
0
0
0
0.214286
false
false
4
0d4cf72d3adaf979d983adcc26243ad91fd471a2
37,495,064,503,598
d75a290b1ad85fff52efb46558a7587cbf66b585
/src/main/java/api_rest/rest/UserResource.java
53a0dc088933a00b075e3534988e53401d6d9e81
[]
no_license
ferPiece/api-rest
https://github.com/ferPiece/api-rest
ac7aedcecf606004afa2e180c715a41b0869f897
500890c0c910929ac80a23fc0aef5a00dc56806e
refs/heads/master
2021-01-23T12:52:59.170000
2017-06-05T20:02:12
2017-06-05T20:02:12
93,205,345
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package api_rest.rest; import api_rest.model.User; import api_rest.service.UserService; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; /** * Created by ferlopez on 02/06/2017. */ @Path("users") @RequestScoped public class UserResource { @EJB UserService userService; @GET @Path("/{id: \\d+}") @Produces(MediaType.APPLICATION_JSON) public User get(@PathParam("id") Long id) throws NotFoundException{ return userService.get(id); } @GET @Produces(MediaType.APPLICATION_JSON) public List<User> query(){ return userService.listAll(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response add(User user){ userService.add(user); return Response.status(Response.Status.CREATED).build(); } @PUT @Path("/{id: \\d+}") @Consumes(MediaType.APPLICATION_JSON) public Response update(User user, @PathParam("id") Long id) throws NotFoundException{ user.setId(id); userService.update(user); return Response.status(Response.Status.NO_CONTENT).build(); } @DELETE @Path("/{id: \\d+}") public Response remove(@PathParam("id") Long id) throws NotFoundException{ userService.remove(id); return Response.status(Response.Status.NO_CONTENT).build(); } }
UTF-8
Java
1,455
java
UserResource.java
Java
[ { "context": "esponse;\nimport java.util.List;\n\n/**\n * Created by ferlopez on 02/06/2017.\n */\n\n@Path(\"users\")\n@RequestScoped", "end": 300, "score": 0.9996650815010071, "start": 292, "tag": "USERNAME", "value": "ferlopez" } ]
null
[]
package api_rest.rest; import api_rest.model.User; import api_rest.service.UserService; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; /** * Created by ferlopez on 02/06/2017. */ @Path("users") @RequestScoped public class UserResource { @EJB UserService userService; @GET @Path("/{id: \\d+}") @Produces(MediaType.APPLICATION_JSON) public User get(@PathParam("id") Long id) throws NotFoundException{ return userService.get(id); } @GET @Produces(MediaType.APPLICATION_JSON) public List<User> query(){ return userService.listAll(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response add(User user){ userService.add(user); return Response.status(Response.Status.CREATED).build(); } @PUT @Path("/{id: \\d+}") @Consumes(MediaType.APPLICATION_JSON) public Response update(User user, @PathParam("id") Long id) throws NotFoundException{ user.setId(id); userService.update(user); return Response.status(Response.Status.NO_CONTENT).build(); } @DELETE @Path("/{id: \\d+}") public Response remove(@PathParam("id") Long id) throws NotFoundException{ userService.remove(id); return Response.status(Response.Status.NO_CONTENT).build(); } }
1,455
0.662543
0.657045
63
22.095238
21.867359
89
false
false
0
0
0
0
0
0
0.31746
false
false
4
ecf023bdf9154c1c14d8c82113498ac17c87f1b8
34,565,896,836,098
41db66a65ea6ef2ce2abe1c1f2edc26b69021f6a
/src/Collision/DualCircles.java
0276be3608a1e821f58c2793778ff70c436e1390
[]
no_license
GiCarden-GC/NuclearDeterrence
https://github.com/GiCarden-GC/NuclearDeterrence
3e07234c8690b93098564b0556a24b4ed7bc4b68
2274fba8db181fc905ce504f969630379637f2d2
refs/heads/master
2020-04-12T02:10:28.959000
2018-12-18T06:24:16
2018-12-18T06:24:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Collision; import Graphics.Shapes.Circle; import java.awt.*; /** * Code created by: Brett Bearden & Giovanni Cardenas * * Copyright (c) 2016, Nuclear Deterrence * * Dual Circles is designed as a collision model. The circles follow a sprite and circle 1 is centered over the sprite while circle 2 has an offset from the center. */ public class DualCircles { public Circle circle1; public Circle circle2; // Offset's are for Circle 2 in order to move and rotate in sync with Circle 1's center private int offsetR; private int offsetX; // Dual Circles public DualCircles(int r1, int r2, int offsetR, int offsetX) { this.offsetR = offsetR; this.offsetX = offsetX; // new Circle (float x, float y, int r) this.circle1 = new Circle(0, 0, r1); this.circle2 = new Circle(0, 0, r2); } // Draw public void draw(Graphics2D g, double cosA, double sinA) { // Draw Circle 1 circle1.draw(g, cosA, sinA); // Draw Circle 2 circle2.draw(g, cosA, sinA); } // Get OffSetR public int getOffsetR() { return offsetR; } // Get OffSetX public int getOffsetX() { return offsetX; } } // End of Class.
UTF-8
Java
1,235
java
DualCircles.java
Java
[ { "context": "rcle;\nimport java.awt.*;\n\n/**\n * Code created by: Brett Bearden & Giovanni Cardenas\n *\n * Copyright (c) 2016, Nu", "end": 109, "score": 0.9998703002929688, "start": 96, "tag": "NAME", "value": "Brett Bearden" }, { "context": "a.awt.*;\n\n/**\n * Code created by: Brett Bearden & Giovanni Cardenas\n *\n * Copyright (c) 2016, Nuclear Deterrence\n *\n", "end": 129, "score": 0.9998676776885986, "start": 112, "tag": "NAME", "value": "Giovanni Cardenas" } ]
null
[]
package Collision; import Graphics.Shapes.Circle; import java.awt.*; /** * Code created by: <NAME> & <NAME> * * Copyright (c) 2016, Nuclear Deterrence * * Dual Circles is designed as a collision model. The circles follow a sprite and circle 1 is centered over the sprite while circle 2 has an offset from the center. */ public class DualCircles { public Circle circle1; public Circle circle2; // Offset's are for Circle 2 in order to move and rotate in sync with Circle 1's center private int offsetR; private int offsetX; // Dual Circles public DualCircles(int r1, int r2, int offsetR, int offsetX) { this.offsetR = offsetR; this.offsetX = offsetX; // new Circle (float x, float y, int r) this.circle1 = new Circle(0, 0, r1); this.circle2 = new Circle(0, 0, r2); } // Draw public void draw(Graphics2D g, double cosA, double sinA) { // Draw Circle 1 circle1.draw(g, cosA, sinA); // Draw Circle 2 circle2.draw(g, cosA, sinA); } // Get OffSetR public int getOffsetR() { return offsetR; } // Get OffSetX public int getOffsetX() { return offsetX; } } // End of Class.
1,217
0.638866
0.618623
49
24.224489
29.296001
165
false
false
0
0
0
0
0
0
0.632653
false
false
4
c4362e5b65b55ea83df0aff7e2e5c2307271741a
34,857,954,592,840
869afb5ddb2406a8f23d6bddde22161f3f97517d
/training/src/training/Bank.java
9c6d74e9d2ef9d731462c6d9af175cfb06b31d2f
[]
no_license
krish71/training
https://github.com/krish71/training
343db43581dad9c71348aa7c1254e36de5c7be69
a004632a5c83dd20d48b99e7d70d96c647e5ae18
refs/heads/master
2020-03-24T23:56:12.555000
2018-08-29T13:16:11
2018-08-29T13:16:11
143,161,430
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package training; public interface Bank { void summary(); double getBalance(); void deposit(double amount); void withdraw(double amount) throws BalanceException; void statement(); void currentstatement(); int INIT_ACNT_NO = 1001; double MIN_SAV_BAL = 1000; double INIT_CUR_BAL = 5000; double MIN_CUR_BAL = 0; double OVERDRAFT_AMT = 10000; }
UTF-8
Java
380
java
Bank.java
Java
[]
null
[]
package training; public interface Bank { void summary(); double getBalance(); void deposit(double amount); void withdraw(double amount) throws BalanceException; void statement(); void currentstatement(); int INIT_ACNT_NO = 1001; double MIN_SAV_BAL = 1000; double INIT_CUR_BAL = 5000; double MIN_CUR_BAL = 0; double OVERDRAFT_AMT = 10000; }
380
0.678947
0.631579
22
15.363636
14.527546
54
false
false
0
0
0
0
0
0
1.045455
false
false
4
60fb5d7f6f41c0d5ab0d170ceae0014d33829168
37,709,812,862,369
fb61070c48c43ae8e8b23fbc3f09d423b6d7ca23
/android/MenuClient/src/emenu/client/bus/task/GetOrderedItemUpdateTask.java
9f5a6c87b81e516b7ceb45e60083bb7a717a45f4
[]
no_license
minhkhanh/UofS-LV
https://github.com/minhkhanh/UofS-LV
3f585e6864485fdb6782697cac5b83a1dfb8e78c
551ba5d89a53ebd6c46c5652ca6804d14eeccad1
refs/heads/master
2021-05-28T16:48:10.347000
2012-07-16T16:38:32
2012-07-16T16:38:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package emenu.client.bus.task; import emenu.client.dao.OrderDAO; public class GetOrderedItemUpdateTask extends CustomAsyncTask<Void, Void, Boolean> { private Integer mItemId; private int mVarQuantity; private String mItemNote; public GetOrderedItemUpdateTask(Integer itemId, int varQuantity, String itemNote) { mItemId = itemId; mVarQuantity = varQuantity; mItemNote = itemNote; } @Override protected Boolean doInBackground(Void... params) { try { return OrderDAO.getInstance().getOrderedItemUpdate(mItemId, mVarQuantity, mItemNote); } catch (Exception e) { e.printStackTrace(); return false; } } }
UTF-8
Java
765
java
GetOrderedItemUpdateTask.java
Java
[]
null
[]
package emenu.client.bus.task; import emenu.client.dao.OrderDAO; public class GetOrderedItemUpdateTask extends CustomAsyncTask<Void, Void, Boolean> { private Integer mItemId; private int mVarQuantity; private String mItemNote; public GetOrderedItemUpdateTask(Integer itemId, int varQuantity, String itemNote) { mItemId = itemId; mVarQuantity = varQuantity; mItemNote = itemNote; } @Override protected Boolean doInBackground(Void... params) { try { return OrderDAO.getInstance().getOrderedItemUpdate(mItemId, mVarQuantity, mItemNote); } catch (Exception e) { e.printStackTrace(); return false; } } }
765
0.627451
0.627451
26
27.423077
25.115385
87
false
false
0
0
0
0
0
0
0.653846
false
false
4
2da4fa59651f4e60bfb51080b2e090f9955f636b
7,138,235,712,806
842047d3c0abbd37fdeea82fe20c28828ea9241f
/ch4/src/ch4/CalcEx.java
c78d2781336c50477dde5521049df83e6e2b0845
[]
no_license
purelove2u/JavaClass
https://github.com/purelove2u/JavaClass
c19072a36d7fc8876b3129b38d8a5a74f902c732
ec9c0bf2923e0aa3ba1ed8d099bbbeedb03cc897
refs/heads/master
2023-07-04T15:52:22.342000
2021-08-18T09:38:52
2021-08-18T09:38:52
268,464,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch4; public class CalcEx { public static void main(String[] args) { Calc calc = new Calc(); // 리턴없는 메소드 호출 calc.powerOn(); // int a = calc.powerOn(); 불가능. 오류 // System.out.println(calc.powerOn()); 불가능. 오류 // add 메소드 호출 int result = calc.add(5, 7); // return 값 받기 int로 보냈으니 int로 받음 System.out.println(result); result = calc.add(12, 6); System.out.println(result); result = calc.add(18, 19); System.out.println(result); System.out.println(calc.add(24, 25)); System.out.println(calc.subtrac(5, 3)); System.out.println(calc.subtrac(12, 24)); System.out.println(calc.subtrac(15, 6)); System.out.println(calc.multiply(6, 9)); System.out.println(calc.divide(10, 3)); } }
UTF-8
Java
804
java
CalcEx.java
Java
[]
null
[]
package ch4; public class CalcEx { public static void main(String[] args) { Calc calc = new Calc(); // 리턴없는 메소드 호출 calc.powerOn(); // int a = calc.powerOn(); 불가능. 오류 // System.out.println(calc.powerOn()); 불가능. 오류 // add 메소드 호출 int result = calc.add(5, 7); // return 값 받기 int로 보냈으니 int로 받음 System.out.println(result); result = calc.add(12, 6); System.out.println(result); result = calc.add(18, 19); System.out.println(result); System.out.println(calc.add(24, 25)); System.out.println(calc.subtrac(5, 3)); System.out.println(calc.subtrac(12, 24)); System.out.println(calc.subtrac(15, 6)); System.out.println(calc.multiply(6, 9)); System.out.println(calc.divide(10, 3)); } }
804
0.637602
0.599455
31
22.67742
17.755302
63
false
false
0
0
0
0
0
0
2.548387
false
false
4
00ea1ab80fd391c3f6154a22b2562e76673c4a96
25,503,515,821,674
0f90d6227e090e6f269c44783a5e60ef3fb70b67
/components/org.wso2.carbon.data.provider/src/main/java/org/wso2/carbon/data/provider/rdbms/RDBMSStreamingDataProvider.java
22d30adf547f9499720d91d5372b73bbf2cc00cb
[ "Apache-2.0" ]
permissive
wso2/carbon-analytics
https://github.com/wso2/carbon-analytics
723e89ed061164f1755fbe90dfda32176a75a51e
03f4e6231633fd24112f3cede4597627df3661e8
refs/heads/master
2023-08-27T01:25:28.862000
2023-05-05T03:59:10
2023-05-05T03:59:10
16,543,113
63
301
Apache-2.0
false
2023-05-05T03:59:12
2014-02-05T11:40:58
2023-03-23T05:48:45
2023-05-05T03:59:11
122,461
29
194
38
JavaScript
false
false
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.data.provider.rdbms; import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.carbon.data.provider.DataProvider; import org.wso2.carbon.data.provider.bean.DataSetMetadata; import org.wso2.carbon.datasource.core.exception.DataSourceException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import static org.wso2.carbon.data.provider.rdbms.utils.RDBMSProviderConstants.LAST_RECORD_VALUE_PLACEHOLDER; /** * RDBMS streaming data provider instance. */ @Component( service = DataProvider.class, immediate = true ) public class RDBMSStreamingDataProvider extends AbstractRDBMSDataProvider { private static final Logger LOGGER = LoggerFactory.getLogger(RDBMSStreamingDataProvider.class); private double lastRecordValue = 0; @Override public void publish(String topic, String sessionId) { String customQuery = getRecordLimitQuery(); DataSetMetadata metadata = getMetadata(); int columnCount = getColumnCount(); if (customQuery != null) { Connection connection; try { connection = getConnection(getRdbmsProviderConfig().getDatasourceName()); PreparedStatement statement = null; ResultSet resultSet = null; try { if (lastRecordValue > 0) { String greaterThanWhereQuery = getGreaterThanWhereSQLQuery().replace (LAST_RECORD_VALUE_PLACEHOLDER, Double.toString(lastRecordValue)); statement = connection.prepareStatement(greaterThanWhereQuery); } else { statement = connection.prepareStatement(customQuery); } resultSet = statement.executeQuery(); ArrayList<Object[]> data = new ArrayList<>(); while (resultSet.next()) { Object[] rowData = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { if (metadata.getTypes()[i].equals(DataSetMetadata.Types.LINEAR)) { rowData[i] = resultSet.getDouble(i + 1); } else if (metadata.getTypes()[i].equals(DataSetMetadata.Types.ORDINAL)) { rowData[i] = resultSet.getString(i + 1); } else if (metadata.getTypes()[i].equals(DataSetMetadata.Types.TIME)) { rowData[i] = resultSet.getTimestamp(i + 1); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Meta Data type not defined, added value of the given column as a " + "java object."); } rowData[i] = resultSet.getObject(i + 1); } if (metadata.getNames()[i].equalsIgnoreCase(getRdbmsProviderConfig() .getIncrementalColumn()) && !metadata.getTypes()[i].equals(DataSetMetadata.Types.TIME)) { double value; if (rowData[i] instanceof Integer) { value = (int) rowData[i]; } else { value = (double) rowData[i]; } if (lastRecordValue < value) { lastRecordValue = value; } } } data.add(rowData); } if (!data.isEmpty() || lastRecordValue == 0) { publishToEndPoint(data, sessionId, topic); } } catch (SQLException e) { LOGGER.error("SQL exception occurred " + e.getMessage(), e); } finally { cleanupConnection(resultSet, statement, connection); } } catch (SQLException | DataSourceException e) { LOGGER.error("Failed to create a connection to the database " + e.getMessage(), e); } } } }
UTF-8
Java
5,290
java
RDBMSStreamingDataProvider.java
Java
[]
null
[]
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.data.provider.rdbms; import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.carbon.data.provider.DataProvider; import org.wso2.carbon.data.provider.bean.DataSetMetadata; import org.wso2.carbon.datasource.core.exception.DataSourceException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import static org.wso2.carbon.data.provider.rdbms.utils.RDBMSProviderConstants.LAST_RECORD_VALUE_PLACEHOLDER; /** * RDBMS streaming data provider instance. */ @Component( service = DataProvider.class, immediate = true ) public class RDBMSStreamingDataProvider extends AbstractRDBMSDataProvider { private static final Logger LOGGER = LoggerFactory.getLogger(RDBMSStreamingDataProvider.class); private double lastRecordValue = 0; @Override public void publish(String topic, String sessionId) { String customQuery = getRecordLimitQuery(); DataSetMetadata metadata = getMetadata(); int columnCount = getColumnCount(); if (customQuery != null) { Connection connection; try { connection = getConnection(getRdbmsProviderConfig().getDatasourceName()); PreparedStatement statement = null; ResultSet resultSet = null; try { if (lastRecordValue > 0) { String greaterThanWhereQuery = getGreaterThanWhereSQLQuery().replace (LAST_RECORD_VALUE_PLACEHOLDER, Double.toString(lastRecordValue)); statement = connection.prepareStatement(greaterThanWhereQuery); } else { statement = connection.prepareStatement(customQuery); } resultSet = statement.executeQuery(); ArrayList<Object[]> data = new ArrayList<>(); while (resultSet.next()) { Object[] rowData = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { if (metadata.getTypes()[i].equals(DataSetMetadata.Types.LINEAR)) { rowData[i] = resultSet.getDouble(i + 1); } else if (metadata.getTypes()[i].equals(DataSetMetadata.Types.ORDINAL)) { rowData[i] = resultSet.getString(i + 1); } else if (metadata.getTypes()[i].equals(DataSetMetadata.Types.TIME)) { rowData[i] = resultSet.getTimestamp(i + 1); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Meta Data type not defined, added value of the given column as a " + "java object."); } rowData[i] = resultSet.getObject(i + 1); } if (metadata.getNames()[i].equalsIgnoreCase(getRdbmsProviderConfig() .getIncrementalColumn()) && !metadata.getTypes()[i].equals(DataSetMetadata.Types.TIME)) { double value; if (rowData[i] instanceof Integer) { value = (int) rowData[i]; } else { value = (double) rowData[i]; } if (lastRecordValue < value) { lastRecordValue = value; } } } data.add(rowData); } if (!data.isEmpty() || lastRecordValue == 0) { publishToEndPoint(data, sessionId, topic); } } catch (SQLException e) { LOGGER.error("SQL exception occurred " + e.getMessage(), e); } finally { cleanupConnection(resultSet, statement, connection); } } catch (SQLException | DataSourceException e) { LOGGER.error("Failed to create a connection to the database " + e.getMessage(), e); } } } }
5,290
0.532703
0.527977
111
46.657658
29.331131
118
false
false
0
0
0
0
0
0
0.567568
false
false
4
be8fb9f19ed9368f77c407d6f4a636828b02b749
31,928,786,938,618
5b652af09e8392353a86bccb59427c22ebdd5a7d
/src/com/kingdee/eas/cp/bc/TravelAccountBillEntryCollection.java
889e789cf52923b581da8eb874f8d37e8f2c65a1
[]
no_license
yangpengfei0810/ypfGit
https://github.com/yangpengfei0810/ypfGit
595384192a8349634931e318303959cbabf7ea49
b5fc6a79f2cbb9ea817ba10766a061359ad7c006
refs/heads/master
2016-09-12T13:01:47.560000
2016-04-18T04:29:18
2016-04-18T04:29:18
56,286,364
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kingdee.eas.cp.bc; import com.kingdee.bos.dao.AbstractObjectCollection; import com.kingdee.bos.dao.IObjectPK; public class TravelAccountBillEntryCollection extends AbstractObjectCollection { public TravelAccountBillEntryCollection() { super(TravelAccountBillEntryInfo.class); } public boolean add(TravelAccountBillEntryInfo item) { return addObject(item); } public boolean addCollection(TravelAccountBillEntryCollection item) { return addObjectCollection(item); } public boolean remove(TravelAccountBillEntryInfo item) { return removeObject(item); } public TravelAccountBillEntryInfo get(int index) { return(TravelAccountBillEntryInfo)getObject(index); } public TravelAccountBillEntryInfo get(Object key) { return(TravelAccountBillEntryInfo)getObject(key); } public void set(int index, TravelAccountBillEntryInfo item) { setObject(index, item); } public boolean contains(TravelAccountBillEntryInfo item) { return containsObject(item); } public boolean contains(Object key) { return containsKey(key); } public int indexOf(TravelAccountBillEntryInfo item) { return super.indexOf(item); } }
UTF-8
Java
1,302
java
TravelAccountBillEntryCollection.java
Java
[]
null
[]
package com.kingdee.eas.cp.bc; import com.kingdee.bos.dao.AbstractObjectCollection; import com.kingdee.bos.dao.IObjectPK; public class TravelAccountBillEntryCollection extends AbstractObjectCollection { public TravelAccountBillEntryCollection() { super(TravelAccountBillEntryInfo.class); } public boolean add(TravelAccountBillEntryInfo item) { return addObject(item); } public boolean addCollection(TravelAccountBillEntryCollection item) { return addObjectCollection(item); } public boolean remove(TravelAccountBillEntryInfo item) { return removeObject(item); } public TravelAccountBillEntryInfo get(int index) { return(TravelAccountBillEntryInfo)getObject(index); } public TravelAccountBillEntryInfo get(Object key) { return(TravelAccountBillEntryInfo)getObject(key); } public void set(int index, TravelAccountBillEntryInfo item) { setObject(index, item); } public boolean contains(TravelAccountBillEntryInfo item) { return containsObject(item); } public boolean contains(Object key) { return containsKey(key); } public int indexOf(TravelAccountBillEntryInfo item) { return super.indexOf(item); } }
1,302
0.702765
0.702765
48
26.145834
23.858952
79
false
false
0
0
0
0
0
0
0.3125
false
false
4
7c10d0179e73a952d224a9b90d92cbd809603a16
1,769,526,551,532
e7a2185f56b7613eb3986971d38f0d0588fbe2bd
/androidClient/app/src/main/java/com/csatimes/dojma/viewholders/UtilitiesLinksViewHolder.java
51da739a6a7b2d3a8d4bc0b63de4fb16c11e0aff
[]
no_license
MysteriousAcadia/DoJMA
https://github.com/MysteriousAcadia/DoJMA
c4f28c5a1d4c2de03045b2ec9d036596b8aaa304
2bf3deb72c4f77d1f68fbc77e63f65d6dcc59e83
refs/heads/master
2020-05-04T18:58:06.371000
2019-04-04T07:06:22
2019-04-04T07:06:22
179,373,994
0
0
null
true
2019-04-03T21:36:41
2019-04-03T21:36:40
2019-04-01T19:49:34
2019-04-01T19:49:32
35,189
0
0
0
null
false
false
package com.csatimes.dojma.viewholders; import android.content.Context; import android.content.Intent; import android.net.Uri; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.Button; import com.csatimes.dojma.R; import com.csatimes.dojma.activities.UtilitiesLinksActivity; /** * Created by Vikramaditya Kukreja on 21-07-2016. */ public class UtilitiesLinksViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private Context context; public UtilitiesLinksViewHolder(View itemView, Context context) { super(itemView); Button link1 = (Button) itemView.findViewById(R.id.viewholder_links_format_link1); Button link2 = (Button) itemView.findViewById(R.id.viewholder_links_format_link2); Button link3 = (Button) itemView.findViewById(R.id.viewholder_links_format_link3); Button link4 = (Button) itemView.findViewById(R.id.viewholder_links_format_link4); Button link5 = (Button) itemView.findViewById(R.id.viewholder_links_format_link5); Button link6 = (Button) itemView.findViewById(R.id.viewholder_links_format_link6); this.context = context; link1.setOnClickListener(this); link2.setOnClickListener(this); link3.setOnClickListener(this); link4.setOnClickListener(this); link5.setOnClickListener(this); link6.setOnClickListener(this); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (view.getId() == R.id.viewholder_links_format_link1) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://10.1.1.242/lms/")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link2) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://swd.bits-goa.ac.in/")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link3) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://csatimes.co.in")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link4) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.bits-pilani.ac.in/Goa/")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link5) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.bits-pilani.ac.in/goa/login")); context.startActivity(intent); } else if (view.getId() == itemView.getId()) { Intent intent = new Intent(context, UtilitiesLinksActivity.class); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link6) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://bpgc-cte.org/")); context.startActivity(intent); } } }
UTF-8
Java
3,037
java
UtilitiesLinksViewHolder.java
Java
[ { "context": "ivities.UtilitiesLinksActivity;\n\n/**\n * Created by Vikramaditya Kukreja on 21-07-2016.\n */\n\npublic class UtilitiesLinksVi", "end": 364, "score": 0.9998770952224731, "start": 344, "tag": "NAME", "value": "Vikramaditya Kukreja" }, { "context": " new Intent(Intent.ACTION_VIEW, Uri.parse(\"http://10.1.1.242/lms/\"));\n context.startActivity(intent", "end": 1688, "score": 0.9996482729911804, "start": 1678, "tag": "IP_ADDRESS", "value": "10.1.1.242" } ]
null
[]
package com.csatimes.dojma.viewholders; import android.content.Context; import android.content.Intent; import android.net.Uri; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.Button; import com.csatimes.dojma.R; import com.csatimes.dojma.activities.UtilitiesLinksActivity; /** * Created by <NAME> on 21-07-2016. */ public class UtilitiesLinksViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private Context context; public UtilitiesLinksViewHolder(View itemView, Context context) { super(itemView); Button link1 = (Button) itemView.findViewById(R.id.viewholder_links_format_link1); Button link2 = (Button) itemView.findViewById(R.id.viewholder_links_format_link2); Button link3 = (Button) itemView.findViewById(R.id.viewholder_links_format_link3); Button link4 = (Button) itemView.findViewById(R.id.viewholder_links_format_link4); Button link5 = (Button) itemView.findViewById(R.id.viewholder_links_format_link5); Button link6 = (Button) itemView.findViewById(R.id.viewholder_links_format_link6); this.context = context; link1.setOnClickListener(this); link2.setOnClickListener(this); link3.setOnClickListener(this); link4.setOnClickListener(this); link5.setOnClickListener(this); link6.setOnClickListener(this); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (view.getId() == R.id.viewholder_links_format_link1) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://10.1.1.242/lms/")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link2) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://swd.bits-goa.ac.in/")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link3) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://csatimes.co.in")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link4) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.bits-pilani.ac.in/Goa/")); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link5) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.bits-pilani.ac.in/goa/login")); context.startActivity(intent); } else if (view.getId() == itemView.getId()) { Intent intent = new Intent(context, UtilitiesLinksActivity.class); context.startActivity(intent); } else if (view.getId() == R.id.viewholder_links_format_link6) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://bpgc-cte.org/")); context.startActivity(intent); } } }
3,023
0.673033
0.660191
72
41.180557
34.161106
112
false
false
0
0
0
0
0
0
0.652778
false
false
4
4a8e494a7fd454848cf945bbb85fbf8c10c55f52
11,862,699,739,391
872b4e84a5862215e3c90c7ac410509beb2088ca
/ebase/src/main/java/com/dsdl/eidea/core/entity/bo/LabelBo.java
8ac86100e0a34f1eb757d84001bd2b8027d3cbc8
[]
no_license
chengbom/eidea4
https://github.com/chengbom/eidea4
9b219adaa5c762f40432734d8972c1309b431bf9
634da797bee45a80e0218676ab9519e45f66b5f4
refs/heads/master
2021-01-25T08:13:01.676000
2017-06-07T08:17:16
2017-06-07T08:17:16
93,729,671
1
0
null
true
2017-06-08T09:11:22
2017-06-08T09:11:22
2017-06-08T07:23:07
2017-06-07T08:24:58
6,672
0
0
0
null
null
null
package com.dsdl.eidea.core.entity.bo; import java.util.ArrayList; import java.util.List; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; @Data public class LabelBo { private Integer id; @NotNull(message = "identity.not.allowed.empty") private String key; @Length(min = 1,max = 45,message = "base.msgtext.length") private String msgtext; @Length(min = 1,max = 1,message = "isactive.length") private String isactive; /** * 是否新建 默认为false */ private boolean created=false; private List<LabelTrlBo> labelTrlBoList = new ArrayList<>(); }
UTF-8
Java
667
java
LabelBo.java
Java
[]
null
[]
package com.dsdl.eidea.core.entity.bo; import java.util.ArrayList; import java.util.List; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; @Data public class LabelBo { private Integer id; @NotNull(message = "identity.not.allowed.empty") private String key; @Length(min = 1,max = 45,message = "base.msgtext.length") private String msgtext; @Length(min = 1,max = 1,message = "isactive.length") private String isactive; /** * 是否新建 默认为false */ private boolean created=false; private List<LabelTrlBo> labelTrlBoList = new ArrayList<>(); }
667
0.707504
0.699847
25
25.120001
19.516804
65
false
false
0
0
0
0
0
0
1.16
false
false
4
8b870a550047e28117eb272db4683df44a363fe3
3,762,391,353,266
1032b2a4abfd9e545e5e3a1e676bb78c0ea2490b
/src/logic/ReturnNum.java
85dff602b234b5edeecd847b5c1e675216122aaf
[]
no_license
BaiWenchao/HISProject2.0
https://github.com/BaiWenchao/HISProject2.0
5eeef77fb4c9f28d18c9e6dd500e6cbc3b72bfd1
8b64fa36464b61987b837388919ae33b4b43487b
refs/heads/master
2020-07-10T00:51:27.138000
2020-02-02T10:59:54
2020-02-02T10:59:54
204,124,166
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package logic; import entity.Hospital; import java.text.SimpleDateFormat; import java.util.Date; public class ReturnNum { //单例模式: private static ReturnNum instance; private ReturnNum(){} public static synchronized ReturnNum getInstance(){ if(instance == null){ instance = new ReturnNum(); } return instance; } // 创建医院单例 Hospital hospital = Hospital.getInstance(); public String returnHosRecordNum(){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); return sdf.format(date); } public String returnRecordNum(){ hospital.setRecordNum(hospital.getRecordNum() + 1); return hospital.getRecordNum().toString(); } public String returnTime(){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.format(date); } }
UTF-8
Java
973
java
ReturnNum.java
Java
[]
null
[]
package logic; import entity.Hospital; import java.text.SimpleDateFormat; import java.util.Date; public class ReturnNum { //单例模式: private static ReturnNum instance; private ReturnNum(){} public static synchronized ReturnNum getInstance(){ if(instance == null){ instance = new ReturnNum(); } return instance; } // 创建医院单例 Hospital hospital = Hospital.getInstance(); public String returnHosRecordNum(){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); return sdf.format(date); } public String returnRecordNum(){ hospital.setRecordNum(hospital.getRecordNum() + 1); return hospital.getRecordNum().toString(); } public String returnTime(){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.format(date); } }
973
0.638276
0.637224
39
23.384615
20.447075
75
false
false
0
0
0
0
0
0
0.410256
false
false
4
07c470abd54e9ea681ee1911e7035509caccc408
19,619,410,669,944
7d60228dd63321071b58aa5cbc3988bb4b696e6f
/client/app/src/main/java/org/faudroids/mrhyde/bitbucket/BitbucketLink.java
86f45fb0e10dc044ce67d6d0507f3966e0ed22b9
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
FauDroids/MrHyde
https://github.com/FauDroids/MrHyde
430a3a0b3b4b4f5d12b7cd7f9761b249033463f0
a339aa520633a93d5c87bf503b6d048c1d4b4047
refs/heads/master
2020-02-26T19:57:09.275000
2017-03-19T21:08:00
2017-03-19T21:08:00
33,619,781
87
25
null
false
2017-03-12T19:35:16
2015-04-08T16:52:27
2017-01-26T04:32:00
2017-03-12T19:35:15
9,782
53
10
20
Dart
null
null
package org.faudroids.mrhyde.bitbucket; /** * Bitbucket Link object. */ public class BitbucketLink { private String href; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
UTF-8
Java
381
java
BitbucketLink.java
Java
[]
null
[]
package org.faudroids.mrhyde.bitbucket; /** * Bitbucket Link object. */ public class BitbucketLink { private String href; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
381
0.648294
0.648294
26
13.653846
13.228589
39
false
false
0
0
0
0
0
0
0.269231
false
false
4
999745f5bfd97ef0060e42ebd102ace4a5b0f5d4
9,990,093,999,350
2400c36324adb79909f6147a015bb7abd224d48a
/app/src/main/java/com/robotium/solo/SoloExt.java
05bd6ead8c4f054142a4b4c050c4d66eb35f46e0
[]
no_license
LubinXuan/RobotiumWX
https://github.com/LubinXuan/RobotiumWX
b4ade5f39b13be1a6e53cbfd0e1d259b451e5041
b99183110060dbc2ab02ea12de331778d008fef0
refs/heads/master
2021-01-19T16:09:31.542000
2017-05-04T09:48:11
2017-05-04T09:48:11
88,251,408
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.robotium.solo; import android.app.Activity; import android.app.Instrumentation; import android.os.SystemClock; import android.view.View; import com.robotium.solo.Solo; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Created by xuanlubin on 2017/4/14. */ public class SoloExt extends Solo { public SoloExt(Instrumentation instrumentation, Activity activity) { super(instrumentation, activity); } public SoloExt(Instrumentation instrumentation, Config config) { super(instrumentation, config); } public SoloExt(Instrumentation instrumentation, Config config, Activity activity) { super(instrumentation, config, activity); } public SoloExt(Instrumentation instrumentation) { super(instrumentation); } public <T extends View> T getViewByDesc(String desc, Class<T> classFilterBy) { return getViewByDesc(desc, classFilterBy, 0); } public <T extends View> T getViewByDesc(String desc, Class<T> classFilterBy, int index) { return getViewByDesc(desc, classFilterBy, index, 0); } public <T extends View> T getViewByDesc(String desc, Class<T> classFilterBy, int index, int timeout) { return waitForViewDesc(desc, classFilterBy, index, timeout, true); } private <T extends View> T waitForViewDesc(String desc, Class<T> classFilterBy, int index, int timeout, boolean scroll) { long endTime = SystemClock.uptimeMillis() + timeout; while (SystemClock.uptimeMillis() <= endTime) { super.sleeper.sleep(); ArrayList<T> list = viewFetcher.getCurrentViews(classFilterBy, true); if (null != list && !list.isEmpty()) { for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) { T view = iterator.next(); if (null == view.getContentDescription() || !view.getContentDescription().equals(desc)) { iterator.remove(); } } if (!list.isEmpty() && list.size() > index) { return list.get(index); } } if (scroll) scroller.scrollDown(); } return null; } public <T extends View> T getView(Class<T> classFilterBy, View parent) { return getView(classFilterBy, parent, 0, 0, true); } public <T extends View> T getView(Class<T> classFilterBy, View parent, int index) { return getView(classFilterBy, parent, index, 0, true); } public <T extends View> T getView(Class<T> classFilterBy, View parent, int index, int timeout, boolean scroll) { long endTime = SystemClock.uptimeMillis() + timeout; while (SystemClock.uptimeMillis() <= endTime) { super.sleeper.sleep(); ArrayList<T> list = viewFetcher.getCurrentViews(classFilterBy, true, parent); if (null != list && !list.isEmpty() && list.size() > index) { return list.get(index); } if (scroll) scroller.scrollDown(); } return null; } }
UTF-8
Java
3,205
java
SoloExt.java
Java
[ { "context": "Iterator;\nimport java.util.Set;\n\n/**\n * Created by xuanlubin on 2017/4/14.\n */\npublic class SoloExt extends So", "end": 313, "score": 0.9996679425239563, "start": 304, "tag": "USERNAME", "value": "xuanlubin" } ]
null
[]
package com.robotium.solo; import android.app.Activity; import android.app.Instrumentation; import android.os.SystemClock; import android.view.View; import com.robotium.solo.Solo; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Created by xuanlubin on 2017/4/14. */ public class SoloExt extends Solo { public SoloExt(Instrumentation instrumentation, Activity activity) { super(instrumentation, activity); } public SoloExt(Instrumentation instrumentation, Config config) { super(instrumentation, config); } public SoloExt(Instrumentation instrumentation, Config config, Activity activity) { super(instrumentation, config, activity); } public SoloExt(Instrumentation instrumentation) { super(instrumentation); } public <T extends View> T getViewByDesc(String desc, Class<T> classFilterBy) { return getViewByDesc(desc, classFilterBy, 0); } public <T extends View> T getViewByDesc(String desc, Class<T> classFilterBy, int index) { return getViewByDesc(desc, classFilterBy, index, 0); } public <T extends View> T getViewByDesc(String desc, Class<T> classFilterBy, int index, int timeout) { return waitForViewDesc(desc, classFilterBy, index, timeout, true); } private <T extends View> T waitForViewDesc(String desc, Class<T> classFilterBy, int index, int timeout, boolean scroll) { long endTime = SystemClock.uptimeMillis() + timeout; while (SystemClock.uptimeMillis() <= endTime) { super.sleeper.sleep(); ArrayList<T> list = viewFetcher.getCurrentViews(classFilterBy, true); if (null != list && !list.isEmpty()) { for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) { T view = iterator.next(); if (null == view.getContentDescription() || !view.getContentDescription().equals(desc)) { iterator.remove(); } } if (!list.isEmpty() && list.size() > index) { return list.get(index); } } if (scroll) scroller.scrollDown(); } return null; } public <T extends View> T getView(Class<T> classFilterBy, View parent) { return getView(classFilterBy, parent, 0, 0, true); } public <T extends View> T getView(Class<T> classFilterBy, View parent, int index) { return getView(classFilterBy, parent, index, 0, true); } public <T extends View> T getView(Class<T> classFilterBy, View parent, int index, int timeout, boolean scroll) { long endTime = SystemClock.uptimeMillis() + timeout; while (SystemClock.uptimeMillis() <= endTime) { super.sleeper.sleep(); ArrayList<T> list = viewFetcher.getCurrentViews(classFilterBy, true, parent); if (null != list && !list.isEmpty() && list.size() > index) { return list.get(index); } if (scroll) scroller.scrollDown(); } return null; } }
3,205
0.619033
0.615289
91
34.21978
31.923948
125
false
false
0
0
0
0
0
0
0.901099
false
false
4
5a30548739b540109376cfe752b083bf9df3293c
19,078,244,796,255
3cb94418de34ff8e402a6f92873d2d1217af4d67
/src/main/java/com/nhan/minisocial/core/service/CommentResourceService.java
7164a9d4e15810276e640b0df9d5cde3e900edab
[]
no_license
nguyentrinhan-dev/mini-social-network
https://github.com/nguyentrinhan-dev/mini-social-network
296e2fe2338365f916fc8d21a9ea71ca91a01159
2b2f72897e9346fd0823e2bdd82ac515fc071dad
refs/heads/master
2023-05-29T08:29:01.446000
2022-06-11T16:13:09
2022-06-11T16:13:09
340,608,098
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nhan.minisocial.core.service; import com.nhan.minisocial.core.entity.Article; import com.nhan.minisocial.core.entity.Comment; import com.nhan.minisocial.core.entity.User; import com.nhan.minisocial.core.payload.CommentRequest; import com.nhan.minisocial.core.resource.CommentResource; import com.nhan.minisocial.core.security.UserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class CommentResourceService { @Autowired private UserResourceService userResourceService; @Autowired private ArticleService articleService; @Autowired private UserService userService; @Autowired private CommentService commentService; private Comment toEntity(UserPrincipal currentUser ,CommentRequest commentRequest, long articleId) { Comment comment = new Comment(); comment.setId(commentRequest.getId()); comment.setDescription(commentRequest.getDescription()); User user = userService.getUser(currentUser.getId()); comment.setUser(user); Article article = articleService.getOne(articleId); comment.setArticle(article); return comment; } private CommentResource toResource(Comment comment){ CommentResource resource = new CommentResource(); resource.setId((comment.getId())); resource.setArticleId(comment.getArticle().getId()); resource.setDescription(comment.getDescription()); resource.setUser(userResourceService.getUser(comment.getUser().getId())); return resource; } public void commentAnArticle(UserPrincipal currentUser, long articleId, CommentRequest commentRequest) { Comment comment = toEntity(currentUser ,commentRequest, articleId); commentService.save(comment); } public List<CommentResource> getComments(long articleId) { List<CommentResource> resources = new ArrayList<>(); List<Comment> comments = listAllCommentByArticle(articleId); for (Comment comment: comments) { resources.add(toResource(comment)); } return resources; } private List<Comment> listAllCommentByArticle(long articleId) { return commentService.getComments(articleId); } }
UTF-8
Java
2,362
java
CommentResourceService.java
Java
[]
null
[]
package com.nhan.minisocial.core.service; import com.nhan.minisocial.core.entity.Article; import com.nhan.minisocial.core.entity.Comment; import com.nhan.minisocial.core.entity.User; import com.nhan.minisocial.core.payload.CommentRequest; import com.nhan.minisocial.core.resource.CommentResource; import com.nhan.minisocial.core.security.UserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class CommentResourceService { @Autowired private UserResourceService userResourceService; @Autowired private ArticleService articleService; @Autowired private UserService userService; @Autowired private CommentService commentService; private Comment toEntity(UserPrincipal currentUser ,CommentRequest commentRequest, long articleId) { Comment comment = new Comment(); comment.setId(commentRequest.getId()); comment.setDescription(commentRequest.getDescription()); User user = userService.getUser(currentUser.getId()); comment.setUser(user); Article article = articleService.getOne(articleId); comment.setArticle(article); return comment; } private CommentResource toResource(Comment comment){ CommentResource resource = new CommentResource(); resource.setId((comment.getId())); resource.setArticleId(comment.getArticle().getId()); resource.setDescription(comment.getDescription()); resource.setUser(userResourceService.getUser(comment.getUser().getId())); return resource; } public void commentAnArticle(UserPrincipal currentUser, long articleId, CommentRequest commentRequest) { Comment comment = toEntity(currentUser ,commentRequest, articleId); commentService.save(comment); } public List<CommentResource> getComments(long articleId) { List<CommentResource> resources = new ArrayList<>(); List<Comment> comments = listAllCommentByArticle(articleId); for (Comment comment: comments) { resources.add(toResource(comment)); } return resources; } private List<Comment> listAllCommentByArticle(long articleId) { return commentService.getComments(articleId); } }
2,362
0.733277
0.733277
67
34.253731
27.095928
108
false
false
0
0
0
0
0
0
0.626866
false
false
4
1b9eadcc69be221c2345f8cc3a8797e056ce6360
6,038,724,034,134
ec40ef3ee0a46c30b286db7ffcf6e1dcd153f0d9
/src/main/java/money/fluid/ilp/ledger/web/model/MetadataRepresentation.java
38566d5ff3d37ece49d294887db64990d7356f5f
[]
no_license
fluid-money/ilp-ledger-java
https://github.com/fluid-money/ilp-ledger-java
693d4040aa892cb0eaacdab431c53c8a52709203
aa11892bf415512268cedcc216cf0d334d129f30
refs/heads/master
2021-01-12T00:48:56.520000
2017-06-11T03:01:26
2017-06-11T03:01:26
78,298,967
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package money.fluid.ilp.ledger.web.model; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.ToString; import org.ilpx.ledger.core.Ledger; /** * Meta-data about a {@link Ledger}. */ @RequiredArgsConstructor @Builder @Getter @ToString @EqualsAndHashCode public class MetadataRepresentation { /** * Information about the currency or other asset that a {@link Ledger} tracks. */ @JsonProperty("asset_info") @NonNull private final AssetRepresentation assetInfo; /** * The ILP Address prefix of the ledger. */ @JsonProperty("ilp_prefix") @NonNull private final String ilpPrefix; /** * Get the precision for this {@link Ledger}, which is how many total decimal digits this ledger uses to represent * currency amounts. A value of 0 indicated unlimited precision, which is the default value for this method. */ @JsonProperty("precision") @NonNull private final Integer precision; /** * Get the scale for this {@link Ledger}, which is how many digits after the decimal place this ledger supports in * currency amounts. This method defaults to 2. */ @JsonProperty("scale") @NonNull private final Integer scale; /** * Get a {@link String} representation of the rounding used internally by ledger for values that exceed the reported * scale or precision. */ @JsonProperty("rounding") @NonNull private final String rounding; }
UTF-8
Java
1,628
java
MetadataRepresentation.java
Java
[]
null
[]
package money.fluid.ilp.ledger.web.model; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.ToString; import org.ilpx.ledger.core.Ledger; /** * Meta-data about a {@link Ledger}. */ @RequiredArgsConstructor @Builder @Getter @ToString @EqualsAndHashCode public class MetadataRepresentation { /** * Information about the currency or other asset that a {@link Ledger} tracks. */ @JsonProperty("asset_info") @NonNull private final AssetRepresentation assetInfo; /** * The ILP Address prefix of the ledger. */ @JsonProperty("ilp_prefix") @NonNull private final String ilpPrefix; /** * Get the precision for this {@link Ledger}, which is how many total decimal digits this ledger uses to represent * currency amounts. A value of 0 indicated unlimited precision, which is the default value for this method. */ @JsonProperty("precision") @NonNull private final Integer precision; /** * Get the scale for this {@link Ledger}, which is how many digits after the decimal place this ledger supports in * currency amounts. This method defaults to 2. */ @JsonProperty("scale") @NonNull private final Integer scale; /** * Get a {@link String} representation of the rounding used internally by ledger for values that exceed the reported * scale or precision. */ @JsonProperty("rounding") @NonNull private final String rounding; }
1,628
0.703931
0.702703
60
26.133333
29.589676
120
false
false
0
0
0
0
0
0
0.283333
false
false
4
c380a88162008bf5eaaff5c67542e9a0ae132934
29,326,036,766,467
b188d834bf486c65d9616d542dace24b73af7f86
/app/src/main/java/com/example/dahir/sqlitesimpleplaceapp/activities/MainActivity.java
61627e6658a33e2ade5f9843c9aaf834c00356cf
[]
no_license
AbdaliDahir/MobileTest
https://github.com/AbdaliDahir/MobileTest
2185b0cbf0b3cdbc26fdb6351b54776ddff098e5
64fb675dd46e337df523e29ff63a78587e08ab7e
refs/heads/master
2020-05-27T00:34:50.559000
2019-05-25T01:16:55
2019-05-25T01:16:55
188,426,097
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dahir.sqlitesimpleplaceapp.activities; import android.app.DatePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.TextInputEditText; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.dahir.sqlitesimpleplaceapp.R; import com.example.dahir.sqlitesimpleplaceapp.adapters.PendingplaceAdapter; import com.example.dahir.sqlitesimpleplaceapp.helpers.TagDBHelper; import com.example.dahir.sqlitesimpleplaceapp.helpers.placeDBHelper; import com.example.dahir.sqlitesimpleplaceapp.models.PendingplaceModel; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; /** * Start 23 : 05 : 2019 */ public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener{ private RecyclerView pendingplaces; private LinearLayoutManager linearLayoutManager; private ArrayList<PendingplaceModel> pendingplaceModels; private PendingplaceAdapter pendingplaceAdapter; private FloatingActionButton addNewplace; private TagDBHelper tagDBHelper; private String getTagTitleString; private placeDBHelper placeDBHelper; private LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); setTitle(getString(R.string.app_title)); showDrawerLayout(); navigationMenuInit(); loadPendingplaces(); } //loading all the pending places private void loadPendingplaces(){ pendingplaces=(RecyclerView)findViewById(R.id.pending_places_view); linearLayout=(LinearLayout)findViewById(R.id.no_pending_place_section); tagDBHelper=new TagDBHelper(this); placeDBHelper=new placeDBHelper(this); if(placeDBHelper.countplaces()==0){ linearLayout.setVisibility(View.VISIBLE); pendingplaces.setVisibility(View.GONE); }else{ pendingplaceModels=new ArrayList<>(); pendingplaceModels=placeDBHelper.fetchAllplaces(); pendingplaceAdapter=new PendingplaceAdapter(pendingplaceModels,this); } linearLayoutManager=new LinearLayoutManager(this); pendingplaces.setAdapter(pendingplaceAdapter); pendingplaces.setLayoutManager(linearLayoutManager); addNewplace=(FloatingActionButton)findViewById(R.id.fabAddplace); addNewplace.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.fabAddplace: if(tagDBHelper.countTags()==0){ showDialog(); }else{ showNewplaceDialog(); } break; } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } //add the drawer layout private void showDrawerLayout(){ DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer,(Toolbar) findViewById(R.id.toolbar) , R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); } //initialize navigation menu private void navigationMenuInit(){ NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.pending_task_options,menu); MenuItem menuItem=menu.findItem(R.id.search); SearchView searchView=(SearchView)menuItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { newText=newText.toLowerCase(); ArrayList<PendingplaceModel> newPendingplaceModels=new ArrayList<>(); for(PendingplaceModel pendingplaceModel:pendingplaceModels){ String getplaceTitle=pendingplaceModel.getplaceTitle().toLowerCase(); String getplaceContent=pendingplaceModel.getplaceContent().toLowerCase(); String getplaceTag=pendingplaceModel.getplaceTag().toLowerCase(); if(getplaceTitle.contains(newText) || getplaceContent.contains(newText) || getplaceTag.contains(newText)){ newPendingplaceModels.add(pendingplaceModel); } } pendingplaceAdapter.filterplaces(newPendingplaceModels); pendingplaceAdapter.notifyDataSetChanged(); return true; } }); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.search: return true; case R.id.all_tags: startActivity(new Intent(this,AllTags.class)); return true; case R.id.settings: startActivity(new Intent(this,AppSettings.class)); return true; default: return super.onOptionsItemSelected(item); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.pending_places) { startActivity(new Intent(this,MainActivity.class)); } else if (id == R.id.tags) { startActivity(new Intent(this,AllTags.class)); } else if (id == R.id.settings) { startActivity(new Intent(this,AppSettings.class)); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } //show dialog if there is no tag in the database private void showDialog(){ AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle(R.string.tag_create_dialog_title_text); builder.setMessage(R.string.no_tag_in_the_db_text); builder.setPositiveButton(R.string.create_new_tag, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(MainActivity.this,AllTags.class)); } }).setNegativeButton(R.string.tag_edit_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }).create().show(); } //show add new places dialog and adding the places into the database private void showNewplaceDialog(){ //getting current calendar credentials final Calendar calendar=Calendar.getInstance(); final int year=calendar.get(Calendar.YEAR); final int month=calendar.get(Calendar.MONTH); final int day=calendar.get(Calendar.DAY_OF_MONTH); final int hour=calendar.get(Calendar.HOUR); final int minute=calendar.get(Calendar.MINUTE); final AlertDialog.Builder builder=new AlertDialog.Builder(this); LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View view=layoutInflater.inflate(R.layout.add_new_place_dialog,null); builder.setView(view); final TextInputEditText placeTitle=(TextInputEditText)view.findViewById(R.id.place_title); final TextInputEditText placeContent=(TextInputEditText)view.findViewById(R.id.place_content); Spinner placeTags=(Spinner)view.findViewById(R.id.place_tag); //stores all the tags title in string format ArrayAdapter<String> tagsModelArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,tagDBHelper.fetchTagStrings()); //setting dropdown view resouce for spinner tagsModelArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //setting the spinner adapter placeTags.setAdapter(tagsModelArrayAdapter); placeTags.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { getTagTitleString=adapterView.getItemAtPosition(i).toString(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); final TextInputEditText placeDate=(TextInputEditText)view.findViewById(R.id.place_date); //getting the placedate placeDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatePickerDialog datePickerDialog=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { calendar.set(Calendar.YEAR,i); calendar.set(Calendar.MONTH,i1); calendar.set(Calendar.DAY_OF_MONTH,i2); placeDate.setText(DateFormat.getDateInstance(DateFormat.MEDIUM).format(calendar.getTime())); } },year,month,day); datePickerDialog.show(); } }); TextView cancel=(TextView)view.findViewById(R.id.cancel); TextView addplace=(TextView)view.findViewById(R.id.add_new_place); addplace.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //getting all the values from add new places dialog String getplaceTitle=placeTitle.getText().toString(); String getplaceContent=placeContent.getText().toString(); int placeTagID=tagDBHelper.fetchTagID(getTagTitleString); String getplaceDate=placeDate.getText().toString(); //checking the data fiels boolean isTitleEmpty=placeTitle.getText().toString().isEmpty(); boolean isContentEmpty=placeContent.getText().toString().isEmpty(); boolean isDateEmpty=placeDate.getText().toString().isEmpty(); //adding the places if(isTitleEmpty){ placeTitle.setError("place title required !"); }else if(isContentEmpty){ placeContent.setError("place content required !"); }else if(isDateEmpty){ placeDate.setError("place date required !"); }else if(placeDBHelper.addNewplace( new PendingplaceModel(getplaceTitle,getplaceContent,String.valueOf(placeTagID),getplaceDate) )){ Toast.makeText(MainActivity.this, R.string.place_title_add_success_msg, Toast.LENGTH_SHORT).show(); startActivity(new Intent(MainActivity.this,MainActivity.class)); } } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this,MainActivity.class)); } }); builder.create().show(); } }
UTF-8
Java
13,124
java
MainActivity.java
Java
[]
null
[]
package com.example.dahir.sqlitesimpleplaceapp.activities; import android.app.DatePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.TextInputEditText; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.dahir.sqlitesimpleplaceapp.R; import com.example.dahir.sqlitesimpleplaceapp.adapters.PendingplaceAdapter; import com.example.dahir.sqlitesimpleplaceapp.helpers.TagDBHelper; import com.example.dahir.sqlitesimpleplaceapp.helpers.placeDBHelper; import com.example.dahir.sqlitesimpleplaceapp.models.PendingplaceModel; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; /** * Start 23 : 05 : 2019 */ public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener{ private RecyclerView pendingplaces; private LinearLayoutManager linearLayoutManager; private ArrayList<PendingplaceModel> pendingplaceModels; private PendingplaceAdapter pendingplaceAdapter; private FloatingActionButton addNewplace; private TagDBHelper tagDBHelper; private String getTagTitleString; private placeDBHelper placeDBHelper; private LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); setTitle(getString(R.string.app_title)); showDrawerLayout(); navigationMenuInit(); loadPendingplaces(); } //loading all the pending places private void loadPendingplaces(){ pendingplaces=(RecyclerView)findViewById(R.id.pending_places_view); linearLayout=(LinearLayout)findViewById(R.id.no_pending_place_section); tagDBHelper=new TagDBHelper(this); placeDBHelper=new placeDBHelper(this); if(placeDBHelper.countplaces()==0){ linearLayout.setVisibility(View.VISIBLE); pendingplaces.setVisibility(View.GONE); }else{ pendingplaceModels=new ArrayList<>(); pendingplaceModels=placeDBHelper.fetchAllplaces(); pendingplaceAdapter=new PendingplaceAdapter(pendingplaceModels,this); } linearLayoutManager=new LinearLayoutManager(this); pendingplaces.setAdapter(pendingplaceAdapter); pendingplaces.setLayoutManager(linearLayoutManager); addNewplace=(FloatingActionButton)findViewById(R.id.fabAddplace); addNewplace.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.fabAddplace: if(tagDBHelper.countTags()==0){ showDialog(); }else{ showNewplaceDialog(); } break; } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } //add the drawer layout private void showDrawerLayout(){ DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer,(Toolbar) findViewById(R.id.toolbar) , R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); } //initialize navigation menu private void navigationMenuInit(){ NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.pending_task_options,menu); MenuItem menuItem=menu.findItem(R.id.search); SearchView searchView=(SearchView)menuItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { newText=newText.toLowerCase(); ArrayList<PendingplaceModel> newPendingplaceModels=new ArrayList<>(); for(PendingplaceModel pendingplaceModel:pendingplaceModels){ String getplaceTitle=pendingplaceModel.getplaceTitle().toLowerCase(); String getplaceContent=pendingplaceModel.getplaceContent().toLowerCase(); String getplaceTag=pendingplaceModel.getplaceTag().toLowerCase(); if(getplaceTitle.contains(newText) || getplaceContent.contains(newText) || getplaceTag.contains(newText)){ newPendingplaceModels.add(pendingplaceModel); } } pendingplaceAdapter.filterplaces(newPendingplaceModels); pendingplaceAdapter.notifyDataSetChanged(); return true; } }); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.search: return true; case R.id.all_tags: startActivity(new Intent(this,AllTags.class)); return true; case R.id.settings: startActivity(new Intent(this,AppSettings.class)); return true; default: return super.onOptionsItemSelected(item); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.pending_places) { startActivity(new Intent(this,MainActivity.class)); } else if (id == R.id.tags) { startActivity(new Intent(this,AllTags.class)); } else if (id == R.id.settings) { startActivity(new Intent(this,AppSettings.class)); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } //show dialog if there is no tag in the database private void showDialog(){ AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle(R.string.tag_create_dialog_title_text); builder.setMessage(R.string.no_tag_in_the_db_text); builder.setPositiveButton(R.string.create_new_tag, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(MainActivity.this,AllTags.class)); } }).setNegativeButton(R.string.tag_edit_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }).create().show(); } //show add new places dialog and adding the places into the database private void showNewplaceDialog(){ //getting current calendar credentials final Calendar calendar=Calendar.getInstance(); final int year=calendar.get(Calendar.YEAR); final int month=calendar.get(Calendar.MONTH); final int day=calendar.get(Calendar.DAY_OF_MONTH); final int hour=calendar.get(Calendar.HOUR); final int minute=calendar.get(Calendar.MINUTE); final AlertDialog.Builder builder=new AlertDialog.Builder(this); LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View view=layoutInflater.inflate(R.layout.add_new_place_dialog,null); builder.setView(view); final TextInputEditText placeTitle=(TextInputEditText)view.findViewById(R.id.place_title); final TextInputEditText placeContent=(TextInputEditText)view.findViewById(R.id.place_content); Spinner placeTags=(Spinner)view.findViewById(R.id.place_tag); //stores all the tags title in string format ArrayAdapter<String> tagsModelArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,tagDBHelper.fetchTagStrings()); //setting dropdown view resouce for spinner tagsModelArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //setting the spinner adapter placeTags.setAdapter(tagsModelArrayAdapter); placeTags.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { getTagTitleString=adapterView.getItemAtPosition(i).toString(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); final TextInputEditText placeDate=(TextInputEditText)view.findViewById(R.id.place_date); //getting the placedate placeDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DatePickerDialog datePickerDialog=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { calendar.set(Calendar.YEAR,i); calendar.set(Calendar.MONTH,i1); calendar.set(Calendar.DAY_OF_MONTH,i2); placeDate.setText(DateFormat.getDateInstance(DateFormat.MEDIUM).format(calendar.getTime())); } },year,month,day); datePickerDialog.show(); } }); TextView cancel=(TextView)view.findViewById(R.id.cancel); TextView addplace=(TextView)view.findViewById(R.id.add_new_place); addplace.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //getting all the values from add new places dialog String getplaceTitle=placeTitle.getText().toString(); String getplaceContent=placeContent.getText().toString(); int placeTagID=tagDBHelper.fetchTagID(getTagTitleString); String getplaceDate=placeDate.getText().toString(); //checking the data fiels boolean isTitleEmpty=placeTitle.getText().toString().isEmpty(); boolean isContentEmpty=placeContent.getText().toString().isEmpty(); boolean isDateEmpty=placeDate.getText().toString().isEmpty(); //adding the places if(isTitleEmpty){ placeTitle.setError("place title required !"); }else if(isContentEmpty){ placeContent.setError("place content required !"); }else if(isDateEmpty){ placeDate.setError("place date required !"); }else if(placeDBHelper.addNewplace( new PendingplaceModel(getplaceTitle,getplaceContent,String.valueOf(placeTagID),getplaceDate) )){ Toast.makeText(MainActivity.this, R.string.place_title_add_success_msg, Toast.LENGTH_SHORT).show(); startActivity(new Intent(MainActivity.this,MainActivity.class)); } } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this,MainActivity.class)); } }); builder.create().show(); } }
13,124
0.664813
0.66306
300
42.746666
29.321934
158
false
false
0
0
0
0
0
0
0.666667
false
false
4
bb7d1456eb64dd3de1d3aabfec4aac20b6176484
5,291,399,717,790
6652a6428e29f5a1061e8757f9dc16bf58cf31cf
/app/src/main/java/com/sds/android/cloudapi/ttpod/data/CirclePoster.java
88d3a0dbb9122c8613648686c9679f783b85f08c
[]
no_license
liupeng110/sds
https://github.com/liupeng110/sds
d33f6163fa7298171e12c1d84692789642b2f724
4e6948e49ed3bd06ca08269f623dd47354abaf60
refs/heads/master
2021-08-12T02:45:32.708000
2017-11-14T10:09:50
2017-11-14T10:09:50
110,672,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sds.android.cloudapi.ttpod.data; import com.b.a.a.c; import java.io.Serializable; public class CirclePoster implements Serializable { private static final String KEY_MSG_ID = "msg_id"; private static final String KEY_PIC = "pic"; private static final String KEY_TYPE = "type"; private static final String KEY_URL = "url"; public static final int TYPE_CIRCLE = 8; public static final int TYPE_URL = 3; @c(a = "url") private String mContentUrl; @c(a = "msg_id") private long mMsgId; @c(a = "pic") private String mPicUrl; @c(a = "type") private int mType; public int getType() { return this.mType; } public long getMsgId() { return this.mMsgId; } public String getPicUrl() { return this.mPicUrl; } public String getContentUrl() { return this.mContentUrl; } }
UTF-8
Java
894
java
CirclePoster.java
Java
[ { "context": "e {\n private static final String KEY_MSG_ID = \"msg_id\";\n private static final String KEY_PIC = \"pic\"", "end": 200, "score": 0.9879146218299866, "start": 194, "tag": "KEY", "value": "msg_id" }, { "context": "g_id\";\n private static final String KEY_PIC = \"pic\";\n private static final String KEY_TYPE = \"typ", "end": 249, "score": 0.9686598777770996, "start": 246, "tag": "KEY", "value": "pic" }, { "context": "pic\";\n private static final String KEY_TYPE = \"type\";\n private static final String KEY_URL = \"url\"", "end": 300, "score": 0.9475293159484863, "start": 296, "tag": "KEY", "value": "type" }, { "context": "type\";\n private static final String KEY_URL = \"url\";\n public static final int TYPE_CIRCLE = 8;\n ", "end": 349, "score": 0.6060181856155396, "start": 346, "tag": "KEY", "value": "url" } ]
null
[]
package com.sds.android.cloudapi.ttpod.data; import com.b.a.a.c; import java.io.Serializable; public class CirclePoster implements Serializable { private static final String KEY_MSG_ID = "msg_id"; private static final String KEY_PIC = "pic"; private static final String KEY_TYPE = "type"; private static final String KEY_URL = "url"; public static final int TYPE_CIRCLE = 8; public static final int TYPE_URL = 3; @c(a = "url") private String mContentUrl; @c(a = "msg_id") private long mMsgId; @c(a = "pic") private String mPicUrl; @c(a = "type") private int mType; public int getType() { return this.mType; } public long getMsgId() { return this.mMsgId; } public String getPicUrl() { return this.mPicUrl; } public String getContentUrl() { return this.mContentUrl; } }
894
0.630872
0.628635
37
23.162163
16.833868
54
false
false
0
0
0
0
0
0
0.459459
false
false
4
a9d1c451553606dedf08e46a6ed6837483bb7295
15,264,313,809,685
7666c51c6ef38e4916633317b5286ab56e0fe3cf
/Java/CS 555 Image Processing and Computer Vision/Filter Based Image Editor/src/UsefulFilters/ImageGrayRes.java
6cdb6b4433c1cb626e715fcd3eea29661c7eab4a
[]
no_license
MatthewLai90/Code-Examples
https://github.com/MatthewLai90/Code-Examples
a3b10819b95ad1c1009abd4566f2f273b2564221
d57d04e87ee2e7d0c90c812c6b405acd1cd340cd
refs/heads/master
2021-01-01T16:03:02.096000
2017-08-02T19:44:21
2017-08-02T19:44:21
97,763,856
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package UsefulFilters; import FilterInterface.ImageFilter; import FilterUtilities.RGBObject; import GUI.GUIUtilities; import Utilities.RGBPixelArray; import javax.swing.JFrame; /** * Program to vary the image's Gray Resolution. Displays each image after a * less significant digit has been removed; * * @author Matthew Lai */ public class ImageGrayRes extends ImageFilter{ @Override public RGBPixelArray filterImage(RGBPixelArray original) { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Bins the larger K gray resolutions to smaller ones and displays them. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Loops 7 times, each time lowering the grayscale resolution for(int i = 1; i <= 7; i++) { int[][] newImage = new int[original.getWidth()][original.getLength()]; for (int j = 0; j < newImage.length; j++) { for (int k = 0; k < newImage[0].length; k++) { // Calculates the current value of the pixel int value = original.getGrayscaleValues()[j][k]; // Calculates the new value of the pixel by performing a logical and with the appropriate byte value. int newValue = value & (int) (Math.pow(2, 8) - Math.pow(2, i)); // Writes the pixel value to the image array to be returned. newImage[j][k] = new RGBObject(newValue,newValue,newValue).getIntRGB(); } } newImage = ImageProcessor.ImageUtilities.normalize(newImage, 8); // Displays each image as the grayscale resolution is lowered. JFrame newFrame = new JFrame(); newFrame.add(GUIUtilities.getScrollWindow(GUIUtilities.getImagePanel(new RGBPixelArray(newImage)))); newFrame.setTitle("Grayscale Resolution k=" + (8-i)); newFrame.setSize(1000, 1000); newFrame.setVisible(true); } return null; } @Override public String getFilterName() { return "Gray Resolution Filter"; } @Override public String getFilterDecription() { return "Varies the Gray Resolution of the image."; } @Override public String getFilterCategory() { return "Useful Filters"; } }
UTF-8
Java
2,405
java
ImageGrayRes.java
Java
[ { "context": "significant digit has been removed;\n * \n * @author Matthew Lai\n */\npublic class ImageGrayRes extends ImageFilter", "end": 334, "score": 0.999861478805542, "start": 323, "tag": "NAME", "value": "Matthew Lai" } ]
null
[]
package UsefulFilters; import FilterInterface.ImageFilter; import FilterUtilities.RGBObject; import GUI.GUIUtilities; import Utilities.RGBPixelArray; import javax.swing.JFrame; /** * Program to vary the image's Gray Resolution. Displays each image after a * less significant digit has been removed; * * @author <NAME> */ public class ImageGrayRes extends ImageFilter{ @Override public RGBPixelArray filterImage(RGBPixelArray original) { /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Bins the larger K gray resolutions to smaller ones and displays them. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Loops 7 times, each time lowering the grayscale resolution for(int i = 1; i <= 7; i++) { int[][] newImage = new int[original.getWidth()][original.getLength()]; for (int j = 0; j < newImage.length; j++) { for (int k = 0; k < newImage[0].length; k++) { // Calculates the current value of the pixel int value = original.getGrayscaleValues()[j][k]; // Calculates the new value of the pixel by performing a logical and with the appropriate byte value. int newValue = value & (int) (Math.pow(2, 8) - Math.pow(2, i)); // Writes the pixel value to the image array to be returned. newImage[j][k] = new RGBObject(newValue,newValue,newValue).getIntRGB(); } } newImage = ImageProcessor.ImageUtilities.normalize(newImage, 8); // Displays each image as the grayscale resolution is lowered. JFrame newFrame = new JFrame(); newFrame.add(GUIUtilities.getScrollWindow(GUIUtilities.getImagePanel(new RGBPixelArray(newImage)))); newFrame.setTitle("Grayscale Resolution k=" + (8-i)); newFrame.setSize(1000, 1000); newFrame.setVisible(true); } return null; } @Override public String getFilterName() { return "Gray Resolution Filter"; } @Override public String getFilterDecription() { return "Varies the Gray Resolution of the image."; } @Override public String getFilterCategory() { return "Useful Filters"; } }
2,400
0.568815
0.560915
64
36.546875
32.298862
122
false
false
0
0
0
0
123
0.101039
0.53125
false
false
4
658c6328bf75fede249262b9fa4c6aaf16166b54
30,150,670,454,350
7e032866553cbc2227a5b9f8db7d36f9639158dd
/src/aula2/TrianguloCalculos.java
7d407280096334349a51a3ba279d5ea8c9e912dd
[ "MIT" ]
permissive
ericAndrade/IAL-002
https://github.com/ericAndrade/IAL-002
74ef22b6718f05349baa2d8bda2aaa881adc8c20
4971baf20c02bafccd1d4ee37d9253bbc22ac050
refs/heads/master
2021-05-02T10:34:26.972000
2015-05-14T14:46:57
2015-05-14T14:46:57
34,963,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aula2; import java.util.Scanner; public class TrianguloCalculos { public static void main(String[] args) { Scanner ler = new Scanner(System.in); int a=0; int b=0; int c=0; double s=0; double area=0; System.out.println("Digite A"); a = ler.nextInt(); System.out.println("Digite B"); b = ler.nextInt(); System.out.println("Digite C"); c = ler.nextInt(); s = (a+b+c)/2.0; area = Math.sqrt(s*(s-a)*(s-b)*(s-c)); if((a<(b+c))&&(c<(a+b))&&(b<(a+c))) { if(a == b && b == c) { System.out.println("Triângulo equilátero"); }else{ if(a == b || b == c || c == a) { System.out.println("Triângulo isóceles"); }else{ System.out.println("Triângulo escaleno"); } } System.out.println("Perímetro = "+ (a+b+c)); System.out.println("Área = "+ area); } ler.close(); } }
UTF-8
Java
878
java
TrianguloCalculos.java
Java
[]
null
[]
package aula2; import java.util.Scanner; public class TrianguloCalculos { public static void main(String[] args) { Scanner ler = new Scanner(System.in); int a=0; int b=0; int c=0; double s=0; double area=0; System.out.println("Digite A"); a = ler.nextInt(); System.out.println("Digite B"); b = ler.nextInt(); System.out.println("Digite C"); c = ler.nextInt(); s = (a+b+c)/2.0; area = Math.sqrt(s*(s-a)*(s-b)*(s-c)); if((a<(b+c))&&(c<(a+b))&&(b<(a+c))) { if(a == b && b == c) { System.out.println("Triângulo equilátero"); }else{ if(a == b || b == c || c == a) { System.out.println("Triângulo isóceles"); }else{ System.out.println("Triângulo escaleno"); } } System.out.println("Perímetro = "+ (a+b+c)); System.out.println("Área = "+ area); } ler.close(); } }
878
0.544202
0.535017
48
17.145834
15.680387
47
false
false
0
0
0
0
0
0
2.6875
false
false
4
bad5234ca45eb6dc0fc510ced0a22097744436ec
5,111,011,122,311
8a91020135da353dd25f9b4ae5df97302a03f032
/WebDocTruyen/src/main/java/group1/service/TacGiaServiceimpl.java
a80ff1ad1f693f25a6a035f61f34758f023e2059
[]
no_license
huyhieuno1/webdoctruyenvs4
https://github.com/huyhieuno1/webdoctruyenvs4
6c8c939da0dbd746388e79aeab940102e10d4b2a
ee5f7e0a3b303c3f7af59e15d09d516d34747715
refs/heads/master
2021-05-14T01:55:16.701000
2018-01-07T16:28:02
2018-01-07T16:28:02
116,580,504
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package group1.service; import group1.model.TacGia; public class TacGiaServiceimpl implements ITacGiaService{ @Override public TacGia tgia() { // TODO Auto-generated method stub return null; } }
UTF-8
Java
219
java
TacGiaServiceimpl.java
Java
[]
null
[]
package group1.service; import group1.model.TacGia; public class TacGiaServiceimpl implements ITacGiaService{ @Override public TacGia tgia() { // TODO Auto-generated method stub return null; } }
219
0.712329
0.703196
13
14.846154
17.024174
57
false
false
0
0
0
0
0
0
0.769231
false
false
4
26a68bbc4002e68d8764541afc762da163f798d3
3,839,700,827,142
a1e63481e515b2c41bc8cbda4daa9671d44b5ca0
/3264.dcordb.java
e77c1d358366e432ac34e3763b2f89514e82d998
[]
no_license
frarteaga/cojSolutions
https://github.com/frarteaga/cojSolutions
b05134ed793b7f36f2dbcc74f61d55b3e5c6a825
b93b53e092e417670584ec240cfa5010d33b55cf
refs/heads/master
2020-04-15T15:01:24.156000
2019-12-30T14:32:48
2019-12-30T14:32:48
55,257,183
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
//Prob: Contando Cadenas (3264) //Matrix exponentiation import java.util.Scanner; public class Main { static int M[][]; static int MOD = 1000000007; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); sc.close(); M = new int[11][11]; for(int i = 1; i <= 10; i++) M[i][i] = i; for(int i = 0; i <= 9; i++) M[i][i + 1] = 10 - i; int[][] res = exp(M, n); int sol = 0; for(int i = a; i <= b; i++) sol = (sol + res[0][i]) % MOD; System.out.println(sol); } public static int[][] mult(int[][] A, int[][] B) { int n = A.length, m = A[0].length; int p = B[0].length; int[][] res = new int[n][p]; for(int i = 0; i < n; i++) { for(int j = 0; j < p; j++) { res[i][j] = 0; for(int k = 0; k < m; k++) { long x = (A[i][k] * 1L * B[k][j]) % MOD; res[i][j] = (res[i][j] + (int) x) % MOD; } } } return res; } public static int[][] exp(int[][] A, int e) { if(e == 1) return A; if((e & 1) == 1) return mult(A, exp(A, e - 1)); int[][] S = exp(A, e / 2); return mult(S, S); } }
UTF-8
Java
1,244
java
3264.dcordb.java
Java
[]
null
[]
//Prob: Contando Cadenas (3264) //Matrix exponentiation import java.util.Scanner; public class Main { static int M[][]; static int MOD = 1000000007; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); sc.close(); M = new int[11][11]; for(int i = 1; i <= 10; i++) M[i][i] = i; for(int i = 0; i <= 9; i++) M[i][i + 1] = 10 - i; int[][] res = exp(M, n); int sol = 0; for(int i = a; i <= b; i++) sol = (sol + res[0][i]) % MOD; System.out.println(sol); } public static int[][] mult(int[][] A, int[][] B) { int n = A.length, m = A[0].length; int p = B[0].length; int[][] res = new int[n][p]; for(int i = 0; i < n; i++) { for(int j = 0; j < p; j++) { res[i][j] = 0; for(int k = 0; k < m; k++) { long x = (A[i][k] * 1L * B[k][j]) % MOD; res[i][j] = (res[i][j] + (int) x) % MOD; } } } return res; } public static int[][] exp(int[][] A, int e) { if(e == 1) return A; if((e & 1) == 1) return mult(A, exp(A, e - 1)); int[][] S = exp(A, e / 2); return mult(S, S); } }
1,244
0.446945
0.414791
62
18.064516
14.268023
51
false
false
0
0
0
0
0
0
2.677419
false
false
4
3f8f9a90f57fe566d7fa2d66329e69a1a06ec278
3,839,700,827,603
0d12254307433302ca28b69c61c82fead4b04096
/util/src/test/java/net/automatalib/util/automata/equivalence/DeterministicEquivalenceTestTest.java
dd5822ec4da237d0a4975744e0ca4e542024f6ee
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
LearnLib/automatalib
https://github.com/LearnLib/automatalib
ea2a82c52dafdbd913efcbc4467b50c7b1215d8c
d7d81b0c56308bac4384a2aaa1558d9537967ddc
refs/heads/develop
2023-08-17T08:00:37.687000
2023-08-02T20:50:06
2023-08-02T20:50:06
8,791,847
65
40
Apache-2.0
false
2023-02-15T19:48:03
2013-03-15T04:02:44
2022-11-18T21:50:05
2023-02-15T19:48:02
35,238
72
31
3
Java
false
false
/* Copyright (C) 2013-2023 TU Dortmund * This file is part of AutomataLib, http://www.automatalib.net/. * * 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 net.automatalib.util.automata.equivalence; import java.util.Collection; import java.util.Random; import net.automatalib.automata.UniversalDeterministicAutomaton; import net.automatalib.automata.concepts.Output; import net.automatalib.automata.fsa.DFA; import net.automatalib.automata.fsa.impl.compact.CompactDFA; import net.automatalib.automata.transducers.MealyMachine; import net.automatalib.automata.transducers.impl.compact.CompactMealy; import net.automatalib.util.automata.random.RandomAutomata; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; import net.automatalib.words.impl.Alphabets; import org.testng.Assert; import org.testng.annotations.Test; /** * @author frohme */ public class DeterministicEquivalenceTestTest { private static final Random RANDOM = new Random(0); private static final int AUTOMATON_SIZE_SMALL = 20; // Equivalence check switches implementation when stateSize**2 is > 10000 private static final int AUTOMATON_SIZE_LARGE = 200; @Test public void testEquivalenceDFA() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final DFA<?, Integer> a1 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_SMALL, alphabet); final DFA<?, Integer> a2 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_SMALL, alphabet); testEquivalenceInternal(a1, a1, alphabet, true); testEquivalenceInternal(a1, a2, alphabet, false); } @Test public void testEquivalenceDFALarge() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final DFA<?, Integer> a1 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_LARGE, alphabet, false); final DFA<?, Integer> a2 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_LARGE, alphabet, false); testEquivalenceInternal(a1, a1, alphabet, true); testEquivalenceInternal(a1, a2, alphabet, false); } @Test public void testEquivalenceMealy() { final Alphabet<Integer> inputAlphabet = Alphabets.integers(0, 5); final Alphabet<Character> outputAlphabet = Alphabets.characters('a', 'f'); final MealyMachine<?, Integer, ?, Character> a1 = RandomAutomata.randomMealy(RANDOM, AUTOMATON_SIZE_SMALL, inputAlphabet, outputAlphabet); final MealyMachine<?, Integer, ?, Character> a2 = RandomAutomata.randomMealy(RANDOM, AUTOMATON_SIZE_SMALL, inputAlphabet, outputAlphabet); testEquivalenceInternal(a1, a1, inputAlphabet, true); testEquivalenceInternal(a1, a2, inputAlphabet, false); } @Test public void testEmptyDFAs() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final CompactDFA<Integer> uninit = new CompactDFA<>(alphabet, 0); final CompactDFA<Integer> empty = new CompactDFA<>(alphabet, 1); empty.addInitialState(false); testForEmptySepWord(uninit, empty, alphabet); } @Test public void testEmptyMealies() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final CompactMealy<Integer, ?> uninit = new CompactMealy<>(alphabet, 0); final CompactMealy<Integer, ?> empty = new CompactMealy<>(alphabet, 1); empty.addInitialState(); testForEmptySepWord(uninit, empty, alphabet); } private static <I> void testForEmptySepWord(UniversalDeterministicAutomaton<?, I, ?, ?, ?> a1, UniversalDeterministicAutomaton<?, I, ?, ?, ?> a2, Collection<? extends I> inputs) { Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWord(a1, a1, inputs)); Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWord(a2, a2, inputs)); final Word<I> sepWord1 = DeterministicEquivalenceTest.findSeparatingWord(a1, a2, inputs); Assert.assertEquals(sepWord1, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord1), a2.getState(sepWord1)); final Word<I> sepWord2 = DeterministicEquivalenceTest.findSeparatingWord(a2, a1, inputs); Assert.assertEquals(sepWord2, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord2), a2.getState(sepWord2)); // Large version Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWordLarge(a1, a1, inputs)); Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWordLarge(a2, a2, inputs)); final Word<I> sepWord3 = DeterministicEquivalenceTest.findSeparatingWordLarge(a1, a2, inputs); Assert.assertEquals(sepWord3, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord3), a2.getState(sepWord3)); final Word<I> sepWord4 = DeterministicEquivalenceTest.findSeparatingWordLarge(a2, a1, inputs); Assert.assertEquals(sepWord4, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord4), a2.getState(sepWord4)); } private <I, M extends UniversalDeterministicAutomaton<?, I, ?, ?, ?> & Output<I, ?>> void testEquivalenceInternal(M a1, M a2, Alphabet<I> alphabet, boolean equivalent) { final UniversalDeterministicAutomaton<?, I, ?, ?, ?> m1 = a1; final UniversalDeterministicAutomaton<?, I, ?, ?, ?> m2 = a2; final Word<I> separatingWord = DeterministicEquivalenceTest.findSeparatingWord(m1, m2, alphabet); Assert.assertEquals(equivalent, separatingWord == null); if (!equivalent) { Assert.assertNotEquals(a1.computeOutput(separatingWord), a2.computeOutput(separatingWord)); } } }
UTF-8
Java
6,610
java
DeterministicEquivalenceTestTest.java
Java
[ { "context": "/* Copyright (C) 2013-2023 TU Dortmund\n * This file is part of AutomataLib, http://www.a", "end": 38, "score": 0.9791932702064514, "start": 27, "tag": "NAME", "value": "TU Dortmund" }, { "context": "mport org.testng.annotations.Test;\n\n/**\n * @author frohme\n */\npublic class DeterministicEquivalenceTestTest", "end": 1382, "score": 0.9995609521865845, "start": 1376, "tag": "USERNAME", "value": "frohme" } ]
null
[]
/* Copyright (C) 2013-2023 <NAME> * This file is part of AutomataLib, http://www.automatalib.net/. * * 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 net.automatalib.util.automata.equivalence; import java.util.Collection; import java.util.Random; import net.automatalib.automata.UniversalDeterministicAutomaton; import net.automatalib.automata.concepts.Output; import net.automatalib.automata.fsa.DFA; import net.automatalib.automata.fsa.impl.compact.CompactDFA; import net.automatalib.automata.transducers.MealyMachine; import net.automatalib.automata.transducers.impl.compact.CompactMealy; import net.automatalib.util.automata.random.RandomAutomata; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; import net.automatalib.words.impl.Alphabets; import org.testng.Assert; import org.testng.annotations.Test; /** * @author frohme */ public class DeterministicEquivalenceTestTest { private static final Random RANDOM = new Random(0); private static final int AUTOMATON_SIZE_SMALL = 20; // Equivalence check switches implementation when stateSize**2 is > 10000 private static final int AUTOMATON_SIZE_LARGE = 200; @Test public void testEquivalenceDFA() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final DFA<?, Integer> a1 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_SMALL, alphabet); final DFA<?, Integer> a2 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_SMALL, alphabet); testEquivalenceInternal(a1, a1, alphabet, true); testEquivalenceInternal(a1, a2, alphabet, false); } @Test public void testEquivalenceDFALarge() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final DFA<?, Integer> a1 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_LARGE, alphabet, false); final DFA<?, Integer> a2 = RandomAutomata.randomDFA(RANDOM, AUTOMATON_SIZE_LARGE, alphabet, false); testEquivalenceInternal(a1, a1, alphabet, true); testEquivalenceInternal(a1, a2, alphabet, false); } @Test public void testEquivalenceMealy() { final Alphabet<Integer> inputAlphabet = Alphabets.integers(0, 5); final Alphabet<Character> outputAlphabet = Alphabets.characters('a', 'f'); final MealyMachine<?, Integer, ?, Character> a1 = RandomAutomata.randomMealy(RANDOM, AUTOMATON_SIZE_SMALL, inputAlphabet, outputAlphabet); final MealyMachine<?, Integer, ?, Character> a2 = RandomAutomata.randomMealy(RANDOM, AUTOMATON_SIZE_SMALL, inputAlphabet, outputAlphabet); testEquivalenceInternal(a1, a1, inputAlphabet, true); testEquivalenceInternal(a1, a2, inputAlphabet, false); } @Test public void testEmptyDFAs() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final CompactDFA<Integer> uninit = new CompactDFA<>(alphabet, 0); final CompactDFA<Integer> empty = new CompactDFA<>(alphabet, 1); empty.addInitialState(false); testForEmptySepWord(uninit, empty, alphabet); } @Test public void testEmptyMealies() { final Alphabet<Integer> alphabet = Alphabets.integers(0, 5); final CompactMealy<Integer, ?> uninit = new CompactMealy<>(alphabet, 0); final CompactMealy<Integer, ?> empty = new CompactMealy<>(alphabet, 1); empty.addInitialState(); testForEmptySepWord(uninit, empty, alphabet); } private static <I> void testForEmptySepWord(UniversalDeterministicAutomaton<?, I, ?, ?, ?> a1, UniversalDeterministicAutomaton<?, I, ?, ?, ?> a2, Collection<? extends I> inputs) { Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWord(a1, a1, inputs)); Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWord(a2, a2, inputs)); final Word<I> sepWord1 = DeterministicEquivalenceTest.findSeparatingWord(a1, a2, inputs); Assert.assertEquals(sepWord1, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord1), a2.getState(sepWord1)); final Word<I> sepWord2 = DeterministicEquivalenceTest.findSeparatingWord(a2, a1, inputs); Assert.assertEquals(sepWord2, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord2), a2.getState(sepWord2)); // Large version Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWordLarge(a1, a1, inputs)); Assert.assertNull(DeterministicEquivalenceTest.findSeparatingWordLarge(a2, a2, inputs)); final Word<I> sepWord3 = DeterministicEquivalenceTest.findSeparatingWordLarge(a1, a2, inputs); Assert.assertEquals(sepWord3, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord3), a2.getState(sepWord3)); final Word<I> sepWord4 = DeterministicEquivalenceTest.findSeparatingWordLarge(a2, a1, inputs); Assert.assertEquals(sepWord4, Word.epsilon()); Assert.assertNotEquals(a1.getState(sepWord4), a2.getState(sepWord4)); } private <I, M extends UniversalDeterministicAutomaton<?, I, ?, ?, ?> & Output<I, ?>> void testEquivalenceInternal(M a1, M a2, Alphabet<I> alphabet, boolean equivalent) { final UniversalDeterministicAutomaton<?, I, ?, ?, ?> m1 = a1; final UniversalDeterministicAutomaton<?, I, ?, ?, ?> m2 = a2; final Word<I> separatingWord = DeterministicEquivalenceTest.findSeparatingWord(m1, m2, alphabet); Assert.assertEquals(equivalent, separatingWord == null); if (!equivalent) { Assert.assertNotEquals(a1.computeOutput(separatingWord), a2.computeOutput(separatingWord)); } } }
6,605
0.667927
0.651588
141
45.879433
37.316071
139
false
false
0
0
0
0
0
0
1.319149
false
false
4
1725f9c8fb18717c382de87cbdeca04e547cd809
27,668,179,331,185
a93fa464773ee01474788641be1014da7396f3d1
/MyDivineProject/src/main/java/my/divine/project/db/transaction/GradeBookTransactionManager.java
11d23ff56c4363fc4babfeb80164634681731c81
[]
no_license
Vlad-semenuk/MyDivineProject
https://github.com/Vlad-semenuk/MyDivineProject
7ab8fcc07beb2f940f070695e7db3fa4fa131859
1ab839e4a3c8d7fd4f6c767336a8f7a6c19c1378
refs/heads/master
2022-11-08T09:33:07.723000
2019-11-15T15:31:51
2019-11-15T15:31:51
221,935,068
0
0
null
false
2022-09-22T18:57:10
2019-11-15T13:59:47
2019-11-15T15:32:07
2022-09-22T18:57:08
15,744
0
0
2
Java
false
false
package my.divine.project.db.transaction; import com.google.common.collect.Table; import my.divine.project.exception.db.DBException; import my.divine.project.model.constant.State; import my.divine.project.model.entity.Course; import my.divine.project.model.entity.User; import java.util.List; import java.util.Map; /** * Created by Semenuk Vladislav */ public interface GradeBookTransactionManager { boolean setUserToCourse (String login, int courseID) throws DBException; Map< User,Integer> getUsersByCourse (int courseID) throws DBException; Map<Course, Integer> getCoursesByUserLogin (String userLogin, State state) throws DBException; Map<User, Boolean> getUsersCourseResult(int courseId) throws DBException; boolean checkUserReg(String login, int courseID) throws DBException; Integer getQuantityStudentFromCourse (int courseID)throws DBException; boolean deleteUserFromCourse (String userLogin, int courseID) throws DBException; boolean setAssessmentToUserByCourse (String userLogin, int courseID, int assessment, boolean result)throws DBException; }
UTF-8
Java
1,107
java
GradeBookTransactionManager.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by Semenuk Vladislav\n */\n\n\npublic interface GradeBookTransactionManage", "end": 353, "score": 0.9998556971549988, "start": 336, "tag": "NAME", "value": "Semenuk Vladislav" } ]
null
[]
package my.divine.project.db.transaction; import com.google.common.collect.Table; import my.divine.project.exception.db.DBException; import my.divine.project.model.constant.State; import my.divine.project.model.entity.Course; import my.divine.project.model.entity.User; import java.util.List; import java.util.Map; /** * Created by <NAME> */ public interface GradeBookTransactionManager { boolean setUserToCourse (String login, int courseID) throws DBException; Map< User,Integer> getUsersByCourse (int courseID) throws DBException; Map<Course, Integer> getCoursesByUserLogin (String userLogin, State state) throws DBException; Map<User, Boolean> getUsersCourseResult(int courseId) throws DBException; boolean checkUserReg(String login, int courseID) throws DBException; Integer getQuantityStudentFromCourse (int courseID)throws DBException; boolean deleteUserFromCourse (String userLogin, int courseID) throws DBException; boolean setAssessmentToUserByCourse (String userLogin, int courseID, int assessment, boolean result)throws DBException; }
1,096
0.794941
0.794941
37
28.918919
34.706787
123
false
false
0
0
0
0
0
0
0.702703
false
false
4
33a896f3130daae10224f3617e6578717447da08
20,899,310,930,232
7ed552eba4e81970d014f27043a87d321c70f14a
/src/main/java/chapter_1/Question_1_4.java
596a4b9537f0df9e6c960a6208c5b8755d2899ad
[]
no_license
aorlandogit/CtCl_Solutions
https://github.com/aorlandogit/CtCl_Solutions
4a3125ceda7a934cef761cf1a847b2c8a2d1779d
52982f8a8bc8086d0cc2912a9f07fa698afd522b
refs/heads/master
2016-05-26T09:53:37.921000
2015-09-07T15:06:49
2015-09-07T15:06:49
41,449,187
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter_1; /*** * Cracking the Code Interview * Chapter 1: Arrays and Strings * Question 1.4 * * Write a method to replace all spaces in a string with '%20'. You may * assume that the string has sufficient space at the end to hold the * additional characters, and that you are given the "true" length of * the string. * * Example: * Input: "Mr John Smith ", 13 * Output: "Mr%20John%20Smith" */ public final class Question_1_4 { public static String strReplace(char[] str, int length) { /* * // This procedure is necessary in C, etc. * // Using the length field of a character string * // we can find the length of the new string as * // it is specified in the instructions that the * // input string will be padded to accommodate the * // the replace string. * * int spaceCount = 0; * for (int i = 0; i < length; i++) { * if (str[i] == ' ') { * spaceCount++; * } * } * * // Our replace string is "%20". Each space * // already has once place, thus we need to * // account for 2n more spaces where n is the * // the number of spaces found in the input string. * * int newLength = length + spaceCount * 2; * * // A change to this could be that we are just * // given an input string without the extra * // padding or string length. In this case we * // would carry out the procedure above and create * // a new array of size length + spaceCount * 2 * // and copy over the current array. * * char[] paddedStr = new char[newLength]; * for (int i = 0; i < str.length; i++) paddedStr[i] = str[i]; */ // Initialize a pointer to sit above the last index of the new string. int newLength = str.length; /* * Iterate backwards through the char[] and either * copy the character at position i to the newLength pointer's * index - 1, or if there is a space, copy the replacement string * the the newLength pointer index - 1, - 2, and -3. This works * because we have padded the string with enough spaces to facilitate * a clean copy. */ for (int i = length - 1; i >= 0; i--) { if (str[i] == ' ') { str[newLength - 1] = '0'; str[newLength - 2] = '2'; str[newLength - 3] = '%'; newLength = newLength - 3; } else { str[newLength - 1] = str[i]; newLength--; } } return new String(str); } }
UTF-8
Java
2,495
java
Question_1_4.java
Java
[ { "context": "of \r\n *\tthe string.\r\n *\r\n *\tExample:\r\n *\tInput: \"Mr John Smith \", 13\r\n *\tOutput: \"Mr%20John%20Smit", "end": 378, "score": 0.8500486612319946, "start": 376, "tag": "NAME", "value": "Mr" }, { "context": " \r\n *\tthe string.\r\n *\r\n *\tExample:\r\n *\tInput: \"Mr John Smith \", 13\r\n *\tOutput: \"Mr%20John%20Smith\"\r\n */\r\n\r\n", "end": 389, "score": 0.9015672206878662, "start": 379, "tag": "NAME", "value": "John Smith" }, { "context": "\r\n *\tInput: \"Mr John Smith \", 13\r\n *\tOutput: \"Mr%20John%20Smith\"\r\n */\r\n\r\npublic final class Questi", "end": 414, "score": 0.5142560005187988, "start": 412, "tag": "NAME", "value": "Mr" }, { "context": "Input: \"Mr John Smith \", 13\r\n *\tOutput: \"Mr%20John%20Smith\"\r\n */\r\n\r\npublic final class Question_1_4 ", "end": 421, "score": 0.45502734184265137, "start": 417, "tag": "NAME", "value": "John" }, { "context": " \"Mr John Smith \", 13\r\n *\tOutput: \"Mr%20John%20Smith\"\r\n */\r\n\r\npublic final class Question_1_4 {\r\n\tpubl", "end": 429, "score": 0.7501114010810852, "start": 424, "tag": "NAME", "value": "Smith" } ]
null
[]
package chapter_1; /*** * Cracking the Code Interview * Chapter 1: Arrays and Strings * Question 1.4 * * Write a method to replace all spaces in a string with '%20'. You may * assume that the string has sufficient space at the end to hold the * additional characters, and that you are given the "true" length of * the string. * * Example: * Input: "Mr <NAME> ", 13 * Output: "Mr%20John%20Smith" */ public final class Question_1_4 { public static String strReplace(char[] str, int length) { /* * // This procedure is necessary in C, etc. * // Using the length field of a character string * // we can find the length of the new string as * // it is specified in the instructions that the * // input string will be padded to accommodate the * // the replace string. * * int spaceCount = 0; * for (int i = 0; i < length; i++) { * if (str[i] == ' ') { * spaceCount++; * } * } * * // Our replace string is "%20". Each space * // already has once place, thus we need to * // account for 2n more spaces where n is the * // the number of spaces found in the input string. * * int newLength = length + spaceCount * 2; * * // A change to this could be that we are just * // given an input string without the extra * // padding or string length. In this case we * // would carry out the procedure above and create * // a new array of size length + spaceCount * 2 * // and copy over the current array. * * char[] paddedStr = new char[newLength]; * for (int i = 0; i < str.length; i++) paddedStr[i] = str[i]; */ // Initialize a pointer to sit above the last index of the new string. int newLength = str.length; /* * Iterate backwards through the char[] and either * copy the character at position i to the newLength pointer's * index - 1, or if there is a space, copy the replacement string * the the newLength pointer index - 1, - 2, and -3. This works * because we have padded the string with enough spaces to facilitate * a clean copy. */ for (int i = length - 1; i >= 0; i--) { if (str[i] == ' ') { str[newLength - 1] = '0'; str[newLength - 2] = '2'; str[newLength - 3] = '%'; newLength = newLength - 3; } else { str[newLength - 1] = str[i]; newLength--; } } return new String(str); } }
2,491
0.585972
0.571944
78
29.987179
22.922106
72
false
false
0
0
0
0
0
0
2.25641
false
false
4
200f67016a93328601152b79d144d500ca2dc7b3
20,899,310,929,864
8313257b171087f49f95574155aa392b87eebe29
/src/main/java/ali_leetcode_daily/dynamic_programming/string/Solution1143.java
77fe76283102dd27c8dc7cadf66e4a0d392b647b
[]
no_license
Jessie0914/leetcode
https://github.com/Jessie0914/leetcode
d4c26e729aa0bc8a3a86c1121fe7d9d48c9f2287
1c521a7313a170b69a39f2591094fcf88e8be05b
refs/heads/master
2021-07-09T13:56:09.692000
2020-08-04T17:08:57
2020-08-04T17:08:57
194,860,763
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ali_leetcode_daily.dynamic_programming.string; /** * @ClassName Solution1143 * @Description 1143. 最长公共子序列 * @Author shishi * @Date 2020/6/29 21:18 **/ /** * 输入:text1 = "abcde", text2 = "ace" * 输出:3 * 解释:最长公共子序列是 "ace",它的长度为 3。 */ public class Solution1143 { public int longestCommonSubsequence(String text1, String text2) { if (text1 == null || text2 == null || text1.length() == 0 || text2.length() == 0) return 0; int len1 = text1.length(); int len2 = text2.length(); int[][] dp = new int[len1 + 1][len2 + 1]; // base case for (int i = 0; i < len1 + 1; i++) { dp[i][0] = 0; } for (int j = 0; j < len2 + 1; j++) { dp[0][j] = 0; } // dp for (int i = 1; i < len1 + 1; i++) { for (int j = 1; j < len2 + 1; j++) { if (text1.charAt(i - 1) == text2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } return dp[len1][len2]; } }
UTF-8
Java
1,207
java
Solution1143.java
Java
[ { "context": "ution1143\n * @Description 1143. 最长公共子序列\n * @Author shishi\n * @Date 2020/6/29 21:18\n **/\n\n/**\n * 输入:text1 = ", "end": 134, "score": 0.9229226112365723, "start": 128, "tag": "USERNAME", "value": "shishi" } ]
null
[]
package ali_leetcode_daily.dynamic_programming.string; /** * @ClassName Solution1143 * @Description 1143. 最长公共子序列 * @Author shishi * @Date 2020/6/29 21:18 **/ /** * 输入:text1 = "abcde", text2 = "ace" * 输出:3 * 解释:最长公共子序列是 "ace",它的长度为 3。 */ public class Solution1143 { public int longestCommonSubsequence(String text1, String text2) { if (text1 == null || text2 == null || text1.length() == 0 || text2.length() == 0) return 0; int len1 = text1.length(); int len2 = text2.length(); int[][] dp = new int[len1 + 1][len2 + 1]; // base case for (int i = 0; i < len1 + 1; i++) { dp[i][0] = 0; } for (int j = 0; j < len2 + 1; j++) { dp[0][j] = 0; } // dp for (int i = 1; i < len1 + 1; i++) { for (int j = 1; j < len2 + 1; j++) { if (text1.charAt(i - 1) == text2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } return dp[len1][len2]; } }
1,207
0.441048
0.379039
45
24.444445
22.19565
89
false
false
0
0
0
0
0
0
0.6
false
false
4
2b652be4ac730e15210e55e83a6038591697a257
798,863,983,184
b7056bca1018e904713935419a245fb53ea0c541
/chapter_007/src/main/java/ru/job4j/servlets/music/model/persistence/dao/concrete/AddressDao.java
e139dd7df90aa6d10dc88d3bcd7814b2bb749cee
[ "Apache-2.0" ]
permissive
dkhlopunov/dkhlopunov
https://github.com/dkhlopunov/dkhlopunov
a82becd20fff40d6187f12790b45c054e3e6fcba
ed6ade443596dd87b8fb6392d6346cff161c0500
refs/heads/master
2018-11-10T06:18:45.213000
2018-10-30T14:01:02
2018-10-30T14:01:02
116,726,023
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.job4j.servlets.music.model.persistence.dao.concrete; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.servlets.music.model.persistence.dao.AbstractDao; import ru.job4j.servlets.music.model.entity.Address; import javax.sql.DataSource; import java.sql.*; import java.util.*; public class AddressDao extends AbstractDao<Address, Integer> { private static final Logger logger = LoggerFactory.getLogger(AddressDao.class); private static final String CREATE_ADDRESS = "INSERT INTO Address (userId, city, street, postCode) VALUES (?, ?, ?, ?)"; private static final String SELECT_ADDRESS = "SELECT city, street, postcode FROM Address WHERE userId = ? LIMIT 1"; private static final String UPDATE_ADDRESS = "UPDATE Address SET city = ?, street = ?, postCode = ? WHERE userId = ?"; private static final String DELETE_ADDRESS = "DELETE FROM Address WHERE userId = ?"; private static final String LOAD_ADDRESSES = "SELECT * FROM Address"; public AddressDao(DataSource dataSource) { super(dataSource); } @Override public Integer create(Address instance) { int result = 0; try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(CREATE_ADDRESS, Statement.RETURN_GENERATED_KEYS)) { ps.setInt(1, instance.getUserId()); ps.setString(2, instance.getCity()); ps.setString(3, instance.getStreet()); ps.setInt(4, instance.getPostcode()); result = ps.executeUpdate(); } catch (SQLException e) { logger.error("Error adding address", e); } return result; } @Override public Optional<Address> read(Integer id) { Optional<Address> optional = Optional.empty(); try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(SELECT_ADDRESS)) { ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { optional = Optional.of(mapAddress(id, rs)); } } } catch (SQLException e) { logger.error("Error fetching address by id", e); } return optional; } @Override public void update(Address instance) { try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(UPDATE_ADDRESS)) { ps.setString(1, instance.getCity()); ps.setString(2, instance.getStreet()); ps.setInt(3, instance.getPostcode()); ps.setInt(4, instance.getUserId()); ps.executeUpdate(); } catch (SQLException e) { logger.error("Error updating address", e); } } @Override public boolean delete(Integer id) { int rowsAffected = 0; try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(DELETE_ADDRESS)) { ps.setInt(1, id); rowsAffected = ps.executeUpdate(); } catch (SQLException e) { logger.error("Error deleting address", e); } return rowsAffected > 0; } @Override public List<Address> findAll() { List<Address> addresses = Collections.emptyList(); try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(LOAD_ADDRESSES); ResultSet rs = ps.executeQuery()) { addresses = new ArrayList<>(); while (rs.next()) { addresses.add(mapAddress(rs.getInt("userId"), rs)); } } catch (SQLException e) { logger.error("Error fetching address list", e); } return addresses; } private Address mapAddress(Integer id, ResultSet rs) throws SQLException { String city = rs.getString("city"); String street = rs.getString("street"); int postcode = rs.getInt("postcode"); return new Address(id, city, street, postcode); } }
UTF-8
Java
4,143
java
AddressDao.java
Java
[]
null
[]
package ru.job4j.servlets.music.model.persistence.dao.concrete; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.servlets.music.model.persistence.dao.AbstractDao; import ru.job4j.servlets.music.model.entity.Address; import javax.sql.DataSource; import java.sql.*; import java.util.*; public class AddressDao extends AbstractDao<Address, Integer> { private static final Logger logger = LoggerFactory.getLogger(AddressDao.class); private static final String CREATE_ADDRESS = "INSERT INTO Address (userId, city, street, postCode) VALUES (?, ?, ?, ?)"; private static final String SELECT_ADDRESS = "SELECT city, street, postcode FROM Address WHERE userId = ? LIMIT 1"; private static final String UPDATE_ADDRESS = "UPDATE Address SET city = ?, street = ?, postCode = ? WHERE userId = ?"; private static final String DELETE_ADDRESS = "DELETE FROM Address WHERE userId = ?"; private static final String LOAD_ADDRESSES = "SELECT * FROM Address"; public AddressDao(DataSource dataSource) { super(dataSource); } @Override public Integer create(Address instance) { int result = 0; try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(CREATE_ADDRESS, Statement.RETURN_GENERATED_KEYS)) { ps.setInt(1, instance.getUserId()); ps.setString(2, instance.getCity()); ps.setString(3, instance.getStreet()); ps.setInt(4, instance.getPostcode()); result = ps.executeUpdate(); } catch (SQLException e) { logger.error("Error adding address", e); } return result; } @Override public Optional<Address> read(Integer id) { Optional<Address> optional = Optional.empty(); try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(SELECT_ADDRESS)) { ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { optional = Optional.of(mapAddress(id, rs)); } } } catch (SQLException e) { logger.error("Error fetching address by id", e); } return optional; } @Override public void update(Address instance) { try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(UPDATE_ADDRESS)) { ps.setString(1, instance.getCity()); ps.setString(2, instance.getStreet()); ps.setInt(3, instance.getPostcode()); ps.setInt(4, instance.getUserId()); ps.executeUpdate(); } catch (SQLException e) { logger.error("Error updating address", e); } } @Override public boolean delete(Integer id) { int rowsAffected = 0; try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(DELETE_ADDRESS)) { ps.setInt(1, id); rowsAffected = ps.executeUpdate(); } catch (SQLException e) { logger.error("Error deleting address", e); } return rowsAffected > 0; } @Override public List<Address> findAll() { List<Address> addresses = Collections.emptyList(); try (Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(LOAD_ADDRESSES); ResultSet rs = ps.executeQuery()) { addresses = new ArrayList<>(); while (rs.next()) { addresses.add(mapAddress(rs.getInt("userId"), rs)); } } catch (SQLException e) { logger.error("Error fetching address list", e); } return addresses; } private Address mapAddress(Integer id, ResultSet rs) throws SQLException { String city = rs.getString("city"); String street = rs.getString("street"); int postcode = rs.getInt("postcode"); return new Address(id, city, street, postcode); } }
4,143
0.615737
0.611151
113
35.663715
29.053387
124
false
false
0
0
0
0
0
0
0.769912
false
false
4
33a1143f58ed4c301d0f43d82db9558a484f62a0
21,517,786,153,896
b7af5e61c12bb9b11d9e99329ede5a74f3a59a3e
/app/src/main/java/com/usearch/helpers/VolleyQueue.java
8d6c790b15057431bae3272216b36566eb042c10
[ "Apache-2.0" ]
permissive
uSearchApp/usearchapp
https://github.com/uSearchApp/usearchapp
60147e11638fb62882f21adb23945a88a65e3a73
d53bbe785e46118696ddd6d293a48e9528e9d6d6
refs/heads/master
2021-01-20T03:14:47.445000
2017-06-11T04:15:50
2017-06-11T04:15:50
89,517,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.usearch.helpers; import android.content.Context; import android.util.Log; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import static android.content.ContentValues.TAG; public class VolleyQueue { private static final int MAX_IMAGE_CACHE_ENTIRES = 3024; private static RequestQueue mRequestQueue; private VolleyQueue() {} public static void init(Context context) { if ( mRequestQueue == null) mRequestQueue = Volley.newRequestQueue(context); } public static RequestQueue getRequestQueue() { if (mRequestQueue != null) { return mRequestQueue; } else { throw new IllegalStateException("RequestQueue not initialized"); } } public static <T> void addToRequestQueue(Request<T> req) { req.setTag(TAG); getRequestQueue().add(req); } }
UTF-8
Java
941
java
VolleyQueue.java
Java
[]
null
[]
package com.usearch.helpers; import android.content.Context; import android.util.Log; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import static android.content.ContentValues.TAG; public class VolleyQueue { private static final int MAX_IMAGE_CACHE_ENTIRES = 3024; private static RequestQueue mRequestQueue; private VolleyQueue() {} public static void init(Context context) { if ( mRequestQueue == null) mRequestQueue = Volley.newRequestQueue(context); } public static RequestQueue getRequestQueue() { if (mRequestQueue != null) { return mRequestQueue; } else { throw new IllegalStateException("RequestQueue not initialized"); } } public static <T> void addToRequestQueue(Request<T> req) { req.setTag(TAG); getRequestQueue().add(req); } }
941
0.682253
0.678002
37
24.432432
21.96624
76
false
false
0
0
0
0
0
0
0.378378
false
false
4
ed8c6892bdd5d5a14fd1d343632bb04b33d5a3f0
34,986,803,618,377
af745ea71fcd3a2a152a564d35c5c230015c252d
/src/de/haw/mps/offer/api/OfferController.java
5982e4b3361419ad18df4d88ead742ba87e974fc
[]
no_license
futjikato/HAW-AI-MPS
https://github.com/futjikato/HAW-AI-MPS
9a1cf218ffd83b167c0128385b17b94dcb0749b1
0bd4bb6c1bb373835fcf69d5b8706bb1f48592d0
refs/heads/master
2016-09-11T03:16:32.132000
2014-06-25T15:11:47
2014-06-25T15:11:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.haw.mps.offer.api; import de.haw.mps.MpsLogger; import de.haw.mps.api.ActionController; import de.haw.mps.api.Request; import de.haw.mps.api.Response; import de.haw.mps.api.ResponseCode; import de.haw.mps.fabrication.entity.ElementEntity; import de.haw.mps.fabrication.model.ElementModel; import de.haw.mps.offer.entity.CustomerEntity; import de.haw.mps.offer.entity.OfferEntity; import de.haw.mps.offer.entity.OrderEntity; import de.haw.mps.offer.model.CustomerModel; import de.haw.mps.offer.model.OfferModel; import de.haw.mps.offer.model.OrderModel; import de.haw.mps.persistence.MpsSessionFactory; import de.haw.mps.persistence.WorkflowException; import org.hibernate.Session; import org.hibernate.Transaction; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import java.util.Set; import java.util.logging.Level; public class OfferController extends ActionController { public enum Actions { GET_CUSTOMERS() { @Override public Response process(Request request) { try { CustomerModel model = new CustomerModel(); List customers = model.getCustomers(); String[] params = new String[customers.size() * 2]; int i = 0; for(Object entity : customers) { if(entity instanceof CustomerEntity) { CustomerEntity customerEntity = (CustomerEntity)entity; params[i++] = String.valueOf(customerEntity.getId()); params[i++] = customerEntity.getName(); } } return ActionController.createResponse("customers", ResponseCode.OK, params); } catch (Exception e) { MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load customers."}); } } }, NEW_CUSTOMER() { @Override public Response process(Request request) { String[] params = request.getParameters(); if(params.length != 1) { return ActionController.createResponse(ResponseCode.BADREQUEST, new String[]{"Exactly one parameter is expected."}); } String name = params[0]; try { // get model CustomerModel model = new CustomerModel(); // create new entity CustomerEntity newCustomer = model.createCustomer(name); // persist entity Session session = MpsSessionFactory.getcurrentSession(); Transaction transaction = session.beginTransaction(); model.add(newCustomer); transaction.commit(); // send response String[] responseParams = new String[]{String.valueOf(newCustomer.getId()), newCustomer.getName()}; return ActionController.createResponse("new_customer", ResponseCode.OK, responseParams); } catch (Exception e) { MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load customers."}); } } }, GET_OFFERS() { @Override public Response process(Request request) { try { Session session = MpsSessionFactory.getcurrentSession(); Transaction transaction = session.beginTransaction(); OfferModel model = new OfferModel(); List customers = model.getOffers(); String[] params = new String[customers.size() * 4]; int i = 0; for(Object entity : customers) { if(entity instanceof OfferEntity) { OfferEntity offerEntity = (OfferEntity)entity; params[i++] = String.valueOf(offerEntity.getId()); params[i++] = offerEntity.getCustomer().getName(); params[i++] = offerEntity.getOrderObject().getName(); OrderEntity order = offerEntity.getResultingOrder(); if(order == null) { params[i++] = "-1"; } else { params[i++] = String.valueOf(order.getId()); } } } transaction.commit(); return ActionController.createResponse("offers", ResponseCode.OK, params); } catch (Exception e) { MpsLogger.getLogger().log(Level.WARNING, "Unable to load offers", e); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load offers."}); } } }, NEW_OFFER() { @Override public Response process(Request request) { String[] params = request.getParameters(); if(params.length != 2) { return ActionController.createResponse(ResponseCode.BADREQUEST, new String[]{"Exactly two parameter are expected."}); } String customerName = params[0]; String elementName = params[1]; try { // get model CustomerModel customerModel = new CustomerModel(); ElementModel elementModel = new ElementModel(); OfferModel offerModel = new OfferModel(); // load objects CustomerEntity customerEntity = customerModel.getCustomerByName(customerName); ElementEntity elementEntity = elementModel.getElementByName(elementName); // create new offer OfferEntity newOffer = offerModel.createOffer(customerEntity, elementEntity); // persist entity Session session = MpsSessionFactory.getcurrentSession(); Transaction transaction = session.beginTransaction(); offerModel.add(newOffer); transaction.commit(); // send response String[] responseParams = new String[]{ String.valueOf(newOffer.getId()), newOffer.getCustomer().getName(), newOffer.getOrderObject().getName() }; return ActionController.createResponse("new_offer", ResponseCode.OK, responseParams); } catch (Exception e) { MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load customers."}); } } }, OFFER_TO_ORDER() { @Override public Response process(Request request) { String[] params = request.getParameters(); // get id from params if(params.length != 1) { return ActionController.createResponse(ResponseCode.BADREQUEST, new String[]{"Exactly one parameter must be given."}); } Long id = Long.valueOf(params[0]); OfferModel model = new OfferModel(); model.startTransaction(); // load offer OfferEntity offerEntity; try { offerEntity = model.get(id); } catch (WorkflowException e) { try { model.rollbackTransaction(); } catch (WorkflowException e1) { // already logged in model } return ActionController.createResponse(ResponseCode.NOTFOUND, new String[]{"Offer not found."}); } // check if already ordered if(offerEntity.getResultingOrder() != null) { try { model.rollbackTransaction(); } catch (WorkflowException e) { // already logged in model } return ActionController.createResponse(ResponseCode.ALREADYDONE, new String[]{"Offer has already been ordered."}); } OrderModel orderModel = new OrderModel(); OrderEntity orderEntity = orderModel.createOrder(offerEntity, new GregorianCalendar()); try { offerEntity.setResultingOrder(orderEntity); model.update(offerEntity); orderModel.add(orderEntity); } catch (WorkflowException e) { // at least try a rollback try { model.rollbackTransaction(); } catch (WorkflowException e1) { // already logged in model } MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to save order."}); } String[] resultParams = OrderHelper.getApiParameter(orderEntity); try { model.commitTransaction(); } catch(WorkflowException e) { return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to commit transaction."}); } return ActionController.createResponse("new_order", ResponseCode.OK, resultParams); } }, GET_ORDERS() { @Override public Response process(Request request) { try { OrderModel model = new OrderModel(); model.startTransaction(); List orders = model.getOrders(); String[] params = new String[0]; for(Object entity : orders) { if(entity instanceof OrderEntity) { OrderEntity orderEntity = (OrderEntity)entity; String[] entityParams = OrderHelper.getApiParameter(orderEntity); // concat entityParams array to params String[] newParams = new String[params.length + entityParams.length]; System.arraycopy(params, 0, newParams, 0, params.length); System.arraycopy(entityParams, 0, newParams, params.length, entityParams.length); params = newParams; } } model.commitTransaction(); return ActionController.createResponse("orders", ResponseCode.OK, params); } catch (Exception e) { MpsLogger.getLogger().log(Level.SEVERE, "Error loading orders", e); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load orders."}); } } }; public abstract Response process(Request request); } @Override public boolean liableForAction(String action) { try { return (Actions.valueOf(action) != null); } catch (IllegalArgumentException e) { return false; } } @Override public void process(Request request) { Actions action = Actions.valueOf(request.requestedAction()); request.setResponse(action.process(request)); } }
UTF-8
Java
12,142
java
OfferController.java
Java
[]
null
[]
package de.haw.mps.offer.api; import de.haw.mps.MpsLogger; import de.haw.mps.api.ActionController; import de.haw.mps.api.Request; import de.haw.mps.api.Response; import de.haw.mps.api.ResponseCode; import de.haw.mps.fabrication.entity.ElementEntity; import de.haw.mps.fabrication.model.ElementModel; import de.haw.mps.offer.entity.CustomerEntity; import de.haw.mps.offer.entity.OfferEntity; import de.haw.mps.offer.entity.OrderEntity; import de.haw.mps.offer.model.CustomerModel; import de.haw.mps.offer.model.OfferModel; import de.haw.mps.offer.model.OrderModel; import de.haw.mps.persistence.MpsSessionFactory; import de.haw.mps.persistence.WorkflowException; import org.hibernate.Session; import org.hibernate.Transaction; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.List; import java.util.Set; import java.util.logging.Level; public class OfferController extends ActionController { public enum Actions { GET_CUSTOMERS() { @Override public Response process(Request request) { try { CustomerModel model = new CustomerModel(); List customers = model.getCustomers(); String[] params = new String[customers.size() * 2]; int i = 0; for(Object entity : customers) { if(entity instanceof CustomerEntity) { CustomerEntity customerEntity = (CustomerEntity)entity; params[i++] = String.valueOf(customerEntity.getId()); params[i++] = customerEntity.getName(); } } return ActionController.createResponse("customers", ResponseCode.OK, params); } catch (Exception e) { MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load customers."}); } } }, NEW_CUSTOMER() { @Override public Response process(Request request) { String[] params = request.getParameters(); if(params.length != 1) { return ActionController.createResponse(ResponseCode.BADREQUEST, new String[]{"Exactly one parameter is expected."}); } String name = params[0]; try { // get model CustomerModel model = new CustomerModel(); // create new entity CustomerEntity newCustomer = model.createCustomer(name); // persist entity Session session = MpsSessionFactory.getcurrentSession(); Transaction transaction = session.beginTransaction(); model.add(newCustomer); transaction.commit(); // send response String[] responseParams = new String[]{String.valueOf(newCustomer.getId()), newCustomer.getName()}; return ActionController.createResponse("new_customer", ResponseCode.OK, responseParams); } catch (Exception e) { MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load customers."}); } } }, GET_OFFERS() { @Override public Response process(Request request) { try { Session session = MpsSessionFactory.getcurrentSession(); Transaction transaction = session.beginTransaction(); OfferModel model = new OfferModel(); List customers = model.getOffers(); String[] params = new String[customers.size() * 4]; int i = 0; for(Object entity : customers) { if(entity instanceof OfferEntity) { OfferEntity offerEntity = (OfferEntity)entity; params[i++] = String.valueOf(offerEntity.getId()); params[i++] = offerEntity.getCustomer().getName(); params[i++] = offerEntity.getOrderObject().getName(); OrderEntity order = offerEntity.getResultingOrder(); if(order == null) { params[i++] = "-1"; } else { params[i++] = String.valueOf(order.getId()); } } } transaction.commit(); return ActionController.createResponse("offers", ResponseCode.OK, params); } catch (Exception e) { MpsLogger.getLogger().log(Level.WARNING, "Unable to load offers", e); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load offers."}); } } }, NEW_OFFER() { @Override public Response process(Request request) { String[] params = request.getParameters(); if(params.length != 2) { return ActionController.createResponse(ResponseCode.BADREQUEST, new String[]{"Exactly two parameter are expected."}); } String customerName = params[0]; String elementName = params[1]; try { // get model CustomerModel customerModel = new CustomerModel(); ElementModel elementModel = new ElementModel(); OfferModel offerModel = new OfferModel(); // load objects CustomerEntity customerEntity = customerModel.getCustomerByName(customerName); ElementEntity elementEntity = elementModel.getElementByName(elementName); // create new offer OfferEntity newOffer = offerModel.createOffer(customerEntity, elementEntity); // persist entity Session session = MpsSessionFactory.getcurrentSession(); Transaction transaction = session.beginTransaction(); offerModel.add(newOffer); transaction.commit(); // send response String[] responseParams = new String[]{ String.valueOf(newOffer.getId()), newOffer.getCustomer().getName(), newOffer.getOrderObject().getName() }; return ActionController.createResponse("new_offer", ResponseCode.OK, responseParams); } catch (Exception e) { MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load customers."}); } } }, OFFER_TO_ORDER() { @Override public Response process(Request request) { String[] params = request.getParameters(); // get id from params if(params.length != 1) { return ActionController.createResponse(ResponseCode.BADREQUEST, new String[]{"Exactly one parameter must be given."}); } Long id = Long.valueOf(params[0]); OfferModel model = new OfferModel(); model.startTransaction(); // load offer OfferEntity offerEntity; try { offerEntity = model.get(id); } catch (WorkflowException e) { try { model.rollbackTransaction(); } catch (WorkflowException e1) { // already logged in model } return ActionController.createResponse(ResponseCode.NOTFOUND, new String[]{"Offer not found."}); } // check if already ordered if(offerEntity.getResultingOrder() != null) { try { model.rollbackTransaction(); } catch (WorkflowException e) { // already logged in model } return ActionController.createResponse(ResponseCode.ALREADYDONE, new String[]{"Offer has already been ordered."}); } OrderModel orderModel = new OrderModel(); OrderEntity orderEntity = orderModel.createOrder(offerEntity, new GregorianCalendar()); try { offerEntity.setResultingOrder(orderEntity); model.update(offerEntity); orderModel.add(orderEntity); } catch (WorkflowException e) { // at least try a rollback try { model.rollbackTransaction(); } catch (WorkflowException e1) { // already logged in model } MpsLogger.getLogger().severe(e.getMessage()); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to save order."}); } String[] resultParams = OrderHelper.getApiParameter(orderEntity); try { model.commitTransaction(); } catch(WorkflowException e) { return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to commit transaction."}); } return ActionController.createResponse("new_order", ResponseCode.OK, resultParams); } }, GET_ORDERS() { @Override public Response process(Request request) { try { OrderModel model = new OrderModel(); model.startTransaction(); List orders = model.getOrders(); String[] params = new String[0]; for(Object entity : orders) { if(entity instanceof OrderEntity) { OrderEntity orderEntity = (OrderEntity)entity; String[] entityParams = OrderHelper.getApiParameter(orderEntity); // concat entityParams array to params String[] newParams = new String[params.length + entityParams.length]; System.arraycopy(params, 0, newParams, 0, params.length); System.arraycopy(entityParams, 0, newParams, params.length, entityParams.length); params = newParams; } } model.commitTransaction(); return ActionController.createResponse("orders", ResponseCode.OK, params); } catch (Exception e) { MpsLogger.getLogger().log(Level.SEVERE, "Error loading orders", e); return ActionController.createResponse(ResponseCode.ERROR, new String[]{"Unable to load orders."}); } } }; public abstract Response process(Request request); } @Override public boolean liableForAction(String action) { try { return (Actions.valueOf(action) != null); } catch (IllegalArgumentException e) { return false; } } @Override public void process(Request request) { Actions action = Actions.valueOf(request.requestedAction()); request.setResponse(action.process(request)); } }
12,142
0.523225
0.521743
289
41.01384
32.367908
138
false
false
0
0
0
0
0
0
0.588235
false
false
4
b9d034c241fa3c6cbc166957a7784e0990813be6
24,893,630,473,030
db150ae4bda69d81aae6024356533f08edb0217d
/tradecenter/src/main/java/com/kariqu/tradecenter/domain/Order.java
655facd4c492ba15c60c68ed99d8f9228a15bfdf
[]
no_license
bellmit/shop-mall
https://github.com/bellmit/shop-mall
e515abefa65f5e6f49b608d3d655fe58afccdd52
8616591595e8932574bd28892cd5f35ed176ddf8
refs/heads/master
2023-07-14T17:48:33.849000
2015-02-12T06:26:08
2015-02-12T06:26:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kariqu.tradecenter.domain; import com.kariqu.productcenter.domain.Money; import com.kariqu.productcenter.service.SkuService; import com.kariqu.suppliercenter.domain.DeliveryInfo; import com.kariqu.tradecenter.excepiton.OrderNoTransactionalException; import com.kariqu.tradecenter.helper.OrderAssert; import com.kariqu.tradecenter.service.CouponService; import com.kariqu.tradecenter.service.OrderQueryService; import com.kariqu.tradecenter.service.OrderWriteService; import com.kariqu.usercenter.domain.AccountType; import com.kariqu.usercenter.domain.UserPoint; import com.kariqu.usercenter.service.UserPointService; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.log4j.Logger; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 订单对象 * 这个对象是否有效必须系统仔细确认,比如可能发生如下情况: * 1,没货了 * 2,等待在线付款 * 订单真正生效就进入实际的物流流程,订单从入库开始在它上面就会发生一系列事件,同时也开始了状态迁移 * User: Asion * Date: 11-10-11 * Time: 下午12:36 */ public class Order { private static final Logger LOGGER = Logger.getLogger(Order.class); private long id; //商品条目 private List<OrderItem> orderItemList = new ArrayList<OrderItem>(); //物流 private Logistics logistics; //支付信息 private PayType payType; //支付银行 private PayBank payBank; //发票信息 private InvoiceInfo invoiceInfo; //是否有效,如果被用户取消或者没有付款都是无效的 private boolean valid; //订单是永久存储的,所以这里保存了这次订单总价格 private String totalPrice; //订单每时每刻都必然对应一个状态 private OrderState orderState; //谁下的单 private int userId; private String userName; //账户类型,可区别出来自什么网站,比如QQ,sina,KRQ代表我们自己 private AccountType accountType; //下单时间 private Date createDate; /** * 更新时间 */ private Date modifyDate; /** * 付款时间 */ private Date payDate; /** * 最终时间(取消 关闭 交易完成) */ private Date endDate; // 取消时间 private Date cancelDate; //下单时间的long型表示 private long milliDate; /** * 商家Id */ private int customerId; /** * 商家名(快照冗余) */ private String supplierName; /** * 仓库Id */ private int storageId; /** * 仓库名(快照冗余) */ private String storageName; /** * 关联的虚拟订单ID */ private long virtualOrderId; /** * 订单编号 */ private long orderNo; /** * 订单所发的物流公司(顺风, 中通等), 与订单物流表中冗余 */ private DeliveryInfo.DeliveryType deliveryType; /** * 必须的订单前置状态, 只在更新 SQL 时有效, 不写入数据库 */ private OrderState mustPreviousState; /** * 优惠劵 */ private Coupon coupon; /** * 使用现金券或积分时记录其订单价格相关说明 */ private String priceMessage; /** * 使用现金券或积分时记录其订单价格相关详细说明 */ private String priceMessageDetail; /** * 积分比例 */ private double integralPercent; /** * 计算订单总价. * * @throws OrderNoTransactionalException */ public void calculateTotalPrice() throws OrderNoTransactionalException { long total = 0; for (OrderItem orderItem : orderItemList) { total += orderItem.getItemTotalPrice(); } totalPrice = Money.getMoneyString(total); } /** * 计算原始订单总价. * * @return */ public long calculateOldTotalPrice() { long total = 0; for (OrderItem orderItem : orderItemList) { total += orderItem.totalPrice(); } return total; } public boolean checkCanNBack() { return new Money(totalPrice).getCent() > 0 && !this.orderState.checkCanNotBack(); } /** * 提供给前台显示原始订单总价 */ public String calculateOldTotalPriceMoney() { return Money.getMoneyString(this.calculateOldTotalPrice()); } // ====================================== 优惠券积分独用表来管理了, 此段需要重构 ====================================== /** * 计算订单总价. */ public void calculateTotalPrice(Coupon coupon, long integral, int orderListSize) { long total = 0; for (OrderItem orderItem : orderItemList) { total += orderItem.getItemTotalPrice(); } totalPrice = Money.getMoneyString(total); // 如果有使用优惠券或积分, 则两个价格不可能一致 if (coupon != null || integral > 0){ StringBuilder priceMessageDetail = new StringBuilder(); StringBuilder priceMessage = new StringBuilder(); // ~满减~ // 记录当前订单使用的优惠券信息 if (coupon != null) { priceMessage.append(ChangePriceElement.coupon); priceMessageDetail.append("现金").append(ChangePriceElement.coupon.toDesc()).append("(") .append(coupon.getCode()).append(")").append(ChangePriceElement.money.toDesc()).append("(").append(coupon.getMoney()).append(")"); if (orderListSize > 1) { priceMessageDetail.append(",平摊回的").append(ChangePriceElement.money.toDesc()).append("("); long couponRatio = 0; for (OrderItem orderItem : orderItemList) { couponRatio += orderItem.getCouponApportion(); } priceMessageDetail.append(Money.getMoneyString(couponRatio)).append(")"); } } // 记录当前订单使用的积分 if (integral > 0) { if (StringUtils.isNotBlank(priceMessageDetail.toString())) { priceMessage.append(";"); priceMessageDetail.append(";"); } priceMessage.append(ChangePriceElement.integral); priceMessageDetail.append(ChangePriceElement.integral.toDesc()).append("(").append(com.kariqu.usercenter.domain.Currency.IntegralToCurrency(integral)).append(")点"); if (orderListSize > 1) { priceMessageDetail.append(",平摊回的").append(ChangePriceElement.integral.toDesc()).append("("); long integralRatio = 0; for (OrderItem orderItem : orderItemList) { integralRatio += orderItem.getIntegralApportion(); } priceMessageDetail.append(com.kariqu.usercenter.domain.Currency.IntegralToCurrency(integralRatio)).append(")点"); } } this.priceMessage = priceMessage.toString(); this.priceMessageDetail = priceMessageDetail.toString(); } } /** * 回加积分和让用过的现金券可用 */ public void backToCouponAndIntegral(CouponService couponService, UserPointService userPointService, OrderQueryService orderQueryService) { // 现金券 String couponCode = getCouponCode(); if (StringUtils.isNotBlank(couponCode)) { // 将现金券置为可用 Coupon cp = couponService.getCouponByCode(couponCode); if (cp != null && cp.isUsed() && cp.getCouponType() == Coupon.CouponType.Normal) { // 查询此现金券对应的其他订单是不是已经都取消了 List<Map<String, Object>> orderList = orderQueryService.queryCountByCouponIdWithoutId(cp.getId(), id); if (orderList == null || orderList.size() == 0) { cp.setUsed(false); couponService.updateCoupon(cp); LOGGER.warn("操作订单(" + orderNo + ")时, 将现金券 (" + couponCode + ") 置回可用, 此订单对应用户(id: " + userId + ", name: " + userName + ")."); } else { StringBuilder sbd = new StringBuilder(); int i = 0; for (Map order : orderList) { sbd.append(order.get("orderNo")).append("/").append(order.get("orderState")); i++; if (i != orderList.size()) sbd.append(","); } LOGGER.warn("操作订单(" + orderNo + ")时, 现金券 (" + couponCode + ") 有作用在其他还没取消的订单(" + sbd.toString() + ")上, 不能被置回可用. 此订单对应用户(id: " + userId + ", name: " + userName + ")."); } } } // 积分 long integral = getIntegral(); if (integral > 0) { UserPoint userPoint = new UserPoint(); userPoint.setUserId(userId); userPoint.setPoint(Math.abs(integral)); userPoint.setType(UserPoint.PointType.InComing); userPoint.setInOutComingType(UserPoint.InOutComingType.Cancel); userPoint.setDescription("取消订单(" + orderNo + ")时回加积分"); userPointService.createUsePoint(userPoint); LOGGER.warn("操作订单(" + orderNo + ")时, 回加用户(id: " + userId + ", name: " + userName + ")积分(" + Money.getMoneyString(integral) + "点)"); } // 满减 } private enum ChangePriceElement { /** * 现金券 */ coupon, money, /** * 积分 */ integral; // 满减 private static Map<ChangePriceElement, String> map = new HashMap<ChangePriceElement, String>(); static { map.put(coupon, "券"); map.put(money, "金额"); map.put(integral, "积分"); } private String toDesc() { return map.get(this); } /** * 获取当前因素对应的价格值 * * @param priceMessageDetail 订单的价格信息说明 * @return */ private String getPriceValueByOrderPriceMessageDetail(String priceMessageDetail) { if (StringUtils.isBlank(priceMessageDetail)) return ""; Matcher matcher = Pattern.compile(toDesc() + "\\(([^)]*)\\)").matcher(priceMessageDetail); String find = ""; // 使用最后一个匹配(如下面这种情况时, 取后面的金额或积分数: "优惠券(om677735)金额(50.00),平摊回的金额(30.00);积分(47),平摊回的积分(30)点") while (matcher.find()) find = matcher.group(1); return find; } } /** * 订单使用的优惠券编号 */ public String getCouponCode() { return ChangePriceElement.coupon.getPriceValueByOrderPriceMessageDetail(priceMessageDetail); } /** * 订单使用的优惠券平摊的价格 */ public String getCouponMoney() { return ChangePriceElement.money.getPriceValueByOrderPriceMessageDetail(priceMessageDetail); } /** * 订单使用的积分点数 */ public long getIntegral() { String currency = ChangePriceElement.integral.getPriceValueByOrderPriceMessageDetail(priceMessageDetail); return com.kariqu.usercenter.domain.Currency.CurrencyToIntegral(StringUtils.isBlank(currency) ? "0" : currency); } // ====================================== 优惠券积分单独用表来管理了, 此段需要重构 ====================================== /** * 添加订单项. * * @param orderItem */ public void addOrderItem(OrderItem orderItem) { orderItemList.add(orderItem); } /** * 检查订单项对应的商品, 操作库存, 创建订单项 * * @param orderWriteService 创建订单, 订单项, 历史记录 * @param skuService 查询 Sku 信息 及 扣减库存 */ public void createOrderItemsAndOperateStorage(OrderWriteService orderWriteService, SkuService skuService, OrderQueryService orderQueryService) { for (OrderItem orderItem : orderItemList) { orderItem.setOrderId(id); // 订单项状态 orderItem.setOrderState(orderState); OrderAssert.assertOrderItem(orderItem, this); // 创建订单项 orderWriteService.createOrderItem(orderItem); // 通过策略操作库存 orderItem.getStoreStrategy().operateStorageWhenCreateOrder(skuService, orderItem.getSkuId(), orderItem.getStorageId(), orderItem.getNumber(), payType != PayType.OnLine); try { orderItem.recordPayNumber(orderWriteService, orderQueryService); } catch (Exception e) { LOGGER.error("附加(skuId:" + orderItem.getSkuId() + ", productId:" + orderItem.getProductId() + ")付款数量(" + orderItem.getNumber() + ")时异常:", e); } } } /** * 订单项状态置为取消或关闭, 操作库存 * * @param orderWriteService 创建订单项, 历史记录 * @param skuService 操作库存 */ public void cancelOrCloseOrderItems(OrderWriteService orderWriteService, SkuService skuService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); // 操作库存 orderItem.getStoreStrategy().operateStorageWhenCancelOrder(skuService, orderItem.getSkuId(), orderItem.getStorageId(), orderItem.getNumber(), payType != PayType.OnLine); } } /** * 更新订单项状态为已支付, 操作库存 * * @param orderWriteService 创建订单, 订单项, 历史记录 * @param skuService 操作库存 */ public void payOrderItems(OrderWriteService orderWriteService, SkuService skuService, OrderQueryService orderQueryService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); // 操作库存 orderItem.getStoreStrategy().operateStorageWhenPayOrder(skuService, orderItem.getSkuId(), orderItem.getStorageId(), orderItem.getNumber()); try { orderItem.recordPayNumber(orderWriteService, orderQueryService); } catch (Exception e) { LOGGER.error("附加(skuId:" + orderItem.getSkuId() + ", productId:" + orderItem.getProductId() + ")付款数量(" + orderItem.getNumber() + ")时异常:", e); } } } /** * 订单交易完成. 统计销售量. * * @param orderWriteService * @param orderQueryService */ public void successOrderItems(OrderWriteService orderWriteService, OrderQueryService orderQueryService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); // 统计销售量, 若统计时出现异常, 不能影响前面的订单状态更新. try { orderItem.recordSalesNumber(orderWriteService, orderQueryService); } catch (Exception e) { LOGGER.error("附加(skuId:" + orderItem.getSkuId() + ", productId:" + orderItem.getProductId() + ")销售数量(" + orderItem.getNumber() + ")时异常:", e); } } } private void rebuildOperateOrderItem(OrderWriteService orderWriteService, OrderItem orderItem) { OrderState oldItemState = orderItem.getOrderState(); orderItem.setOrderState(orderState); orderItem.setMustPreviousState(mustPreviousState); if (orderWriteService.updateOrderItemState(orderItem.getId(), orderItem.getOrderState(), orderItem.getMustPreviousState()) != 1) { LOGGER.error("订单[" + orderNo + "]项[" + orderItem.getSkuName() + "]不能从[" + oldItemState.serviceDesc() + "]变更为[" + orderItem.getOrderState().serviceDesc() + "](只能从[" + orderItem.getMustPreviousState().serviceDesc() + "]变更)"); // 订单项的值可能会不一样, 此时只需要记录一下即可. 不能往外抛出异常 } } /** * 更新订单项状态(以 order 的 mustPreviousState 和 orderState 值为基础进行更新) * * @param orderWriteService */ public void updateOrderItemsState(OrderWriteService orderWriteService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); } } /** * 查询订单是否有评价, 若所有的订单项都已评, 则返回 true. * * @return */ public boolean isAppraise() { for (OrderItem orderItem : orderItemList) { // 发现有未评价的则返回 false if (!orderItem.isAppraise()) return false; } return true; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getOrderNo() { return orderNo; } public void setOrderNo(long orderNo) { this.orderNo = orderNo; } /** * 订单所发的物流公司(顺风, 中通等), 与订单物流表中冗余 */ public DeliveryInfo.DeliveryType getDeliveryType() { return deliveryType; } /** * 订单所发的物流公司(顺风, 中通等), 与订单物流表中冗余 */ public void setDeliveryType(DeliveryInfo.DeliveryType deliveryType) { this.deliveryType = deliveryType; } /** * 原先的订单状态, 只在更新 SQL 时有效, 不写入数据库 */ public OrderState getMustPreviousState() { return mustPreviousState; } /** * 原先的订单状态, 只在更新 SQL 时有效, 不写入数据库 */ public void setMustPreviousState(OrderState mustPreviousState) { this.mustPreviousState = mustPreviousState; } public List<OrderItem> getOrderItemList() { return orderItemList; } /** * 获取单个订单项 */ public OrderItem getOrderItem(long orderItemId) { for (OrderItem orderItem : orderItemList) { if (orderItem.getId() == orderItemId) { return orderItem; } } return null; } public void setOrderItemList(List<OrderItem> orderItemList) { this.orderItemList = orderItemList; } public boolean isValid() { return valid; } public void setValid(boolean valid) { this.valid = valid; } public Logistics getLogistics() { return logistics; } public void setLogistics(Logistics logistics) { this.logistics = logistics; } public PayType getPayType() { return payType; } public void setPayType(PayType payType) { this.payType = payType; } public long getMilliDate() { return milliDate; } public void setMilliDate(long milliDate) { this.milliDate = milliDate; } public InvoiceInfo getInvoiceInfo() { return invoiceInfo; } public void setInvoiceInfo(InvoiceInfo invoiceInfo) { this.invoiceInfo = invoiceInfo; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } public OrderState getOrderState() { return orderState; } public void setOrderState(OrderState orderState) { this.orderState = orderState; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; this.milliDate = createDate.getTime(); } /** * 更新时间 */ public Date getModifyDate() { return modifyDate; } /** * 更新时间 */ public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } public Date getPayDate() { return payDate; } public void setPayDate(Date payDate) { this.payDate = payDate; } public AccountType getAccountType() { return accountType; } public void setAccountType(AccountType accountType) { this.accountType = accountType; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getCancelDate() { return cancelDate; } public void setCancelDate(Date cancelDate) { this.cancelDate = cancelDate; } public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public int getStorageId() { return storageId; } public void setStorageId(int storageId) { this.storageId = storageId; } public long getVirtualOrderId() { return virtualOrderId; } public void setVirtualOrderId(long virtualOrderId) { this.virtualOrderId = virtualOrderId; } public PayBank getPayBank() { return payBank; } public void setPayBank(PayBank payBank) { this.payBank = payBank; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSupplierName() { return supplierName; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } public String getStorageName() { return storageName; } public void setStorageName(String storageName) { this.storageName = storageName; } public Coupon getCoupon() { return coupon; } public void setCoupon(Coupon coupon) { this.coupon = coupon; } /** * 使用现金券或积分时记录其订单价格相关说明 */ public String getPriceMessage() { return priceMessage; } /** * 使用现金券或积分时记录其订单价格相关说明 */ public void setPriceMessage(String priceMessage) { this.priceMessage = priceMessage; } /** * 使用现金券或积分时记录其订单价格相关详细说明 */ public String getPriceMessageDetail() { return priceMessageDetail; } /** * 使用现金券或积分时记录其订单价格相关详细说明 */ public void setPriceMessageDetail(String priceMessageDetail) { this.priceMessageDetail = priceMessageDetail; } /** * 积分比例 */ public double getIntegralPercent() { return integralPercent; } /** * 积分比例 */ public void setIntegralPercent(double integralPercent) { this.integralPercent = integralPercent; } @Override public String toString() { return "Order{" + "id=" + id + ", orderItemList=" + orderItemList + ", logistics=" + logistics + ", payType=" + payType + ", payBank=" + payBank + ", invoiceInfo=" + invoiceInfo + ", valid=" + valid + ", totalPrice='" + totalPrice + '\'' + ", orderState=" + orderState + ", userId=" + userId + ", userName='" + userName + '\'' + ", accountType=" + accountType + ", createDate=" + createDate + ", modifyDate=" + modifyDate + ", payDate=" + payDate + ", endDate=" + endDate + ", cancelDate=" + cancelDate + ", milliDate=" + milliDate + ", customerId=" + customerId + ", supplierName='" + supplierName + '\'' + ", storageId=" + storageId + ", storageName='" + storageName + '\'' + ", virtualOrderId=" + virtualOrderId + ", orderNo=" + orderNo + ", deliveryType=" + deliveryType + ", mustPreviousState=" + mustPreviousState + ", coupon=" + coupon + '}'; } }
UTF-8
Java
25,154
java
Order.java
Java
[ { "context": "进入实际的物流流程,订单从入库开始在它上面就会发生一系列事件,同时也开始了状态迁移\n * User: Asion\n * Date: 11-10-11\n * Time: 下午12:36\n */\npublic cla", "end": 973, "score": 0.999500572681427, "start": 968, "tag": "USERNAME", "value": "Asion" }, { "context": "//谁下的单\n private int userId;\n\n private String userName;\n\n //账户类型,可区别出来自什么网站,比如QQ,sina,KRQ代表我们自己\n p", "end": 1629, "score": 0.9873635768890381, "start": 1621, "tag": "USERNAME", "value": "userName" }, { "context": "e + \") 置回可用, 此订单对应用户(id: \" + userId + \", name: \" + userName + \").\");\n } else {\n ", "end": 7396, "score": 0.99186772108078, "start": 7388, "tag": "USERNAME", "value": "userName" }, { "context": ")上, 不能被置回可用. 此订单对应用户(id: \" + userId + \", name: \" + userName + \").\");\n }\n }\n ", "end": 8027, "score": 0.8966498374938965, "start": 8019, "tag": "USERNAME", "value": "userName" }, { "context": " orderNo + \")时, 回加用户(id: \" + userId + \", name: \" + userName + \")积分(\" + Money.getMoneyString(integral) + \"点)\")", "end": 8659, "score": 0.9178243279457092, "start": 8651, "tag": "USERNAME", "value": "userName" }, { "context": "\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userNa", "end": 19962, "score": 0.9382324814796448, "start": 19954, "tag": "USERNAME", "value": "userName" }, { "context": "serName(String userName) {\n this.userName = userName;\n }\n\n public String getSupplierName() {\n ", "end": 20050, "score": 0.9414469003677368, "start": 20042, "tag": "USERNAME", "value": "userName" }, { "context": "erId=\" + userId +\n \", userName='\" + userName + '\\'' +\n \", accountType=\" + accou", "end": 21923, "score": 0.9819279313087463, "start": 21915, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.kariqu.tradecenter.domain; import com.kariqu.productcenter.domain.Money; import com.kariqu.productcenter.service.SkuService; import com.kariqu.suppliercenter.domain.DeliveryInfo; import com.kariqu.tradecenter.excepiton.OrderNoTransactionalException; import com.kariqu.tradecenter.helper.OrderAssert; import com.kariqu.tradecenter.service.CouponService; import com.kariqu.tradecenter.service.OrderQueryService; import com.kariqu.tradecenter.service.OrderWriteService; import com.kariqu.usercenter.domain.AccountType; import com.kariqu.usercenter.domain.UserPoint; import com.kariqu.usercenter.service.UserPointService; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.log4j.Logger; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 订单对象 * 这个对象是否有效必须系统仔细确认,比如可能发生如下情况: * 1,没货了 * 2,等待在线付款 * 订单真正生效就进入实际的物流流程,订单从入库开始在它上面就会发生一系列事件,同时也开始了状态迁移 * User: Asion * Date: 11-10-11 * Time: 下午12:36 */ public class Order { private static final Logger LOGGER = Logger.getLogger(Order.class); private long id; //商品条目 private List<OrderItem> orderItemList = new ArrayList<OrderItem>(); //物流 private Logistics logistics; //支付信息 private PayType payType; //支付银行 private PayBank payBank; //发票信息 private InvoiceInfo invoiceInfo; //是否有效,如果被用户取消或者没有付款都是无效的 private boolean valid; //订单是永久存储的,所以这里保存了这次订单总价格 private String totalPrice; //订单每时每刻都必然对应一个状态 private OrderState orderState; //谁下的单 private int userId; private String userName; //账户类型,可区别出来自什么网站,比如QQ,sina,KRQ代表我们自己 private AccountType accountType; //下单时间 private Date createDate; /** * 更新时间 */ private Date modifyDate; /** * 付款时间 */ private Date payDate; /** * 最终时间(取消 关闭 交易完成) */ private Date endDate; // 取消时间 private Date cancelDate; //下单时间的long型表示 private long milliDate; /** * 商家Id */ private int customerId; /** * 商家名(快照冗余) */ private String supplierName; /** * 仓库Id */ private int storageId; /** * 仓库名(快照冗余) */ private String storageName; /** * 关联的虚拟订单ID */ private long virtualOrderId; /** * 订单编号 */ private long orderNo; /** * 订单所发的物流公司(顺风, 中通等), 与订单物流表中冗余 */ private DeliveryInfo.DeliveryType deliveryType; /** * 必须的订单前置状态, 只在更新 SQL 时有效, 不写入数据库 */ private OrderState mustPreviousState; /** * 优惠劵 */ private Coupon coupon; /** * 使用现金券或积分时记录其订单价格相关说明 */ private String priceMessage; /** * 使用现金券或积分时记录其订单价格相关详细说明 */ private String priceMessageDetail; /** * 积分比例 */ private double integralPercent; /** * 计算订单总价. * * @throws OrderNoTransactionalException */ public void calculateTotalPrice() throws OrderNoTransactionalException { long total = 0; for (OrderItem orderItem : orderItemList) { total += orderItem.getItemTotalPrice(); } totalPrice = Money.getMoneyString(total); } /** * 计算原始订单总价. * * @return */ public long calculateOldTotalPrice() { long total = 0; for (OrderItem orderItem : orderItemList) { total += orderItem.totalPrice(); } return total; } public boolean checkCanNBack() { return new Money(totalPrice).getCent() > 0 && !this.orderState.checkCanNotBack(); } /** * 提供给前台显示原始订单总价 */ public String calculateOldTotalPriceMoney() { return Money.getMoneyString(this.calculateOldTotalPrice()); } // ====================================== 优惠券积分独用表来管理了, 此段需要重构 ====================================== /** * 计算订单总价. */ public void calculateTotalPrice(Coupon coupon, long integral, int orderListSize) { long total = 0; for (OrderItem orderItem : orderItemList) { total += orderItem.getItemTotalPrice(); } totalPrice = Money.getMoneyString(total); // 如果有使用优惠券或积分, 则两个价格不可能一致 if (coupon != null || integral > 0){ StringBuilder priceMessageDetail = new StringBuilder(); StringBuilder priceMessage = new StringBuilder(); // ~满减~ // 记录当前订单使用的优惠券信息 if (coupon != null) { priceMessage.append(ChangePriceElement.coupon); priceMessageDetail.append("现金").append(ChangePriceElement.coupon.toDesc()).append("(") .append(coupon.getCode()).append(")").append(ChangePriceElement.money.toDesc()).append("(").append(coupon.getMoney()).append(")"); if (orderListSize > 1) { priceMessageDetail.append(",平摊回的").append(ChangePriceElement.money.toDesc()).append("("); long couponRatio = 0; for (OrderItem orderItem : orderItemList) { couponRatio += orderItem.getCouponApportion(); } priceMessageDetail.append(Money.getMoneyString(couponRatio)).append(")"); } } // 记录当前订单使用的积分 if (integral > 0) { if (StringUtils.isNotBlank(priceMessageDetail.toString())) { priceMessage.append(";"); priceMessageDetail.append(";"); } priceMessage.append(ChangePriceElement.integral); priceMessageDetail.append(ChangePriceElement.integral.toDesc()).append("(").append(com.kariqu.usercenter.domain.Currency.IntegralToCurrency(integral)).append(")点"); if (orderListSize > 1) { priceMessageDetail.append(",平摊回的").append(ChangePriceElement.integral.toDesc()).append("("); long integralRatio = 0; for (OrderItem orderItem : orderItemList) { integralRatio += orderItem.getIntegralApportion(); } priceMessageDetail.append(com.kariqu.usercenter.domain.Currency.IntegralToCurrency(integralRatio)).append(")点"); } } this.priceMessage = priceMessage.toString(); this.priceMessageDetail = priceMessageDetail.toString(); } } /** * 回加积分和让用过的现金券可用 */ public void backToCouponAndIntegral(CouponService couponService, UserPointService userPointService, OrderQueryService orderQueryService) { // 现金券 String couponCode = getCouponCode(); if (StringUtils.isNotBlank(couponCode)) { // 将现金券置为可用 Coupon cp = couponService.getCouponByCode(couponCode); if (cp != null && cp.isUsed() && cp.getCouponType() == Coupon.CouponType.Normal) { // 查询此现金券对应的其他订单是不是已经都取消了 List<Map<String, Object>> orderList = orderQueryService.queryCountByCouponIdWithoutId(cp.getId(), id); if (orderList == null || orderList.size() == 0) { cp.setUsed(false); couponService.updateCoupon(cp); LOGGER.warn("操作订单(" + orderNo + ")时, 将现金券 (" + couponCode + ") 置回可用, 此订单对应用户(id: " + userId + ", name: " + userName + ")."); } else { StringBuilder sbd = new StringBuilder(); int i = 0; for (Map order : orderList) { sbd.append(order.get("orderNo")).append("/").append(order.get("orderState")); i++; if (i != orderList.size()) sbd.append(","); } LOGGER.warn("操作订单(" + orderNo + ")时, 现金券 (" + couponCode + ") 有作用在其他还没取消的订单(" + sbd.toString() + ")上, 不能被置回可用. 此订单对应用户(id: " + userId + ", name: " + userName + ")."); } } } // 积分 long integral = getIntegral(); if (integral > 0) { UserPoint userPoint = new UserPoint(); userPoint.setUserId(userId); userPoint.setPoint(Math.abs(integral)); userPoint.setType(UserPoint.PointType.InComing); userPoint.setInOutComingType(UserPoint.InOutComingType.Cancel); userPoint.setDescription("取消订单(" + orderNo + ")时回加积分"); userPointService.createUsePoint(userPoint); LOGGER.warn("操作订单(" + orderNo + ")时, 回加用户(id: " + userId + ", name: " + userName + ")积分(" + Money.getMoneyString(integral) + "点)"); } // 满减 } private enum ChangePriceElement { /** * 现金券 */ coupon, money, /** * 积分 */ integral; // 满减 private static Map<ChangePriceElement, String> map = new HashMap<ChangePriceElement, String>(); static { map.put(coupon, "券"); map.put(money, "金额"); map.put(integral, "积分"); } private String toDesc() { return map.get(this); } /** * 获取当前因素对应的价格值 * * @param priceMessageDetail 订单的价格信息说明 * @return */ private String getPriceValueByOrderPriceMessageDetail(String priceMessageDetail) { if (StringUtils.isBlank(priceMessageDetail)) return ""; Matcher matcher = Pattern.compile(toDesc() + "\\(([^)]*)\\)").matcher(priceMessageDetail); String find = ""; // 使用最后一个匹配(如下面这种情况时, 取后面的金额或积分数: "优惠券(om677735)金额(50.00),平摊回的金额(30.00);积分(47),平摊回的积分(30)点") while (matcher.find()) find = matcher.group(1); return find; } } /** * 订单使用的优惠券编号 */ public String getCouponCode() { return ChangePriceElement.coupon.getPriceValueByOrderPriceMessageDetail(priceMessageDetail); } /** * 订单使用的优惠券平摊的价格 */ public String getCouponMoney() { return ChangePriceElement.money.getPriceValueByOrderPriceMessageDetail(priceMessageDetail); } /** * 订单使用的积分点数 */ public long getIntegral() { String currency = ChangePriceElement.integral.getPriceValueByOrderPriceMessageDetail(priceMessageDetail); return com.kariqu.usercenter.domain.Currency.CurrencyToIntegral(StringUtils.isBlank(currency) ? "0" : currency); } // ====================================== 优惠券积分单独用表来管理了, 此段需要重构 ====================================== /** * 添加订单项. * * @param orderItem */ public void addOrderItem(OrderItem orderItem) { orderItemList.add(orderItem); } /** * 检查订单项对应的商品, 操作库存, 创建订单项 * * @param orderWriteService 创建订单, 订单项, 历史记录 * @param skuService 查询 Sku 信息 及 扣减库存 */ public void createOrderItemsAndOperateStorage(OrderWriteService orderWriteService, SkuService skuService, OrderQueryService orderQueryService) { for (OrderItem orderItem : orderItemList) { orderItem.setOrderId(id); // 订单项状态 orderItem.setOrderState(orderState); OrderAssert.assertOrderItem(orderItem, this); // 创建订单项 orderWriteService.createOrderItem(orderItem); // 通过策略操作库存 orderItem.getStoreStrategy().operateStorageWhenCreateOrder(skuService, orderItem.getSkuId(), orderItem.getStorageId(), orderItem.getNumber(), payType != PayType.OnLine); try { orderItem.recordPayNumber(orderWriteService, orderQueryService); } catch (Exception e) { LOGGER.error("附加(skuId:" + orderItem.getSkuId() + ", productId:" + orderItem.getProductId() + ")付款数量(" + orderItem.getNumber() + ")时异常:", e); } } } /** * 订单项状态置为取消或关闭, 操作库存 * * @param orderWriteService 创建订单项, 历史记录 * @param skuService 操作库存 */ public void cancelOrCloseOrderItems(OrderWriteService orderWriteService, SkuService skuService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); // 操作库存 orderItem.getStoreStrategy().operateStorageWhenCancelOrder(skuService, orderItem.getSkuId(), orderItem.getStorageId(), orderItem.getNumber(), payType != PayType.OnLine); } } /** * 更新订单项状态为已支付, 操作库存 * * @param orderWriteService 创建订单, 订单项, 历史记录 * @param skuService 操作库存 */ public void payOrderItems(OrderWriteService orderWriteService, SkuService skuService, OrderQueryService orderQueryService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); // 操作库存 orderItem.getStoreStrategy().operateStorageWhenPayOrder(skuService, orderItem.getSkuId(), orderItem.getStorageId(), orderItem.getNumber()); try { orderItem.recordPayNumber(orderWriteService, orderQueryService); } catch (Exception e) { LOGGER.error("附加(skuId:" + orderItem.getSkuId() + ", productId:" + orderItem.getProductId() + ")付款数量(" + orderItem.getNumber() + ")时异常:", e); } } } /** * 订单交易完成. 统计销售量. * * @param orderWriteService * @param orderQueryService */ public void successOrderItems(OrderWriteService orderWriteService, OrderQueryService orderQueryService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); // 统计销售量, 若统计时出现异常, 不能影响前面的订单状态更新. try { orderItem.recordSalesNumber(orderWriteService, orderQueryService); } catch (Exception e) { LOGGER.error("附加(skuId:" + orderItem.getSkuId() + ", productId:" + orderItem.getProductId() + ")销售数量(" + orderItem.getNumber() + ")时异常:", e); } } } private void rebuildOperateOrderItem(OrderWriteService orderWriteService, OrderItem orderItem) { OrderState oldItemState = orderItem.getOrderState(); orderItem.setOrderState(orderState); orderItem.setMustPreviousState(mustPreviousState); if (orderWriteService.updateOrderItemState(orderItem.getId(), orderItem.getOrderState(), orderItem.getMustPreviousState()) != 1) { LOGGER.error("订单[" + orderNo + "]项[" + orderItem.getSkuName() + "]不能从[" + oldItemState.serviceDesc() + "]变更为[" + orderItem.getOrderState().serviceDesc() + "](只能从[" + orderItem.getMustPreviousState().serviceDesc() + "]变更)"); // 订单项的值可能会不一样, 此时只需要记录一下即可. 不能往外抛出异常 } } /** * 更新订单项状态(以 order 的 mustPreviousState 和 orderState 值为基础进行更新) * * @param orderWriteService */ public void updateOrderItemsState(OrderWriteService orderWriteService) { for (OrderItem orderItem : orderItemList) { rebuildOperateOrderItem(orderWriteService, orderItem); } } /** * 查询订单是否有评价, 若所有的订单项都已评, 则返回 true. * * @return */ public boolean isAppraise() { for (OrderItem orderItem : orderItemList) { // 发现有未评价的则返回 false if (!orderItem.isAppraise()) return false; } return true; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getOrderNo() { return orderNo; } public void setOrderNo(long orderNo) { this.orderNo = orderNo; } /** * 订单所发的物流公司(顺风, 中通等), 与订单物流表中冗余 */ public DeliveryInfo.DeliveryType getDeliveryType() { return deliveryType; } /** * 订单所发的物流公司(顺风, 中通等), 与订单物流表中冗余 */ public void setDeliveryType(DeliveryInfo.DeliveryType deliveryType) { this.deliveryType = deliveryType; } /** * 原先的订单状态, 只在更新 SQL 时有效, 不写入数据库 */ public OrderState getMustPreviousState() { return mustPreviousState; } /** * 原先的订单状态, 只在更新 SQL 时有效, 不写入数据库 */ public void setMustPreviousState(OrderState mustPreviousState) { this.mustPreviousState = mustPreviousState; } public List<OrderItem> getOrderItemList() { return orderItemList; } /** * 获取单个订单项 */ public OrderItem getOrderItem(long orderItemId) { for (OrderItem orderItem : orderItemList) { if (orderItem.getId() == orderItemId) { return orderItem; } } return null; } public void setOrderItemList(List<OrderItem> orderItemList) { this.orderItemList = orderItemList; } public boolean isValid() { return valid; } public void setValid(boolean valid) { this.valid = valid; } public Logistics getLogistics() { return logistics; } public void setLogistics(Logistics logistics) { this.logistics = logistics; } public PayType getPayType() { return payType; } public void setPayType(PayType payType) { this.payType = payType; } public long getMilliDate() { return milliDate; } public void setMilliDate(long milliDate) { this.milliDate = milliDate; } public InvoiceInfo getInvoiceInfo() { return invoiceInfo; } public void setInvoiceInfo(InvoiceInfo invoiceInfo) { this.invoiceInfo = invoiceInfo; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } public OrderState getOrderState() { return orderState; } public void setOrderState(OrderState orderState) { this.orderState = orderState; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; this.milliDate = createDate.getTime(); } /** * 更新时间 */ public Date getModifyDate() { return modifyDate; } /** * 更新时间 */ public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } public Date getPayDate() { return payDate; } public void setPayDate(Date payDate) { this.payDate = payDate; } public AccountType getAccountType() { return accountType; } public void setAccountType(AccountType accountType) { this.accountType = accountType; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Date getCancelDate() { return cancelDate; } public void setCancelDate(Date cancelDate) { this.cancelDate = cancelDate; } public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public int getStorageId() { return storageId; } public void setStorageId(int storageId) { this.storageId = storageId; } public long getVirtualOrderId() { return virtualOrderId; } public void setVirtualOrderId(long virtualOrderId) { this.virtualOrderId = virtualOrderId; } public PayBank getPayBank() { return payBank; } public void setPayBank(PayBank payBank) { this.payBank = payBank; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSupplierName() { return supplierName; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } public String getStorageName() { return storageName; } public void setStorageName(String storageName) { this.storageName = storageName; } public Coupon getCoupon() { return coupon; } public void setCoupon(Coupon coupon) { this.coupon = coupon; } /** * 使用现金券或积分时记录其订单价格相关说明 */ public String getPriceMessage() { return priceMessage; } /** * 使用现金券或积分时记录其订单价格相关说明 */ public void setPriceMessage(String priceMessage) { this.priceMessage = priceMessage; } /** * 使用现金券或积分时记录其订单价格相关详细说明 */ public String getPriceMessageDetail() { return priceMessageDetail; } /** * 使用现金券或积分时记录其订单价格相关详细说明 */ public void setPriceMessageDetail(String priceMessageDetail) { this.priceMessageDetail = priceMessageDetail; } /** * 积分比例 */ public double getIntegralPercent() { return integralPercent; } /** * 积分比例 */ public void setIntegralPercent(double integralPercent) { this.integralPercent = integralPercent; } @Override public String toString() { return "Order{" + "id=" + id + ", orderItemList=" + orderItemList + ", logistics=" + logistics + ", payType=" + payType + ", payBank=" + payBank + ", invoiceInfo=" + invoiceInfo + ", valid=" + valid + ", totalPrice='" + totalPrice + '\'' + ", orderState=" + orderState + ", userId=" + userId + ", userName='" + userName + '\'' + ", accountType=" + accountType + ", createDate=" + createDate + ", modifyDate=" + modifyDate + ", payDate=" + payDate + ", endDate=" + endDate + ", cancelDate=" + cancelDate + ", milliDate=" + milliDate + ", customerId=" + customerId + ", supplierName='" + supplierName + '\'' + ", storageId=" + storageId + ", storageName='" + storageName + '\'' + ", virtualOrderId=" + virtualOrderId + ", orderNo=" + orderNo + ", deliveryType=" + deliveryType + ", mustPreviousState=" + mustPreviousState + ", coupon=" + coupon + '}'; } }
25,154
0.577505
0.575438
819
26.758242
29.251053
180
false
false
0
0
0
0
0
0
0.396825
false
false
4
6f45bd7e90619544aebb1f1cbc5241cc94e4561e
37,984,690,770,087
9965eefd9fb909cc368f122f76a1a4980e3b22c2
/src/main/java/gmail/roadtojob2019/brewery/mapper/ProductMapper.java
cd1d9220eeb82b474211fb156be4d57a3bc74c1e
[]
no_license
MarkelaLippi/brewery
https://github.com/MarkelaLippi/brewery
0f2cf86c069b5c214771c840315548b2d9ac1d11
5f5df0149654acc21d9bd43270bbf5ee9a0fa5c6
refs/heads/master
2020-12-29T14:07:39.416000
2020-04-18T09:34:31
2020-04-18T09:34:31
238,632,657
0
2
null
false
2020-02-28T11:53:45
2020-02-06T07:36:48
2020-02-28T11:36:09
2020-02-28T11:53:44
257
0
1
0
Java
false
false
package gmail.roadtojob2019.brewery.mapper; import gmail.roadtojob2019.brewery.dto.ProductDto; import gmail.roadtojob2019.brewery.entity.Product; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; @Mapper(componentModel = "spring") public interface ProductMapper { @Mappings({ @Mapping(target = "amount", source = "storage.amount"), }) ProductDto productToProductDto(Product product); }
UTF-8
Java
452
java
ProductMapper.java
Java
[]
null
[]
package gmail.roadtojob2019.brewery.mapper; import gmail.roadtojob2019.brewery.dto.ProductDto; import gmail.roadtojob2019.brewery.entity.Product; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Mappings; @Mapper(componentModel = "spring") public interface ProductMapper { @Mappings({ @Mapping(target = "amount", source = "storage.amount"), }) ProductDto productToProductDto(Product product); }
452
0.761062
0.734513
15
29.133333
20.457653
67
false
false
0
0
0
0
0
0
0.6
false
false
4
487f8299bd000534c72f687182dc021d4370af82
36,962,488,557,842
310035fb0cbf9d263ad1ea5a9565a24728fc1d53
/Database/SingleUserDatabase/xml/AttributeList.java
4abfc4c7012a643d8e698a6f12d5c34fdf786d0d
[]
no_license
jwarrick/JEX
https://github.com/jwarrick/JEX
61709cc2ce46f8f7b769ec6b2e440de3e782b3c6
cf47728007ec927ba7293813fa5252923d62e6e0
refs/heads/master
2020-05-19T11:07:14.102000
2012-06-16T07:20:42
2012-06-16T07:20:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Database.SingleUserDatabase.xml; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import utilities.XMLUtility; public class AttributeList extends Element { private static final long serialVersionUID = 1L; public static final String ELEMENTNAME = "AttList"; public AttributeList(){ super(ELEMENTNAME); } public AttributeList(List<Attribute> listOfAttributes){ this(); for (Attribute att: listOfAttributes){ this.addAtt(att); } } public boolean hasAtt(String name) { Attribute att = this.getAttWithName(name); return att != null; } public void addAtt(Attribute att){ this.addContent(att); } public void removeAtt(Attribute att) { if(att != null) this.removeContent(att); } public void removeAttWithName(String name) { this.removeAtt(this.getAttWithName(name)); } @SuppressWarnings("unchecked") public Attribute getAttWithName(String name){ List<Element> children = this.getChildren(); for (Element elem: children){ Attribute att = (Attribute) elem; if (att.getAttName().equals(name)) return att; } return null; } public String getValueOfAttWithName(String name) { Attribute att = this.getAttWithName(name); if (att == null) return null; return att.getAttValue(); } public List<Attribute> getAttsWithCategory(String catName) { List<Attribute> atts = this.getAtts(); List<Attribute> result = new ArrayList<Attribute>(0); for (Attribute att: atts){ if (att.getAttCategory().equals(catName)) result.add(att); } return result; } @SuppressWarnings("unchecked") public List<Attribute> getAtts() { List<Element> children = this.getChildren(); List<Attribute> result = new ArrayList<Attribute>(0); for (Element child: children){ result.add((Attribute)child); } return result; } public List<String> getAttNames() { List<String> result = new ArrayList<String>(0); List<Attribute> atts = this.getAtts(); for (Attribute att: atts) { result.add(att.getAttName()); } return result; } @Override public String toString() { String result = XMLUtility.toXML(this); return result; } }
UTF-8
Java
2,151
java
AttributeList.java
Java
[]
null
[]
package Database.SingleUserDatabase.xml; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import utilities.XMLUtility; public class AttributeList extends Element { private static final long serialVersionUID = 1L; public static final String ELEMENTNAME = "AttList"; public AttributeList(){ super(ELEMENTNAME); } public AttributeList(List<Attribute> listOfAttributes){ this(); for (Attribute att: listOfAttributes){ this.addAtt(att); } } public boolean hasAtt(String name) { Attribute att = this.getAttWithName(name); return att != null; } public void addAtt(Attribute att){ this.addContent(att); } public void removeAtt(Attribute att) { if(att != null) this.removeContent(att); } public void removeAttWithName(String name) { this.removeAtt(this.getAttWithName(name)); } @SuppressWarnings("unchecked") public Attribute getAttWithName(String name){ List<Element> children = this.getChildren(); for (Element elem: children){ Attribute att = (Attribute) elem; if (att.getAttName().equals(name)) return att; } return null; } public String getValueOfAttWithName(String name) { Attribute att = this.getAttWithName(name); if (att == null) return null; return att.getAttValue(); } public List<Attribute> getAttsWithCategory(String catName) { List<Attribute> atts = this.getAtts(); List<Attribute> result = new ArrayList<Attribute>(0); for (Attribute att: atts){ if (att.getAttCategory().equals(catName)) result.add(att); } return result; } @SuppressWarnings("unchecked") public List<Attribute> getAtts() { List<Element> children = this.getChildren(); List<Attribute> result = new ArrayList<Attribute>(0); for (Element child: children){ result.add((Attribute)child); } return result; } public List<String> getAttNames() { List<String> result = new ArrayList<String>(0); List<Attribute> atts = this.getAtts(); for (Attribute att: atts) { result.add(att.getAttName()); } return result; } @Override public String toString() { String result = XMLUtility.toXML(this); return result; } }
2,151
0.708043
0.706183
102
20.088236
19.038713
61
false
false
0
0
0
0
0
0
1.686275
false
false
4
251a3e4e4be11b1711fe522a9bcb52c35696dfe3
17,506,286,748,741
034e38649f9ddedda09d2d923d3aeedc1673070e
/src/main/java/ru/homyakin/zakupki/models/_223fz/purchase/PurchaseCategoryType.java
188a4197df9f0137f3d8e554cacf002fb560c06c
[ "MIT" ]
permissive
Homyakin/ZakupkiParser
https://github.com/Homyakin/ZakupkiParser
fc375e5771f756b3895f58fa874ab7cfca496476
57d6ef55d4eaf94e67e228b3f61d312b1a793a95
refs/heads/master
2022-12-15T21:48:59.107000
2022-04-24T17:54:20
2022-04-24T17:54:20
181,066,321
17
5
MIT
false
2022-12-06T00:43:32
2019-04-12T18:49:35
2022-10-26T09:37:14
2022-12-06T00:43:31
62,671
16
6
2
Java
false
false
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2022.04.24 at 08:20:08 PM MSK // package ru.homyakin.zakupki.models._223fz.purchase; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for purchaseCategoryType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="purchaseCategoryType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="TOTAL"/> * &lt;enumeration value="NOT_PLACED_310"/> * &lt;enumeration value="NOT_PLACED_320"/> * &lt;enumeration value="NOT_PLACED_220"/> * &lt;enumeration value="TOTAL_220"/> * &lt;enumeration value="ALL_PLACED"/> * &lt;enumeration value="PLACED_CANCELLED"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "purchaseCategoryType") @XmlEnum public enum PurchaseCategoryType { /** * Всего договоров, заключенных заказчиком по результатам закупки товаров, работ, услуг * */ TOTAL, /** * Предмет договора, заключенный по результатам закупок, сведения о которых не подлежат размещению в единой информационной системе в соответствии с частью 15 статьи 4 Федерального закона * */ NOT_PLACED_310, /** * Предмет договора, заключенный по результатам закупок, указанных в пунктах 1 - 3 части 15 статьи 4 Федерального закона в случае принятия заказчиком решения о неразмещении сведений о таких закупках в единой информационной системе * */ NOT_PLACED_320, /** * Предмет договора, заключенный по результатам закупок у единственного поставщика (подрядчика, исполнителя), если в соответствии с положением о закупке сведения о таких закупках не размещаются заказчиком в единой информационной системе сфере закупок * */ NOT_PLACED_220, /** * Предмет договора, заключенный по результатам закупок у единственного поставщика (исполнителя, подрядчика), предусмотренных статьей 3.6 Федерального закона * */ TOTAL_220, /** * Всего договоров, заключенных по результатам закупок, сведения о которых размещены в единой информационной системе * */ ALL_PLACED, /** * Всего договоров, заключенных по результатам конкурентных закупок, признанных несостоявшимися (в связи с тем, что на участие в закупке подана только одна заявка и с участником, подавшим такую заявку заключен договор, а также в связи с чем, что по результатам проведения закупки отклонены все заявки, кроме заявки, поданной участником закупки, с которым заключен договор) * */ PLACED_CANCELLED; public String value() { return name(); } public static PurchaseCategoryType fromValue(String v) { return valueOf(v); } }
UTF-8
Java
4,281
java
PurchaseCategoryType.java
Java
[]
null
[]
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2022.04.24 at 08:20:08 PM MSK // package ru.homyakin.zakupki.models._223fz.purchase; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for purchaseCategoryType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="purchaseCategoryType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="TOTAL"/> * &lt;enumeration value="NOT_PLACED_310"/> * &lt;enumeration value="NOT_PLACED_320"/> * &lt;enumeration value="NOT_PLACED_220"/> * &lt;enumeration value="TOTAL_220"/> * &lt;enumeration value="ALL_PLACED"/> * &lt;enumeration value="PLACED_CANCELLED"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "purchaseCategoryType") @XmlEnum public enum PurchaseCategoryType { /** * Всего договоров, заключенных заказчиком по результатам закупки товаров, работ, услуг * */ TOTAL, /** * Предмет договора, заключенный по результатам закупок, сведения о которых не подлежат размещению в единой информационной системе в соответствии с частью 15 статьи 4 Федерального закона * */ NOT_PLACED_310, /** * Предмет договора, заключенный по результатам закупок, указанных в пунктах 1 - 3 части 15 статьи 4 Федерального закона в случае принятия заказчиком решения о неразмещении сведений о таких закупках в единой информационной системе * */ NOT_PLACED_320, /** * Предмет договора, заключенный по результатам закупок у единственного поставщика (подрядчика, исполнителя), если в соответствии с положением о закупке сведения о таких закупках не размещаются заказчиком в единой информационной системе сфере закупок * */ NOT_PLACED_220, /** * Предмет договора, заключенный по результатам закупок у единственного поставщика (исполнителя, подрядчика), предусмотренных статьей 3.6 Федерального закона * */ TOTAL_220, /** * Всего договоров, заключенных по результатам закупок, сведения о которых размещены в единой информационной системе * */ ALL_PLACED, /** * Всего договоров, заключенных по результатам конкурентных закупок, признанных несостоявшимися (в связи с тем, что на участие в закупке подана только одна заявка и с участником, подавшим такую заявку заключен договор, а также в связи с чем, что по результатам проведения закупки отклонены все заявки, кроме заявки, поданной участником закупки, с которым заключен договор) * */ PLACED_CANCELLED; public String value() { return name(); } public static PurchaseCategoryType fromValue(String v) { return valueOf(v); } }
4,281
0.701698
0.67959
90
33.677776
60.045322
376
false
false
0
0
0
0
0
0
0.533333
false
false
4
466b53679e8f30024a577bf218efaf099960dfff
13,769,665,185,218
13d9bd52c9888b53de7fea4576e48ed6127f9ca3
/oasp4j/jumpthequeue/core/src/main/java/com/cap/jumpthequeue/accesscodemanagement/common/api/AccessCode.java
f8960d66dc55f0d3199ff99cdd77a710f1dbe71b
[ "Apache-2.0" ]
permissive
lperezde/oasp-tutorial-sources
https://github.com/lperezde/oasp-tutorial-sources
a1df83357f79d4de6efd4d8e4d991812a6f5ec76
314225cec3d1e2a5d9bae5e26b5e0ece941d5d43
refs/heads/master
2020-03-21T21:00:32.585000
2018-06-06T11:45:53
2018-06-06T11:45:53
139,041,802
0
0
Apache-2.0
true
2018-06-28T16:13:01
2018-06-28T16:13:01
2018-06-06T11:46:32
2018-06-06T11:46:31
881
0
0
0
null
false
null
package com.cap.jumpthequeue.accesscodemanagement.common.api; import java.sql.Timestamp; import com.cap.jumpthequeue.general.common.api.ApplicationEntity; public interface AccessCode extends ApplicationEntity { public String getCode(); public void setCode(String code); public Timestamp getDateAndTime(); public void setDateAndTime(Timestamp dateAndTime); public Long getVisitorId(); public void setVisitorId(Long visitorId); }
UTF-8
Java
450
java
AccessCode.java
Java
[]
null
[]
package com.cap.jumpthequeue.accesscodemanagement.common.api; import java.sql.Timestamp; import com.cap.jumpthequeue.general.common.api.ApplicationEntity; public interface AccessCode extends ApplicationEntity { public String getCode(); public void setCode(String code); public Timestamp getDateAndTime(); public void setDateAndTime(Timestamp dateAndTime); public Long getVisitorId(); public void setVisitorId(Long visitorId); }
450
0.795556
0.795556
21
20.428572
23.375957
65
false
false
0
0
0
0
0
0
0.428571
false
false
4
a1a44aed7099545fad54c1d1aeac0588b2315bd9
36,859,409,351,603
8ec2cbabd6125ceeb00e0c6192c3ce84477bdde6
/com.nokia.as.cswl/src/com/nsn/ood/cls/core/convert/ActivityDetailStatus2StringConverter.java
6277a10c406a7b0892041d2055bf74045bd9453a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nokia/osgi-microfeatures
https://github.com/nokia/osgi-microfeatures
2cc2b007454ec82212237e012290425114eb55e6
50120f20cf929a966364550ca5829ef348d82670
refs/heads/main
2023-08-28T12:13:52.381000
2021-11-12T20:51:05
2021-11-12T20:51:05
378,852,173
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2015 Nokia Solutions and Networks. All rights reserved. */ package com.nsn.ood.cls.core.convert; import org.apache.felix.dm.annotation.api.Component; import org.apache.felix.dm.annotation.api.Property; import com.nsn.ood.cls.model.internal.ActivityDetail.Status; import com.nsn.ood.cls.util.convert.Converter; /** * Activity detail status <-> DB string * * @author marynows * */ @Component @Property(name = "from", value = "activityDetailStatus") @Property(name = "to", value = "string") public class ActivityDetailStatus2StringConverter implements Converter<Status, String> { @Override public String convertTo(final Status status) { if (status != null) { return status.toString(); } return null; } @Override public Status convertFrom(final String string) { try { return Status.fromValue(string); } catch (final IllegalArgumentException e) { return null; } } }
UTF-8
Java
922
java
ActivityDetailStatus2StringConverter.java
Java
[ { "context": "ctivity detail status <-> DB string\n * \n * @author marynows\n * \n */\n@Component\n@Property(name = \"from\", value", "end": 402, "score": 0.9995464086532593, "start": 394, "tag": "USERNAME", "value": "marynows" } ]
null
[]
/* * Copyright (c) 2015 Nokia Solutions and Networks. All rights reserved. */ package com.nsn.ood.cls.core.convert; import org.apache.felix.dm.annotation.api.Component; import org.apache.felix.dm.annotation.api.Property; import com.nsn.ood.cls.model.internal.ActivityDetail.Status; import com.nsn.ood.cls.util.convert.Converter; /** * Activity detail status <-> DB string * * @author marynows * */ @Component @Property(name = "from", value = "activityDetailStatus") @Property(name = "to", value = "string") public class ActivityDetailStatus2StringConverter implements Converter<Status, String> { @Override public String convertTo(final Status status) { if (status != null) { return status.toString(); } return null; } @Override public Status convertFrom(final String string) { try { return Status.fromValue(string); } catch (final IllegalArgumentException e) { return null; } } }
922
0.724512
0.719089
40
22.049999
23.768623
88
false
false
0
0
0
0
0
0
0.975
false
false
4
9ed599a45fca043b79c278bd095edc6c0320dcf5
592,705,548,041
63c5557a43f1fcd4dbc2100f045eea1add5305e0
/commons/ms-graph-sdk/src/test/java/com/enablix/ms/graph/MSGraphSDKTest.java
0e47c2d9aaa5190544a6a159a4fc7ee15b902aeb
[]
no_license
dikshitluthra/enablix
https://github.com/dikshitluthra/enablix
409758260002d371dac88ad88b73a084e932034d
990e162b66efbc0199c01a84bcc441ca802da15f
refs/heads/master
2018-12-25T22:23:11.120000
2018-12-21T19:39:50
2018-12-21T19:39:50
31,672,399
1
3
null
false
2016-12-14T07:21:02
2015-03-04T18:19:40
2016-10-25T10:37:13
2016-12-11T11:49:00
97,494
0
0
0
Java
null
null
package com.enablix.ms.graph; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.util.FileCopyUtils; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import com.enablix.ms.graph.impl.AppLoginHandler; import com.enablix.ms.graph.impl.FileUploadHandler; import com.enablix.ms.graph.impl.MSGraphSDKImpl; public class MSGraphSDKTest { public static void main(String[] args) throws MSGraphException, IOException { String clientId = "d9587371-5577-4815-8be0-a945cee3ce11"; String clientSecret = "qufzFLISX30%ogoKE734[%$"; String orgId = "enablix.onmicrosoft.com"; String driveOwnerId = "admin@enablix.onmicrosoft.com"; try { RestTemplate restTemplate = new RestTemplate(); MSGraphSDK sdk = MSGraphSDKImpl.create(AppLoginHandler.create(restTemplate), restTemplate, FileUploadHandler.create(restTemplate)); MSGraphSession session = sdk.loginAsApp(clientId, clientSecret, orgId, driveOwnerId); /** Post file **/ /* String filePath = "C:\\Users\\dluthra\\Downloads\\Brief.pdf"; File file = new File(filePath); FileInputStream fis = new FileInputStream(file); String uploadPath = "Enablix/Case Studies"; String filename = "Brief.pdf"; OneDriveFile uploadFile = sdk.uploadFile(session, uploadPath, filename, fis, file.length()); System.out.println(uploadFile); */ /** Post file **/ /** Delete file **/ /* String fileId = "01GP3KYYVAINUPX2FHKZBL45IWTZPXHSUC"; sdk.deleteFile(session, fileId); */ /** Delete file end **/ /** Move file **/ /* String fileItemId = "01GP3KYYSBA32PL5E6OVBJ2GLT223CML7Q"; String moveToFileLocation = "Enablix/Test5"; String filename = "Brief.pdf"; OneDriveFolder destFolder = sdk.moveFile(session, fileItemId, moveToFileLocation, filename); System.out.println(destFolder); */ /** Move file end **/ /** Download file **/ File destFile = new File("D:\\enablix\\onedrive\\abc.pdf"); if (destFile.exists()) { destFile.delete(); } destFile.createNewFile(); String fileItemId = "01GP3KYYSBA32PL5E6OVBJ2GLT223CML7Q"; InputStream filestream = sdk.getFileStreamById(session, fileItemId); FileOutputStream fos = new FileOutputStream(destFile); FileCopyUtils.copy(filestream, fos); filestream.close(); fos.close(); /** Download file end **/ } catch (HttpClientErrorException ce) { ce.printStackTrace(); } } }
UTF-8
Java
2,572
java
MSGraphSDKTest.java
Java
[ { "context": "hException, IOException {\n\t\t\n\t\tString clientId = \"d9587371-5577-4815-8be0-a945cee3ce11\";\n\t\tString clientSecret = \"qufzFLISX30%ogoKE734[%", "end": 628, "score": 0.9612292051315308, "start": 592, "tag": "KEY", "value": "d9587371-5577-4815-8be0-a945cee3ce11" }, { "context": "4815-8be0-a945cee3ce11\";\n\t\tString clientSecret = \"qufzFLISX30%ogoKE734[%$\";\n\t\tString orgId = \"enablix.onmicrosoft.com\";\n\t\tS", "end": 679, "score": 0.9992130994796753, "start": 656, "tag": "KEY", "value": "qufzFLISX30%ogoKE734[%$" }, { "context": "nablix.onmicrosoft.com\";\n\t\tString driveOwnerId = \"admin@enablix.onmicrosoft.com\";\n\t\t\n\t\ttry {\n\t\t\t\n\t\t\tRestTemplate restTemplate = n", "end": 780, "score": 0.999904453754425, "start": 751, "tag": "EMAIL", "value": "admin@enablix.onmicrosoft.com" }, { "context": "t file **/\n\t\t\t/*\n\t\t\tString filePath = \"C:\\\\Users\\\\dluthra\\\\Downloads\\\\Brief.pdf\";\n\t\t\tFile file = new File(f", "end": 1148, "score": 0.9497246742248535, "start": 1141, "tag": "USERNAME", "value": "dluthra" } ]
null
[]
package com.enablix.ms.graph; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.util.FileCopyUtils; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import com.enablix.ms.graph.impl.AppLoginHandler; import com.enablix.ms.graph.impl.FileUploadHandler; import com.enablix.ms.graph.impl.MSGraphSDKImpl; public class MSGraphSDKTest { public static void main(String[] args) throws MSGraphException, IOException { String clientId = "d9587371-5577-4815-8be0-a945cee3ce11"; String clientSecret = "<KEY>"; String orgId = "enablix.onmicrosoft.com"; String driveOwnerId = "<EMAIL>"; try { RestTemplate restTemplate = new RestTemplate(); MSGraphSDK sdk = MSGraphSDKImpl.create(AppLoginHandler.create(restTemplate), restTemplate, FileUploadHandler.create(restTemplate)); MSGraphSession session = sdk.loginAsApp(clientId, clientSecret, orgId, driveOwnerId); /** Post file **/ /* String filePath = "C:\\Users\\dluthra\\Downloads\\Brief.pdf"; File file = new File(filePath); FileInputStream fis = new FileInputStream(file); String uploadPath = "Enablix/Case Studies"; String filename = "Brief.pdf"; OneDriveFile uploadFile = sdk.uploadFile(session, uploadPath, filename, fis, file.length()); System.out.println(uploadFile); */ /** Post file **/ /** Delete file **/ /* String fileId = "01GP3KYYVAINUPX2FHKZBL45IWTZPXHSUC"; sdk.deleteFile(session, fileId); */ /** Delete file end **/ /** Move file **/ /* String fileItemId = "01GP3KYYSBA32PL5E6OVBJ2GLT223CML7Q"; String moveToFileLocation = "Enablix/Test5"; String filename = "Brief.pdf"; OneDriveFolder destFolder = sdk.moveFile(session, fileItemId, moveToFileLocation, filename); System.out.println(destFolder); */ /** Move file end **/ /** Download file **/ File destFile = new File("D:\\enablix\\onedrive\\abc.pdf"); if (destFile.exists()) { destFile.delete(); } destFile.createNewFile(); String fileItemId = "01GP3KYYSBA32PL5E6OVBJ2GLT223CML7Q"; InputStream filestream = sdk.getFileStreamById(session, fileItemId); FileOutputStream fos = new FileOutputStream(destFile); FileCopyUtils.copy(filestream, fos); filestream.close(); fos.close(); /** Download file end **/ } catch (HttpClientErrorException ce) { ce.printStackTrace(); } } }
2,532
0.713453
0.690513
85
29.258823
27.152794
134
false
false
0
0
0
0
0
0
2.870588
false
false
4
42bd935a809acf8d27de124b5f5af5172db2efbd
25,726,854,166,902
ddcfe142b6828914ccbf6f50d2cd2e1124af19ab
/app/src/main/java/com/vds/final_project_music_player/Widget/MusicVisualizer.java
5fdfc47d11dfbdf8ad24f4c4b54003ac896db10c
[]
no_license
vdsperera/Final_Project_Music_Player_Test
https://github.com/vdsperera/Final_Project_Music_Player_Test
760ec07d6401cece03cb2e3bf15450594732d7d6
3b6fc872b1f53e7836a70ef21559d24348b9532d
refs/heads/master
2020-03-09T02:07:14.812000
2018-04-08T16:20:27
2018-04-08T16:20:27
128,532,777
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vds.final_project_music_player.Widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import java.util.Random; /** * Created by Vidumini on 2/20/2018. */ public class MusicVisualizer extends View { Random random = new Random(); Paint paint = new Paint(); private Runnable animateView = new Runnable() { @Override public void run() { postDelayed(this,120); invalidate(); } }; public MusicVisualizer(Context context) { super(context); new MusicVisualizer(context, null); } public MusicVisualizer(Context context, @Nullable AttributeSet attrs) { super(context, attrs); removeCallbacks(animateView); post(animateView); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setStyle(Paint.Style.FILL); canvas.drawRect(getDemensionInPixel(0), getHeight() - (40 + random.nextInt((int)(getHeight() / 1.5f) -25)), getDemensionInPixel(7),getHeight() - 15, paint); canvas.drawRect(getDemensionInPixel(10), getHeight() - (40 + random.nextInt((int)(getHeight() / 1.5f) -25)), getDemensionInPixel(17),getHeight() - 15, paint); canvas.drawRect(getDemensionInPixel(20), getHeight() - (40 + random.nextInt((int)(getHeight() / 1.5f) -25)), getDemensionInPixel(27),getHeight() - 15, paint); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if(visibility == VISIBLE){ removeCallbacks(animateView); post(animateView); } else if(visibility == GONE){ removeCallbacks(animateView); } } public void setColor(int color){ paint.setColor(color); invalidate(); } private int getDemensionInPixel(int dp){ return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics()); } }
UTF-8
Java
2,187
java
MusicVisualizer.java
Java
[ { "context": "View;\n\nimport java.util.Random;\n\n/**\n * Created by Vidumini on 2/20/2018.\n */\n\npublic class MusicVisualizer e", "end": 336, "score": 0.8823068141937256, "start": 328, "tag": "NAME", "value": "Vidumini" } ]
null
[]
package com.vds.final_project_music_player.Widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import java.util.Random; /** * Created by Vidumini on 2/20/2018. */ public class MusicVisualizer extends View { Random random = new Random(); Paint paint = new Paint(); private Runnable animateView = new Runnable() { @Override public void run() { postDelayed(this,120); invalidate(); } }; public MusicVisualizer(Context context) { super(context); new MusicVisualizer(context, null); } public MusicVisualizer(Context context, @Nullable AttributeSet attrs) { super(context, attrs); removeCallbacks(animateView); post(animateView); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setStyle(Paint.Style.FILL); canvas.drawRect(getDemensionInPixel(0), getHeight() - (40 + random.nextInt((int)(getHeight() / 1.5f) -25)), getDemensionInPixel(7),getHeight() - 15, paint); canvas.drawRect(getDemensionInPixel(10), getHeight() - (40 + random.nextInt((int)(getHeight() / 1.5f) -25)), getDemensionInPixel(17),getHeight() - 15, paint); canvas.drawRect(getDemensionInPixel(20), getHeight() - (40 + random.nextInt((int)(getHeight() / 1.5f) -25)), getDemensionInPixel(27),getHeight() - 15, paint); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if(visibility == VISIBLE){ removeCallbacks(animateView); post(animateView); } else if(visibility == GONE){ removeCallbacks(animateView); } } public void setColor(int color){ paint.setColor(color); invalidate(); } private int getDemensionInPixel(int dp){ return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics()); } }
2,187
0.658436
0.638317
68
31.161764
35.5704
166
false
false
0
0
0
0
0
0
0.720588
false
false
4
3d9eea8b46c2913cf37a1a07d6b90bc030f8da43
35,785,667,531,880
131d39b9cec5a5bc47629f0f2b036e5792d9afaf
/src/main/java/com/wakabatimes/simplewiki/view/system/SystemController.java
ea177cc0364d2cd572f02c620e70de9d8394a898
[]
no_license
tachikawaYutaka/simple-wiki
https://github.com/tachikawaYutaka/simple-wiki
bbc185e3527bde388643d7449a9025cbccda7e67
a8ed7791955bab80b3de4d1520ebb89b8ac8773e
refs/heads/master
2020-04-07T19:40:54.494000
2019-10-04T15:42:25
2019-10-04T15:42:25
158,657,966
0
0
null
false
2019-10-04T15:42:27
2018-11-22T07:18:31
2019-02-18T13:05:21
2019-10-04T15:42:26
2,393
0
0
0
Java
false
false
package com.wakabatimes.simplewiki.view.system; import com.wakabatimes.simplewiki.app.domain.model.original_html.OriginalHtml; import com.wakabatimes.simplewiki.app.domain.model.original_html.OriginalHtmlBody; import com.wakabatimes.simplewiki.app.domain.model.original_html.OriginalHtmlFactory; import com.wakabatimes.simplewiki.app.domain.model.original_style.OriginalStyle; import com.wakabatimes.simplewiki.app.domain.model.original_style.OriginalStyleBody; import com.wakabatimes.simplewiki.app.domain.model.original_style.OriginalStyleFactory; import com.wakabatimes.simplewiki.app.domain.model.system.System; import com.wakabatimes.simplewiki.app.domain.model.system.SystemName; import com.wakabatimes.simplewiki.app.domain.model.user.User; import com.wakabatimes.simplewiki.app.domain.model.user.UserName; import com.wakabatimes.simplewiki.app.domain.model.user.Users; import com.wakabatimes.simplewiki.app.domain.service.original_html.OriginalHtmlService; import com.wakabatimes.simplewiki.app.domain.service.original_style.OriginalStyleService; import com.wakabatimes.simplewiki.app.domain.service.system.SystemService; import com.wakabatimes.simplewiki.app.domain.service.user.UserService; import com.wakabatimes.simplewiki.app.infrastructure.original_html.dto.OriginalHtmlDto; import com.wakabatimes.simplewiki.app.infrastructure.original_style.dto.OriginalStyleDto; import com.wakabatimes.simplewiki.app.interfaces.original_html.dto.OriginalHtmlResponseDto; import com.wakabatimes.simplewiki.app.interfaces.original_html.form.OriginalHtmlUpdateForm; import com.wakabatimes.simplewiki.app.interfaces.original_style.dto.OriginalStyleResponseDto; import com.wakabatimes.simplewiki.app.interfaces.original_style.form.OriginalStyleUpdateForm; import com.wakabatimes.simplewiki.app.interfaces.system.dto.SystemResponseDto; import com.wakabatimes.simplewiki.app.interfaces.system.form.SystemNameUpdateForm; import com.wakabatimes.simplewiki.app.interfaces.user.dto.UserResponseDto; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.security.Principal; import java.util.ArrayList; import java.util.List; @Slf4j @Controller public class SystemController { @Autowired private UserService userService; @Autowired private SystemService systemService; @Autowired private OriginalStyleService originalStyleService; @Autowired private OriginalHtmlService originalHtmlService; @GetMapping("/system/name") public String systemName(Model model, Principal principal){ Authentication auth = (Authentication)principal; String name = auth.getName(); UserName userName = new UserName(name); User user = userService.get(userName); UserResponseDto userResponseDto = new UserResponseDto(user); model.addAttribute("userInfo",userResponseDto); model.addAttribute("user",true); System system = systemService.get(); SystemResponseDto systemResponseDto = new SystemResponseDto(system); model.addAttribute("system",systemResponseDto); if(originalHtmlService.exist()){ OriginalHtmlDto originalHtmlDto = new OriginalHtmlDto(originalHtmlService.get()); model.addAttribute("originalHtml",originalHtmlDto); } if(originalStyleService.exist()){ OriginalStyleDto originalStyleDto = new OriginalStyleDto(originalStyleService.get()); model.addAttribute("originalStyle",originalStyleDto); } return "system/system_name"; } @PostMapping("/system/name") public String systemNameUpdate(@ModelAttribute SystemNameUpdateForm form, RedirectAttributes attr, Model model){ try { SystemName systemName = new SystemName(form.getSystemName()); System system = systemService.get(); System update = new System(system.getSystemId(),systemName); systemService.update(update); } catch(RuntimeException e) { log.error("error: ", e); attr.addFlashAttribute("error",true); attr.addFlashAttribute("errorMessage",e.getMessage()); return "redirect:/system/name"; } attr.addFlashAttribute("success",true); attr.addFlashAttribute("successMessage","システム名称を更新しました。"); return "redirect:/system/name"; } @GetMapping("/system/style") public String systemStyle(Model model, Principal principal){ Authentication auth = (Authentication)principal; String name = auth.getName(); UserName userName = new UserName(name); User user = userService.get(userName); UserResponseDto userResponseDto = new UserResponseDto(user); model.addAttribute("userInfo",userResponseDto); model.addAttribute("user",true); System system = systemService.get(); SystemResponseDto systemResponseDto = new SystemResponseDto(system); model.addAttribute("system",systemResponseDto); if(originalStyleService.exist()){ OriginalStyle originalStyle = originalStyleService.get(); OriginalStyleResponseDto originalStyleResponseDto = new OriginalStyleResponseDto(originalStyle); model.addAttribute("style",originalStyleResponseDto); } if(originalHtmlService.exist()){ OriginalHtmlDto originalHtmlDto = new OriginalHtmlDto(originalHtmlService.get()); model.addAttribute("originalHtml",originalHtmlDto); } if(originalStyleService.exist()){ OriginalStyleDto originalStyleDto = new OriginalStyleDto(originalStyleService.get()); model.addAttribute("originalStyle",originalStyleDto); } return "system/system_style"; } @PostMapping("/system/style") public String systemStyleUpdate(@ModelAttribute OriginalStyleUpdateForm form, RedirectAttributes attr, Model model){ try { OriginalStyleBody originalStyleBody = new OriginalStyleBody(form.getBody()); if(originalStyleService.exist()){ OriginalStyle originalStyle = originalStyleService.get(); OriginalStyle update = new OriginalStyle(originalStyle.getOriginalStyleId(),originalStyleBody); originalStyleService.update(update); }else { OriginalStyle originalStyle = OriginalStyleFactory.create(originalStyleBody); originalStyleService.save(originalStyle); } } catch(RuntimeException e) { log.error("error: ", e); attr.addFlashAttribute("error",true); attr.addFlashAttribute("errorMessage",e.getMessage()); return "redirect:/system/style"; } attr.addFlashAttribute("success",true); attr.addFlashAttribute("successMessage","スタイル設定を更新しました。"); return "redirect:/system/style"; } @GetMapping("/system/html") public String systemHtml(Model model, Principal principal){ Authentication auth = (Authentication)principal; String name = auth.getName(); UserName userName = new UserName(name); User user = userService.get(userName); UserResponseDto userResponseDto = new UserResponseDto(user); model.addAttribute("userInfo",userResponseDto); model.addAttribute("user",true); System system = systemService.get(); SystemResponseDto systemResponseDto = new SystemResponseDto(system); model.addAttribute("system",systemResponseDto); if(originalHtmlService.exist()){ OriginalHtml originalHtml = originalHtmlService.get(); OriginalHtmlResponseDto originalHtmlResponseDto = new OriginalHtmlResponseDto(originalHtml); model.addAttribute("html",originalHtmlResponseDto); } if(originalHtmlService.exist()){ OriginalHtmlDto originalHtmlDto = new OriginalHtmlDto(originalHtmlService.get()); model.addAttribute("originalHtml",originalHtmlDto); } if(originalStyleService.exist()){ OriginalStyleDto originalStyleDto = new OriginalStyleDto(originalStyleService.get()); model.addAttribute("originalStyle",originalStyleDto); } return "system/system_html"; } @PostMapping("/system/html") public String systemHtmlUpdate(@ModelAttribute OriginalHtmlUpdateForm form, RedirectAttributes attr, Model model){ try { OriginalHtmlBody originalHtmlBody = new OriginalHtmlBody(form.getBody()); if(originalHtmlService.exist()){ OriginalHtml originalHtml = originalHtmlService.get(); OriginalHtml update = new OriginalHtml(originalHtml.getOriginalHtmlId(),originalHtmlBody); originalHtmlService.update(update); }else { OriginalHtml originalHtml = OriginalHtmlFactory.create(originalHtmlBody); originalHtmlService.save(originalHtml); } } catch(RuntimeException e) { log.error("error: ", e); attr.addFlashAttribute("error",true); attr.addFlashAttribute("errorMessage",e.getMessage()); return "redirect:/system/html"; } attr.addFlashAttribute("success",true); attr.addFlashAttribute("successMessage","HTML設定を更新しました。"); return "redirect:/system/html"; } }
UTF-8
Java
9,980
java
SystemController.java
Java
[]
null
[]
package com.wakabatimes.simplewiki.view.system; import com.wakabatimes.simplewiki.app.domain.model.original_html.OriginalHtml; import com.wakabatimes.simplewiki.app.domain.model.original_html.OriginalHtmlBody; import com.wakabatimes.simplewiki.app.domain.model.original_html.OriginalHtmlFactory; import com.wakabatimes.simplewiki.app.domain.model.original_style.OriginalStyle; import com.wakabatimes.simplewiki.app.domain.model.original_style.OriginalStyleBody; import com.wakabatimes.simplewiki.app.domain.model.original_style.OriginalStyleFactory; import com.wakabatimes.simplewiki.app.domain.model.system.System; import com.wakabatimes.simplewiki.app.domain.model.system.SystemName; import com.wakabatimes.simplewiki.app.domain.model.user.User; import com.wakabatimes.simplewiki.app.domain.model.user.UserName; import com.wakabatimes.simplewiki.app.domain.model.user.Users; import com.wakabatimes.simplewiki.app.domain.service.original_html.OriginalHtmlService; import com.wakabatimes.simplewiki.app.domain.service.original_style.OriginalStyleService; import com.wakabatimes.simplewiki.app.domain.service.system.SystemService; import com.wakabatimes.simplewiki.app.domain.service.user.UserService; import com.wakabatimes.simplewiki.app.infrastructure.original_html.dto.OriginalHtmlDto; import com.wakabatimes.simplewiki.app.infrastructure.original_style.dto.OriginalStyleDto; import com.wakabatimes.simplewiki.app.interfaces.original_html.dto.OriginalHtmlResponseDto; import com.wakabatimes.simplewiki.app.interfaces.original_html.form.OriginalHtmlUpdateForm; import com.wakabatimes.simplewiki.app.interfaces.original_style.dto.OriginalStyleResponseDto; import com.wakabatimes.simplewiki.app.interfaces.original_style.form.OriginalStyleUpdateForm; import com.wakabatimes.simplewiki.app.interfaces.system.dto.SystemResponseDto; import com.wakabatimes.simplewiki.app.interfaces.system.form.SystemNameUpdateForm; import com.wakabatimes.simplewiki.app.interfaces.user.dto.UserResponseDto; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.security.Principal; import java.util.ArrayList; import java.util.List; @Slf4j @Controller public class SystemController { @Autowired private UserService userService; @Autowired private SystemService systemService; @Autowired private OriginalStyleService originalStyleService; @Autowired private OriginalHtmlService originalHtmlService; @GetMapping("/system/name") public String systemName(Model model, Principal principal){ Authentication auth = (Authentication)principal; String name = auth.getName(); UserName userName = new UserName(name); User user = userService.get(userName); UserResponseDto userResponseDto = new UserResponseDto(user); model.addAttribute("userInfo",userResponseDto); model.addAttribute("user",true); System system = systemService.get(); SystemResponseDto systemResponseDto = new SystemResponseDto(system); model.addAttribute("system",systemResponseDto); if(originalHtmlService.exist()){ OriginalHtmlDto originalHtmlDto = new OriginalHtmlDto(originalHtmlService.get()); model.addAttribute("originalHtml",originalHtmlDto); } if(originalStyleService.exist()){ OriginalStyleDto originalStyleDto = new OriginalStyleDto(originalStyleService.get()); model.addAttribute("originalStyle",originalStyleDto); } return "system/system_name"; } @PostMapping("/system/name") public String systemNameUpdate(@ModelAttribute SystemNameUpdateForm form, RedirectAttributes attr, Model model){ try { SystemName systemName = new SystemName(form.getSystemName()); System system = systemService.get(); System update = new System(system.getSystemId(),systemName); systemService.update(update); } catch(RuntimeException e) { log.error("error: ", e); attr.addFlashAttribute("error",true); attr.addFlashAttribute("errorMessage",e.getMessage()); return "redirect:/system/name"; } attr.addFlashAttribute("success",true); attr.addFlashAttribute("successMessage","システム名称を更新しました。"); return "redirect:/system/name"; } @GetMapping("/system/style") public String systemStyle(Model model, Principal principal){ Authentication auth = (Authentication)principal; String name = auth.getName(); UserName userName = new UserName(name); User user = userService.get(userName); UserResponseDto userResponseDto = new UserResponseDto(user); model.addAttribute("userInfo",userResponseDto); model.addAttribute("user",true); System system = systemService.get(); SystemResponseDto systemResponseDto = new SystemResponseDto(system); model.addAttribute("system",systemResponseDto); if(originalStyleService.exist()){ OriginalStyle originalStyle = originalStyleService.get(); OriginalStyleResponseDto originalStyleResponseDto = new OriginalStyleResponseDto(originalStyle); model.addAttribute("style",originalStyleResponseDto); } if(originalHtmlService.exist()){ OriginalHtmlDto originalHtmlDto = new OriginalHtmlDto(originalHtmlService.get()); model.addAttribute("originalHtml",originalHtmlDto); } if(originalStyleService.exist()){ OriginalStyleDto originalStyleDto = new OriginalStyleDto(originalStyleService.get()); model.addAttribute("originalStyle",originalStyleDto); } return "system/system_style"; } @PostMapping("/system/style") public String systemStyleUpdate(@ModelAttribute OriginalStyleUpdateForm form, RedirectAttributes attr, Model model){ try { OriginalStyleBody originalStyleBody = new OriginalStyleBody(form.getBody()); if(originalStyleService.exist()){ OriginalStyle originalStyle = originalStyleService.get(); OriginalStyle update = new OriginalStyle(originalStyle.getOriginalStyleId(),originalStyleBody); originalStyleService.update(update); }else { OriginalStyle originalStyle = OriginalStyleFactory.create(originalStyleBody); originalStyleService.save(originalStyle); } } catch(RuntimeException e) { log.error("error: ", e); attr.addFlashAttribute("error",true); attr.addFlashAttribute("errorMessage",e.getMessage()); return "redirect:/system/style"; } attr.addFlashAttribute("success",true); attr.addFlashAttribute("successMessage","スタイル設定を更新しました。"); return "redirect:/system/style"; } @GetMapping("/system/html") public String systemHtml(Model model, Principal principal){ Authentication auth = (Authentication)principal; String name = auth.getName(); UserName userName = new UserName(name); User user = userService.get(userName); UserResponseDto userResponseDto = new UserResponseDto(user); model.addAttribute("userInfo",userResponseDto); model.addAttribute("user",true); System system = systemService.get(); SystemResponseDto systemResponseDto = new SystemResponseDto(system); model.addAttribute("system",systemResponseDto); if(originalHtmlService.exist()){ OriginalHtml originalHtml = originalHtmlService.get(); OriginalHtmlResponseDto originalHtmlResponseDto = new OriginalHtmlResponseDto(originalHtml); model.addAttribute("html",originalHtmlResponseDto); } if(originalHtmlService.exist()){ OriginalHtmlDto originalHtmlDto = new OriginalHtmlDto(originalHtmlService.get()); model.addAttribute("originalHtml",originalHtmlDto); } if(originalStyleService.exist()){ OriginalStyleDto originalStyleDto = new OriginalStyleDto(originalStyleService.get()); model.addAttribute("originalStyle",originalStyleDto); } return "system/system_html"; } @PostMapping("/system/html") public String systemHtmlUpdate(@ModelAttribute OriginalHtmlUpdateForm form, RedirectAttributes attr, Model model){ try { OriginalHtmlBody originalHtmlBody = new OriginalHtmlBody(form.getBody()); if(originalHtmlService.exist()){ OriginalHtml originalHtml = originalHtmlService.get(); OriginalHtml update = new OriginalHtml(originalHtml.getOriginalHtmlId(),originalHtmlBody); originalHtmlService.update(update); }else { OriginalHtml originalHtml = OriginalHtmlFactory.create(originalHtmlBody); originalHtmlService.save(originalHtml); } } catch(RuntimeException e) { log.error("error: ", e); attr.addFlashAttribute("error",true); attr.addFlashAttribute("errorMessage",e.getMessage()); return "redirect:/system/html"; } attr.addFlashAttribute("success",true); attr.addFlashAttribute("successMessage","HTML設定を更新しました。"); return "redirect:/system/html"; } }
9,980
0.719608
0.719305
212
45.71698
30.543119
120
false
false
0
0
0
0
0
0
0.820755
false
false
4
9d6f1ae52b3013df443fcd0d49df5df17da25f3a
11,141,145,232,221
7894bee3ef6e031dc219eb2228b27062a40e5f65
/netty-fakeparser/ServerHandler.java
3d268a4c59c3b5e2d06b9eecdc20dbdf0ae95a8e
[]
no_license
geoffkizer/netperf
https://github.com/geoffkizer/netperf
f7fb1bfe0c1f8288a9665f6371bf0950c6c3cd80
e2527a80eecb5f71968cfac8bb1497faa6664cb7
refs/heads/master
2021-11-27T00:41:21.663000
2021-11-14T07:36:19
2021-11-14T07:36:19
68,159,619
1
4
null
false
2021-11-14T07:36:20
2016-09-14T00:45:26
2021-04-02T17:56:04
2021-11-14T07:36:20
6,843
0
3
1
C#
false
false
//package io.netty.example.discard; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import static java.nio.charset.StandardCharsets.*; import static io.netty.buffer.Unpooled.*; /** * Handles a server-side channel. */ public class ServerHandler extends ChannelInboundHandlerAdapter { // (1) // static final int s_expectedReadSize = 848; static final byte[] s_responseMessage = ( "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n") .getBytes(UTF_8); // int _bytesRead = 0; int requestCount = 0; ByteBuf currentBuf = null; private final boolean parseHttpRequest(ByteBuf buf) { while (true) { int offset = buf.bytesBefore((byte)'\r'); if (offset == -1) { buf.skipBytes(buf.readableBytes()); return false; } buf.skipBytes(offset + 1); if (buf.readableBytes() < 3) { return false; } if ((buf.readByte() == (byte)'\n') && (buf.readByte() == (byte)'\r') && (buf.readByte() == (byte)'\n')) { // buf.discardReadBytes(); return true; } } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2) // (Try to) validate message length ByteBuf buf = (ByteBuf)msg; // System.out.println("Read bytes: " + buf.readableBytes()); if (currentBuf != null) { // Combine with leftovers from previous // System.out.println("Previous bytes: " + currentBuf.readableBytes()); buf = wrappedBuffer(currentBuf, buf); } while (true) { while (requestCount < 16) { if (parseHttpRequest(buf)) { // System.out.println("Parsed one http request, bytes remaining = " + buf.readableBytes()); requestCount++; } else { // need more data if (buf.readableBytes() > 0) { currentBuf = buf; } else { buf.release(); currentBuf = null; } return; } } // Write the response ctx.write(wrappedBuffer(s_responseMessage)); // (1) ctx.flush(); // (2) requestCount = 0; } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4) // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); } }
UTF-8
Java
5,558
java
ServerHandler.java
Java
[]
null
[]
//package io.netty.example.discard; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import static java.nio.charset.StandardCharsets.*; import static io.netty.buffer.Unpooled.*; /** * Handles a server-side channel. */ public class ServerHandler extends ChannelInboundHandlerAdapter { // (1) // static final int s_expectedReadSize = 848; static final byte[] s_responseMessage = ( "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n" + "HTTP/1.1 200 OK\r\nServer: TestServer\r\nDate: Sun, 06 Nov 1994 08:49:37 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nhello world\r\n") .getBytes(UTF_8); // int _bytesRead = 0; int requestCount = 0; ByteBuf currentBuf = null; private final boolean parseHttpRequest(ByteBuf buf) { while (true) { int offset = buf.bytesBefore((byte)'\r'); if (offset == -1) { buf.skipBytes(buf.readableBytes()); return false; } buf.skipBytes(offset + 1); if (buf.readableBytes() < 3) { return false; } if ((buf.readByte() == (byte)'\n') && (buf.readByte() == (byte)'\r') && (buf.readByte() == (byte)'\n')) { // buf.discardReadBytes(); return true; } } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2) // (Try to) validate message length ByteBuf buf = (ByteBuf)msg; // System.out.println("Read bytes: " + buf.readableBytes()); if (currentBuf != null) { // Combine with leftovers from previous // System.out.println("Previous bytes: " + currentBuf.readableBytes()); buf = wrappedBuffer(currentBuf, buf); } while (true) { while (requestCount < 16) { if (parseHttpRequest(buf)) { // System.out.println("Parsed one http request, bytes remaining = " + buf.readableBytes()); requestCount++; } else { // need more data if (buf.readableBytes() > 0) { currentBuf = buf; } else { buf.release(); currentBuf = null; } return; } } // Write the response ctx.write(wrappedBuffer(s_responseMessage)); // (1) ctx.flush(); // (2) requestCount = 0; } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4) // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); } }
5,558
0.570169
0.512235
121
44.933884
51.18008
165
false
false
0
0
0
0
0
0
0.438017
false
false
4
f009a2261cd8b85d7153240d12147ccf8e35a8a6
18,734,647,405,033
5d8a386553a25f0af4ae9e431846d5c103001d21
/src/com/company/GOF23/abstract1/huWeiRouter.java
5cc453529c558627143ffb08986ce9d21d2f6587
[]
no_license
DragonerYan/greenPigHumHumHum
https://github.com/DragonerYan/greenPigHumHumHum
f37e584faf1631121c8c510aa77d4817490c9996
a8805c1f8cdb453f3bd7e093be536bd00303e7db
refs/heads/master
2023-07-15T11:52:17.984000
2021-08-23T13:44:24
2021-08-23T13:44:24
365,897,008
0
0
null
false
2021-08-23T13:44:25
2021-05-10T02:35:13
2021-08-23T13:39:39
2021-08-23T13:44:24
176
0
0
0
Java
false
false
package com.company.gof23.abstract1; public class huWeiRouter implements iRoute{ @Override public void start() { System.out.print("华为路由器开机"); } @Override public void shut() { System.out.print("华为路由器关机"); } }
UTF-8
Java
279
java
huWeiRouter.java
Java
[]
null
[]
package com.company.gof23.abstract1; public class huWeiRouter implements iRoute{ @Override public void start() { System.out.print("华为路由器开机"); } @Override public void shut() { System.out.print("华为路由器关机"); } }
279
0.621514
0.609562
14
16.928572
15.387677
43
false
false
0
0
0
0
0
0
0.214286
false
false
4
61ef7be173772b1b496a96d5bf892d19bdad455c
36,275,293,807,064
941b62c60a9cd4cd4c3533e31b7770ed1b1e046d
/src/com/epam/alexey_shuvalov/java/lesson6/task1/FileUtils.java
c86d4b3f8f2521575bc84ed117129f17fb2c0945
[]
no_license
shuvaloff/learning-java
https://github.com/shuvaloff/learning-java
4e1149eec4cc37df3af61b5d2bd447019b210222
b42346492417c1aa37a3318ec1654fce925cfe3d
refs/heads/master
2020-12-24T15:32:21.993000
2015-05-14T11:48:40
2015-05-14T11:48:40
32,359,054
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.alexey_shuvalov.java.lesson6.task1; import com.epam.alexey_shuvalov.java.lesson6.task1.model.CulinaryVegetable; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; /** * @author Alexey Shuvalov * */ public class FileUtils { public static boolean isFileExist(String filePath) { File file = new File(filePath); return file.isFile() && file.exists(); } public static void serializeObjectsToFile(List<CulinaryVegetable> ingredients, String filePath) { try (ObjectOutput output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filePath)));) { for (CulinaryVegetable ingredient : ingredients) { output.writeObject(ingredient); } output.flush(); } catch (IOException ex) { } } public static List<CulinaryVegetable> deserializeObjectsFromFile(String inputFile) { List<CulinaryVegetable> ingredients = new ArrayList(); try (ObjectInput input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));) { while (true) { try { ingredients.add((CulinaryVegetable) input.readObject()); } catch (EOFException ex) { break; } } return ingredients; } catch (ClassNotFoundException | IOException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } return null; } }
UTF-8
Java
1,952
java
FileUtils.java
Java
[ { "context": "ayList;\r\nimport java.util.List;\r\n\r\n/**\r\n * @author Alexey Shuvalov\r\n *\r\n */\r\npublic class FileUtils {\r\n\r\n public ", "end": 572, "score": 0.9998283386230469, "start": 557, "tag": "NAME", "value": "Alexey Shuvalov" } ]
null
[]
package com.epam.alexey_shuvalov.java.lesson6.task1; import com.epam.alexey_shuvalov.java.lesson6.task1.model.CulinaryVegetable; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; /** * @author <NAME> * */ public class FileUtils { public static boolean isFileExist(String filePath) { File file = new File(filePath); return file.isFile() && file.exists(); } public static void serializeObjectsToFile(List<CulinaryVegetable> ingredients, String filePath) { try (ObjectOutput output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filePath)));) { for (CulinaryVegetable ingredient : ingredients) { output.writeObject(ingredient); } output.flush(); } catch (IOException ex) { } } public static List<CulinaryVegetable> deserializeObjectsFromFile(String inputFile) { List<CulinaryVegetable> ingredients = new ArrayList(); try (ObjectInput input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile)));) { while (true) { try { ingredients.add((CulinaryVegetable) input.readObject()); } catch (EOFException ex) { break; } } return ingredients; } catch (ClassNotFoundException | IOException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } return null; } }
1,943
0.636783
0.634734
58
31.655172
27.773438
117
false
false
0
0
0
0
0
0
0.517241
false
false
4
94f30dce623248a8dd92ff47ed4222bbe39664b4
1,374,389,566,720
b5a182b5e644005359421029aa09d1809c9906b4
/Lesson5/5.4/Map/src/Main.java
35803cb81c9b1f9ccaeff1ec72133ce95ca29afe
[]
no_license
tatianagrubich/mobile
https://github.com/tatianagrubich/mobile
43ff52a5b2b4e05252f370c3440cf67266f68c3b
ce6f117aa1a0f5a3812168425767c31fc0b0328a
refs/heads/main
2023-03-20T08:17:07.808000
2021-03-07T17:15:58
2021-03-07T17:15:58
345,401,816
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; import java.util.TreeMap; public class Main { public static void main (String args[]) { String name = null; String phone = null; TreeMap<String, String> tm = new TreeMap<String, String>(); System.out.println("Телефонная книга"); Scanner scanner = new Scanner(System.in); System.out.println("Введите имя абонента"); name = scanner.nextLine(); //phone = scanner.nextLine(); tm.put(name, phone); for (; ; ) { /*System.out.println("Введите имя абонента"); name = scanner.nextLine(); phone = scanner.nextLine(); tm.put(name, phone);*/ if(name.equals(tm)) { System.out.println("Имя абонента внесено в телефонную книгу. Введите номер телефона абонента"); Scanner scanner1 = new Scanner(System.in); phone = scanner1.nextLine(); tm.put(name, phone); } else { if (phone.equals(tm)) { System.out.println("Номер телефона внесен в телефонную книгу. Введите имя абонента"); Scanner scanner1 = new Scanner(System.in); name = scanner1.nextLine(); tm.put(name, phone); } } /*System.out.println("Введите номер телефона абонента"); phone = scanner.nextLine(); tm.put(name, phone); if (name.equals(tm) && phone == "") { System.out.println("Имя абонента внесено в телефонную книгу. Введите номер телефона абонента"); Scanner scanner1 = new Scanner(System.in); phone = scanner1.nextLine(); tm.put(name, phone); } else { if (phone.equals(tm) && name == null) { System.out.println("Введите имя абонента"); Scanner scanner1 = new Scanner(System.in); name = scanner1.nextLine(); tm.put(name, phone); } }*/ String phoneBook = scanner.nextLine(); if (phoneBook.contains("LIST")) { for (String key : tm.keySet()) { System.out.println(key); } continue; } } } }
UTF-8
Java
2,655
java
Main.java
Java
[]
null
[]
import java.util.Scanner; import java.util.TreeMap; public class Main { public static void main (String args[]) { String name = null; String phone = null; TreeMap<String, String> tm = new TreeMap<String, String>(); System.out.println("Телефонная книга"); Scanner scanner = new Scanner(System.in); System.out.println("Введите имя абонента"); name = scanner.nextLine(); //phone = scanner.nextLine(); tm.put(name, phone); for (; ; ) { /*System.out.println("Введите имя абонента"); name = scanner.nextLine(); phone = scanner.nextLine(); tm.put(name, phone);*/ if(name.equals(tm)) { System.out.println("Имя абонента внесено в телефонную книгу. Введите номер телефона абонента"); Scanner scanner1 = new Scanner(System.in); phone = scanner1.nextLine(); tm.put(name, phone); } else { if (phone.equals(tm)) { System.out.println("Номер телефона внесен в телефонную книгу. Введите имя абонента"); Scanner scanner1 = new Scanner(System.in); name = scanner1.nextLine(); tm.put(name, phone); } } /*System.out.println("Введите номер телефона абонента"); phone = scanner.nextLine(); tm.put(name, phone); if (name.equals(tm) && phone == "") { System.out.println("Имя абонента внесено в телефонную книгу. Введите номер телефона абонента"); Scanner scanner1 = new Scanner(System.in); phone = scanner1.nextLine(); tm.put(name, phone); } else { if (phone.equals(tm) && name == null) { System.out.println("Введите имя абонента"); Scanner scanner1 = new Scanner(System.in); name = scanner1.nextLine(); tm.put(name, phone); } }*/ String phoneBook = scanner.nextLine(); if (phoneBook.contains("LIST")) { for (String key : tm.keySet()) { System.out.println(key); } continue; } } } }
2,655
0.49769
0.49433
73
31.589041
25.771299
111
false
false
0
0
0
0
0
0
0.657534
false
false
4
bd90d48c7f8fd7c57cc4d4fe1d372aa941d7e346
8,813,272,924,136
9eb9df8c9dd7c1763681c2e9e6c4fe43dc46ba42
/app/src/main/java/com/example/trafficofcity/functions/main/view/entity/MainActivity.java
7b336e5f9e45662c69823fd744c5acaaa4d83a9c
[]
no_license
wuyr/TrafficOfCity
https://github.com/wuyr/TrafficOfCity
909df087b79572e09c2ddd800744759cc5c61e26
8577f94f5f398c03ea696c757f1ce422946231a2
refs/heads/master
2016-12-13T07:05:33.587000
2016-05-02T09:54:01
2016-05-02T09:54:01
49,580,140
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.trafficofcity.functions.main.view.entity; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Looper; import android.os.PersistableBundle; import android.provider.MediaStore; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.trafficofcity.R; import com.example.trafficofcity.custom.CustomActionBarDrawerToggle; import com.example.trafficofcity.custom.MySnackbar; import com.example.trafficofcity.functions.discover.view.entity.DiscoverFragment; import com.example.trafficofcity.functions.issue.view.entity.IssueFragment; import com.example.trafficofcity.functions.login_register.view.entity.LoginActivity; import com.example.trafficofcity.functions.main.presenter.IMainPresenter; import com.example.trafficofcity.functions.main.presenter.entity.MainPresenter; import com.example.trafficofcity.functions.main.view.IMainView; import com.example.trafficofcity.functions.mission.MissionFragment; import com.example.trafficofcity.functions.submit.view.entity.SubmitFragment; import com.example.trafficofcity.utils.HttpUtils; import com.example.trafficofcity.utils.RequestStringCollections; import java.io.File; /** * Created by wuyr on 1/4/16 11:02 PM. */ @SuppressLint("RtlHardcoded") public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IMainView { public final int CHOOSE_FROM_GALLERY = 1, CHOOSE_FROM_CAMERA = 2; public static final String SHARED_PREFERENCES_NAME = "AccountInfo"; private final String FRAGMENT_DISCOVER = "Discover", FRAGMENT_ISSUE = "Issue", FRAGMENT_MISSION = "Mission", FRAGMENT_SUBMIT = "Submit"; private String SHOWING_FRAGMENT_TAG; private final int LOGIN = 0; private ImageView mHeader; private TextView mNickname; private CoordinatorLayout mCoordinatorLayout; private DrawerLayout mDrawerLayout; private NavigationView mNavigationView; private SharedPreferences mPreferences; private MenuItem mClear; private boolean isLogged; private static boolean isAdminLogged, isWorkerLogged; private IMainPresenter mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_view); mPresenter = new MainPresenter(this); initViews(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case LOGIN: if (resultCode == RESULT_OK) { mHeader.setImageResource(data.getIntExtra( RequestStringCollections.HEADER_RES, mPresenter.getRandomHeaderRes())); mNickname.setText(data.getStringExtra(RequestStringCollections.NICKNAME)); mDrawerLayout.openDrawer(Gravity.RIGHT); isLogged = true; //帐号是888则认定是工人登录 666则管理员登录 (下同) isWorkerLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 888; isAdminLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 666; syncLoggedStatus(); } else { if (mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) != 0) { mHeader.setImageResource(mPreferences.getInt(RequestStringCollections.HEADER_RES, 0)); mNickname.setText(mPreferences.getString(RequestStringCollections.NICKNAME, "")); isWorkerLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 888; isAdminLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 666; syncLoggedStatus(); isLogged = true; } else { mHeader.setImageResource(mPresenter.getRandomHeaderRes()); mNickname.setText(R.string.not_logged); isLogged = false; } } ((DiscoverFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_DISCOVER)).refreshData(); break; //发表时从相册选择图片 case CHOOSE_FROM_GALLERY: if (resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); IssueFragment fragment = ((IssueFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_ISSUE)); fragment.mOnclickImage.setImageBitmap(BitmapFactory .decodeFile(picturePath)); if (fragment.mOnclickImage == fragment.mImage) fragment.isImage1Select = true; else fragment.isImage2Select = true; } break; //即时照相 case CHOOSE_FROM_CAMERA: File imageFile = new File(Environment.getExternalStorageDirectory() .getPath() + "/DCIM/Camera/temp.jpg"); if (imageFile.exists()) { BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = 8; int degree = mPresenter.readPictureDegree(imageFile.getAbsolutePath()); Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath(), bitmapOptions); bitmap = mPresenter.rotatingImageView(degree, bitmap); IssueFragment fragment = ((IssueFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_ISSUE)); fragment.mOnclickImage.setImageBitmap(bitmap); if (fragment.mOnclickImage == fragment.mImage) fragment.isImage1Select = true; else fragment.isImage2Select = true; } break; default: } } private void initViews() { mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mNavigationView = (NavigationView) findViewById(R.id.navigation_view); mNavigationView.setNavigationItemSelectedListener(this); //点击用户头像时 mNavigationView.getHeaderView(0).findViewById(R.id.login). setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //已登录则显示切换用户和更改密码对话框 未登录直接跳转到登陆界面 if (isLogged) { new AlertDialog.Builder(MainActivity.this).setItems( new String[]{MainActivity.this.getString(R.string.change_user), MainActivity.this.getString(R.string.change_password)}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: //选择切换帐号则跳转 startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN); break; case 1: //选择更改密码则要求输入新密码然后将数据同步至服务器,更改成功将跳转到登录界面要求重新登录 final EditText editText = new EditText(MainActivity.this); new AlertDialog.Builder(MainActivity.this).setTitle(R.string.input_new_pw) .setView(editText).setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!editText.getText().toString().isEmpty()) { final ProgressDialog pd = new ProgressDialog(MainActivity.this); pd.setMessage(getString(R.string.changing_password)); pd.show(); new Thread() { @Override public void run() { Looper.prepare(); if (HttpUtils.changePassword(getCurrentAccount(), editText.getText().toString())) { Toast.makeText(MainActivity.this, R.string.change_password_success, Toast.LENGTH_LONG).show(); startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN); } else Toast.makeText(MainActivity.this, R.string.change_password_failed, Toast.LENGTH_LONG).show(); pd.dismiss(); Looper.loop(); } }.start(); } else //登录失败提示 Toast.makeText(MainActivity.this, R.string.invalid_password, Toast.LENGTH_LONG).show(); } }).show(); default: } } }).show(); } else startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN); } }); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); CustomActionBarDrawerToggle toggle = new CustomActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close); mDrawerLayout.setDrawerListener(toggle); toggle.syncState(); mHeader = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.header); mHeader.setImageResource(mPresenter.getRandomHeaderRes()); mNickname = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.account_name); initPreferences(); initFragments(); } private void initPreferences() { mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE); if (mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) != 0) { mHeader.setImageResource(mPreferences.getInt(RequestStringCollections.HEADER_RES, 0)); mNickname.setText(mPreferences.getString(RequestStringCollections.NICKNAME, "")); isLogged = true; isWorkerLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 888; isAdminLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 666; return; } isLogged = false; } private void initFragments() { int containerViewId = R.id.wait_replace; Fragment discoverFragment = new DiscoverFragment(), issueFragment = new IssueFragment(); getSupportFragmentManager().beginTransaction(). add(containerViewId, discoverFragment, FRAGMENT_DISCOVER). add(containerViewId, issueFragment, FRAGMENT_ISSUE). hide(issueFragment).commitAllowingStateLoss(); //工人登录则显示全部功能(除了删除项目) if (isWorkerLogged) { Fragment missionFragment = new MissionFragment(), submitFragment = new SubmitFragment(); getSupportFragmentManager().beginTransaction(). add(containerViewId, missionFragment, FRAGMENT_MISSION). hide(missionFragment). add(containerViewId, submitFragment, FRAGMENT_SUBMIT). hide(submitFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(true); //管理员登录则屏蔽提交任务功能(能删除用户发表项目) } else if (isAdminLogged) { Fragment missionFragment = new MissionFragment(); getSupportFragmentManager().beginTransaction(). add(containerViewId, missionFragment, FRAGMENT_MISSION). hide(missionFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); //普通用户只有查看列表和发布功能 } else { mNavigationView.getMenu().findItem(R.id.mission).setVisible(false); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); } SHOWING_FRAGMENT_TAG = FRAGMENT_DISCOVER; } public void showDiscoverFragment() { showFragment(FRAGMENT_DISCOVER); ((DiscoverFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_DISCOVER)).refreshData(); MySnackbar.show(mCoordinatorLayout, getString(R.string.commit_success), Snackbar.LENGTH_SHORT); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); hideClearMenu(); } public boolean isLogged() { if (!isLogged) { new AlertDialog.Builder(this). setMessage(getString(R.string.currently_not_logged)). setNegativeButton(R.string.no, null). setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult( new Intent(MainActivity.this, LoginActivity.class), LOGIN); } }).show(); } return isLogged; } //同步帐号功能 同上 public void syncLoggedStatus() { if (isWorkerLogged) { Fragment missionFragment = new MissionFragment(), submitFragment = new SubmitFragment(); getSupportFragmentManager().beginTransaction(). add(R.id.wait_replace, missionFragment, FRAGMENT_MISSION). hide(missionFragment). add(R.id.wait_replace, submitFragment, FRAGMENT_SUBMIT). hide(submitFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(true); showFragment(FRAGMENT_DISCOVER); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); } else if (isAdminLogged) { Fragment missionFragment = new MissionFragment(); getSupportFragmentManager().beginTransaction(). add(R.id.wait_replace, missionFragment, FRAGMENT_MISSION). hide(missionFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); showFragment(FRAGMENT_DISCOVER); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); } else { mNavigationView.getMenu().findItem(R.id.mission).setVisible(false); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); showFragment(FRAGMENT_DISCOVER); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); } } private int getCurrentAccount() { return mPreferences.getInt(RequestStringCollections.ACCOUNT, 0); } public String getHeaderRes() { return String.valueOf(mPreferences.getInt(RequestStringCollections.HEADER_RES, 0)); } public String getNickname() { return mNickname.getText().toString(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.clear: ((IssueFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_ISSUE)). clearInputData(); break; default: break; } return true; } private void showClearMenu() { if (mClear != null && !mClear.isVisible()) mClear.setVisible(true); } private void hideClearMenu() { if (mClear != null && mClear.isVisible()) mClear.setVisible(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); mClear = menu.getItem(0); mClear.setVisible(false); return true; } @Override public boolean onNavigationItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.discover: showFragment(FRAGMENT_DISCOVER); hideClearMenu(); break; case R.id.issue: showFragment(FRAGMENT_ISSUE); showClearMenu(); break; case R.id.mission: showFragment(FRAGMENT_MISSION); ((MissionFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_MISSION)).refreshData(); hideClearMenu(); break; case R.id.submit: showFragment(FRAGMENT_SUBMIT); hideClearMenu(); break; default: } mDrawerLayout.closeDrawer(Gravity.RIGHT); return true; } private void showFragment(String tag) { FragmentManager manager = getSupportFragmentManager(); if (SHOWING_FRAGMENT_TAG != tag) { manager.beginTransaction().hide(manager.findFragmentByTag( SHOWING_FRAGMENT_TAG)).show(manager.findFragmentByTag( tag)).commitAllowingStateLoss(); SHOWING_FRAGMENT_TAG = tag; } } //上次按下返回键的时间 private long mLastTime; @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) mDrawerLayout.closeDrawer(Gravity.RIGHT); else { if ((System.currentTimeMillis() - mLastTime) < 2000) finish(); mLastTime = System.currentTimeMillis(); MySnackbar.show(mCoordinatorLayout, getString(R.string.press_back_exit), Snackbar.LENGTH_SHORT); } } public static boolean isWorkerLogged() { return isWorkerLogged; } public static boolean isAdminLogged() { return isAdminLogged; } @Override protected void onSaveInstanceState(Bundle outState) { } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { } }
UTF-8
Java
22,267
java
MainActivity.java
Java
[ { "context": "lections;\n\nimport java.io.File;\n\n/**\n * Created by wuyr on 1/4/16 11:02 PM.\n */\n@SuppressLint(\"RtlHardcod", "end": 2120, "score": 0.9995128512382507, "start": 2116, "tag": "USERNAME", "value": "wuyr" } ]
null
[]
package com.example.trafficofcity.functions.main.view.entity; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Looper; import android.os.PersistableBundle; import android.provider.MediaStore; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.trafficofcity.R; import com.example.trafficofcity.custom.CustomActionBarDrawerToggle; import com.example.trafficofcity.custom.MySnackbar; import com.example.trafficofcity.functions.discover.view.entity.DiscoverFragment; import com.example.trafficofcity.functions.issue.view.entity.IssueFragment; import com.example.trafficofcity.functions.login_register.view.entity.LoginActivity; import com.example.trafficofcity.functions.main.presenter.IMainPresenter; import com.example.trafficofcity.functions.main.presenter.entity.MainPresenter; import com.example.trafficofcity.functions.main.view.IMainView; import com.example.trafficofcity.functions.mission.MissionFragment; import com.example.trafficofcity.functions.submit.view.entity.SubmitFragment; import com.example.trafficofcity.utils.HttpUtils; import com.example.trafficofcity.utils.RequestStringCollections; import java.io.File; /** * Created by wuyr on 1/4/16 11:02 PM. */ @SuppressLint("RtlHardcoded") public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IMainView { public final int CHOOSE_FROM_GALLERY = 1, CHOOSE_FROM_CAMERA = 2; public static final String SHARED_PREFERENCES_NAME = "AccountInfo"; private final String FRAGMENT_DISCOVER = "Discover", FRAGMENT_ISSUE = "Issue", FRAGMENT_MISSION = "Mission", FRAGMENT_SUBMIT = "Submit"; private String SHOWING_FRAGMENT_TAG; private final int LOGIN = 0; private ImageView mHeader; private TextView mNickname; private CoordinatorLayout mCoordinatorLayout; private DrawerLayout mDrawerLayout; private NavigationView mNavigationView; private SharedPreferences mPreferences; private MenuItem mClear; private boolean isLogged; private static boolean isAdminLogged, isWorkerLogged; private IMainPresenter mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_view); mPresenter = new MainPresenter(this); initViews(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case LOGIN: if (resultCode == RESULT_OK) { mHeader.setImageResource(data.getIntExtra( RequestStringCollections.HEADER_RES, mPresenter.getRandomHeaderRes())); mNickname.setText(data.getStringExtra(RequestStringCollections.NICKNAME)); mDrawerLayout.openDrawer(Gravity.RIGHT); isLogged = true; //帐号是888则认定是工人登录 666则管理员登录 (下同) isWorkerLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 888; isAdminLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 666; syncLoggedStatus(); } else { if (mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) != 0) { mHeader.setImageResource(mPreferences.getInt(RequestStringCollections.HEADER_RES, 0)); mNickname.setText(mPreferences.getString(RequestStringCollections.NICKNAME, "")); isWorkerLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 888; isAdminLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 666; syncLoggedStatus(); isLogged = true; } else { mHeader.setImageResource(mPresenter.getRandomHeaderRes()); mNickname.setText(R.string.not_logged); isLogged = false; } } ((DiscoverFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_DISCOVER)).refreshData(); break; //发表时从相册选择图片 case CHOOSE_FROM_GALLERY: if (resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); IssueFragment fragment = ((IssueFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_ISSUE)); fragment.mOnclickImage.setImageBitmap(BitmapFactory .decodeFile(picturePath)); if (fragment.mOnclickImage == fragment.mImage) fragment.isImage1Select = true; else fragment.isImage2Select = true; } break; //即时照相 case CHOOSE_FROM_CAMERA: File imageFile = new File(Environment.getExternalStorageDirectory() .getPath() + "/DCIM/Camera/temp.jpg"); if (imageFile.exists()) { BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = 8; int degree = mPresenter.readPictureDegree(imageFile.getAbsolutePath()); Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath(), bitmapOptions); bitmap = mPresenter.rotatingImageView(degree, bitmap); IssueFragment fragment = ((IssueFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_ISSUE)); fragment.mOnclickImage.setImageBitmap(bitmap); if (fragment.mOnclickImage == fragment.mImage) fragment.isImage1Select = true; else fragment.isImage2Select = true; } break; default: } } private void initViews() { mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mNavigationView = (NavigationView) findViewById(R.id.navigation_view); mNavigationView.setNavigationItemSelectedListener(this); //点击用户头像时 mNavigationView.getHeaderView(0).findViewById(R.id.login). setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //已登录则显示切换用户和更改密码对话框 未登录直接跳转到登陆界面 if (isLogged) { new AlertDialog.Builder(MainActivity.this).setItems( new String[]{MainActivity.this.getString(R.string.change_user), MainActivity.this.getString(R.string.change_password)}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: //选择切换帐号则跳转 startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN); break; case 1: //选择更改密码则要求输入新密码然后将数据同步至服务器,更改成功将跳转到登录界面要求重新登录 final EditText editText = new EditText(MainActivity.this); new AlertDialog.Builder(MainActivity.this).setTitle(R.string.input_new_pw) .setView(editText).setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!editText.getText().toString().isEmpty()) { final ProgressDialog pd = new ProgressDialog(MainActivity.this); pd.setMessage(getString(R.string.changing_password)); pd.show(); new Thread() { @Override public void run() { Looper.prepare(); if (HttpUtils.changePassword(getCurrentAccount(), editText.getText().toString())) { Toast.makeText(MainActivity.this, R.string.change_password_success, Toast.LENGTH_LONG).show(); startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN); } else Toast.makeText(MainActivity.this, R.string.change_password_failed, Toast.LENGTH_LONG).show(); pd.dismiss(); Looper.loop(); } }.start(); } else //登录失败提示 Toast.makeText(MainActivity.this, R.string.invalid_password, Toast.LENGTH_LONG).show(); } }).show(); default: } } }).show(); } else startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN); } }); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); CustomActionBarDrawerToggle toggle = new CustomActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close); mDrawerLayout.setDrawerListener(toggle); toggle.syncState(); mHeader = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.header); mHeader.setImageResource(mPresenter.getRandomHeaderRes()); mNickname = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.account_name); initPreferences(); initFragments(); } private void initPreferences() { mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE); if (mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) != 0) { mHeader.setImageResource(mPreferences.getInt(RequestStringCollections.HEADER_RES, 0)); mNickname.setText(mPreferences.getString(RequestStringCollections.NICKNAME, "")); isLogged = true; isWorkerLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 888; isAdminLogged = mPreferences.getInt(RequestStringCollections.ACCOUNT, 0) == 666; return; } isLogged = false; } private void initFragments() { int containerViewId = R.id.wait_replace; Fragment discoverFragment = new DiscoverFragment(), issueFragment = new IssueFragment(); getSupportFragmentManager().beginTransaction(). add(containerViewId, discoverFragment, FRAGMENT_DISCOVER). add(containerViewId, issueFragment, FRAGMENT_ISSUE). hide(issueFragment).commitAllowingStateLoss(); //工人登录则显示全部功能(除了删除项目) if (isWorkerLogged) { Fragment missionFragment = new MissionFragment(), submitFragment = new SubmitFragment(); getSupportFragmentManager().beginTransaction(). add(containerViewId, missionFragment, FRAGMENT_MISSION). hide(missionFragment). add(containerViewId, submitFragment, FRAGMENT_SUBMIT). hide(submitFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(true); //管理员登录则屏蔽提交任务功能(能删除用户发表项目) } else if (isAdminLogged) { Fragment missionFragment = new MissionFragment(); getSupportFragmentManager().beginTransaction(). add(containerViewId, missionFragment, FRAGMENT_MISSION). hide(missionFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); //普通用户只有查看列表和发布功能 } else { mNavigationView.getMenu().findItem(R.id.mission).setVisible(false); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); } SHOWING_FRAGMENT_TAG = FRAGMENT_DISCOVER; } public void showDiscoverFragment() { showFragment(FRAGMENT_DISCOVER); ((DiscoverFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_DISCOVER)).refreshData(); MySnackbar.show(mCoordinatorLayout, getString(R.string.commit_success), Snackbar.LENGTH_SHORT); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); hideClearMenu(); } public boolean isLogged() { if (!isLogged) { new AlertDialog.Builder(this). setMessage(getString(R.string.currently_not_logged)). setNegativeButton(R.string.no, null). setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult( new Intent(MainActivity.this, LoginActivity.class), LOGIN); } }).show(); } return isLogged; } //同步帐号功能 同上 public void syncLoggedStatus() { if (isWorkerLogged) { Fragment missionFragment = new MissionFragment(), submitFragment = new SubmitFragment(); getSupportFragmentManager().beginTransaction(). add(R.id.wait_replace, missionFragment, FRAGMENT_MISSION). hide(missionFragment). add(R.id.wait_replace, submitFragment, FRAGMENT_SUBMIT). hide(submitFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(true); showFragment(FRAGMENT_DISCOVER); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); } else if (isAdminLogged) { Fragment missionFragment = new MissionFragment(); getSupportFragmentManager().beginTransaction(). add(R.id.wait_replace, missionFragment, FRAGMENT_MISSION). hide(missionFragment).commitAllowingStateLoss(); mNavigationView.getMenu().findItem(R.id.mission).setVisible(true); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); showFragment(FRAGMENT_DISCOVER); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); } else { mNavigationView.getMenu().findItem(R.id.mission).setVisible(false); mNavigationView.getMenu().findItem(R.id.submit).setVisible(false); showFragment(FRAGMENT_DISCOVER); mNavigationView.getMenu().findItem(R.id.discover).setChecked(true); } } private int getCurrentAccount() { return mPreferences.getInt(RequestStringCollections.ACCOUNT, 0); } public String getHeaderRes() { return String.valueOf(mPreferences.getInt(RequestStringCollections.HEADER_RES, 0)); } public String getNickname() { return mNickname.getText().toString(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.clear: ((IssueFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_ISSUE)). clearInputData(); break; default: break; } return true; } private void showClearMenu() { if (mClear != null && !mClear.isVisible()) mClear.setVisible(true); } private void hideClearMenu() { if (mClear != null && mClear.isVisible()) mClear.setVisible(false); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); mClear = menu.getItem(0); mClear.setVisible(false); return true; } @Override public boolean onNavigationItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.discover: showFragment(FRAGMENT_DISCOVER); hideClearMenu(); break; case R.id.issue: showFragment(FRAGMENT_ISSUE); showClearMenu(); break; case R.id.mission: showFragment(FRAGMENT_MISSION); ((MissionFragment) getSupportFragmentManager(). findFragmentByTag(FRAGMENT_MISSION)).refreshData(); hideClearMenu(); break; case R.id.submit: showFragment(FRAGMENT_SUBMIT); hideClearMenu(); break; default: } mDrawerLayout.closeDrawer(Gravity.RIGHT); return true; } private void showFragment(String tag) { FragmentManager manager = getSupportFragmentManager(); if (SHOWING_FRAGMENT_TAG != tag) { manager.beginTransaction().hide(manager.findFragmentByTag( SHOWING_FRAGMENT_TAG)).show(manager.findFragmentByTag( tag)).commitAllowingStateLoss(); SHOWING_FRAGMENT_TAG = tag; } } //上次按下返回键的时间 private long mLastTime; @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) mDrawerLayout.closeDrawer(Gravity.RIGHT); else { if ((System.currentTimeMillis() - mLastTime) < 2000) finish(); mLastTime = System.currentTimeMillis(); MySnackbar.show(mCoordinatorLayout, getString(R.string.press_back_exit), Snackbar.LENGTH_SHORT); } } public static boolean isWorkerLogged() { return isWorkerLogged; } public static boolean isAdminLogged() { return isAdminLogged; } @Override protected void onSaveInstanceState(Bundle outState) { } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { } }
22,267
0.567709
0.564459
459
46.605663
33.138241
178
false
false
0
0
0
0
0
0
0.716776
false
false
4
0c86187158d9a81535639ad4535bb69c25c70cfa
16,630,113,422,192
5d9d8ed7fa7d914671166f2ddf83d32121c062fc
/java/algo/binary_search/BinarySearchLC62.java
6b78d54e760398eb41293ea372fde24a7832abb5
[]
no_license
LukeDemons/daily-practice
https://github.com/LukeDemons/daily-practice
9c3c1718a5585416eab5fc430e8acea7e52c80d7
cdc5875b2203cf50b50cb5fa50c51020a6c96553
refs/heads/master
2023-07-06T13:16:20.614000
2023-07-01T16:51:03
2023-07-01T16:51:03
95,017,070
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package algo.binary_search; /** * https://leetcode-cn.com/problems/sqrtx/ * <p> * 2021-05-05 二分查找day2 */ public class BinarySearchLC62 { public static void main(String[] args) { BinarySearchLC62 instance = new BinarySearchLC62(); int result = instance.mySqrt(8); System.out.println(result); } public int mySqrt(int x) { int left = 0, right = x; while (left < right) { // +1是为了向上取整,保证不会死循环 int mid = left + right + 1 >>> 1; if (mid == x / mid) { return mid; } else if (mid > x / mid) { right = mid - 1; } else { left = mid; } } return left; } }
UTF-8
Java
784
java
BinarySearchLC62.java
Java
[]
null
[]
package algo.binary_search; /** * https://leetcode-cn.com/problems/sqrtx/ * <p> * 2021-05-05 二分查找day2 */ public class BinarySearchLC62 { public static void main(String[] args) { BinarySearchLC62 instance = new BinarySearchLC62(); int result = instance.mySqrt(8); System.out.println(result); } public int mySqrt(int x) { int left = 0, right = x; while (left < right) { // +1是为了向上取整,保证不会死循环 int mid = left + right + 1 >>> 1; if (mid == x / mid) { return mid; } else if (mid > x / mid) { right = mid - 1; } else { left = mid; } } return left; } }
784
0.478552
0.450402
34
20.941177
16.618454
59
false
false
0
0
0
0
0
0
0.323529
false
false
4
88b249b1253de59e72dbf36179ee280687cd1fc6
9,268,539,429,504
9b988c5f659895ddc12cf3475a7bd6dba29c6a44
/MTSApp/src/moco/android/mtsdevice/salvage/SalvageSingleViewActivity.java
829272783cbc9192fc188038c813bfc924b9f35d
[]
no_license
xa17d/MTS
https://github.com/xa17d/MTS
6ccbfce6a3e1fb69db64d2b9a3bafcf8f005d7a1
083a5dd22344e3984407484902a1e596fa2d9cce
refs/heads/master
2021-01-22T05:06:49.728000
2013-06-21T09:47:56
2013-06-21T09:47:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package moco.android.mtsdevice.salvage; import java.text.NumberFormat; import moco.android.mtsdevice.R; import moco.android.mtsdevice.handler.Mode; import moco.android.mtsdevice.handler.SelectedPatient; import moco.android.mtsdevice.service.PatientService; import moco.android.mtsdevice.service.PatientServiceImpl; import moco.android.mtsdevice.service.ServiceException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import at.mts.entity.Patient; import at.mts.entity.PatientListItem; public class SalvageSingleViewActivity extends Activity implements LocationListener { private PatientService service; private PatientListItem selectedPatientItem; private Patient selectedPatient; private TextView salvageText; private TextView distanceText; private TextView urgencyText; /** * Location */ private LocationManager locationManager; private String provider; private double dLat; private double dLon; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.salvage_single_view); initGps(); service = PatientServiceImpl.getInstance(); selectedPatientItem = SelectedPatient.getPatientItem(); try { selectedPatient = service.loadPatientByUrl(selectedPatientItem.getUrl()); } catch (ServiceException e) { new AlertDialog.Builder(this) .setMessage(R.string.error_load_data) .setNeutralButton(R.string.ok, null) .show(); } initContent(); } private void initContent() { salvageText = (TextView)findViewById(R.id.textViewSalvageSingleSalvageText); distanceText = (TextView)findViewById(R.id.textViewSalvageDistance); urgencyText = (TextView)findViewById(R.id.textViewSalvageUrgency); if(!selectedPatient.getSalvageInfoString().equals("")) salvageText.setText(selectedPatient.getSalvageInfoString()); urgencyText.setText(String.valueOf(selectedPatient.getUrgency())); } public String getDistanceTo(String gps) { if(gps == null) return "unbekannt"; String[] coordinates = gps.split(","); double pLat = Double.valueOf(coordinates[0]); double pLon = Double.valueOf(coordinates[1]); double C = 111.3; double lat = (pLat + dLat) / 2; double dx = C * Math.cos(lat * Math.PI / 180) * (dLon - pLon); double dy = C * (dLat - pLat); double distance = Math.sqrt(dx * dx + dy * dy); return NumberFormat.getInstance().format(distance * 1000) + " Meter"; } private void initGps() { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { onLocationChanged(location); } else if(Mode.getActiveMode() == Mode.triage) { Toast.makeText(this, R.string.error_gps, Toast.LENGTH_LONG).show(); } } @Override protected void onResume() { super.onResume(); locationManager.requestLocationUpdates(provider, 200, 1, this); distanceText.setText(getDistanceTo(selectedPatient.getGps())); } @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(this); } @Override public void onLocationChanged(Location location) { dLat = location.getLatitude(); dLon = location.getLongitude(); } @Override public void onProviderDisabled(String provider) { //do nothing } @Override public void onProviderEnabled(String provider) { //do nothing } @Override public void onStatusChanged(String provider, int status, Bundle extras) { //do nothing } }
UTF-8
Java
3,995
java
SalvageSingleViewActivity.java
Java
[]
null
[]
package moco.android.mtsdevice.salvage; import java.text.NumberFormat; import moco.android.mtsdevice.R; import moco.android.mtsdevice.handler.Mode; import moco.android.mtsdevice.handler.SelectedPatient; import moco.android.mtsdevice.service.PatientService; import moco.android.mtsdevice.service.PatientServiceImpl; import moco.android.mtsdevice.service.ServiceException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import at.mts.entity.Patient; import at.mts.entity.PatientListItem; public class SalvageSingleViewActivity extends Activity implements LocationListener { private PatientService service; private PatientListItem selectedPatientItem; private Patient selectedPatient; private TextView salvageText; private TextView distanceText; private TextView urgencyText; /** * Location */ private LocationManager locationManager; private String provider; private double dLat; private double dLon; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.salvage_single_view); initGps(); service = PatientServiceImpl.getInstance(); selectedPatientItem = SelectedPatient.getPatientItem(); try { selectedPatient = service.loadPatientByUrl(selectedPatientItem.getUrl()); } catch (ServiceException e) { new AlertDialog.Builder(this) .setMessage(R.string.error_load_data) .setNeutralButton(R.string.ok, null) .show(); } initContent(); } private void initContent() { salvageText = (TextView)findViewById(R.id.textViewSalvageSingleSalvageText); distanceText = (TextView)findViewById(R.id.textViewSalvageDistance); urgencyText = (TextView)findViewById(R.id.textViewSalvageUrgency); if(!selectedPatient.getSalvageInfoString().equals("")) salvageText.setText(selectedPatient.getSalvageInfoString()); urgencyText.setText(String.valueOf(selectedPatient.getUrgency())); } public String getDistanceTo(String gps) { if(gps == null) return "unbekannt"; String[] coordinates = gps.split(","); double pLat = Double.valueOf(coordinates[0]); double pLon = Double.valueOf(coordinates[1]); double C = 111.3; double lat = (pLat + dLat) / 2; double dx = C * Math.cos(lat * Math.PI / 180) * (dLon - pLon); double dy = C * (dLat - pLat); double distance = Math.sqrt(dx * dx + dy * dy); return NumberFormat.getInstance().format(distance * 1000) + " Meter"; } private void initGps() { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { onLocationChanged(location); } else if(Mode.getActiveMode() == Mode.triage) { Toast.makeText(this, R.string.error_gps, Toast.LENGTH_LONG).show(); } } @Override protected void onResume() { super.onResume(); locationManager.requestLocationUpdates(provider, 200, 1, this); distanceText.setText(getDistanceTo(selectedPatient.getGps())); } @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(this); } @Override public void onLocationChanged(Location location) { dLat = location.getLatitude(); dLon = location.getLongitude(); } @Override public void onProviderDisabled(String provider) { //do nothing } @Override public void onProviderEnabled(String provider) { //do nothing } @Override public void onStatusChanged(String provider, int status, Bundle extras) { //do nothing } }
3,995
0.744681
0.740175
154
24.941559
23.33918
85
false
false
0
0
0
0
0
0
1.818182
false
false
4
57a2180207396282a53540dfd2272d65dc204f65
20,847,771,317,393
42516b1b100beb9923633c70ecc36cf1c5ccea7c
/src/minesweeper/game/Square.java
546a70720dd720be73a5ed5267407b28a2d5452e
[]
no_license
kanedu828/Minesweeper
https://github.com/kanedu828/Minesweeper
119bd819afc633934eb684f481610b30ff4a0451
d2a416d27d30fc5121b0b2b6259ab11d8f815fca
refs/heads/master
2020-04-10T04:26:02.748000
2019-03-18T03:48:35
2019-03-18T03:48:35
160,797,994
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package minesweeper.game; import java.util.Random; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * This class represents a square of a minesweeper game. */ public class Square{ private Random rand = new Random(); private boolean safe; private boolean flagged; private boolean revealed; private ImageView visual; private Button squareButton; /** * This constructor initializes a map with no bombs. */ public Square(){ safe = true; visual = new ImageView(); visual.setFitWidth(75); visual.setFitHeight(75); flagged = false; revealed = false; squareButton = new Button(); squareButton.setMaxSize(75, 75); squareButton.setMinSize(75, 75); } /** * Sets the square visual * @param visual the square visual */ public void setVisual(Image visual){ this.visual.setImage(visual); squareButton.setGraphic(this.visual); } /** * Returns the squareButton * @return the squareButton */ public Button getSquareButton(){ return squareButton; } /** * Returns the visual * @return the visual */ public Image getVisual(){ return visual.getImage(); } /** * Sets whether or not the square is safe. * @param safe whether or not the square is safe. */ public void setSafe(boolean safe){ this.safe = safe; } /** * Returns whether or not the square is safe. * @return true if the square is safe, false otherwise. */ public boolean getSafe(){ return safe; } /** * Returns whether or not the square is flagged. * @return True if the square is flagged, false otherwise. */ public boolean getFlagged(){ return flagged; } /** * Sets whether the square is flagged. * @param flagged whether or not the square is flagged. */ public void setFlagged(boolean flagged){ this.flagged = flagged; } /** * Returns whether or not the square is revealed. * @return true if the square is revealed, false otherwise. */ public boolean getRevealed() { return revealed; } /** * Sets whether or not if the square is revealed. * @param revealed whether or not if the square is revealed. */ public void setRevealed(boolean revealed) { this.revealed = revealed; } }
UTF-8
Java
2,640
java
Square.java
Java
[]
null
[]
package minesweeper.game; import java.util.Random; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * This class represents a square of a minesweeper game. */ public class Square{ private Random rand = new Random(); private boolean safe; private boolean flagged; private boolean revealed; private ImageView visual; private Button squareButton; /** * This constructor initializes a map with no bombs. */ public Square(){ safe = true; visual = new ImageView(); visual.setFitWidth(75); visual.setFitHeight(75); flagged = false; revealed = false; squareButton = new Button(); squareButton.setMaxSize(75, 75); squareButton.setMinSize(75, 75); } /** * Sets the square visual * @param visual the square visual */ public void setVisual(Image visual){ this.visual.setImage(visual); squareButton.setGraphic(this.visual); } /** * Returns the squareButton * @return the squareButton */ public Button getSquareButton(){ return squareButton; } /** * Returns the visual * @return the visual */ public Image getVisual(){ return visual.getImage(); } /** * Sets whether or not the square is safe. * @param safe whether or not the square is safe. */ public void setSafe(boolean safe){ this.safe = safe; } /** * Returns whether or not the square is safe. * @return true if the square is safe, false otherwise. */ public boolean getSafe(){ return safe; } /** * Returns whether or not the square is flagged. * @return True if the square is flagged, false otherwise. */ public boolean getFlagged(){ return flagged; } /** * Sets whether the square is flagged. * @param flagged whether or not the square is flagged. */ public void setFlagged(boolean flagged){ this.flagged = flagged; } /** * Returns whether or not the square is revealed. * @return true if the square is revealed, false otherwise. */ public boolean getRevealed() { return revealed; } /** * Sets whether or not if the square is revealed. * @param revealed whether or not if the square is revealed. */ public void setRevealed(boolean revealed) { this.revealed = revealed; } }
2,640
0.58447
0.579924
107
22.672897
18.445057
64
false
false
0
0
0
0
0
0
0.327103
false
false
4
c73be2a7c00a5d6a3a99e95e0e817dd07984bcd2
9,964,324,139,884
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/5/5_df208146bdcfdf5932acd6339245257f6c6a656c/LineWrapperInputStream/5_df208146bdcfdf5932acd6339245257f6c6a656c_LineWrapperInputStream_s.java
3ff82b346f52b1517c396ddd859cfc9c8fe0ef70
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package net.northfuse.resources; import java.io.*; /** * @author tylers2 */ public class LineWrapperInputStream extends InputStream { private final InputStream is; public LineWrapperInputStream(InputStream is, String description) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); int lineNumber = 0; boolean inComment = false; while ((line = reader.readLine()) != null) { if (inComment) { writer.println(" d " + description + ":" + (++lineNumber) + " " + line); } else { writer.println("/*d " + description + ":" + (++lineNumber) + " */" + line); } if (!inComment) { int commentIndex = line.lastIndexOf("/*"); if (commentIndex > -1) { if (commentIndex > 0) { //is the comment start inside of a string? if (countOccurences(line.substring(0, commentIndex), "\"") % 2 == 1) { continue; } } if (!line.substring(commentIndex).contains("*/")) { inComment = true; } } } else { int commentIndex = line.lastIndexOf("*/"); if (commentIndex > -1) { if (!line.substring(commentIndex).contains("/*")) { inComment = false; } } } } writer.close(); //get rid of the last new line byte[] data = baos.toByteArray(); this.is = new ByteArrayInputStream(data, 0, data.length - 1); } private int countOccurences(String s, String pattern) { int count = 0; for (char c : s.toCharArray()) { if (c == pattern.charAt(0)) { count++; } } return count; } private int doCountOccurences(String s, String pattern, int count) { int index = s.indexOf(pattern); if (index == -1) { return count; } else { return doCountOccurences(s.substring(index + 1), pattern, count + 1); } } @Override public int read() throws IOException { return is.read(); } @Override public int read(byte[] b) throws IOException { return is.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } @Override public long skip(long n) throws IOException { return is.skip(n); } @Override public int available() throws IOException { return is.available(); } @Override public void close() throws IOException { is.close(); } @Override public void mark(int readlimit) { is.mark(readlimit); } @Override public void reset() throws IOException { is.reset(); } @Override public boolean markSupported() { return is.markSupported(); } }
UTF-8
Java
2,735
java
5_df208146bdcfdf5932acd6339245257f6c6a656c_LineWrapperInputStream_s.java
Java
[ { "context": "resources;\n \n import java.io.*;\n \n /**\n * @author tylers2\n */\n public class LineWrapperInputStream extends", "end": 81, "score": 0.9994261860847473, "start": 74, "tag": "USERNAME", "value": "tylers2" } ]
null
[]
package net.northfuse.resources; import java.io.*; /** * @author tylers2 */ public class LineWrapperInputStream extends InputStream { private final InputStream is; public LineWrapperInputStream(InputStream is, String description) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); int lineNumber = 0; boolean inComment = false; while ((line = reader.readLine()) != null) { if (inComment) { writer.println(" d " + description + ":" + (++lineNumber) + " " + line); } else { writer.println("/*d " + description + ":" + (++lineNumber) + " */" + line); } if (!inComment) { int commentIndex = line.lastIndexOf("/*"); if (commentIndex > -1) { if (commentIndex > 0) { //is the comment start inside of a string? if (countOccurences(line.substring(0, commentIndex), "\"") % 2 == 1) { continue; } } if (!line.substring(commentIndex).contains("*/")) { inComment = true; } } } else { int commentIndex = line.lastIndexOf("*/"); if (commentIndex > -1) { if (!line.substring(commentIndex).contains("/*")) { inComment = false; } } } } writer.close(); //get rid of the last new line byte[] data = baos.toByteArray(); this.is = new ByteArrayInputStream(data, 0, data.length - 1); } private int countOccurences(String s, String pattern) { int count = 0; for (char c : s.toCharArray()) { if (c == pattern.charAt(0)) { count++; } } return count; } private int doCountOccurences(String s, String pattern, int count) { int index = s.indexOf(pattern); if (index == -1) { return count; } else { return doCountOccurences(s.substring(index + 1), pattern, count + 1); } } @Override public int read() throws IOException { return is.read(); } @Override public int read(byte[] b) throws IOException { return is.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } @Override public long skip(long n) throws IOException { return is.skip(n); } @Override public int available() throws IOException { return is.available(); } @Override public void close() throws IOException { is.close(); } @Override public void mark(int readlimit) { is.mark(readlimit); } @Override public void reset() throws IOException { is.reset(); } @Override public boolean markSupported() { return is.markSupported(); } }
2,735
0.610603
0.605119
115
22.773912
22.020962
88
false
false
0
0
0
0
0
0
2.373913
false
false
4
ade1901bed9b7bef6a5547788c27d84f6aa66e34
30,305,289,262,943
f5218314dedbeda55deb7c4afafe9c65f94e6510
/src/main/java/com/entity/Language.java
76013e8e535a4eb6de4a6f68730b35b5028d17fd
[]
no_license
Krasav4k1/WTable
https://github.com/Krasav4k1/WTable
5115216420e8dfd71f0f831ab93d2cac914e28c3
3641ec7988c245733d7ca2a9b8a53364cd67aa45
refs/heads/master
2021-06-03T00:19:54.336000
2016-09-16T07:54:46
2016-09-16T07:54:46
53,608,169
2
0
null
false
2016-09-16T07:54:46
2016-03-10T18:39:33
2016-09-16T06:25:04
2016-09-16T07:54:46
39,131
1
1
0
Java
null
null
package com.entity; import javax.persistence.*; @Entity @Table public class Language { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; public String language; @ManyToOne @JoinColumn private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
UTF-8
Java
652
java
Language.java
Java
[]
null
[]
package com.entity; import javax.persistence.*; @Entity @Table public class Language { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; public String language; @ManyToOne @JoinColumn private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
652
0.592025
0.592025
42
14.523809
14.046247
55
false
false
0
0
0
0
0
0
0.261905
false
false
4
d7245037f12e35dbabc8d265c672451abfd5b07d
31,258,772,005,876
170287bd222be3c129f0abe1afcab06ff4608ea9
/experiment_2/context-aware-meeting-room-client-javame/src/main/java/ac/uk/brunel/mobile/contextaware/presentation/facade/PresentationObjectFactory.java
152bd8c4b134e1ed63858529ea4d7e97f55b6da9
[]
no_license
tormorten/brunelPhD
https://github.com/tormorten/brunelPhD
f252f396d9576508f71939e709e016b5f718966a
b169e56e23713c4b0097ab3af098476877d202c6
refs/heads/master
2021-01-20T04:39:43.271000
2012-04-15T21:06:16
2012-04-15T21:06:16
4,027,000
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ac.uk.brunel.mobile.contextaware.presentation.facade; import java.util.Vector; import ac.uk.brunel.mobile.contextaware.dto.Meeting; import ac.uk.brunel.mobile.contextaware.presentation.dto.PresentationMeeting; public class PresentationObjectFactory { private PresentationObjectFactory() { } static Vector createPresentationMeetingList(final Vector meetingList) { Vector presentationMeetingList = new Vector(); for (int i = 0; i < meetingList.size(); i++) { Meeting meeting = (Meeting) meetingList.elementAt(i); presentationMeetingList.addElement(new PresentationMeeting(meeting.getMeetingId(), meeting.getMeetingNotes(), meeting.getSavedDate())); } return presentationMeetingList; } }
UTF-8
Java
718
java
PresentationObjectFactory.java
Java
[]
null
[]
package ac.uk.brunel.mobile.contextaware.presentation.facade; import java.util.Vector; import ac.uk.brunel.mobile.contextaware.dto.Meeting; import ac.uk.brunel.mobile.contextaware.presentation.dto.PresentationMeeting; public class PresentationObjectFactory { private PresentationObjectFactory() { } static Vector createPresentationMeetingList(final Vector meetingList) { Vector presentationMeetingList = new Vector(); for (int i = 0; i < meetingList.size(); i++) { Meeting meeting = (Meeting) meetingList.elementAt(i); presentationMeetingList.addElement(new PresentationMeeting(meeting.getMeetingId(), meeting.getMeetingNotes(), meeting.getSavedDate())); } return presentationMeetingList; } }
718
0.786908
0.785515
23
30.217392
34.923466
138
false
false
0
0
0
0
0
0
1.304348
false
false
4
3a614cb74aace6106cb9e42cbcbd5a89c45b0ccd
6,451,040,923,355
c9b43aef0291648bf976f53271a192af8c3e912f
/src/main/java/com/duncanturk/cli/api/TaskTerminationType.java
eb509e00f9e6198a93a09de1a3c8011a103c3a4f
[ "MIT" ]
permissive
duncanturk/java-cli-and-text-interface-framework
https://github.com/duncanturk/java-cli-and-text-interface-framework
45f8ec4e072d3dfb4a74aa2397808f7ca6ce4b49
fe5843dc940086c3e619492490333079f42cbdc4
refs/heads/master
2021-09-07T17:25:10.788000
2018-02-26T21:09:40
2018-02-26T21:09:40
122,677,114
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.duncanturk.cli.api; public enum TaskTerminationType { SUCCESS, EXIT, FAILED, CANCELED }
UTF-8
Java
106
java
TaskTerminationType.java
Java
[]
null
[]
package com.duncanturk.cli.api; public enum TaskTerminationType { SUCCESS, EXIT, FAILED, CANCELED }
106
0.754717
0.754717
5
20
15.97498
35
false
false
0
0
0
0
0
0
0.8
false
false
4
94066fc5aa394677bb7af4890a40af394705042d
22,763,326,700,251
0e54faea09ae4e105cae0d74989ec113002a9422
/lianjiu_rest/lianjiu_rest_dao/src/main/java/com/lianjiu/rest/mapper/orders/OrdersFacefaceMapper.java
8e130bd8a0fd531cb3372f2761d00304047be93d
[]
no_license
geilige/recycle-maven
https://github.com/geilige/recycle-maven
e49576463e91e8378c42f45846dcf8266812384b
0cb0f27543f205758e0ae25f30e9361a0eb215b6
refs/heads/master
2023-03-16T02:38:32.158000
2018-02-07T05:57:58
2018-02-07T05:57:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lianjiu.rest.mapper.orders; import java.util.Date; import java.util.List; import org.apache.ibatis.annotations.Param; import com.lianjiu.model.OrdersFaceface; import com.lianjiu.model.vo.SearchObjecVo; import com.lianjiu.rest.model.OrdersFacefaceFull; import com.lianjiu.rest.model.OrdersFacefaceItemVo; public interface OrdersFacefaceMapper { int deleteByPrimaryKey(String orFacefaceId); int insert(OrdersFaceface record); OrdersFaceface selectByPrimaryKey(String orFacefaceId); int updateByPrimaryKeySelective(OrdersFaceface record); int updateByPrimaryKeyWithBLOBs(OrdersFaceface record); int updateByPrimaryKey(OrdersFaceface record); List<OrdersFacefaceFull> selectListByUserId(String userId); int addHomeVisitTime(String orFacefaceId, String visitTime); List<OrdersFacefaceFull> getHomeVistStutsList(OrdersFaceface info); List<OrdersFacefaceFull> getOrdersListByStatus(@Param(value = "uid") String uid, @Param(value = "statusList") List<Byte> status); List<OrdersFaceface> findAll(); List<OrdersFaceface> findByUserId(String userId); List<OrdersFaceface> getFaceFaceByState(Byte state); int selectByOrdersFacefaceCheck(String facefaceId); int updateByStatus(OrdersFaceface ordersFaceface); int updateFacefaceBrothersId(OrdersFaceface ordersFaceface); int updateFacefaceBySubmit(OrdersFaceface ordersFaceface); int updateFaceFaceState(OrdersFaceface ordersFaceface); List<OrdersFacefaceItemVo> selectFacefaceByUserId(String userId); List<OrdersFaceface> findAll(Integer radius, String allianceId); List<OrdersFaceface> selectOrdersByallianceId(@Param(value = "allianceId") String allianceId, @Param(value = "statusList") List<Byte> statusList); List<OrdersFaceface> selectAll(); void updateByPrimaryKey(String orders); int updateFaceFaceStates(OrdersFaceface ordersFaceface); List<OrdersFaceface> selectByOrdersId(String orOrdersId); List<OrdersFaceface> findFaceAll(String allianceId); List<OrdersFacefaceFull> selectByAddressId(String userAddressId); OrdersFaceface getMessage(String orFacefaceId); Integer getOrdersStatusByAcliacneId(String orFacefaceAllianceId); String selectAddressIdById(String orderFaceId); List<String> getByaId(String allianceId); int deleteById(String faceId); int deleteByaId(String allianceId); // 取消价格 int orderPriceRefuse(@Param("orFacefaceId") String orFacefaceId, @Param("updated") Date updated); OrdersFaceface selectFullByPrimaryKey(String orFacefaceId); int ordersAutoCancel(@Param(value = "ordersIdList") List<String> ordersIdList); int modifyOrdersStatus(@Param("status") Byte status, @Param("ordersId") String ordersId); // 查订单状态 Integer getOrdersStatusByOrdersId(@Param("orFacefaceId") String ordersId); List<OrdersFaceface> getOrdersFaceLL(); // 根据订单编号查相应加盟商编号 String getAllianceIDById(String orFacefaceId); int updateForOrderStatusReduction(@Param("ordersIdList") List<String> ordersIdList); int updateFaceFaceFinishState(OrdersFaceface orders); int getCancelCountByAllianceId(String orFacefaceAllianceId); List<OrdersFaceface> selectBySearchObjecVo(SearchObjecVo vo); List<OrdersFaceface> selectBySearchFilter(SearchObjecVo vo); // 获取订单当前的状态 Byte selectOrdersStatus(String ordersId); int ordersCancel(String ordersId); List<OrdersFaceface> vagueQuery(@Param(value="faceface") OrdersFaceface faceface,@Param(value="cratedStart") String cratedStart,@Param(value="cratedOver") String cratedOver); }
UTF-8
Java
3,531
java
OrdersFacefaceMapper.java
Java
[]
null
[]
package com.lianjiu.rest.mapper.orders; import java.util.Date; import java.util.List; import org.apache.ibatis.annotations.Param; import com.lianjiu.model.OrdersFaceface; import com.lianjiu.model.vo.SearchObjecVo; import com.lianjiu.rest.model.OrdersFacefaceFull; import com.lianjiu.rest.model.OrdersFacefaceItemVo; public interface OrdersFacefaceMapper { int deleteByPrimaryKey(String orFacefaceId); int insert(OrdersFaceface record); OrdersFaceface selectByPrimaryKey(String orFacefaceId); int updateByPrimaryKeySelective(OrdersFaceface record); int updateByPrimaryKeyWithBLOBs(OrdersFaceface record); int updateByPrimaryKey(OrdersFaceface record); List<OrdersFacefaceFull> selectListByUserId(String userId); int addHomeVisitTime(String orFacefaceId, String visitTime); List<OrdersFacefaceFull> getHomeVistStutsList(OrdersFaceface info); List<OrdersFacefaceFull> getOrdersListByStatus(@Param(value = "uid") String uid, @Param(value = "statusList") List<Byte> status); List<OrdersFaceface> findAll(); List<OrdersFaceface> findByUserId(String userId); List<OrdersFaceface> getFaceFaceByState(Byte state); int selectByOrdersFacefaceCheck(String facefaceId); int updateByStatus(OrdersFaceface ordersFaceface); int updateFacefaceBrothersId(OrdersFaceface ordersFaceface); int updateFacefaceBySubmit(OrdersFaceface ordersFaceface); int updateFaceFaceState(OrdersFaceface ordersFaceface); List<OrdersFacefaceItemVo> selectFacefaceByUserId(String userId); List<OrdersFaceface> findAll(Integer radius, String allianceId); List<OrdersFaceface> selectOrdersByallianceId(@Param(value = "allianceId") String allianceId, @Param(value = "statusList") List<Byte> statusList); List<OrdersFaceface> selectAll(); void updateByPrimaryKey(String orders); int updateFaceFaceStates(OrdersFaceface ordersFaceface); List<OrdersFaceface> selectByOrdersId(String orOrdersId); List<OrdersFaceface> findFaceAll(String allianceId); List<OrdersFacefaceFull> selectByAddressId(String userAddressId); OrdersFaceface getMessage(String orFacefaceId); Integer getOrdersStatusByAcliacneId(String orFacefaceAllianceId); String selectAddressIdById(String orderFaceId); List<String> getByaId(String allianceId); int deleteById(String faceId); int deleteByaId(String allianceId); // 取消价格 int orderPriceRefuse(@Param("orFacefaceId") String orFacefaceId, @Param("updated") Date updated); OrdersFaceface selectFullByPrimaryKey(String orFacefaceId); int ordersAutoCancel(@Param(value = "ordersIdList") List<String> ordersIdList); int modifyOrdersStatus(@Param("status") Byte status, @Param("ordersId") String ordersId); // 查订单状态 Integer getOrdersStatusByOrdersId(@Param("orFacefaceId") String ordersId); List<OrdersFaceface> getOrdersFaceLL(); // 根据订单编号查相应加盟商编号 String getAllianceIDById(String orFacefaceId); int updateForOrderStatusReduction(@Param("ordersIdList") List<String> ordersIdList); int updateFaceFaceFinishState(OrdersFaceface orders); int getCancelCountByAllianceId(String orFacefaceAllianceId); List<OrdersFaceface> selectBySearchObjecVo(SearchObjecVo vo); List<OrdersFaceface> selectBySearchFilter(SearchObjecVo vo); // 获取订单当前的状态 Byte selectOrdersStatus(String ordersId); int ordersCancel(String ordersId); List<OrdersFaceface> vagueQuery(@Param(value="faceface") OrdersFaceface faceface,@Param(value="cratedStart") String cratedStart,@Param(value="cratedOver") String cratedOver); }
3,531
0.815979
0.815979
116
28.896551
32.001717
177
false
false
0
0
0
0
0
0
1.051724
false
false
4
2d72e5ecaf42debdc86bdfdc296617f54a3a3f41
25,752,623,946,881
d9cade31b29426762c1112b0e2e33960b2c00e84
/src/algorithm/greedy/Code03_CutGoldenBar.java
1f88f64a0db34794ca5456e9ab65ec0385d50d06
[]
no_license
wangyx1024/daydayup
https://github.com/wangyx1024/daydayup
9d75d4f9d17cec3d859f754b4d74390b31e6cc21
6567fe267fcc76a94b93ee898b865d39d6fddf22
refs/heads/main
2023-05-12T13:26:53.194000
2021-06-01T23:14:24
2021-06-01T23:14:24
352,397,472
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithm.greedy; import algorithm.util.Checker; import java.util.*; /** * 切金条问题 */ public class Code03_CutGoldenBar { public static void main(String[] args) { // int[] arr = {2}; // int[] plan1 = greedySolve(arr); // int cost1 = calCost(plan1); // System.out.println("cost1 = " + cost1); // // int[] plan2 = violentSolve(arr); // int cost2 = calCost(plan2); // System.out.println("cost2 = " + cost2); check(100000, 5, 10); } public static void check(int times, int maxSection, int sectionMaxVal) { int[] arr = null; try { while (times-- > 0) { arr = buildGoldBar(maxSection, sectionMaxVal); int[] plan1 = greedySolve(arr); int[] plan2 = violentSolve(arr); // P.print(arr); // P.print(plan1); // P.print(plan2); int cost1 = calCost(plan1); int cost2 = calCost(plan2); if (cost1 != cost2) { throw new RuntimeException("fucking fucked!!!!!!!"); } } System.out.println("成功!!!!"); } catch (Exception e) { System.out.println(e.toString()); System.out.println(arr); } } private static int[] buildGoldBar(int maxSection, int sectionMaxVal) { int len = Checker.generateRandomPositiveNumNoMoreThan(maxSection); int[] arr = new int[len]; for (int i = 0; i < arr.length; i++) { arr[i] = Checker.generateRandomPositiveNumNoMoreThan(sectionMaxVal) + 1; } return arr; } private static class MinComparator implements Comparator<HeapNode> { @Override public int compare(HeapNode o1, HeapNode o2) { return o1.gold - o2.gold; } } private static int[] violentSolve(int[] arr) { if (arr == null) { return new int[0]; } List<Integer> plan = new ArrayList<>(arr.length); List<List<Integer>> plans = new ArrayList<>(); violentProcess(arr, plan, plans); // System.out.println(plans); int lowerCost = Integer.MAX_VALUE; int[] bestPlan = new int[0]; for (List<Integer> p : plans) { int[] planArr = getArrFromList(p); int cost = calCost(planArr); if (cost < lowerCost) { lowerCost = cost; bestPlan = planArr; } } return bestPlan; } private static void violentProcess(int[] arr, List<Integer> plan, List<List<Integer>> plans) { if (plan.size() == arr.length) { List<Integer> realPlan = new ArrayList<>(plan.size()); for (Integer index : plan) { realPlan.add(arr[index]); } plans.add(realPlan); } else { int len = arr.length; for (int i = 0; i < len; i++) { if (plan.contains(i)) { continue; } List<Integer> copiedPlan = copy(plan); copiedPlan.add(i); violentProcess(arr, copiedPlan, plans); } } } private static List<Integer> copy(List<Integer> list) { List<Integer> ret = new ArrayList<>(list.size()); for (int i = 0; i < list.size(); i++) { ret.add(list.get(i)); } return ret; } private static int[] getArrFromList(List<Integer> list) { int[] arr = new int[list.size()]; for (int i = 0; i < list.size(); i++) { arr[i] = list.get(i); } return arr; } public static class HeapNode { public int gold; public boolean join; public HeapNode(int gold, boolean join) { this.gold = gold; this.join = join; } } private static int calCost(int[] arr) { int cost = 0; int len = arr.length; for (int i = 0; i < len - 1; i++) { for (int j = i; j < len; j++) { cost += arr[j]; } } return cost; } private static int[] greedySolve(int[] arr) { if (arr == null) { return new int[]{}; } PriorityQueue<HeapNode> heap = new PriorityQueue(new MinComparator()); for (int i : arr) { heap.add(new HeapNode(i, false)); } // 需要切几刀 int index = 0; int length = arr.length; int[] plan = new int[length]; while (heap.size() > 1) { HeapNode n1 = heap.poll(); HeapNode n2 = heap.poll(); int cost = n1.gold + n2.gold; heap.add(new HeapNode(cost, true)); if (!n1.join) { plan[length - index++ - 1] = n1.gold; } if (!n2.join) { plan[length - index++ - 1] = n2.gold; } } return plan; } }
UTF-8
Java
5,072
java
Code03_CutGoldenBar.java
Java
[]
null
[]
package algorithm.greedy; import algorithm.util.Checker; import java.util.*; /** * 切金条问题 */ public class Code03_CutGoldenBar { public static void main(String[] args) { // int[] arr = {2}; // int[] plan1 = greedySolve(arr); // int cost1 = calCost(plan1); // System.out.println("cost1 = " + cost1); // // int[] plan2 = violentSolve(arr); // int cost2 = calCost(plan2); // System.out.println("cost2 = " + cost2); check(100000, 5, 10); } public static void check(int times, int maxSection, int sectionMaxVal) { int[] arr = null; try { while (times-- > 0) { arr = buildGoldBar(maxSection, sectionMaxVal); int[] plan1 = greedySolve(arr); int[] plan2 = violentSolve(arr); // P.print(arr); // P.print(plan1); // P.print(plan2); int cost1 = calCost(plan1); int cost2 = calCost(plan2); if (cost1 != cost2) { throw new RuntimeException("fucking fucked!!!!!!!"); } } System.out.println("成功!!!!"); } catch (Exception e) { System.out.println(e.toString()); System.out.println(arr); } } private static int[] buildGoldBar(int maxSection, int sectionMaxVal) { int len = Checker.generateRandomPositiveNumNoMoreThan(maxSection); int[] arr = new int[len]; for (int i = 0; i < arr.length; i++) { arr[i] = Checker.generateRandomPositiveNumNoMoreThan(sectionMaxVal) + 1; } return arr; } private static class MinComparator implements Comparator<HeapNode> { @Override public int compare(HeapNode o1, HeapNode o2) { return o1.gold - o2.gold; } } private static int[] violentSolve(int[] arr) { if (arr == null) { return new int[0]; } List<Integer> plan = new ArrayList<>(arr.length); List<List<Integer>> plans = new ArrayList<>(); violentProcess(arr, plan, plans); // System.out.println(plans); int lowerCost = Integer.MAX_VALUE; int[] bestPlan = new int[0]; for (List<Integer> p : plans) { int[] planArr = getArrFromList(p); int cost = calCost(planArr); if (cost < lowerCost) { lowerCost = cost; bestPlan = planArr; } } return bestPlan; } private static void violentProcess(int[] arr, List<Integer> plan, List<List<Integer>> plans) { if (plan.size() == arr.length) { List<Integer> realPlan = new ArrayList<>(plan.size()); for (Integer index : plan) { realPlan.add(arr[index]); } plans.add(realPlan); } else { int len = arr.length; for (int i = 0; i < len; i++) { if (plan.contains(i)) { continue; } List<Integer> copiedPlan = copy(plan); copiedPlan.add(i); violentProcess(arr, copiedPlan, plans); } } } private static List<Integer> copy(List<Integer> list) { List<Integer> ret = new ArrayList<>(list.size()); for (int i = 0; i < list.size(); i++) { ret.add(list.get(i)); } return ret; } private static int[] getArrFromList(List<Integer> list) { int[] arr = new int[list.size()]; for (int i = 0; i < list.size(); i++) { arr[i] = list.get(i); } return arr; } public static class HeapNode { public int gold; public boolean join; public HeapNode(int gold, boolean join) { this.gold = gold; this.join = join; } } private static int calCost(int[] arr) { int cost = 0; int len = arr.length; for (int i = 0; i < len - 1; i++) { for (int j = i; j < len; j++) { cost += arr[j]; } } return cost; } private static int[] greedySolve(int[] arr) { if (arr == null) { return new int[]{}; } PriorityQueue<HeapNode> heap = new PriorityQueue(new MinComparator()); for (int i : arr) { heap.add(new HeapNode(i, false)); } // 需要切几刀 int index = 0; int length = arr.length; int[] plan = new int[length]; while (heap.size() > 1) { HeapNode n1 = heap.poll(); HeapNode n2 = heap.poll(); int cost = n1.gold + n2.gold; heap.add(new HeapNode(cost, true)); if (!n1.join) { plan[length - index++ - 1] = n1.gold; } if (!n2.join) { plan[length - index++ - 1] = n2.gold; } } return plan; } }
5,072
0.481181
0.469493
190
25.56842
21.384279
98
false
false
0
0
0
0
0
0
0.547368
false
false
4
943968dffe025309af401a0de0112b05d5a306a4
29,729,763,676,630
ca95555a6ce6410807699face40f070f92d41d20
/LQian-springboot-algorithm/src/main/java/com/zl/lqian/jianzhi/Solution43.java
d598ae6231cc0fb29ac33ab8d96392d3bc60f798
[]
no_license
SaberSola/LQian
https://github.com/SaberSola/LQian
0000adef39a0940c2771f76e69790643acc6c892
b8a42ffe46d37968ecdbf70b402f7b1b09549f55
refs/heads/master
2022-12-20T23:43:19.657000
2021-12-27T13:18:45
2021-12-27T13:18:45
144,002,792
9
3
null
false
2022-12-16T04:33:33
2018-08-08T11:15:53
2022-06-15T12:33:48
2022-12-16T04:33:27
1,606
8
3
87
Java
false
false
package com.zl.lqian.jianzhi; import java.util.ArrayList; /** * @Author zl * @Date 2020-04-11 * @Des 输入一个递增排序的数组和一个数字S,在数组中查找两个数, * 使得他们的和正好是S,如果有多对数字的和等于S, * 输出两个数的乘积最小的。 */ public class Solution43 { /** * 输入一个递增排序的数组和一个数字S, * 在数组中查找两个数,使得他们的和正好是S, * 如果有多对数字的和等于S,输出两个数的乘积最小的。 * * 还是双指针发 * @param array * @param sum * @return */ public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) { ArrayList<Integer> result = new ArrayList<Integer>(); //边界条件 if (array == null || array.length <= 1) { return result; } int smallIndex = 0; int bigIndex = array.length - 1; while (smallIndex < bigIndex) { if ((array[smallIndex] + array[bigIndex]) == sum) { result.add(array[smallIndex]); result.add(array[bigIndex]); break; } else if ((array[smallIndex] + array[bigIndex]) < sum) { smallIndex++; } else { bigIndex--; } } return result; } }
UTF-8
Java
1,382
java
Solution43.java
Java
[ { "context": "nzhi;\n\nimport java.util.ArrayList;\n\n/**\n * @Author zl\n * @Date 2020-04-11\n * @Des 输入一个递增排序的数组和一个数字S,在数组", "end": 77, "score": 0.9993906021118164, "start": 75, "tag": "USERNAME", "value": "zl" } ]
null
[]
package com.zl.lqian.jianzhi; import java.util.ArrayList; /** * @Author zl * @Date 2020-04-11 * @Des 输入一个递增排序的数组和一个数字S,在数组中查找两个数, * 使得他们的和正好是S,如果有多对数字的和等于S, * 输出两个数的乘积最小的。 */ public class Solution43 { /** * 输入一个递增排序的数组和一个数字S, * 在数组中查找两个数,使得他们的和正好是S, * 如果有多对数字的和等于S,输出两个数的乘积最小的。 * * 还是双指针发 * @param array * @param sum * @return */ public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) { ArrayList<Integer> result = new ArrayList<Integer>(); //边界条件 if (array == null || array.length <= 1) { return result; } int smallIndex = 0; int bigIndex = array.length - 1; while (smallIndex < bigIndex) { if ((array[smallIndex] + array[bigIndex]) == sum) { result.add(array[smallIndex]); result.add(array[bigIndex]); break; } else if ((array[smallIndex] + array[bigIndex]) < sum) { smallIndex++; } else { bigIndex--; } } return result; } }
1,382
0.525939
0.514311
46
23.304348
18.473093
72
false
false
0
0
0
0
0
0
0.326087
false
false
4
943cab7a1b631fa68b51cb7e607182d130d2c4a5
23,295,902,628,177
7b8123a02d4cd482513dd009511e1cfb8586564c
/code/trunk/src/main/java/com/cloudking/openlab/vo/CommonTechPlatformCatVO.java
b43f8c2656c2dc498811943804b4633cad0374b2
[]
no_license
Wanghuaichen/openlab
https://github.com/Wanghuaichen/openlab
7245e9a06a96ac6ce1844ee4adc1ec4eec92f633
5adba613d1bb0d73fdce0ef3da59c08b8ff139ce
refs/heads/master
2020-04-07T12:48:36.279000
2016-04-11T09:52:48
2016-04-11T09:52:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright(c) 2013 ShenZhen CloudKing Technology Co., Ltd. * All rights reserved. * Created on Aug 27, 2013 10:56:55 AM */ package com.cloudking.openlab.vo; import java.util.List; import com.cloudking.openlab.BaseVO; /** * 公共技术服务平台 * * @author CloudKing */ public class CommonTechPlatformCatVO extends BaseVO { /** * 名称 */ private String name; /** * 描述 */ private String desc; /** * 分类中添加单元 */ private List<CommonTechPlatformVO> commonTechPlatformVOs; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public List<CommonTechPlatformVO> getCommonTechPlatformVOs() { return commonTechPlatformVOs; } public void setCommonTechPlatformVOs( List<CommonTechPlatformVO> commonTechPlatformVOs) { this.commonTechPlatformVOs = commonTechPlatformVOs; } }
UTF-8
Java
996
java
CommonTechPlatformCatVO.java
Java
[ { "context": "/**\n * Copyright(c) 2013 ShenZhen CloudKing Technology Co., Ltd.\n * All rights rese", "end": 33, "score": 0.9997235536575317, "start": 25, "tag": "NAME", "value": "ShenZhen" }, { "context": "ng.openlab.BaseVO;\n\n/**\n * 公共技术服务平台\n * \n * @author CloudKing\n */\npublic class CommonTechPlatformCatVO extends ", "end": 271, "score": 0.999113917350769, "start": 262, "tag": "USERNAME", "value": "CloudKing" } ]
null
[]
/** * Copyright(c) 2013 ShenZhen CloudKing Technology Co., Ltd. * All rights reserved. * Created on Aug 27, 2013 10:56:55 AM */ package com.cloudking.openlab.vo; import java.util.List; import com.cloudking.openlab.BaseVO; /** * 公共技术服务平台 * * @author CloudKing */ public class CommonTechPlatformCatVO extends BaseVO { /** * 名称 */ private String name; /** * 描述 */ private String desc; /** * 分类中添加单元 */ private List<CommonTechPlatformVO> commonTechPlatformVOs; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public List<CommonTechPlatformVO> getCommonTechPlatformVOs() { return commonTechPlatformVOs; } public void setCommonTechPlatformVOs( List<CommonTechPlatformVO> commonTechPlatformVOs) { this.commonTechPlatformVOs = commonTechPlatformVOs; } }
996
0.704593
0.687891
58
15.517241
18.374683
63
false
false
0
0
0
0
0
0
0.913793
false
false
4
fe07d1e56d2b64672565f8e7cf0941e2d7456818
22,522,808,516,720
b359a01e113ab3f9e2f5307e02ef9b8de5deef31
/samoa-api/src/main/java/com/yahoo/labs/samoa/streams/FileStream.java
c8004f5f4afad63c6001feb3f301c783ff59df69
[ "Apache-2.0" ]
permissive
suryasingh/samoa
https://github.com/suryasingh/samoa
e9085280815686051da0b28a6dd7c9381f2b1460
0fa1eea47cfa3cd8a59bee4d8149426ae0a11b37
refs/heads/master
2020-05-29T12:16:18.004000
2015-01-27T15:31:20
2015-01-27T15:31:20
34,695,938
1
0
null
true
2015-04-27T23:06:31
2015-04-27T23:06:31
2015-04-24T05:28:53
2015-01-27T15:31:20
6,459
0
0
0
null
null
null
package com.yahoo.labs.samoa.streams; /* * #%L * SAMOA * %% * Copyright (C) 2013 - 2014 Yahoo! Inc. * %% * 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. * #L% */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import com.github.javacliparser.ClassOption; import com.yahoo.labs.samoa.instances.Instances; import com.yahoo.labs.samoa.instances.InstancesHeader; import com.yahoo.labs.samoa.moa.core.InstanceExample; import com.yahoo.labs.samoa.moa.core.ObjectRepository; import com.yahoo.labs.samoa.moa.options.AbstractOptionHandler; import com.yahoo.labs.samoa.moa.streams.InstanceStream; import com.yahoo.labs.samoa.moa.tasks.TaskMonitor; import com.yahoo.labs.samoa.streams.fs.FileStreamSource; /** * InstanceStream for files * (Abstract class: subclass this class for different file formats) * @author Casey */ public abstract class FileStream extends AbstractOptionHandler implements InstanceStream { /** * */ private static final long serialVersionUID = 3028905554604259130L; public ClassOption sourceTypeOption = new ClassOption("sourceType", 's', "Source Type (HDFS, local FS)", FileStreamSource.class, "LocalFileStreamSource"); protected transient FileStreamSource fileSource; protected transient Reader fileReader; protected Instances instances; protected boolean hitEndOfStream; private boolean hasStarted; /* * Constructors */ public FileStream() { this.hitEndOfStream = false; } /* * implement InstanceStream */ @Override public InstancesHeader getHeader() { return new InstancesHeader(this.instances); } @Override public long estimatedRemainingInstances() { return -1; } @Override public boolean hasMoreInstances() { return !this.hitEndOfStream; } @Override public InstanceExample nextInstance() { if (this.getLastInstanceRead() == null) { readNextInstanceFromStream(); } InstanceExample prevInstance = this.getLastInstanceRead(); readNextInstanceFromStream(); return prevInstance; } @Override public boolean isRestartable() { return true; } @Override public void restart() { reset(); hasStarted = false; } protected void reset() { try { if (this.fileReader != null) this.fileReader.close(); fileSource.reset(); } catch (IOException ioe) { throw new RuntimeException("FileStream restart failed.", ioe); } if (!getNextFileReader()) { hitEndOfStream = true; throw new RuntimeException("FileStream is empty."); } this.instances = new Instances(this.fileReader, 1, -1); this.instances.setClassIndex(this.instances.numAttributes() - 1); } protected boolean getNextFileReader() { if (this.fileReader != null) try { this.fileReader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } InputStream inputStream = this.fileSource.getNextInputStream(); if (inputStream == null) return false; this.fileReader = new BufferedReader(new InputStreamReader(inputStream)); return true; } protected boolean readNextInstanceFromStream() { if (!hasStarted) { this.reset(); hasStarted = true; } while (true) { if (readNextInstanceFromFile()) return true; if (!getNextFileReader()) { this.hitEndOfStream = true; return false; } } } /** * Read next instance from the current file and assign it to * lastInstanceRead. * @return true if it was able to read next instance and * false if it was at the end of the file */ protected abstract boolean readNextInstanceFromFile(); protected abstract InstanceExample getLastInstanceRead(); @Override public void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { this.fileSource = sourceTypeOption.getValue(); this.hasStarted = false; } }
UTF-8
Java
4,626
java
FileStream.java
Java
[ { "context": " this class for different file formats)\n * @author Casey\n */\npublic abstract class FileStream extends Abst", "end": 1429, "score": 0.9993966817855835, "start": 1424, "tag": "NAME", "value": "Casey" } ]
null
[]
package com.yahoo.labs.samoa.streams; /* * #%L * SAMOA * %% * Copyright (C) 2013 - 2014 Yahoo! Inc. * %% * 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. * #L% */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import com.github.javacliparser.ClassOption; import com.yahoo.labs.samoa.instances.Instances; import com.yahoo.labs.samoa.instances.InstancesHeader; import com.yahoo.labs.samoa.moa.core.InstanceExample; import com.yahoo.labs.samoa.moa.core.ObjectRepository; import com.yahoo.labs.samoa.moa.options.AbstractOptionHandler; import com.yahoo.labs.samoa.moa.streams.InstanceStream; import com.yahoo.labs.samoa.moa.tasks.TaskMonitor; import com.yahoo.labs.samoa.streams.fs.FileStreamSource; /** * InstanceStream for files * (Abstract class: subclass this class for different file formats) * @author Casey */ public abstract class FileStream extends AbstractOptionHandler implements InstanceStream { /** * */ private static final long serialVersionUID = 3028905554604259130L; public ClassOption sourceTypeOption = new ClassOption("sourceType", 's', "Source Type (HDFS, local FS)", FileStreamSource.class, "LocalFileStreamSource"); protected transient FileStreamSource fileSource; protected transient Reader fileReader; protected Instances instances; protected boolean hitEndOfStream; private boolean hasStarted; /* * Constructors */ public FileStream() { this.hitEndOfStream = false; } /* * implement InstanceStream */ @Override public InstancesHeader getHeader() { return new InstancesHeader(this.instances); } @Override public long estimatedRemainingInstances() { return -1; } @Override public boolean hasMoreInstances() { return !this.hitEndOfStream; } @Override public InstanceExample nextInstance() { if (this.getLastInstanceRead() == null) { readNextInstanceFromStream(); } InstanceExample prevInstance = this.getLastInstanceRead(); readNextInstanceFromStream(); return prevInstance; } @Override public boolean isRestartable() { return true; } @Override public void restart() { reset(); hasStarted = false; } protected void reset() { try { if (this.fileReader != null) this.fileReader.close(); fileSource.reset(); } catch (IOException ioe) { throw new RuntimeException("FileStream restart failed.", ioe); } if (!getNextFileReader()) { hitEndOfStream = true; throw new RuntimeException("FileStream is empty."); } this.instances = new Instances(this.fileReader, 1, -1); this.instances.setClassIndex(this.instances.numAttributes() - 1); } protected boolean getNextFileReader() { if (this.fileReader != null) try { this.fileReader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } InputStream inputStream = this.fileSource.getNextInputStream(); if (inputStream == null) return false; this.fileReader = new BufferedReader(new InputStreamReader(inputStream)); return true; } protected boolean readNextInstanceFromStream() { if (!hasStarted) { this.reset(); hasStarted = true; } while (true) { if (readNextInstanceFromFile()) return true; if (!getNextFileReader()) { this.hitEndOfStream = true; return false; } } } /** * Read next instance from the current file and assign it to * lastInstanceRead. * @return true if it was able to read next instance and * false if it was at the end of the file */ protected abstract boolean readNextInstanceFromFile(); protected abstract InstanceExample getLastInstanceRead(); @Override public void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) { this.fileSource = sourceTypeOption.getValue(); this.hasStarted = false; } }
4,626
0.687203
0.679637
174
25.586206
23.178246
90
false
false
0
0
0
0
0
0
0.867816
false
false
4
0448aa15e0e7719523c072e2bededf332fc36a8b
9,723,805,985,806
c31546a1133885c0d03d9576538adca28beb3ed4
/src/com/amazon/algorithm/implementation/DesignerPDFViewer.java
1cb59f3f8464a16d0bae2a4925540ab3462ab789
[]
no_license
haokaibo/AmazonTest
https://github.com/haokaibo/AmazonTest
61bdb87383b14a8fe85d0196eda521042b30de9e
d6632b663823b5f744ee7d42fc7c392738348d61
refs/heads/master
2021-01-12T12:32:14.746000
2020-10-16T12:47:30
2020-10-16T12:47:30
72,543,149
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amazon.algorithm.implementation; import java.util.Scanner; /** * Created by kaibohao on 2016-12-25. */ public class DesignerPDFViewer { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = 26; int h[] = new int[n]; for (int h_i = 0; h_i < n; h_i++) { h[h_i] = in.nextInt(); } String word = in.next(); int maxHeight = 0; int wordWidth = 1; for (char c : word.toCharArray()) { int index = c - 'a'; int height = h[index]; if (height > maxHeight) { maxHeight = height; } } int area = word.length() * wordWidth * maxHeight; System.out.println(area); } }
UTF-8
Java
778
java
DesignerPDFViewer.java
Java
[ { "context": "ion;\n\nimport java.util.Scanner;\n\n/**\n * Created by kaibohao on 2016-12-25.\n */\npublic class DesignerPDFViewer", "end": 99, "score": 0.9993257522583008, "start": 91, "tag": "USERNAME", "value": "kaibohao" } ]
null
[]
package com.amazon.algorithm.implementation; import java.util.Scanner; /** * Created by kaibohao on 2016-12-25. */ public class DesignerPDFViewer { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = 26; int h[] = new int[n]; for (int h_i = 0; h_i < n; h_i++) { h[h_i] = in.nextInt(); } String word = in.next(); int maxHeight = 0; int wordWidth = 1; for (char c : word.toCharArray()) { int index = c - 'a'; int height = h[index]; if (height > maxHeight) { maxHeight = height; } } int area = word.length() * wordWidth * maxHeight; System.out.println(area); } }
778
0.503856
0.487147
29
25.827587
15.974266
57
false
false
0
0
0
0
0
0
0.551724
false
false
4
b35442c7bb3cd179d8fc08b2726fc8f2a265fd1b
10,385,230,967,049
9963591c69cd7f1b5bb6e7751b0fde6e9227d0bf
/src/main/java/com/fmatusiak/libraryapi/repository/TitleBookRepository.java
3ea7c47b4fdfa2a09259836b74d798a44e2ad9c1
[]
no_license
fmatusiak/library-rest-api
https://github.com/fmatusiak/library-rest-api
859839aa20e6fc6ca0e6808e40e6215ec1729a18
f8f87fb6b1e7ce81d989aa0ba2fafdf23b8988b7
refs/heads/master
2020-04-26T20:19:53.739000
2019-06-16T22:48:12
2019-06-16T22:48:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fmatusiak.libraryapi.repository; import com.fmatusiak.libraryapi.domain.TitleBook; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.Optional; public interface TitleBookRepository extends CrudRepository<TitleBook, Long> { @Override Optional<TitleBook> findById(Long id); @Override TitleBook save(TitleBook titleBook); @Override void delete(TitleBook titleBook); TitleBook findTitleBookByTitle(String title); List<TitleBook> findTitleBooksByAuthor(String author); }
UTF-8
Java
567
java
TitleBookRepository.java
Java
[]
null
[]
package com.fmatusiak.libraryapi.repository; import com.fmatusiak.libraryapi.domain.TitleBook; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.Optional; public interface TitleBookRepository extends CrudRepository<TitleBook, Long> { @Override Optional<TitleBook> findById(Long id); @Override TitleBook save(TitleBook titleBook); @Override void delete(TitleBook titleBook); TitleBook findTitleBookByTitle(String title); List<TitleBook> findTitleBooksByAuthor(String author); }
567
0.781305
0.781305
24
22.625
23.862125
78
false
false
0
0
0
0
0
0
0.458333
false
false
4
fb18db819ce6c85d7880604f126c800f26a28e94
35,923,106,475,333
38efe348c954f6c9b72f7e83763babe0d275595f
/src/main/java/org/wxh/topic/dao/IPictureDao.java
06d1648c359b9d509712ceda824d8b9ce9134dd9
[]
no_license
wuxiaohao/cms
https://github.com/wuxiaohao/cms
e28360291e0c7f87bde193e4e68a043e11f2e204
9f81e9c94419bd670196bea03f045cdce90e67e6
refs/heads/master
2021-01-21T04:27:34.198000
2015-12-24T06:29:05
2015-12-24T06:29:05
41,613,402
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.wxh.topic.dao; import java.util.List; import org.wxh.basic.dao.IBaseDao; import org.wxh.topic.model.Attachment; import org.wxh.topic.model.Picture; import org.wxh.topic.model.PictureTopic; public interface IPictureDao extends IBaseDao<Picture>{ /** * 获取某个图片 * @param tid 组图新闻idR * @return */ public List<Picture> listByPicTopic(int tid); /** * 删除某个组图新闻的所有图片 * @param tid 新闻图片id */ public void deleteByPicTopic(int tid); /** * 更新图片名称和图片序号 * @param pics 所有图片id * @param picNameOlds 所有图片名称 * @param ids */ public void updateNameAndSort(String[] picNameOlds, Integer[] pics); /** * 更新图片序号 * @param id 组图新闻的id * @param orders */ public void updateOrder(int id, int orders); }
UTF-8
Java
884
java
IPictureDao.java
Java
[]
null
[]
package org.wxh.topic.dao; import java.util.List; import org.wxh.basic.dao.IBaseDao; import org.wxh.topic.model.Attachment; import org.wxh.topic.model.Picture; import org.wxh.topic.model.PictureTopic; public interface IPictureDao extends IBaseDao<Picture>{ /** * 获取某个图片 * @param tid 组图新闻idR * @return */ public List<Picture> listByPicTopic(int tid); /** * 删除某个组图新闻的所有图片 * @param tid 新闻图片id */ public void deleteByPicTopic(int tid); /** * 更新图片名称和图片序号 * @param pics 所有图片id * @param picNameOlds 所有图片名称 * @param ids */ public void updateNameAndSort(String[] picNameOlds, Integer[] pics); /** * 更新图片序号 * @param id 组图新闻的id * @param orders */ public void updateOrder(int id, int orders); }
884
0.665796
0.665796
36
19.277779
17.379124
69
false
false
0
0
0
0
0
0
1.027778
false
false
4
294ab7399de147c3d8ccbede99a60922b9cc071a
22,505,628,691,516
0a5c90d755e1486c3a1ce3bf3eacf6a89c26d25a
/crm-notes/src/main/java/spire/crm/notes/orm/util/tables/Notes.java
69357a6664b7d2f995ecb6c6788e59df64b4f162
[]
no_license
Ayush1990/spire-services
https://github.com/Ayush1990/spire-services
11e420f7963728ffe72ec8936f4fffb59de1a11a
55079efc250ea17eac87fc3c4c779ff5114fb287
refs/heads/master
2016-08-17T20:39:46.031000
2016-08-05T13:08:11
2016-08-05T13:08:11
65,019,065
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * This class is generated by jOOQ */ package spire.crm.notes.orm.util.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import spire.crm.notes.orm.util.Keys; import spire.crm.notes.orm.util.NotesService; import spire.crm.notes.orm.util.tables.records.NotesRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.6.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Notes extends TableImpl<NotesRecord> { private static final long serialVersionUID = -1486719020; /** * The reference instance of <code>NOTES_SERVICE.NOTES</code> */ public static final Notes NOTES = new Notes(); /** * The class holding records for this type */ @Override public Class<NotesRecord> getRecordType() { return NotesRecord.class; } /** * The column <code>NOTES_SERVICE.NOTES.ID</code>. */ public final TableField<NotesRecord, byte[]> ID = createField("ID", org.jooq.impl.SQLDataType.BINARY.length(20).nullable(false), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.USER_ID</code>. */ public final TableField<NotesRecord, byte[]> USER_ID = createField("USER_ID", org.jooq.impl.SQLDataType.BINARY.length(20).nullable(false), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.ENTITY_ID</code>. */ public final TableField<NotesRecord, byte[]> ENTITY_ID = createField("ENTITY_ID", org.jooq.impl.SQLDataType.BINARY.length(20).nullable(false), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.NOTES_TITLE</code>. */ public final TableField<NotesRecord, String> NOTES_TITLE = createField("NOTES_TITLE", org.jooq.impl.SQLDataType.VARCHAR.length(100), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.NOTES_MSG</code>. */ public final TableField<NotesRecord, String> NOTES_MSG = createField("NOTES_MSG", org.jooq.impl.SQLDataType.VARCHAR.length(5000), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.CREATED_BY</code>. */ public final TableField<NotesRecord, byte[]> CREATED_BY = createField("CREATED_BY", org.jooq.impl.SQLDataType.BINARY.length(20), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.MODIFIED_BY</code>. */ public final TableField<NotesRecord, byte[]> MODIFIED_BY = createField("MODIFIED_BY", org.jooq.impl.SQLDataType.BINARY.length(20), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.CREATED_ON</code>. */ public final TableField<NotesRecord, Timestamp> CREATED_ON = createField("CREATED_ON", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaulted(true), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.MODIFIED_ON</code>. */ public final TableField<NotesRecord, Timestamp> MODIFIED_ON = createField("MODIFIED_ON", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaulted(true), this, ""); /** * Create a <code>NOTES_SERVICE.NOTES</code> table reference */ public Notes() { this("NOTES", null); } /** * Create an aliased <code>NOTES_SERVICE.NOTES</code> table reference */ public Notes(String alias) { this(alias, NOTES); } private Notes(String alias, Table<NotesRecord> aliased) { this(alias, aliased, null); } private Notes(String alias, Table<NotesRecord> aliased, Field<?>[] parameters) { super(alias, NotesService.NOTES_SERVICE, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public UniqueKey<NotesRecord> getPrimaryKey() { return Keys.KEY_NOTES_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<NotesRecord>> getKeys() { return Arrays.<UniqueKey<NotesRecord>>asList(Keys.KEY_NOTES_PRIMARY); } /** * {@inheritDoc} */ @Override public Notes as(String alias) { return new Notes(alias, this); } /** * Rename this table */ public Notes rename(String name) { return new Notes(name, null); } }
UTF-8
Java
4,066
java
Notes.java
Java
[]
null
[]
/** * This class is generated by jOOQ */ package spire.crm.notes.orm.util.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import spire.crm.notes.orm.util.Keys; import spire.crm.notes.orm.util.NotesService; import spire.crm.notes.orm.util.tables.records.NotesRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.6.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Notes extends TableImpl<NotesRecord> { private static final long serialVersionUID = -1486719020; /** * The reference instance of <code>NOTES_SERVICE.NOTES</code> */ public static final Notes NOTES = new Notes(); /** * The class holding records for this type */ @Override public Class<NotesRecord> getRecordType() { return NotesRecord.class; } /** * The column <code>NOTES_SERVICE.NOTES.ID</code>. */ public final TableField<NotesRecord, byte[]> ID = createField("ID", org.jooq.impl.SQLDataType.BINARY.length(20).nullable(false), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.USER_ID</code>. */ public final TableField<NotesRecord, byte[]> USER_ID = createField("USER_ID", org.jooq.impl.SQLDataType.BINARY.length(20).nullable(false), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.ENTITY_ID</code>. */ public final TableField<NotesRecord, byte[]> ENTITY_ID = createField("ENTITY_ID", org.jooq.impl.SQLDataType.BINARY.length(20).nullable(false), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.NOTES_TITLE</code>. */ public final TableField<NotesRecord, String> NOTES_TITLE = createField("NOTES_TITLE", org.jooq.impl.SQLDataType.VARCHAR.length(100), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.NOTES_MSG</code>. */ public final TableField<NotesRecord, String> NOTES_MSG = createField("NOTES_MSG", org.jooq.impl.SQLDataType.VARCHAR.length(5000), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.CREATED_BY</code>. */ public final TableField<NotesRecord, byte[]> CREATED_BY = createField("CREATED_BY", org.jooq.impl.SQLDataType.BINARY.length(20), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.MODIFIED_BY</code>. */ public final TableField<NotesRecord, byte[]> MODIFIED_BY = createField("MODIFIED_BY", org.jooq.impl.SQLDataType.BINARY.length(20), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.CREATED_ON</code>. */ public final TableField<NotesRecord, Timestamp> CREATED_ON = createField("CREATED_ON", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaulted(true), this, ""); /** * The column <code>NOTES_SERVICE.NOTES.MODIFIED_ON</code>. */ public final TableField<NotesRecord, Timestamp> MODIFIED_ON = createField("MODIFIED_ON", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaulted(true), this, ""); /** * Create a <code>NOTES_SERVICE.NOTES</code> table reference */ public Notes() { this("NOTES", null); } /** * Create an aliased <code>NOTES_SERVICE.NOTES</code> table reference */ public Notes(String alias) { this(alias, NOTES); } private Notes(String alias, Table<NotesRecord> aliased) { this(alias, aliased, null); } private Notes(String alias, Table<NotesRecord> aliased, Field<?>[] parameters) { super(alias, NotesService.NOTES_SERVICE, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public UniqueKey<NotesRecord> getPrimaryKey() { return Keys.KEY_NOTES_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<NotesRecord>> getKeys() { return Arrays.<UniqueKey<NotesRecord>>asList(Keys.KEY_NOTES_PRIMARY); } /** * {@inheritDoc} */ @Override public Notes as(String alias) { return new Notes(alias, this); } /** * Rename this table */ public Notes rename(String name) { return new Notes(name, null); } }
4,066
0.700689
0.69331
149
26.288591
37.803677
169
false
false
0
0
0
0
0
0
1.308725
false
false
4
8724ae899f93b85cdfd1d9f10e30e4f0046d74e5
13,769,665,172,166
c577f5380b4799b4db54722749cc33f9346eacc1
/BugSwarm/checkstyle-checkstyle-74845202/buggy_files/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java
2b6a5fa08c302d68055a26d23e5c603b8e3bac68
[]
no_license
tdurieux/BugSwarm-dissection
https://github.com/tdurieux/BugSwarm-dissection
55db683fd95f071ff818f9ca5c7e79013744b27b
ee6b57cfef2119523a083e82d902a6024e0d995a
refs/heads/master
2020-04-30T17:11:52.050000
2019-05-09T13:42:03
2019-05-09T13:42:03
176,972,414
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Arrays; import org.junit.Test; public class FileContentsTest { @Test public void testCppCommentIntersect() { // just to make UT coverage 100% FileContents o = new FileContents( FileText.fromLines(new File("filename"), Arrays.asList(" // "))); o.reportCppComment(1, 2); assertTrue(o.hasIntersectionWithComment(1, 5, 1, 6)); } }
UTF-8
Java
1,555
java
FileContentsTest.java
Java
[]
null
[]
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Arrays; import org.junit.Test; public class FileContentsTest { @Test public void testCppCommentIntersect() { // just to make UT coverage 100% FileContents o = new FileContents( FileText.fromLines(new File("filename"), Arrays.asList(" // "))); o.reportCppComment(1, 2); assertTrue(o.hasIntersectionWithComment(1, 5, 1, 6)); } }
1,555
0.645016
0.623794
40
37.875
29.394037
84
false
false
0
0
0
0
93
0.113183
0.625
false
false
4
3e06532e3fc332f1647428fc6c953851d44c6134
8,289,286,897,234
952324db466230d42deab20655025db23641954e
/app/src/main/java/west/code/recyclerparsequeryadapterexample/adapters/RecyclerParseQueryAdapter.java
9079d1b125857a9f733a3f3e781ef4c771d18e5e
[]
no_license
arturwest/RecyclerParseQueryAdapter
https://github.com/arturwest/RecyclerParseQueryAdapter
6a2befd4238da3363a6652f8ad30fd5434da46db
bdcf0a22f9ca8b5cb99274e5a23ccc3ee068fb9f
refs/heads/master
2020-04-06T03:37:56.302000
2016-07-24T09:12:19
2016-07-24T09:12:19
64,056,866
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package west.code.recyclerparsequeryadapterexample.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.parse.FindCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseImageView; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseQueryAdapter; import java.util.ArrayList; import java.util.List; import west.code.recyclerparsequeryadapterexample.R; import west.code.recyclerparsequeryadapterexample.helpers.Const; /** * Created by Artco on 23.07.2016. */ public class RecyclerParseQueryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public interface OnQueryLoadListener<ParseObject> { public void onLoading(); public void onLoaded(List<ParseObject> objects, Exception e); } private List<OnQueryLoadListener<ParseObject>> onQueryLoadListeners = new ArrayList<>(); int viewType; String className; ArrayList<ParseObject> items = new ArrayList<>(); Context context; private ParseQueryAdapter.QueryFactory<ParseObject> queryFactory; private int objectsPerPage = 25; private boolean paginationEnabled = true; private boolean hasNextPage = true; private int currentPage = 0; private List<List<ParseObject>> objectPages = new ArrayList<>(); public RecyclerParseQueryAdapter(Context context, int viewType, final String className, final String orderBy) { this.viewType = viewType; this.context = context; this.className = className; queryFactory = new ParseQueryAdapter.QueryFactory<ParseObject>() { @Override public ParseQuery<ParseObject> create() { ParseQuery<ParseObject> query = ParseQuery.getQuery(className); query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK); query.orderByAscending(orderBy); return query; } }; loadObjects(currentPage); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v; switch (viewType){ case Const.VIEW_TYPE_CITY_ITEM: v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.city_item, parent, false); return new CityViewHolder(v); case Const.VIEW_TYPE_CATEGORY_ITEM: v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.categories_item, parent, false); return new CategoriesViewHolder(v); default: return null; } } @Override public int getItemViewType(int position) { return viewType; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ParseObject object = getItem(position); switch (viewType){ case Const.VIEW_TYPE_CITY_ITEM: ((CityViewHolder)holder).cityName.setText(object.getString("name")); break; case Const.VIEW_TYPE_CATEGORY_ITEM: break; default: break; } } @Override public int getItemCount() { return items.size(); } public ParseObject getItem(int position){ return items.get(position); } public static class CategoriesViewHolder extends RecyclerView.ViewHolder { public ParseImageView image; public TextView text; public ImageView arrow; public CategoriesViewHolder(View v) { super(v); image = (ParseImageView) v.findViewById(R.id.categoriesImage); arrow = (ImageView)v.findViewById(R.id.categoriesArrow); text = (TextView)v.findViewById(R.id.categoriesName); } } public static class CityViewHolder extends RecyclerView.ViewHolder { public TextView cityName; public CityViewHolder(View v) { super(v); cityName = (TextView) v; } } private void loadObjects(final int page) { final ParseQuery<ParseObject> query = this.queryFactory.create(); if (this.objectsPerPage > 0 && this.paginationEnabled) { this.setPageOnQuery(page, query); } this.notifyOnLoadingListeners(); if (page >= objectPages.size()) { objectPages.add(page, new ArrayList<ParseObject>()); } query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> foundObjects, ParseException e) { if ((e != null) && ((e.getCode() == ParseException.CONNECTION_FAILED) || (e.getCode() != ParseException.CACHE_MISS))) { hasNextPage = true; } else if (foundObjects != null) { // Only advance the page, this prevents second call back from CACHE_THEN_NETWORK to // reset the page. if (page >= currentPage) { currentPage = page; // since we set limit == objectsPerPage + 1 hasNextPage = (foundObjects.size() > objectsPerPage); } if (paginationEnabled && foundObjects.size() > objectsPerPage) { // Remove the last object, fetched in order to tell us whether there was a "next page" foundObjects.remove(objectsPerPage); } List<ParseObject> currentPage = objectPages.get(page); currentPage.clear(); currentPage.addAll(foundObjects); syncObjectsWithPages(); // executes on the UI thread notifyDataSetChanged(); } notifyOnLoadedListeners(foundObjects, e); } }); } public void loadNextPage() { if (items.size() == 0) { loadObjects(0); } else { loadObjects(currentPage + 1); } } public void setObjectsPerPage(int objectsPerPage) { this.objectsPerPage = objectsPerPage; } private void syncObjectsWithPages() { items.clear(); for (List<ParseObject> pageOfObjects : objectPages) { items.addAll(pageOfObjects); } } protected void setPageOnQuery(int page, ParseQuery<ParseObject> query) { query.setLimit(this.objectsPerPage + 1); query.setSkip(page * this.objectsPerPage); } public void addOnQueryLoadListener(OnQueryLoadListener<ParseObject> listener) { this.onQueryLoadListeners.add(listener); } public void removeOnQueryLoadListener(OnQueryLoadListener<ParseObject> listener) { this.onQueryLoadListeners.remove(listener); } private void notifyOnLoadingListeners() { for (OnQueryLoadListener<ParseObject> listener : this.onQueryLoadListeners) { listener.onLoading(); } } private void notifyOnLoadedListeners(List<ParseObject> objects, Exception e) { for (OnQueryLoadListener<ParseObject> listener : this.onQueryLoadListeners) { listener.onLoaded(objects, e); } } }
UTF-8
Java
7,615
java
RecyclerParseQueryAdapter.java
Java
[ { "context": "yadapterexample.helpers.Const;\n\n\n/**\n * Created by Artco on 23.07.2016.\n */\npublic class RecyclerParseQuer", "end": 712, "score": 0.6207482814788818, "start": 707, "tag": "USERNAME", "value": "Artco" } ]
null
[]
package west.code.recyclerparsequeryadapterexample.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.parse.FindCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseImageView; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseQueryAdapter; import java.util.ArrayList; import java.util.List; import west.code.recyclerparsequeryadapterexample.R; import west.code.recyclerparsequeryadapterexample.helpers.Const; /** * Created by Artco on 23.07.2016. */ public class RecyclerParseQueryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public interface OnQueryLoadListener<ParseObject> { public void onLoading(); public void onLoaded(List<ParseObject> objects, Exception e); } private List<OnQueryLoadListener<ParseObject>> onQueryLoadListeners = new ArrayList<>(); int viewType; String className; ArrayList<ParseObject> items = new ArrayList<>(); Context context; private ParseQueryAdapter.QueryFactory<ParseObject> queryFactory; private int objectsPerPage = 25; private boolean paginationEnabled = true; private boolean hasNextPage = true; private int currentPage = 0; private List<List<ParseObject>> objectPages = new ArrayList<>(); public RecyclerParseQueryAdapter(Context context, int viewType, final String className, final String orderBy) { this.viewType = viewType; this.context = context; this.className = className; queryFactory = new ParseQueryAdapter.QueryFactory<ParseObject>() { @Override public ParseQuery<ParseObject> create() { ParseQuery<ParseObject> query = ParseQuery.getQuery(className); query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK); query.orderByAscending(orderBy); return query; } }; loadObjects(currentPage); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v; switch (viewType){ case Const.VIEW_TYPE_CITY_ITEM: v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.city_item, parent, false); return new CityViewHolder(v); case Const.VIEW_TYPE_CATEGORY_ITEM: v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.categories_item, parent, false); return new CategoriesViewHolder(v); default: return null; } } @Override public int getItemViewType(int position) { return viewType; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ParseObject object = getItem(position); switch (viewType){ case Const.VIEW_TYPE_CITY_ITEM: ((CityViewHolder)holder).cityName.setText(object.getString("name")); break; case Const.VIEW_TYPE_CATEGORY_ITEM: break; default: break; } } @Override public int getItemCount() { return items.size(); } public ParseObject getItem(int position){ return items.get(position); } public static class CategoriesViewHolder extends RecyclerView.ViewHolder { public ParseImageView image; public TextView text; public ImageView arrow; public CategoriesViewHolder(View v) { super(v); image = (ParseImageView) v.findViewById(R.id.categoriesImage); arrow = (ImageView)v.findViewById(R.id.categoriesArrow); text = (TextView)v.findViewById(R.id.categoriesName); } } public static class CityViewHolder extends RecyclerView.ViewHolder { public TextView cityName; public CityViewHolder(View v) { super(v); cityName = (TextView) v; } } private void loadObjects(final int page) { final ParseQuery<ParseObject> query = this.queryFactory.create(); if (this.objectsPerPage > 0 && this.paginationEnabled) { this.setPageOnQuery(page, query); } this.notifyOnLoadingListeners(); if (page >= objectPages.size()) { objectPages.add(page, new ArrayList<ParseObject>()); } query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> foundObjects, ParseException e) { if ((e != null) && ((e.getCode() == ParseException.CONNECTION_FAILED) || (e.getCode() != ParseException.CACHE_MISS))) { hasNextPage = true; } else if (foundObjects != null) { // Only advance the page, this prevents second call back from CACHE_THEN_NETWORK to // reset the page. if (page >= currentPage) { currentPage = page; // since we set limit == objectsPerPage + 1 hasNextPage = (foundObjects.size() > objectsPerPage); } if (paginationEnabled && foundObjects.size() > objectsPerPage) { // Remove the last object, fetched in order to tell us whether there was a "next page" foundObjects.remove(objectsPerPage); } List<ParseObject> currentPage = objectPages.get(page); currentPage.clear(); currentPage.addAll(foundObjects); syncObjectsWithPages(); // executes on the UI thread notifyDataSetChanged(); } notifyOnLoadedListeners(foundObjects, e); } }); } public void loadNextPage() { if (items.size() == 0) { loadObjects(0); } else { loadObjects(currentPage + 1); } } public void setObjectsPerPage(int objectsPerPage) { this.objectsPerPage = objectsPerPage; } private void syncObjectsWithPages() { items.clear(); for (List<ParseObject> pageOfObjects : objectPages) { items.addAll(pageOfObjects); } } protected void setPageOnQuery(int page, ParseQuery<ParseObject> query) { query.setLimit(this.objectsPerPage + 1); query.setSkip(page * this.objectsPerPage); } public void addOnQueryLoadListener(OnQueryLoadListener<ParseObject> listener) { this.onQueryLoadListeners.add(listener); } public void removeOnQueryLoadListener(OnQueryLoadListener<ParseObject> listener) { this.onQueryLoadListeners.remove(listener); } private void notifyOnLoadingListeners() { for (OnQueryLoadListener<ParseObject> listener : this.onQueryLoadListeners) { listener.onLoading(); } } private void notifyOnLoadedListeners(List<ParseObject> objects, Exception e) { for (OnQueryLoadListener<ParseObject> listener : this.onQueryLoadListeners) { listener.onLoaded(objects, e); } } }
7,615
0.611031
0.608667
262
28.064886
27.667044
115
false
false
0
0
0
0
0
0
0.427481
false
false
14
8c8a6124575cd15ccbaa6fad2498a216afbfe764
23,055,384,462,903
12139fa9355415551468ba0735f1353452c620b9
/qtz-ht-session-service/src/main/java/com/qtz/ht/session/service/ht/user/dao/impl/HtBusinessDaoImpl.java
e879646b891346d70904d39397e23d683adcb642
[]
no_license
moutainhigh/upgrade-1
https://github.com/moutainhigh/upgrade-1
1133cefa8beff9b6b65605c237dfd9649214afc5
999a158446b4f86079518f6cc4fe0c241eec6b1f
refs/heads/master
2021-06-04T08:04:48.960000
2016-08-30T10:14:27
2016-08-30T10:14:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qtz.ht.session.service.ht.user.dao.impl; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.stereotype.Repository; import com.qtz.base.dao.impl.MyBaitsDaoImpl; import com.qtz.base.exception.DaoException; import com.qtz.ht.session.service.ht.user.dao.HtBusinessDao; import com.qtz.ht.session.spi.user.vo.HtBusiness; /** * <p>Title:HtBusinessDaoImpl</p> * <p>Description:商户信息DAO实现类</p> * <p>Copyright: Copyright (c) 2016</p> * <p>Company: 深圳市好实再商贸有限公司</p> * @author tanglijun * @version v1.0 2016-01-25 */ @Repository("htBusinessDaoImpl") public class HtBusinessDaoImpl extends MyBaitsDaoImpl<HtBusiness,Long> implements HtBusinessDao { /**MYBatis命名空间名*/ private static String preName = HtBusinessDao.class.getName(); /** * 【取得】MYBatis命名空间名 * @return MYBatis命名空间名 */ @Override protected String getPreName() { return preName; } @Override public List<HtBusiness> findListByBusinessesId(Set<Long> idS) throws DaoException { if (idS == null || idS.isEmpty()) { return null; } List<Long> list = new ArrayList<>(); list.addAll(idS); return getMyBaitsTemplate().getSqlSession().selectList(getPreName() + ".findListByBusinessesId", list.toArray()); } }
UTF-8
Java
1,358
java
HtBusinessDaoImpl.java
Java
[ { "context": "6</p>\r\n * <p>Company: 深圳市好实再商贸有限公司</p>\r\n * @author tanglijun\r\n * @version v1.0 2016-01-25\r\n */\r\n@Repository(\"h", "end": 557, "score": 0.9986041188240051, "start": 548, "tag": "USERNAME", "value": "tanglijun" } ]
null
[]
package com.qtz.ht.session.service.ht.user.dao.impl; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.stereotype.Repository; import com.qtz.base.dao.impl.MyBaitsDaoImpl; import com.qtz.base.exception.DaoException; import com.qtz.ht.session.service.ht.user.dao.HtBusinessDao; import com.qtz.ht.session.spi.user.vo.HtBusiness; /** * <p>Title:HtBusinessDaoImpl</p> * <p>Description:商户信息DAO实现类</p> * <p>Copyright: Copyright (c) 2016</p> * <p>Company: 深圳市好实再商贸有限公司</p> * @author tanglijun * @version v1.0 2016-01-25 */ @Repository("htBusinessDaoImpl") public class HtBusinessDaoImpl extends MyBaitsDaoImpl<HtBusiness,Long> implements HtBusinessDao { /**MYBatis命名空间名*/ private static String preName = HtBusinessDao.class.getName(); /** * 【取得】MYBatis命名空间名 * @return MYBatis命名空间名 */ @Override protected String getPreName() { return preName; } @Override public List<HtBusiness> findListByBusinessesId(Set<Long> idS) throws DaoException { if (idS == null || idS.isEmpty()) { return null; } List<Long> list = new ArrayList<>(); list.addAll(idS); return getMyBaitsTemplate().getSqlSession().selectList(getPreName() + ".findListByBusinessesId", list.toArray()); } }
1,358
0.719189
0.708268
41
29.317074
26.135145
115
false
false
0
0
0
0
0
0
1.146341
false
false
14
95ab33c38eb2ed3fa9db6ffe75bc787ed2d8d354
24,807,731,108,492
fc3f1fd5eb3897f56a0fcb1c6f065140eba154a2
/app/src/main/java/com/widas/demo_ac/common/SessionManager.java
c3de636a243015056e66c7896284a1fca57dbe31
[]
no_license
Kundan-Android/AndroidAccessControlApp
https://github.com/Kundan-Android/AndroidAccessControlApp
9b1ff0e38c13df37c96e61668022204b75613243
d021c3b5391534832c91b3983e1b49b09090f3f0
refs/heads/master
2022-12-21T21:09:09.266000
2020-09-03T10:28:58
2020-09-03T10:28:58
292,538,293
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.widas.demo_ac.common; import android.content.Context; import android.content.SharedPreferences; import com.example.cidaasv2.Service.Entity.UserinfoEntity; import com.google.gson.Gson; public class SessionManager { private static final String PREFS_NAME = "accessControlPrefsFile"; private static final String KEY_ACCESS_TOKEN = "access_token"; // Shared Preferences SharedPreferences preferences; // Editor for Shared preferences SharedPreferences.Editor editor; //Application context Context context; public SessionManager(Context context) { this.context = context; preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); editor = preferences.edit(); editor.apply(); } public String getAccessToken() { return preferences.getString(KEY_ACCESS_TOKEN, ""); } public void setAccessToken(String accessToken) { editor.putString(KEY_ACCESS_TOKEN, accessToken); editor.apply(); } public void setUserDetails(UserinfoEntity userinfoEntity){ Gson gson = new Gson(); String str = gson.toJson(userinfoEntity); editor.putString("UserDetails",str); editor.apply(); } public UserinfoEntity getUserDetails(){ Gson gson = new Gson(); String json = preferences.getString("UserDetails", ""); UserinfoEntity obj = gson.fromJson(json, UserinfoEntity.class); return obj; } }
UTF-8
Java
1,491
java
SessionManager.java
Java
[ { "context": " private static final String KEY_ACCESS_TOKEN = \"access_token\";\n\n // Shared Preferences\n SharedPref", "end": 359, "score": 0.5766058564186096, "start": 353, "tag": "KEY", "value": "access" } ]
null
[]
package com.widas.demo_ac.common; import android.content.Context; import android.content.SharedPreferences; import com.example.cidaasv2.Service.Entity.UserinfoEntity; import com.google.gson.Gson; public class SessionManager { private static final String PREFS_NAME = "accessControlPrefsFile"; private static final String KEY_ACCESS_TOKEN = "access_token"; // Shared Preferences SharedPreferences preferences; // Editor for Shared preferences SharedPreferences.Editor editor; //Application context Context context; public SessionManager(Context context) { this.context = context; preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); editor = preferences.edit(); editor.apply(); } public String getAccessToken() { return preferences.getString(KEY_ACCESS_TOKEN, ""); } public void setAccessToken(String accessToken) { editor.putString(KEY_ACCESS_TOKEN, accessToken); editor.apply(); } public void setUserDetails(UserinfoEntity userinfoEntity){ Gson gson = new Gson(); String str = gson.toJson(userinfoEntity); editor.putString("UserDetails",str); editor.apply(); } public UserinfoEntity getUserDetails(){ Gson gson = new Gson(); String json = preferences.getString("UserDetails", ""); UserinfoEntity obj = gson.fromJson(json, UserinfoEntity.class); return obj; } }
1,491
0.686787
0.686117
52
27.673077
23.461689
85
false
false
0
0
0
0
0
0
0.596154
false
false
14
b5586b591b69a6b52585c1fa886bb65b71cd6c7d
28,887,950,055,382
41e896939220c0c6802e851fb0751ed3987a2329
/LeetCode/src/DP/爬楼梯.java
e80b417e5670491bf64fabec5da2894d1795aa23
[]
no_license
czjczj/LeetCode
https://github.com/czjczj/LeetCode
2ddbee695d8c3767063186c41ef086939ad8604b
46588f859351d806b28754f83ea4e23d78757d7f
refs/heads/master
2020-04-26T17:17:48.635000
2019-06-28T03:34:42
2019-06-28T03:34:42
173,563,242
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DP; /** * @author czj * @date 2019��2��25�� * ������������¥�ݡ���Ҫ n ������ܵ���¥���� ÿ��������� 1 �� 2 ��̨�ס����ж����ֲ�ͬ�ķ�����������¥���أ� dp[i] ��ʾ��į���ߵ�¥���IJ�ͬ�߷� */ public class 爬楼梯 { public static void main(String[] args) { System.out.println(climbStairs(2)); } public static int climbStairs(int n) { int[] dp = new int[n]; for (int i = 0; i < dp.length; i++) { dp[i] = -1; } int res = dfs(dp,0,n); return res; } private static int dfs(int[] dp, int i, int n) { if(i == n) return 1; if(i > n) return 0; if(dp[i] != -1) return dp[i]; int ans = 0; ans += dfs(dp,i+1,n); ans += dfs(dp,i+2,n); dp[i] = ans; return ans; } }
UTF-8
Java
894
java
爬楼梯.java
Java
[ { "context": "package DP;\n\n/**\n * @author czj\n * @date 2019��2��25��\n * ������������¥�ݡ���Ҫ n", "end": 31, "score": 0.9996320009231567, "start": 28, "tag": "USERNAME", "value": "czj" } ]
null
[]
package DP; /** * @author czj * @date 2019��2��25�� * ������������¥�ݡ���Ҫ n ������ܵ���¥���� ÿ��������� 1 �� 2 ��̨�ס����ж����ֲ�ͬ�ķ�����������¥���أ� dp[i] ��ʾ��į���ߵ�¥���IJ�ͬ�߷� */ public class 爬楼梯 { public static void main(String[] args) { System.out.println(climbStairs(2)); } public static int climbStairs(int n) { int[] dp = new int[n]; for (int i = 0; i < dp.length; i++) { dp[i] = -1; } int res = dfs(dp,0,n); return res; } private static int dfs(int[] dp, int i, int n) { if(i == n) return 1; if(i > n) return 0; if(dp[i] != -1) return dp[i]; int ans = 0; ans += dfs(dp,i+1,n); ans += dfs(dp,i+2,n); dp[i] = ans; return ans; } }
894
0.458755
0.431259
32
20.59375
15.140714
55
false
false
0
0
0
0
0
0
1.875
false
false
14
7a46b830086b9cd91c1144fa6f87f91379eb60e2
14,963,666,076,474
c8ad7d7255ea4e4c6ebbb241ec9d528adf3c35a4
/src/main/java/com/fuwu/blog/service/PrivilegeService.java
f16fbfc1ec7e40d855f961ec848c91ca06495c6b
[]
no_license
fengwfe/blog
https://github.com/fengwfe/blog
5114bec982977643dfd1b22143724c63ccdcd9f0
bd6d941632e4c68573fc5f91c7857d6a6a96eec3
refs/heads/master
2021-01-14T07:19:44.781000
2020-02-28T11:15:14
2020-02-28T11:15:14
242,637,651
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fuwu.blog.service; import java.util.List; import java.util.Map; import com.fuwu.blog.dto.param.CreatePrivilegeDTO; import com.fuwu.blog.dto.param.FetchByIdDTO; import com.fuwu.blog.dto.param.FetchPrivilegeDTO; import com.fuwu.blog.dto.param.UpdatePrivilegeDTO; import com.fuwu.blog.dto.response.PrivilegeDTO; import com.fuwu.blog.dto.response.RestResourceDTO; import com.fuwu.blog.model.entity.Privilege; public interface PrivilegeService extends BaseCRUDService<Privilege,CreatePrivilegeDTO,UpdatePrivilegeDTO,FetchPrivilegeDTO,PrivilegeDTO>{ public Map<RestResourceDTO, List<String>> fetchResourcePrivilegeMap(); public List<PrivilegeDTO> fetchByRoleId(FetchByIdDTO roleId); public List<PrivilegeDTO> fetchByRestResourceId(FetchByIdDTO restResourceId); }
UTF-8
Java
776
java
PrivilegeService.java
Java
[]
null
[]
package com.fuwu.blog.service; import java.util.List; import java.util.Map; import com.fuwu.blog.dto.param.CreatePrivilegeDTO; import com.fuwu.blog.dto.param.FetchByIdDTO; import com.fuwu.blog.dto.param.FetchPrivilegeDTO; import com.fuwu.blog.dto.param.UpdatePrivilegeDTO; import com.fuwu.blog.dto.response.PrivilegeDTO; import com.fuwu.blog.dto.response.RestResourceDTO; import com.fuwu.blog.model.entity.Privilege; public interface PrivilegeService extends BaseCRUDService<Privilege,CreatePrivilegeDTO,UpdatePrivilegeDTO,FetchPrivilegeDTO,PrivilegeDTO>{ public Map<RestResourceDTO, List<String>> fetchResourcePrivilegeMap(); public List<PrivilegeDTO> fetchByRoleId(FetchByIdDTO roleId); public List<PrivilegeDTO> fetchByRestResourceId(FetchByIdDTO restResourceId); }
776
0.841495
0.841495
19
39.842106
33.764297
138
false
false
0
0
0
0
0
0
1.105263
false
false
14
a2dc047eccaa64e3428efe3faae4ebae3edde581
14,963,666,077,224
7f195c508f2603bd40be2a5b2b42dba442040ecb
/src/main/java/cn/skylarkai/sdk/https/HttpsContext.java
5669f0793e66679f5720f1cd480f2f1368860588
[]
no_license
skylarkai/erqi-sdk
https://github.com/skylarkai/erqi-sdk
fe75a358e8e7f90f698399226b96305088e77d90
9fe9c54779ac98083d9861e066548c6d8321f851
refs/heads/master
2022-10-25T15:56:32.811000
2019-06-17T06:14:59
2019-06-17T06:14:59
164,776,435
0
0
null
false
2022-10-12T20:26:14
2019-01-09T03:02:19
2019-06-17T06:15:01
2022-10-12T20:26:11
42
0
0
4
Java
false
false
package cn.skylarkai.sdk.https; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; /** * httpsContext * * @author chuhl */ public class HttpsContext { public SSLContext HttpsContext() { SSLContext sc=null; try { sc = SSLContext.getInstance("TLS"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; sc.init( null, new TrustManager[] {trustManager}, null ); }catch (Exception e){ } return sc; } }
UTF-8
Java
1,389
java
HttpsContext.java
Java
[ { "context": "icateException;\n\n/**\n * httpsContext\n *\n * @author chuhl\n */\npublic class HttpsContext {\n\n public SSLCo", "end": 228, "score": 0.9996044635772705, "start": 223, "tag": "USERNAME", "value": "chuhl" } ]
null
[]
package cn.skylarkai.sdk.https; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; /** * httpsContext * * @author chuhl */ public class HttpsContext { public SSLContext HttpsContext() { SSLContext sc=null; try { sc = SSLContext.getInstance("TLS"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; sc.init( null, new TrustManager[] {trustManager}, null ); }catch (Exception e){ } return sc; } }
1,389
0.574088
0.553984
44
29.522728
25.867222
89
false
false
0
0
0
0
0
0
0.340909
false
false
14
f03292fb6a5695cc30f69d42ad48d567137197a5
19,945,828,136,475
271ca0f86d3930d791ec19c6b3322edb2be91bc8
/src/main/java/org/py/model/Bigtable.java
ae5f183cb0bbfa004e610425554ce4a44c6042d0
[]
no_license
powerfocus/spring-boot-JAVA-SE
https://github.com/powerfocus/spring-boot-JAVA-SE
7e3717295df94d04a891665bb5114744137f227a
65a7eeef06dd67f52dc7b7d5e7bfc00bd4543094
refs/heads/master
2020-04-14T23:50:10.262000
2019-01-06T03:00:46
2019-01-06T03:00:46
164,218,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.py.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.io.Serializable; @Entity public class Bigtable implements Serializable { private static final long serialVersionUID = 9091144996604066944L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private Double num; public Bigtable() { } public Bigtable(Long id, String title, Double num) { this.id = id; this.title = title; this.num = num; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Double getNum() { return num; } public void setNum(Double num) { this.num = num; } @Override public String toString() { return "Bigtable{" + "id=" + id + ", title='" + title + '\'' + ", num=" + num + '}'; } }
UTF-8
Java
1,213
java
Bigtable.java
Java
[]
null
[]
package org.py.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.io.Serializable; @Entity public class Bigtable implements Serializable { private static final long serialVersionUID = 9091144996604066944L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private Double num; public Bigtable() { } public Bigtable(Long id, String title, Double num) { this.id = id; this.title = title; this.num = num; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Double getNum() { return num; } public void setNum(Double num) { this.num = num; } @Override public String toString() { return "Bigtable{" + "id=" + id + ", title='" + title + '\'' + ", num=" + num + '}'; } }
1,213
0.576257
0.560594
59
19.559322
16.513243
70
false
false
0
0
0
0
0
0
0.40678
false
false
14
b37652661034b90d12ed087169dc3c1a2288e567
22,660,247,476,873
7429c8641d73ed50b75f2f1356906cfd66cdb2ea
/src/com/kh/tc/category/model/vo/Category.java
7cd66d098ccadc237882b41088105a2205968029
[]
no_license
bell204/jspTeamPro
https://github.com/bell204/jspTeamPro
5c9a1eb345f1c2911af16912991af2157c61582c
c9d69687be2d0d51ed23d2f12e3f405dbf984c8e
refs/heads/master
2020-03-08T08:55:06.437000
2018-04-04T09:47:24
2018-04-04T09:47:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kh.tc.category.model.vo; public class Category implements java.io.Serializable { private int cate_code; private String cate1; private String cate2; private String cate3; private String cate4; public Category() { } public Category(int cate_code, String cate1, String cate2, String cate3, String cate4) { super(); this.cate_code = cate_code; this.cate1 = cate1; this.cate2 = cate2; this.cate3 = cate3; this.cate4 = cate4; } public int getCate_code() { return cate_code; } public void setCate_code(int cate_code) { this.cate_code = cate_code; } public String getCate1() { return cate1; } public void setCate1(String cate1) { this.cate1 = cate1; } public String getCate2() { return cate2; } public void setCate2(String cate2) { this.cate2 = cate2; } public String getCate3() { return cate3; } public void setCate3(String cate3) { this.cate3 = cate3; } public String getCate4() { return cate4; } public void setCate4(String cate4) { this.cate4 = cate4; } @Override public String toString() { return "Category [cate_code=" + cate_code + ", cate1=" + cate1 + ", cate2=" + cate2 + ", cate3=" + cate3 + ", cate4=" + cate4 + "]"; } }
UTF-8
Java
1,221
java
Category.java
Java
[]
null
[]
package com.kh.tc.category.model.vo; public class Category implements java.io.Serializable { private int cate_code; private String cate1; private String cate2; private String cate3; private String cate4; public Category() { } public Category(int cate_code, String cate1, String cate2, String cate3, String cate4) { super(); this.cate_code = cate_code; this.cate1 = cate1; this.cate2 = cate2; this.cate3 = cate3; this.cate4 = cate4; } public int getCate_code() { return cate_code; } public void setCate_code(int cate_code) { this.cate_code = cate_code; } public String getCate1() { return cate1; } public void setCate1(String cate1) { this.cate1 = cate1; } public String getCate2() { return cate2; } public void setCate2(String cate2) { this.cate2 = cate2; } public String getCate3() { return cate3; } public void setCate3(String cate3) { this.cate3 = cate3; } public String getCate4() { return cate4; } public void setCate4(String cate4) { this.cate4 = cate4; } @Override public String toString() { return "Category [cate_code=" + cate_code + ", cate1=" + cate1 + ", cate2=" + cate2 + ", cate3=" + cate3 + ", cate4=" + cate4 + "]"; } }
1,221
0.663391
0.624079
68
16.955883
19.608997
106
false
false
0
0
0
0
0
0
1.485294
false
false
14
8366372574a4266f60ac1197fd2325ff8f83117b
33,148,557,596,994
4aa2055995e1704a577e8436926c6c04b69a7fda
/src/Chapter6/ArrayListDemo.java
590f2bae3e163eb4b5700f1483bfa5b62c798945
[]
no_license
Hasnake/HeadFirstJava
https://github.com/Hasnake/HeadFirstJava
a055808a07b06aca13104939e451525797ab9489
5e97be8346ec4b53a91a14f92d2b5f077055b85a
refs/heads/master
2020-03-11T12:45:23.199000
2018-06-25T17:55:04
2018-06-25T17:55:04
130,006,265
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Chapter6; import java.util.ArrayList; public class ArrayListDemo { public static void main(String []Args){ // create an empty array list with an initial capacity ArrayList<Integer> myList = new ArrayList<Integer>(5); // use add() method to add elements in the list myList.add(15); myList.add(22); myList.add(30); myList.add(40); myList.add(2,25);//Add: adding element 25 at third position myList.remove(3);//Remove:removing element index at position boolean isIn=myList.contains(15);//Contains:Find out if it conatins something,it returns true or false. boolean isempty=myList.isEmpty();//isEmpty:Find out if the list is empty or not,it returns true or false. int indexofmynum=myList.indexOf(22);//IndexOf:Findout the index of an object in the arrayList. // let us print all the elements available in list for (Integer number : myList) { System.out.println("Number = " + number); } System.out.println("The size of myList array is :"+myList.size()); System.out.println("is my number in the list :"+isIn); System.out.println("is my list empty :"+isempty); System.out.println("index of my number in the list is :"+indexofmynum); } } // ArrayList<Egg> myList=new ArrayList<Egg>(); // Egg s=new Egg(); // myList.add(s); // Egg b=new Egg(); // myList.add(b); // int theSize=myList.size(); // System.out.println(theSize); // } //}
UTF-8
Java
1,572
java
ArrayListDemo.java
Java
[]
null
[]
package Chapter6; import java.util.ArrayList; public class ArrayListDemo { public static void main(String []Args){ // create an empty array list with an initial capacity ArrayList<Integer> myList = new ArrayList<Integer>(5); // use add() method to add elements in the list myList.add(15); myList.add(22); myList.add(30); myList.add(40); myList.add(2,25);//Add: adding element 25 at third position myList.remove(3);//Remove:removing element index at position boolean isIn=myList.contains(15);//Contains:Find out if it conatins something,it returns true or false. boolean isempty=myList.isEmpty();//isEmpty:Find out if the list is empty or not,it returns true or false. int indexofmynum=myList.indexOf(22);//IndexOf:Findout the index of an object in the arrayList. // let us print all the elements available in list for (Integer number : myList) { System.out.println("Number = " + number); } System.out.println("The size of myList array is :"+myList.size()); System.out.println("is my number in the list :"+isIn); System.out.println("is my list empty :"+isempty); System.out.println("index of my number in the list is :"+indexofmynum); } } // ArrayList<Egg> myList=new ArrayList<Egg>(); // Egg s=new Egg(); // myList.add(s); // Egg b=new Egg(); // myList.add(b); // int theSize=myList.size(); // System.out.println(theSize); // } //}
1,572
0.618321
0.605598
53
28.622641
31.317141
113
false
false
0
0
0
0
0
0
0.509434
false
false
14
468b796ac17c0d813d0a36ef496eb0c4af978105
16,758,962,410,212
509ce8da5b8fae7fe0bcbe2a745eae3eac2982c6
/Stockkeeper/src/main/java/stockkeeper/gui/OpenOverviewMenuEvent.java
deff6ade37d547d4a15c8b1c071ae8f94a4e3c86
[ "BSD-3-Clause" ]
permissive
FreyaFreed/Stockkeeper
https://github.com/FreyaFreed/Stockkeeper
c3ae9f45834b1bbf9dd378671f7955fcdeb17277
4db9358c081b9649334dbf40e47cd6d493511a37
refs/heads/master
2021-05-04T04:56:42.428000
2017-06-18T01:15:29
2017-06-18T01:15:29
70,904,283
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stockkeeper.gui; import java.util.List; import net.minecraftforge.fml.common.eventhandler.Event; import stockkeeper.data.Stack; public class OpenOverviewMenuEvent extends Event { public List<Stack> stacks; public OpenOverviewMenuEvent(List<Stack> stacks) { super(); this.stacks = stacks; } }
UTF-8
Java
331
java
OpenOverviewMenuEvent.java
Java
[]
null
[]
package stockkeeper.gui; import java.util.List; import net.minecraftforge.fml.common.eventhandler.Event; import stockkeeper.data.Stack; public class OpenOverviewMenuEvent extends Event { public List<Stack> stacks; public OpenOverviewMenuEvent(List<Stack> stacks) { super(); this.stacks = stacks; } }
331
0.731118
0.731118
17
17.470589
19.360718
56
false
false
0
0
0
0
0
0
0.882353
false
false
14
1499ab6ef1d0f4301161a9e1bb3b742575629a37
28,802,050,687,655
d9338e2ab0aca7b005212046da75e10fbd8904c9
/src/backup.java
9eeb53379b6e70dbdc0cccffb5a3256969d5c8a1
[]
no_license
mohanck/Internet-Banking-System
https://github.com/mohanck/Internet-Banking-System
e4de7281fe9760579fa562c712786f359ddcf849
b68a684b1e2492c58d86d55b9f544c28697e0510
refs/heads/master
2021-01-10T06:06:11.298000
2017-03-08T19:19:48
2017-03-08T19:19:48
54,296,328
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.*; import java.sql.*; /** * Servlet implementation class for Servlet: backup * */ public class backup extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public backup() { super(); } Connection con = null; /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub int rows_exported; String msg_retrieval = null; String msg_removal = null; String sqlcode = null; String msg = null; CallableStatement callStmt1 = null; ResultSet rs1 = null; PreparedStatement stmt1 = null; ResultSet rs2 = null; CallableStatement callStmt2 = null; try { // initialize DB2Driver and establish database connection. Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance(); con = DriverManager.getConnection("jdbc:db2:IBANK"); System.out.println("HOW TO PERFORM EXPORT USING ADMIN_CMD.\n"); // prepare the CALL statement for OUT_LANGUAGE String sql = "CALL SYSPROC.ADMIN_CMD(?)"; callStmt1 = con.prepareCall(sql); String param = "export to D://org_ex1.ixf "; param = param + "of ixf messages on server select * from system.usacc" ; // set the imput parameter callStmt1.setString(1, param); System.out.println("CALL ADMIN_CMD('" + param + "')"); // execute export by calling ADMIN_CMD callStmt1.execute(); rs1 = callStmt1.getResultSet(); // retrieve the resultset if( rs1.next()) { // the numbers of rows exported rows_exported = rs1.getInt(1); // retrieve the select stmt for message retrival // containing SYSPROC.ADMIN_GET_MSGS msg_retrieval = rs1.getString(2); // retrive the stmt for message cleanup // containing CALL of SYSPROC.ADMIN_REMOVE_MSGS msg_removal = rs1.getString(3); // display the output System.out.println("Total number of rows exported : " + rows_exported); System.out.println("SQL for retrieving the messages: " + msg_retrieval); System.out.println("SQL for removing the messages : " + msg_removal); } stmt1 = con.prepareStatement(msg_retrieval); System.out.println("\n" + "Executing " + msg_retrieval); // message retrivel rs2 = stmt1.executeQuery(); // retrieve the resultset while(rs2.next()) { // retrieve the sqlcode sqlcode = rs2.getString(1); // retrieve the error message msg = rs2.getString(2); System.out.println("Sqlcode : " +sqlcode); System.out.println("Msg : " +msg); } System.out.println("\nExecuting " + msg_removal); callStmt2 = con.prepareCall(msg_removal); // executing the message retrivel callStmt2.execute(); } catch(Exception e) { System.out.println("jdbc exception"); } finally { try { // close the statements callStmt1.close(); callStmt2.close(); stmt1.close(); // close the resultsets rs1.close(); rs2.close(); // roll back any changes to the database made by this sample con.rollback(); // close the connection con.close(); System.gc(); } catch (Exception x) { System.out.print("\n Unable to Rollback/Disconnect "); System.out.println("from 'sample' database"); } } } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see javax.servlet.GenericServlet#init() */ public void init() throws ServletException { // TODO Auto-generated method stub ServletContext ctx=getServletContext(); super.init(); try { Class.forName("com.ibm.db2.jcc.DB2Driver"); con = DriverManager.getConnection("jdbc:db2://localhost:50000/IBANK",ctx.getInitParameter("Username"),ctx.getInitParameter("Password")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
5,246
java
backup.java
Java
[]
null
[]
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.*; import java.sql.*; /** * Servlet implementation class for Servlet: backup * */ public class backup extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public backup() { super(); } Connection con = null; /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub int rows_exported; String msg_retrieval = null; String msg_removal = null; String sqlcode = null; String msg = null; CallableStatement callStmt1 = null; ResultSet rs1 = null; PreparedStatement stmt1 = null; ResultSet rs2 = null; CallableStatement callStmt2 = null; try { // initialize DB2Driver and establish database connection. Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance(); con = DriverManager.getConnection("jdbc:db2:IBANK"); System.out.println("HOW TO PERFORM EXPORT USING ADMIN_CMD.\n"); // prepare the CALL statement for OUT_LANGUAGE String sql = "CALL SYSPROC.ADMIN_CMD(?)"; callStmt1 = con.prepareCall(sql); String param = "export to D://org_ex1.ixf "; param = param + "of ixf messages on server select * from system.usacc" ; // set the imput parameter callStmt1.setString(1, param); System.out.println("CALL ADMIN_CMD('" + param + "')"); // execute export by calling ADMIN_CMD callStmt1.execute(); rs1 = callStmt1.getResultSet(); // retrieve the resultset if( rs1.next()) { // the numbers of rows exported rows_exported = rs1.getInt(1); // retrieve the select stmt for message retrival // containing SYSPROC.ADMIN_GET_MSGS msg_retrieval = rs1.getString(2); // retrive the stmt for message cleanup // containing CALL of SYSPROC.ADMIN_REMOVE_MSGS msg_removal = rs1.getString(3); // display the output System.out.println("Total number of rows exported : " + rows_exported); System.out.println("SQL for retrieving the messages: " + msg_retrieval); System.out.println("SQL for removing the messages : " + msg_removal); } stmt1 = con.prepareStatement(msg_retrieval); System.out.println("\n" + "Executing " + msg_retrieval); // message retrivel rs2 = stmt1.executeQuery(); // retrieve the resultset while(rs2.next()) { // retrieve the sqlcode sqlcode = rs2.getString(1); // retrieve the error message msg = rs2.getString(2); System.out.println("Sqlcode : " +sqlcode); System.out.println("Msg : " +msg); } System.out.println("\nExecuting " + msg_removal); callStmt2 = con.prepareCall(msg_removal); // executing the message retrivel callStmt2.execute(); } catch(Exception e) { System.out.println("jdbc exception"); } finally { try { // close the statements callStmt1.close(); callStmt2.close(); stmt1.close(); // close the resultsets rs1.close(); rs2.close(); // roll back any changes to the database made by this sample con.rollback(); // close the connection con.close(); System.gc(); } catch (Exception x) { System.out.print("\n Unable to Rollback/Disconnect "); System.out.println("from 'sample' database"); } } } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see javax.servlet.GenericServlet#init() */ public void init() throws ServletException { // TODO Auto-generated method stub ServletContext ctx=getServletContext(); super.init(); try { Class.forName("com.ibm.db2.jcc.DB2Driver"); con = DriverManager.getConnection("jdbc:db2://localhost:50000/IBANK",ctx.getInitParameter("Username"),ctx.getInitParameter("Password")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
5,246
0.588258
0.579298
160
31.78125
26.833439
143
false
false
0
0
0
0
0
0
1.4875
false
false
14
104eeafbe7ceae640f28ee7da4c12b9b0e9dba58
2,173,253,475,822
eb2be86a098fab314169db7ce09aec4882468ff5
/Security-Learning/Shiro/Shiro-SpringBoot/src/main/java/com/amber/shiro/UserRealm.java
743cdc9cd031fdd15beb5fd5a30a94414c9f889b
[]
no_license
AmberBar/Learning
https://github.com/AmberBar/Learning
473a8e5b37b0e783b1e2a72b190a0d31dff1c8af
47b5dff1a206557cf9696ab21e56d9d11d42ea8f
refs/heads/master
2022-12-20T03:58:45.589000
2020-07-28T12:54:33
2020-07-28T12:54:33
148,492,790
0
0
null
false
2022-12-16T01:17:12
2018-09-12T14:23:57
2020-07-28T12:54:58
2022-12-16T01:17:10
12,568
0
0
25
Java
false
false
package com.amber.shiro; import com.amber.data.po.Role; import com.amber.data.po.User; import com.amber.service.UserService; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; /** * 认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException{ //加这一步的目的是在Post请求的时候会先进认证,然后在到请求 System.out.println("认证"); if (authenticationToken.getPrincipal() == null) { return null; } //获取用户信息 String name = authenticationToken.getPrincipal().toString(); User user = userService.findUserByUsername(name); if (user == null) { //这里返回后会报出对应异常 throw new AuthenticationException("account does not exist"); } SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword().toString(), getName()); return simpleAuthenticationInfo; } /** * 授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { String username = (String) principalCollection.getPrimaryPrincipal(); User user = userService.findUserByUsername(username); List<Role> roles = user.getRoles(); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); roles.forEach(role -> { String name = role.getName(); simpleAuthorizationInfo.addRole(name); simpleAuthorizationInfo.addStringPermissions(role.getPermssions().stream().map(permssion -> permssion.getName()).collect(Collectors.toSet())); }); System.out.println("授权"); return simpleAuthorizationInfo; } }
UTF-8
Java
2,712
java
UserRealm.java
Java
[]
null
[]
package com.amber.shiro; import com.amber.data.po.Role; import com.amber.data.po.User; import com.amber.service.UserService; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; /** * 认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException{ //加这一步的目的是在Post请求的时候会先进认证,然后在到请求 System.out.println("认证"); if (authenticationToken.getPrincipal() == null) { return null; } //获取用户信息 String name = authenticationToken.getPrincipal().toString(); User user = userService.findUserByUsername(name); if (user == null) { //这里返回后会报出对应异常 throw new AuthenticationException("account does not exist"); } SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword().toString(), getName()); return simpleAuthenticationInfo; } /** * 授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { String username = (String) principalCollection.getPrimaryPrincipal(); User user = userService.findUserByUsername(username); List<Role> roles = user.getRoles(); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); roles.forEach(role -> { String name = role.getName(); simpleAuthorizationInfo.addRole(name); simpleAuthorizationInfo.addStringPermissions(role.getPermssions().stream().map(permssion -> permssion.getName()).collect(Collectors.toSet())); }); System.out.println("授权"); return simpleAuthorizationInfo; } }
2,712
0.722009
0.722009
74
34.243244
31.919582
154
false
false
0
0
0
0
0
0
0.5
false
false
14
64eb1a5946307604f51d2227f7c2a5a137608517
6,253,472,384,603
ddbd4a2bf24096ce2a38d6c29481681a034dcf7c
/assignment2/src/app/mainUI.java
213003f59c0cf5ce0c6067452f2373cb80777b28
[]
no_license
Thinushika/Java_101
https://github.com/Thinushika/Java_101
3d044d3543b46926774bfba4aed8f5686c6d100a
9a883838e933fba630268967b4f3dffb09d114fe
refs/heads/master
2023-06-04T21:03:25.745000
2021-12-17T09:59:39
2021-12-17T09:59:39
377,714,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app; import java.awt.Color; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; public class mainUI extends javax.swing.JFrame { public mainUI() { initComponents(); setLocationRelativeTo(null); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bg_pnl = new javax.swing.JPanel(); Traveller = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); close = new javax.swing.JLabel(); DName_lbl = new javax.swing.JLabel(); TSpace_lbl = new javax.swing.JLabel(); FSpace_lbl = new javax.swing.JLabel(); Tspace_txt = new javax.swing.JTextField(); Fspace_txt = new javax.swing.JTextField(); SelectD = new javax.swing.JComboBox<>(); Btn_create = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(500, 350)); setMinimumSize(new java.awt.Dimension(500, 350)); setUndecorated(true); bg_pnl.setBackground(new java.awt.Color(255, 255, 255)); Traveller.setBackground(new java.awt.Color(250, 250, 250)); Traveller.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { TravellerMouseDragged(evt); } }); Traveller.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { TravellerMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { TravellerMouseReleased(evt); } }); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel1.setForeground(new java.awt.Color(51, 51, 51)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Dummy File Creater"); close.setBackground(new java.awt.Color(250, 250, 250)); close.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N close.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); close.setText("X"); close.setOpaque(true); close.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { closeMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { closeMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { closeMouseExited(evt); } }); javax.swing.GroupLayout TravellerLayout = new javax.swing.GroupLayout(Traveller); Traveller.setLayout(TravellerLayout); TravellerLayout.setHorizontalGroup( TravellerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(TravellerLayout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)) ); TravellerLayout.setVerticalGroup( TravellerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(close, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE) ); DName_lbl.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N DName_lbl.setForeground(new java.awt.Color(51, 51, 51)); DName_lbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); DName_lbl.setText("Drive Name : "); TSpace_lbl.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N TSpace_lbl.setForeground(new java.awt.Color(51, 51, 51)); TSpace_lbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); TSpace_lbl.setText("Total Space : "); FSpace_lbl.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N FSpace_lbl.setForeground(new java.awt.Color(51, 51, 51)); FSpace_lbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); FSpace_lbl.setText("Free Space : "); Tspace_txt.setBackground(new java.awt.Color(250, 250, 250)); Tspace_txt.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N Tspace_txt.setForeground(new java.awt.Color(102, 102, 102)); Tspace_txt.setBorder(null); Fspace_txt.setBackground(new java.awt.Color(250, 250, 250)); Fspace_txt.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N Fspace_txt.setForeground(new java.awt.Color(102, 102, 102)); Fspace_txt.setBorder(null); SelectD.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "C:", "D:", "E:", "F:", "G:" })); SelectD.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SelectDActionPerformed(evt); } }); Btn_create.setBackground(new java.awt.Color(51, 51, 51)); Btn_create.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N Btn_create.setForeground(new java.awt.Color(204, 204, 204)); Btn_create.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); Btn_create.setText("Create "); Btn_create.setOpaque(true); Btn_create.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Btn_createMouseClicked(evt); } }); javax.swing.GroupLayout bg_pnlLayout = new javax.swing.GroupLayout(bg_pnl); bg_pnl.setLayout(bg_pnlLayout); bg_pnlLayout.setHorizontalGroup( bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Traveller, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(bg_pnlLayout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(FSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Btn_create, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE) .addComponent(Fspace_txt))) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(TSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(Tspace_txt)) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(DName_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(SelectD, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(183, Short.MAX_VALUE)) ); bg_pnlLayout.setVerticalGroup( bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(Traveller, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(55, 55, 55) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DName_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(SelectD, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(TSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Tspace_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(FSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Fspace_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(37, 37, 37) .addComponent(Btn_create, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(132, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bg_pnl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bg_pnl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private String location = "C:"; private boolean execute = true; private void TravellerMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TravellerMouseDragged }//GEN-LAST:event_TravellerMouseDragged private void TravellerMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TravellerMousePressed }//GEN-LAST:event_TravellerMousePressed private void TravellerMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TravellerMouseReleased }//GEN-LAST:event_TravellerMouseReleased private void closeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeMouseClicked System.exit(0); }//GEN-LAST:event_closeMouseClicked private void closeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeMouseEntered close.setBackground(new Color(255,0,0)); close.setForeground(new Color(255,255,255)); }//GEN-LAST:event_closeMouseEntered private void closeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeMouseExited close.setBackground(new Color(250,250,250)); close.setForeground(new Color(0,0,0)); }//GEN-LAST:event_closeMouseExited private void Btn_createMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Btn_createMouseClicked int i=0; while(true){ DummyFile(this.location,"dummy "+i); i++; } }//GEN-LAST:event_Btn_createMouseClicked private void SelectDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SelectDActionPerformed this.location = SelectD.getSelectedItem().toString(); File file = new File(SelectD.getSelectedItem().toString()); //display total space double totalSpace = file.getTotalSpace()/ (1024.0 * 1024 * 1024); BigDecimal bd = new BigDecimal(totalSpace).setScale(2, RoundingMode.HALF_UP);//to round the result Double total = bd.doubleValue(); String totalAsString = Double.toString(total);//convert double to string Tspace_txt.setText(totalAsString+" GB"); //display free space double freeSpace = file.getFreeSpace() / (1024.0 * 1024 * 1024); BigDecimal fs = new BigDecimal(freeSpace).setScale(2, RoundingMode.HALF_UP); Double free = fs.doubleValue(); String freeAsString = Double.toString(free);//convert double to string Fspace_txt.setText(freeAsString+" GB"); }//GEN-LAST:event_SelectDActionPerformed private void DummyFile(String location,String fileName){ String FixfileName = location+"\\"+fileName; try{ RandomAccessFile stream = new RandomAccessFile(FixfileName, "rw"); stream.setLength(1024*1024*10); // set file size is 1kB FileChannel channel = stream.getChannel(); String value = "Writting dummy..."; byte[] strBytes = value.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length); buffer.put(strBytes); buffer.flip(); channel.write(buffer); stream.close(); channel.close(); }catch(Exception ex){} } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Btn_create; private javax.swing.JLabel DName_lbl; private javax.swing.JLabel FSpace_lbl; private javax.swing.JTextField Fspace_txt; private javax.swing.JComboBox<String> SelectD; private javax.swing.JLabel TSpace_lbl; private javax.swing.JPanel Traveller; private javax.swing.JTextField Tspace_txt; private javax.swing.JPanel bg_pnl; private javax.swing.JLabel close; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables }
UTF-8
Java
16,832
java
mainUI.java
Java
[]
null
[]
package app; import java.awt.Color; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; public class mainUI extends javax.swing.JFrame { public mainUI() { initComponents(); setLocationRelativeTo(null); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bg_pnl = new javax.swing.JPanel(); Traveller = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); close = new javax.swing.JLabel(); DName_lbl = new javax.swing.JLabel(); TSpace_lbl = new javax.swing.JLabel(); FSpace_lbl = new javax.swing.JLabel(); Tspace_txt = new javax.swing.JTextField(); Fspace_txt = new javax.swing.JTextField(); SelectD = new javax.swing.JComboBox<>(); Btn_create = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(500, 350)); setMinimumSize(new java.awt.Dimension(500, 350)); setUndecorated(true); bg_pnl.setBackground(new java.awt.Color(255, 255, 255)); Traveller.setBackground(new java.awt.Color(250, 250, 250)); Traveller.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { TravellerMouseDragged(evt); } }); Traveller.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { TravellerMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { TravellerMouseReleased(evt); } }); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jLabel1.setForeground(new java.awt.Color(51, 51, 51)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Dummy File Creater"); close.setBackground(new java.awt.Color(250, 250, 250)); close.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N close.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); close.setText("X"); close.setOpaque(true); close.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { closeMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { closeMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { closeMouseExited(evt); } }); javax.swing.GroupLayout TravellerLayout = new javax.swing.GroupLayout(Traveller); Traveller.setLayout(TravellerLayout); TravellerLayout.setHorizontalGroup( TravellerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(TravellerLayout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)) ); TravellerLayout.setVerticalGroup( TravellerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(close, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE) ); DName_lbl.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N DName_lbl.setForeground(new java.awt.Color(51, 51, 51)); DName_lbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); DName_lbl.setText("Drive Name : "); TSpace_lbl.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N TSpace_lbl.setForeground(new java.awt.Color(51, 51, 51)); TSpace_lbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); TSpace_lbl.setText("Total Space : "); FSpace_lbl.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N FSpace_lbl.setForeground(new java.awt.Color(51, 51, 51)); FSpace_lbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); FSpace_lbl.setText("Free Space : "); Tspace_txt.setBackground(new java.awt.Color(250, 250, 250)); Tspace_txt.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N Tspace_txt.setForeground(new java.awt.Color(102, 102, 102)); Tspace_txt.setBorder(null); Fspace_txt.setBackground(new java.awt.Color(250, 250, 250)); Fspace_txt.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N Fspace_txt.setForeground(new java.awt.Color(102, 102, 102)); Fspace_txt.setBorder(null); SelectD.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "C:", "D:", "E:", "F:", "G:" })); SelectD.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SelectDActionPerformed(evt); } }); Btn_create.setBackground(new java.awt.Color(51, 51, 51)); Btn_create.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N Btn_create.setForeground(new java.awt.Color(204, 204, 204)); Btn_create.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); Btn_create.setText("Create "); Btn_create.setOpaque(true); Btn_create.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Btn_createMouseClicked(evt); } }); javax.swing.GroupLayout bg_pnlLayout = new javax.swing.GroupLayout(bg_pnl); bg_pnl.setLayout(bg_pnlLayout); bg_pnlLayout.setHorizontalGroup( bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Traveller, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(bg_pnlLayout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(FSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Btn_create, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE) .addComponent(Fspace_txt))) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(TSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(Tspace_txt)) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(DName_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(SelectD, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(183, Short.MAX_VALUE)) ); bg_pnlLayout.setVerticalGroup( bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(bg_pnlLayout.createSequentialGroup() .addComponent(Traveller, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(55, 55, 55) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DName_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(SelectD, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(TSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Tspace_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(bg_pnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(FSpace_lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Fspace_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(37, 37, 37) .addComponent(Btn_create, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(132, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bg_pnl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bg_pnl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private String location = "C:"; private boolean execute = true; private void TravellerMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TravellerMouseDragged }//GEN-LAST:event_TravellerMouseDragged private void TravellerMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TravellerMousePressed }//GEN-LAST:event_TravellerMousePressed private void TravellerMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TravellerMouseReleased }//GEN-LAST:event_TravellerMouseReleased private void closeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeMouseClicked System.exit(0); }//GEN-LAST:event_closeMouseClicked private void closeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeMouseEntered close.setBackground(new Color(255,0,0)); close.setForeground(new Color(255,255,255)); }//GEN-LAST:event_closeMouseEntered private void closeMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_closeMouseExited close.setBackground(new Color(250,250,250)); close.setForeground(new Color(0,0,0)); }//GEN-LAST:event_closeMouseExited private void Btn_createMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Btn_createMouseClicked int i=0; while(true){ DummyFile(this.location,"dummy "+i); i++; } }//GEN-LAST:event_Btn_createMouseClicked private void SelectDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SelectDActionPerformed this.location = SelectD.getSelectedItem().toString(); File file = new File(SelectD.getSelectedItem().toString()); //display total space double totalSpace = file.getTotalSpace()/ (1024.0 * 1024 * 1024); BigDecimal bd = new BigDecimal(totalSpace).setScale(2, RoundingMode.HALF_UP);//to round the result Double total = bd.doubleValue(); String totalAsString = Double.toString(total);//convert double to string Tspace_txt.setText(totalAsString+" GB"); //display free space double freeSpace = file.getFreeSpace() / (1024.0 * 1024 * 1024); BigDecimal fs = new BigDecimal(freeSpace).setScale(2, RoundingMode.HALF_UP); Double free = fs.doubleValue(); String freeAsString = Double.toString(free);//convert double to string Fspace_txt.setText(freeAsString+" GB"); }//GEN-LAST:event_SelectDActionPerformed private void DummyFile(String location,String fileName){ String FixfileName = location+"\\"+fileName; try{ RandomAccessFile stream = new RandomAccessFile(FixfileName, "rw"); stream.setLength(1024*1024*10); // set file size is 1kB FileChannel channel = stream.getChannel(); String value = "Writting dummy..."; byte[] strBytes = value.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length); buffer.put(strBytes); buffer.flip(); channel.write(buffer); stream.close(); channel.close(); }catch(Exception ex){} } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Btn_create; private javax.swing.JLabel DName_lbl; private javax.swing.JLabel FSpace_lbl; private javax.swing.JTextField Fspace_txt; private javax.swing.JComboBox<String> SelectD; private javax.swing.JLabel TSpace_lbl; private javax.swing.JPanel Traveller; private javax.swing.JTextField Tspace_txt; private javax.swing.JPanel bg_pnl; private javax.swing.JLabel close; private javax.swing.JLabel jLabel1; // End of variables declaration//GEN-END:variables }
16,832
0.651497
0.634268
326
50.631901
36.820816
158
false
false
0
0
0
0
0
0
0.892638
false
false
14
f457b615c8d7da62249e16707d1a30c48d40bbb2
27,290,222,257,428
a4d0d80809eef4d90f01c3b79969f740eedde4a6
/FreeLanceCalc/app/src/main/java/studioborges/freecalc2/MainActivity.java
89e6909fc529ff5b5ccdd24810a62af689f58404
[]
no_license
jegborges/freelancecalcapp
https://github.com/jegborges/freelancecalcapp
f0b8a3fd280a68e27aad16c7f0c40cc981d0a472
14d56e96fa985e0446f16586edf2c8ba1333d75b
refs/heads/master
2021-07-18T02:39:31.061000
2017-10-25T21:26:59
2017-10-25T21:26:59
108,328,158
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package studioborges.freecalc2; import android.content.Intent; import android.support.v4.widget.TextViewCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.Html; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView link; private String sitio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); TextView link = (TextView) findViewById(R.id.textview7); sitio = "http://studioborges.com"; link.setText(Html.fromHtml(sitio)); } /** Called when the user clicks the Siguiente button */ public void Time(View view) { // Do something in response to button Intent intent = new Intent(this, TimeActivity.class); startActivity(intent); } }
UTF-8
Java
1,164
java
MainActivity.java
Java
[]
null
[]
package studioborges.freecalc2; import android.content.Intent; import android.support.v4.widget.TextViewCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.Html; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView link; private String sitio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); TextView link = (TextView) findViewById(R.id.textview7); sitio = "http://studioborges.com"; link.setText(Html.fromHtml(sitio)); } /** Called when the user clicks the Siguiente button */ public void Time(View view) { // Do something in response to button Intent intent = new Intent(this, TimeActivity.class); startActivity(intent); } }
1,164
0.719931
0.715636
38
29.631578
21.951406
68
false
false
0
0
0
0
0
0
0.578947
false
false
14
fcd86a56c3a27a50e2e172bc523f8d6e0a69bf6c
4,999,341,989,002
22041957a57cd2749c355116bde38b8c750214a8
/src/test/java/cn/effine/Test.java
a5d32f078a50d229766673ff9daec6c359096d4f
[]
no_license
effine/hibernateDemo
https://github.com/effine/hibernateDemo
730758b1e0492e89e2236cc2d3587c6caf77c198
c1f64fe3d53a1db6eb9467de6cc55bfbed726779
refs/heads/master
2021-01-17T11:50:12.832000
2017-02-26T14:56:35
2017-02-26T14:56:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.effine; /** * @author effine * @Date 2016-12-30 08:05 * @email iballader#gmail.com * @site http://www.effine.cn * @sine 0.2 */ public class Test { }
UTF-8
Java
169
java
Test.java
Java
[ { "context": "package cn.effine;\n\n/**\n * @author effine\n * @Date 2016-12-30 08:05\n * @email iballader#gma", "end": 41, "score": 0.9995499849319458, "start": 35, "tag": "USERNAME", "value": "effine" }, { "context": "@author effine\n * @Date 2016-12-30 08:05\n * @email iballader#gmail.com\n * @site http://www.effine.cn\n * @sine 0.2\n */\npu", "end": 97, "score": 0.9998727440834045, "start": 78, "tag": "EMAIL", "value": "iballader#gmail.com" } ]
null
[]
package cn.effine; /** * @author effine * @Date 2016-12-30 08:05 * @email <EMAIL> * @site http://www.effine.cn * @sine 0.2 */ public class Test { }
157
0.621302
0.538462
13
12
10.996503
29
false
false
0
0
0
0
0
0
0.076923
false
false
14
6242060681980cf76d7eaf3078f53ec87dcf608f
11,287,174,089,605
b00be74b893499df83e6674c74211a6d6b27ff9a
/src/main/java/com/ddu/shiro_demo/dao/UserDao.java
e38c66e9c65db8da5ae806d793639cbe37b5edfb
[]
no_license
ChunKitAu/shiro_demo
https://github.com/ChunKitAu/shiro_demo
7b1390336437b548a0ec6c7b987df3dd358a8774
65c87293ff4cc9307b0ce520fa49d6a39425eb54
refs/heads/master
2020-08-23T03:50:54.273000
2019-10-27T09:02:35
2019-10-27T09:02:35
216,537,352
2
0
null
true
2019-10-21T10:09:14
2019-10-21T10:09:14
2019-10-20T01:27:39
2019-10-20T01:27:38
68
0
0
0
null
false
false
package com.ddu.shiro_demo.dao; import com.ddu.shiro_demo.bean.User; import org.springframework.stereotype.Component; import java.util.Set; import java.util.HashSet; @Component public class UserDao { static Set<User> db; static { db = new HashSet<>(); db.add(new User("u001", "user01", "123456")); db.add(new User("u002", "user02", "123456")); db.add(new User("u003", "user03", "123456")); } /** * 查询所有记录 * * @return */ public Set<User> getUsers() { return db; } /** * 单条查询 * * @param id 用户id * @return */ public User getOne(String id) { for (User user : db) { if (user.getId().equals(id)) { return user; } } return null; } }
UTF-8
Java
844
java
UserDao.java
Java
[]
null
[]
package com.ddu.shiro_demo.dao; import com.ddu.shiro_demo.bean.User; import org.springframework.stereotype.Component; import java.util.Set; import java.util.HashSet; @Component public class UserDao { static Set<User> db; static { db = new HashSet<>(); db.add(new User("u001", "user01", "123456")); db.add(new User("u002", "user02", "123456")); db.add(new User("u003", "user03", "123456")); } /** * 查询所有记录 * * @return */ public Set<User> getUsers() { return db; } /** * 单条查询 * * @param id 用户id * @return */ public User getOne(String id) { for (User user : db) { if (user.getId().equals(id)) { return user; } } return null; } }
844
0.508537
0.468293
46
16.826086
15.727716
53
false
false
0
0
0
0
0
0
0.413043
false
false
14
5f380cf5fa24b569177f4cbd7d97aa6f92cb2bcc
6,390,911,366,353
36fb7e5d594ab0f6ab23dd0cbfc35a40e5e8c5a4
/fmsb-bo/.svn/pristine/69/69c9a695c663e5f20099dd40ee618b8f4c75d467.svn-base
0c228066761f87a2a464bf46180e4581aaebc34a
[]
no_license
LLJLS/tsglxt
https://github.com/LLJLS/tsglxt
ed95f44e7e2b82415475849ac84a8026acfa5d8f
48bc0b9245881270182bd11801a4737493a11ff5
refs/heads/master
2019-01-20T15:08:33.469000
2017-10-20T08:52:57
2017-10-20T08:52:57
96,991,970
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.newtouch.crm.models.business; import com.newtouch.lightframework.common.Entity; public class EmbTwodCode implements Entity<Long>{ /** * */ private static final long serialVersionUID = -7975616158657106616L; private Long id; /** 网点工号 */ private String websiteNo; /** 产品类型 */ private String productType; /** 分公司 */ private String branch; /** 二维码链接 */ private String url; /** 产品名称 */ private String productName; /** 是否删除 0:否 1:是 */ private String isDelete; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getWebsiteNo() { return websiteNo; } public void setWebsiteNo(String websiteNo) { this.websiteNo = websiteNo; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete; } }
UTF-8
Java
1,410
69c9a695c663e5f20099dd40ee618b8f4c75d467.svn-base
Java
[]
null
[]
package com.newtouch.crm.models.business; import com.newtouch.lightframework.common.Entity; public class EmbTwodCode implements Entity<Long>{ /** * */ private static final long serialVersionUID = -7975616158657106616L; private Long id; /** 网点工号 */ private String websiteNo; /** 产品类型 */ private String productType; /** 分公司 */ private String branch; /** 二维码链接 */ private String url; /** 产品名称 */ private String productName; /** 是否删除 0:否 1:是 */ private String isDelete; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getWebsiteNo() { return websiteNo; } public void setWebsiteNo(String websiteNo) { this.websiteNo = websiteNo; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete; } }
1,410
0.699853
0.684366
71
18.098591
15.990451
68
false
false
0
0
0
0
0
0
1.422535
false
false
14
ade312d18869a1b2871f9a5ffccd1bca9d3772ea
32,581,621,929,302
e948298229ce282718f93a5e511e6efea8f2f76a
/src/main/java/org/reactome/server/tools/diagram/exporter/raster/itext/awt/DefaultFontMapper.java
11920cf38361d25397abe7850430a6c072f31f1b
[]
no_license
reactome-bck/diagram-exporter
https://github.com/reactome-bck/diagram-exporter
beda6c8304f846fe72c9f88a0cd42ad4cc0a65b8
8288deb30973b7bf58fb597c36ed861027cf3f6b
refs/heads/master
2023-05-22T20:24:01.212000
2019-06-26T15:06:08
2019-06-26T15:06:08
266,587,388
0
0
null
false
2021-06-07T18:51:23
2020-05-24T17:07:38
2020-05-24T17:09:14
2021-06-07T18:51:23
18,936
0
0
3
Java
false
false
/* * * This file is part of the iText (R) project. Copyright (c) 1998-2018 iText Group NV * Authors: Bruno Lowagie, Paulo Soares, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: sales@itextpdf.com */ package org.reactome.server.tools.diagram.exporter.raster.itext.awt; import com.itextpdf.io.font.FontNames; import com.itextpdf.io.font.PdfEncodings; import com.itextpdf.io.font.constants.FontStyles; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import org.apache.commons.io.IOUtils; import org.reactome.server.tools.diagram.exporter.raster.resources.Resources; import java.awt.*; import java.io.IOException; /** * Default class to map awt fonts to BaseFont. * * @author Paulo Soares */ public class DefaultFontMapper { private PdfFont REGULAR; private PdfFont BOLD; public DefaultFontMapper() { byte[] bytes; try { bytes = IOUtils.toByteArray(Resources.class.getResourceAsStream("fonts/arial.ttf")); REGULAR = PdfFontFactory.createFont(bytes, PdfEncodings.UTF8, true, true); bytes = IOUtils.toByteArray(Resources.class.getResourceAsStream("fonts/arialbd.ttf")); BOLD = PdfFontFactory.createFont(bytes, PdfEncodings.UTF8, true, true); } catch (IOException e) { e.printStackTrace(); } } /** * Returns a BaseFont which can be used to represent the given AWT Font * * @param font the font to be converted * * @return a BaseFont which has similar properties to the provided Font */ public PdfFont awtToPdf(Font font) { if (font.isBold()) return BOLD; return REGULAR; // try { // // fontName - either a font alias, if the font file has been registered with an alias, or just a font name otherwise // // encoding - the encoding of the font to be created. See PdfEncodings // // embedded - indicates whether the font is to be embedded into the target document // // style - the style of the font to look for. Possible values are listed in FontStyles. See FontStyles.BOLD, FontStyles.ITALIC, FontStyles.NORMAL, FontStyles.BOLDITALIC, FontStyles.UNDEFINED // // cached - whether to try to get the font program from cache // FontProgramFactory.createRegisteredFont(font.getPSName(), extractItextStyle(font)); //// return PdfFontFactory.createRegisteredFont(font.getPSName(), PdfEncodings.UTF8, false, extractItextStyle(font), true); // } catch (IOException e) { // LoggerFactory.getLogger(DefaultFontMapper.class).error("Font " + font.getName() + " is not registered"); // } // return null; } private int extractAwtStyle(PdfFont font) { final FontNames fontNames = font.getFontProgram().getFontNames(); int style = Font.PLAIN; if (fontNames.isBold()) style |= Font.BOLD; if (fontNames.isItalic()) style |= Font.ITALIC; return style; } /** * Returns an AWT Font which can be used to represent the given BaseFont * * @param font the font to be converted * @param size the desired point size of the resulting font * * @return a Font which has similar properties to the provided BaseFont */ public Font pdfToAwt(PdfFont font, int size) { final String fontName = font.getFontProgram().getFontNames().getFontName(); //noinspection MagicConstant return Font.getFont(fontName) .deriveFont(extractAwtStyle(font), size); } private int extractItextStyle(Font font) { if (font.isItalic() && font.isBold()) return FontStyles.BOLDITALIC; if (font.isBold()) return FontStyles.BOLD; if (font.isItalic()) return FontStyles.ITALIC; if (font.isPlain()) return FontStyles.NORMAL; return FontStyles.UNDEFINED; } }
UTF-8
Java
5,527
java
DefaultFontMapper.java
Java
[ { "context": "Copyright (c) 1998-2018 iText Group NV\n * Authors: Bruno Lowagie, Paulo Soares, et al.\n *\n * This program is free ", "end": 121, "score": 0.9998465180397034, "start": 108, "tag": "NAME", "value": "Bruno Lowagie" }, { "context": "998-2018 iText Group NV\n * Authors: Bruno Lowagie, Paulo Soares, et al.\n *\n * This program is free software; you ", "end": 135, "score": 0.999829113483429, "start": 123, "tag": "NAME", "value": "Paulo Soares" }, { "context": "e contact iText Software Corp. at this\n * address: sales@itextpdf.com\n */\npackage org.reactome.server.tools.diagram.exp", "end": 2160, "score": 0.9999247789382935, "start": 2142, "tag": "EMAIL", "value": "sales@itextpdf.com" }, { "context": " class to map awt fonts to BaseFont.\n *\n * @author Paulo Soares\n */\n\npublic class DefaultFontMapper {\n\n\tprivate P", "end": 2697, "score": 0.999780535697937, "start": 2685, "tag": "NAME", "value": "Paulo Soares" } ]
null
[]
/* * * This file is part of the iText (R) project. Copyright (c) 1998-2018 iText Group NV * Authors: <NAME>, <NAME>, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, * a covered work must retain the producer line in every PDF that is created * or manipulated using iText. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the iText software without * disclosing the source code of your own applications. * These activities include: offering paid services to customers as an ASP, * serving PDFs on the fly in a web application, shipping iText with a closed * source product. * * For more information, please contact iText Software Corp. at this * address: <EMAIL> */ package org.reactome.server.tools.diagram.exporter.raster.itext.awt; import com.itextpdf.io.font.FontNames; import com.itextpdf.io.font.PdfEncodings; import com.itextpdf.io.font.constants.FontStyles; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import org.apache.commons.io.IOUtils; import org.reactome.server.tools.diagram.exporter.raster.resources.Resources; import java.awt.*; import java.io.IOException; /** * Default class to map awt fonts to BaseFont. * * @author <NAME> */ public class DefaultFontMapper { private PdfFont REGULAR; private PdfFont BOLD; public DefaultFontMapper() { byte[] bytes; try { bytes = IOUtils.toByteArray(Resources.class.getResourceAsStream("fonts/arial.ttf")); REGULAR = PdfFontFactory.createFont(bytes, PdfEncodings.UTF8, true, true); bytes = IOUtils.toByteArray(Resources.class.getResourceAsStream("fonts/arialbd.ttf")); BOLD = PdfFontFactory.createFont(bytes, PdfEncodings.UTF8, true, true); } catch (IOException e) { e.printStackTrace(); } } /** * Returns a BaseFont which can be used to represent the given AWT Font * * @param font the font to be converted * * @return a BaseFont which has similar properties to the provided Font */ public PdfFont awtToPdf(Font font) { if (font.isBold()) return BOLD; return REGULAR; // try { // // fontName - either a font alias, if the font file has been registered with an alias, or just a font name otherwise // // encoding - the encoding of the font to be created. See PdfEncodings // // embedded - indicates whether the font is to be embedded into the target document // // style - the style of the font to look for. Possible values are listed in FontStyles. See FontStyles.BOLD, FontStyles.ITALIC, FontStyles.NORMAL, FontStyles.BOLDITALIC, FontStyles.UNDEFINED // // cached - whether to try to get the font program from cache // FontProgramFactory.createRegisteredFont(font.getPSName(), extractItextStyle(font)); //// return PdfFontFactory.createRegisteredFont(font.getPSName(), PdfEncodings.UTF8, false, extractItextStyle(font), true); // } catch (IOException e) { // LoggerFactory.getLogger(DefaultFontMapper.class).error("Font " + font.getName() + " is not registered"); // } // return null; } private int extractAwtStyle(PdfFont font) { final FontNames fontNames = font.getFontProgram().getFontNames(); int style = Font.PLAIN; if (fontNames.isBold()) style |= Font.BOLD; if (fontNames.isItalic()) style |= Font.ITALIC; return style; } /** * Returns an AWT Font which can be used to represent the given BaseFont * * @param font the font to be converted * @param size the desired point size of the resulting font * * @return a Font which has similar properties to the provided BaseFont */ public Font pdfToAwt(PdfFont font, int size) { final String fontName = font.getFontProgram().getFontNames().getFontName(); //noinspection MagicConstant return Font.getFont(fontName) .deriveFont(extractAwtStyle(font), size); } private int extractItextStyle(Font font) { if (font.isItalic() && font.isBold()) return FontStyles.BOLDITALIC; if (font.isBold()) return FontStyles.BOLD; if (font.isItalic()) return FontStyles.ITALIC; if (font.isPlain()) return FontStyles.NORMAL; return FontStyles.UNDEFINED; } }
5,497
0.746155
0.741089
137
39.343067
34.231167
195
false
false
0
0
0
0
0
0
1.40146
false
false
14
977fd63bd864540cd2475cf4e1018425ae597b64
25,778,393,735,726
d36e21307b7d173a978eca53043bbcaca10af3c7
/buidmydream/src/main/java/com/example/builddream/pojo/mybatisdo/RoleDo.java
f1bed4354c8e8924fee16c98480d3916e1df3ce3
[]
no_license
shewoqishuiry/springbootLearning
https://github.com/shewoqishuiry/springbootLearning
3b81c60c45c78f3835e3a8f4aed6cbb07d5035b2
fb0562d07d808c3a25e3c1f4f362f2d389b76fbe
refs/heads/main
2023-02-22T20:47:16.981000
2021-01-23T05:20:11
2021-01-23T05:20:11
302,771,787
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.builddream.pojo.mybatisdo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("roles") public class RoleDo { /** * id */ @TableId(value = "role_id",type = IdType.AUTO) private Long id; /** * 角色名称 */ @TableField(value = "role_name") private String roleName; }
UTF-8
Java
532
java
RoleDo.java
Java
[]
null
[]
package com.example.builddream.pojo.mybatisdo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("roles") public class RoleDo { /** * id */ @TableId(value = "role_id",type = IdType.AUTO) private Long id; /** * 角色名称 */ @TableField(value = "role_name") private String roleName; }
532
0.706107
0.706107
23
21.782608
19.332235
54
false
false
0
0
0
0
0
0
0.391304
false
false
14
b951a9b0ebeb7478c470b9570700c18a970c55a3
23,278,722,787,014
ba2c4c33a526ced5e397a5d9cd33178a4e87c5f3
/lab9/lab9j2fast.java
015470aee67385ed93738669e0027a67f58d7a02
[]
no_license
jerrylususu/dsaa_new
https://github.com/jerrylususu/dsaa_new
f25b263d380e7171d37b800c2aa62b2eb689dd04
997fab961e2845af12492e3118d38c3053ab1376
refs/heads/master
2020-04-10T05:01:59.779000
2019-01-09T13:01:20
2019-01-09T13:01:20
160,815,848
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lab9; // hdu 6370 // brute force with fast read and write // still tle // updated ver // using union set // still tle... // seems the cause is that the backward bfs check is too slow // add bfs marker // wa // the judge of union set contain was wrong // perhaps the root is different, and it won't be a valid wolf // ac import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * Author: Wavator */ public class lab9j2fast { static class UnionSet<T>{ UnionSetNode<T>[] arr; int size; public UnionSet(int size) { this.size = size; this.arr = new UnionSetNode[size]; } public UnionSetNode<T> find(int i){ UnionSetNode<T> node = arr[i]; while(node.parent!=-1){ node = arr[node.parent]; } return node; } public LinkedList<UnionSetNode<T>> findLink(int i){ LinkedList<UnionSetNode<T>> ll = new LinkedList<>(); UnionSetNode<T> node = arr[i]; ll.add(node); while(node.parent!=-1){ node = arr[node.parent]; ll.add(node); } return ll; } public void unionWithInfo(int i, int j, UnionSetNode<T> f1, UnionSetNode<T> f2){ UnionSetNode<T> n1 = arr[i], n2 = arr[j]; boolean f1bigger = f1.size>=f2.size; if(!f1bigger){ UnionSetNode<T> tmp = f1; f1 = f2; f2 = tmp; } f2.parent = f1.id; f1.size += f2.size; } public void union(int i, int j){ UnionSetNode<T> n1 = arr[i], n2 = arr[j]; UnionSetNode<T> f1 = find(n1.id); UnionSetNode<T> f2 = find(n2.id); boolean f1bigger = f1.size>=f2.size; if(!f1bigger){ UnionSetNode<T> tmp = f1; f1 = f2; f2 = tmp; } f2.parent = f1.id; f1.size += f2.size; } public void union2(int i, int j, List<UnionSetNode<T>> ll1, List<UnionSetNode<T>> ll2){ UnionSetNode<T> n1 = arr[i], n2 = arr[j]; n1.inus = true; n2.inus = true; boolean ll1bigger = ll1.size()>=ll2.size(); UnionSetNode<T> f = (ll1bigger)?ll1.get(ll1.size()-1):ll2.get(ll2.size()-1); int fid = f.id; int ffid = f.parent; if(ll1bigger){ for(UnionSetNode<T> node:ll1){ if(node.id!=fid&&node.parent!=fid&&node.parent!=-1){ arr[node.parent].size-=node.size; node.parent=fid; //f.size+=node.size; } } for(UnionSetNode<T> node:ll2){ if(node.id!=fid){ UnionSetNode<T> updatenode = node; int removesize = node.size; // if(node.parent!=-1){ // arr[node.parent].size-=node.size; // } while(updatenode.parent!=-1){ arr[updatenode.parent].size-=removesize; updatenode = arr[updatenode.parent]; } node.parent=fid; f.size+=node.size; } } } else { for(UnionSetNode<T> node:ll1){ if(node.id!=fid){ UnionSetNode<T> updatenode = node; int removesize = node.size; // if(node.parent!=-1){ // arr[node.parent].size-=node.size; // } while(updatenode.parent!=-1){ arr[updatenode.parent].size-=removesize; updatenode = arr[updatenode.parent]; } node.parent=fid; f.size+=node.size; } } for(UnionSetNode<T> node:ll2){ if(node.id!=fid&&node.parent!=fid&&node.parent!=-1){ arr[node.parent].size-=node.size; node.parent=fid; //f.size+=node.size; } } } f.parent=ffid; // f.size+=(ll1bigger)?ll2.size():ll1.size(); } } static class UnionSetNode<T>{ int id; int parent = -1; int size = 1; boolean inus = false; T thing; public UnionSetNode(int id, T thing) { this.id = id; this.thing = thing; } @Override public String toString() { return "UnionSetNode{" + "id=" + id + ", parent=" + parent + ", size=" + size + '}'; } } static class MyEdge{ int from, to, sum; boolean toIsWolf; public MyEdge(int from, int to, boolean toIsWolf) { this.from = from; this.to = to; this.sum = from+to; this.toIsWolf = toIsWolf; } } static class MyNode{ int id; boolean isWolf = false; boolean marker = false; boolean vis = false; MyEdge out = null; List<MyEdge> in; public MyNode(int id) { this.id = id; this.in = new LinkedList<>(); } @Override public String toString() { return "MyNode{" + "id=" + id + ", isWolf=" + isWolf + ", marker=" + marker + ", out=" + out + ", in=" + in.size() + '}'; } } // With credit to SA Zhu static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException{ InputStream inputStream = System.in;//new FileInputStream("C:\\Users\\wavator\\Downloads\\test.in"); OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out) throws IOException { int totalnum = in.nextInt(); while(totalnum-->0){ int n = in.nextInt(); MyNode[] nodes = new MyNode[n]; for (int i = 0; i < n; i++) { nodes[i] = new MyNode(i); } MyEdge[] edges = new MyEdge[n]; for (int i = 0; i < n; i++) { int to = in.nextInt()-1; boolean toIsWolf = in.next().charAt(0)=='w'; MyEdge e = new MyEdge(i,to,toIsWolf); nodes[i].out = e; nodes[to].in.add(e); edges[i] = e; } // using union set UnionSet<MyNode> us = new UnionSet<>(n); for (int i = 0; i < n; i++) { us.arr[i] = new UnionSetNode<>(i,nodes[i]); } int count = 0; // first deal with villagers for(MyEdge e:edges){ if(!e.toIsWolf){ LinkedList<UnionSetNode<MyNode>> ll1 = us.findLink(e.from), ll2 = us.findLink(e.to); us.arr[e.from].inus = true; us.arr[e.to].inus = true; us.union2(e.from,e.to,ll1,ll2); } } // then find those wolves LinkedList<MyNode> q = new LinkedList<>(); for(MyEdge e:edges){ if(e.toIsWolf&&!nodes[e.to].marker){ LinkedList<UnionSetNode<MyNode>> ll1 = us.findLink(e.from), ll2 =us.findLink(e.to); if(ll1.getLast()==ll2.getLast()){ // from and to both inside union set // count++; if(!nodes[e.to].marker){ q.add(nodes[e.to]); nodes[e.to].marker = true; } } } } while(!q.isEmpty()){ MyNode curnode = q.pollFirst(); if(curnode.vis){ continue; } count++; curnode.vis = true; for(MyEdge e:curnode.in){ if(!e.toIsWolf){ if(!nodes[e.from].vis) q.add(nodes[e.from]); } } } out.println(count); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } // public boolean hasNext() { // try { // return reader.ready(); // } catch(IOException e) { // throw new RuntimeException(e); // } // } public boolean hasNext() { try { String string = reader.readLine(); if (string == null) { return false; } tokenizer = new StringTokenizer(string); return tokenizer.hasMoreTokens(); } catch(IOException e) { return false; } } public BigInteger nextBigInteger() { return new BigInteger(next()); } public BigDecimal nextBigDecinal() { return new BigDecimal(next()); } } }
UTF-8
Java
14,377
java
lab9j2fast.java
Java
[ { "context": "lug-in\n * Actual solution is at the top\n * Author: Wavator\n */\npublic class lab9j2fast {\n\n\n static class ", "end": 583, "score": 0.952492892742157, "start": 576, "tag": "NAME", "value": "Wavator" }, { "context": " '}';\n }\n }\n // With credit to SA Zhu\n\n static class Reader\n {\n final priv", "end": 6207, "score": 0.9885324835777283, "start": 6201, "tag": "NAME", "value": "SA Zhu" }, { "context": "eam = System.in;//new FileInputStream(\"C:\\\\Users\\\\wavator\\\\Downloads\\\\test.in\");\n OutputStream o", "end": 9507, "score": 0.5237715840339661, "start": 9504, "tag": "NAME", "value": "wav" }, { "context": " = System.in;//new FileInputStream(\"C:\\\\Users\\\\wavator\\\\Downloads\\\\test.in\");\n OutputStream outpu", "end": 9511, "score": 0.6986864805221558, "start": 9507, "tag": "USERNAME", "value": "ator" } ]
null
[]
package lab9; // hdu 6370 // brute force with fast read and write // still tle // updated ver // using union set // still tle... // seems the cause is that the backward bfs check is too slow // add bfs marker // wa // the judge of union set contain was wrong // perhaps the root is different, and it won't be a valid wolf // ac import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top * Author: Wavator */ public class lab9j2fast { static class UnionSet<T>{ UnionSetNode<T>[] arr; int size; public UnionSet(int size) { this.size = size; this.arr = new UnionSetNode[size]; } public UnionSetNode<T> find(int i){ UnionSetNode<T> node = arr[i]; while(node.parent!=-1){ node = arr[node.parent]; } return node; } public LinkedList<UnionSetNode<T>> findLink(int i){ LinkedList<UnionSetNode<T>> ll = new LinkedList<>(); UnionSetNode<T> node = arr[i]; ll.add(node); while(node.parent!=-1){ node = arr[node.parent]; ll.add(node); } return ll; } public void unionWithInfo(int i, int j, UnionSetNode<T> f1, UnionSetNode<T> f2){ UnionSetNode<T> n1 = arr[i], n2 = arr[j]; boolean f1bigger = f1.size>=f2.size; if(!f1bigger){ UnionSetNode<T> tmp = f1; f1 = f2; f2 = tmp; } f2.parent = f1.id; f1.size += f2.size; } public void union(int i, int j){ UnionSetNode<T> n1 = arr[i], n2 = arr[j]; UnionSetNode<T> f1 = find(n1.id); UnionSetNode<T> f2 = find(n2.id); boolean f1bigger = f1.size>=f2.size; if(!f1bigger){ UnionSetNode<T> tmp = f1; f1 = f2; f2 = tmp; } f2.parent = f1.id; f1.size += f2.size; } public void union2(int i, int j, List<UnionSetNode<T>> ll1, List<UnionSetNode<T>> ll2){ UnionSetNode<T> n1 = arr[i], n2 = arr[j]; n1.inus = true; n2.inus = true; boolean ll1bigger = ll1.size()>=ll2.size(); UnionSetNode<T> f = (ll1bigger)?ll1.get(ll1.size()-1):ll2.get(ll2.size()-1); int fid = f.id; int ffid = f.parent; if(ll1bigger){ for(UnionSetNode<T> node:ll1){ if(node.id!=fid&&node.parent!=fid&&node.parent!=-1){ arr[node.parent].size-=node.size; node.parent=fid; //f.size+=node.size; } } for(UnionSetNode<T> node:ll2){ if(node.id!=fid){ UnionSetNode<T> updatenode = node; int removesize = node.size; // if(node.parent!=-1){ // arr[node.parent].size-=node.size; // } while(updatenode.parent!=-1){ arr[updatenode.parent].size-=removesize; updatenode = arr[updatenode.parent]; } node.parent=fid; f.size+=node.size; } } } else { for(UnionSetNode<T> node:ll1){ if(node.id!=fid){ UnionSetNode<T> updatenode = node; int removesize = node.size; // if(node.parent!=-1){ // arr[node.parent].size-=node.size; // } while(updatenode.parent!=-1){ arr[updatenode.parent].size-=removesize; updatenode = arr[updatenode.parent]; } node.parent=fid; f.size+=node.size; } } for(UnionSetNode<T> node:ll2){ if(node.id!=fid&&node.parent!=fid&&node.parent!=-1){ arr[node.parent].size-=node.size; node.parent=fid; //f.size+=node.size; } } } f.parent=ffid; // f.size+=(ll1bigger)?ll2.size():ll1.size(); } } static class UnionSetNode<T>{ int id; int parent = -1; int size = 1; boolean inus = false; T thing; public UnionSetNode(int id, T thing) { this.id = id; this.thing = thing; } @Override public String toString() { return "UnionSetNode{" + "id=" + id + ", parent=" + parent + ", size=" + size + '}'; } } static class MyEdge{ int from, to, sum; boolean toIsWolf; public MyEdge(int from, int to, boolean toIsWolf) { this.from = from; this.to = to; this.sum = from+to; this.toIsWolf = toIsWolf; } } static class MyNode{ int id; boolean isWolf = false; boolean marker = false; boolean vis = false; MyEdge out = null; List<MyEdge> in; public MyNode(int id) { this.id = id; this.in = new LinkedList<>(); } @Override public String toString() { return "MyNode{" + "id=" + id + ", isWolf=" + isWolf + ", marker=" + marker + ", out=" + out + ", in=" + in.size() + '}'; } } // With credit to <NAME> static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException{ InputStream inputStream = System.in;//new FileInputStream("C:\\Users\\wavator\\Downloads\\test.in"); OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out) throws IOException { int totalnum = in.nextInt(); while(totalnum-->0){ int n = in.nextInt(); MyNode[] nodes = new MyNode[n]; for (int i = 0; i < n; i++) { nodes[i] = new MyNode(i); } MyEdge[] edges = new MyEdge[n]; for (int i = 0; i < n; i++) { int to = in.nextInt()-1; boolean toIsWolf = in.next().charAt(0)=='w'; MyEdge e = new MyEdge(i,to,toIsWolf); nodes[i].out = e; nodes[to].in.add(e); edges[i] = e; } // using union set UnionSet<MyNode> us = new UnionSet<>(n); for (int i = 0; i < n; i++) { us.arr[i] = new UnionSetNode<>(i,nodes[i]); } int count = 0; // first deal with villagers for(MyEdge e:edges){ if(!e.toIsWolf){ LinkedList<UnionSetNode<MyNode>> ll1 = us.findLink(e.from), ll2 = us.findLink(e.to); us.arr[e.from].inus = true; us.arr[e.to].inus = true; us.union2(e.from,e.to,ll1,ll2); } } // then find those wolves LinkedList<MyNode> q = new LinkedList<>(); for(MyEdge e:edges){ if(e.toIsWolf&&!nodes[e.to].marker){ LinkedList<UnionSetNode<MyNode>> ll1 = us.findLink(e.from), ll2 =us.findLink(e.to); if(ll1.getLast()==ll2.getLast()){ // from and to both inside union set // count++; if(!nodes[e.to].marker){ q.add(nodes[e.to]); nodes[e.to].marker = true; } } } } while(!q.isEmpty()){ MyNode curnode = q.pollFirst(); if(curnode.vis){ continue; } count++; curnode.vis = true; for(MyEdge e:curnode.in){ if(!e.toIsWolf){ if(!nodes[e.from].vis) q.add(nodes[e.from]); } } } out.println(count); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } // public boolean hasNext() { // try { // return reader.ready(); // } catch(IOException e) { // throw new RuntimeException(e); // } // } public boolean hasNext() { try { String string = reader.readLine(); if (string == null) { return false; } tokenizer = new StringTokenizer(string); return tokenizer.hasMoreTokens(); } catch(IOException e) { return false; } } public BigInteger nextBigInteger() { return new BigInteger(next()); } public BigDecimal nextBigDecinal() { return new BigDecimal(next()); } } }
14,377
0.410865
0.401475
489
28.398773
20.309629
108
false
false
0
0
0
0
0
0
0.494888
false
false
14
1fbfa7a65ea88c62c71da92a7f9e7d64fb91142b
29,171,417,893,240
dc62d8c0c6b5b264073dfd0ca6d952f0749f14d0
/src/com/cettco/buycar/activity/SelectCarColorActivity.java
3e5a4c3445dfe8844b8e9e21a2d0e6b0330a9d73
[]
no_license
jcheng77/andriod-auto2o
https://github.com/jcheng77/andriod-auto2o
b9bd2c578d2a94947e70e559eff46c8457499d1f
57aa60afd79312da17c158e64f333a210c1e25c9
refs/heads/master
2020-04-30T03:10:38.173000
2015-01-08T09:12:13
2015-01-08T09:12:13
22,744,393
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cettco.buycar.activity; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.cettco.buycar.R; import com.cettco.buycar.adapter.CarColorAdapter; import com.cettco.buycar.entity.CarColorEntity; import com.cettco.buycar.entity.CarColorListEntity; import com.cettco.buycar.utils.db.DatabaseHelperColor; import com.google.gson.Gson; import com.umeng.analytics.MobclickAgent; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; public class SelectCarColorActivity extends Activity { private List<CarColorEntity> colorList; private ListView listView; private CarColorAdapter mycarColorAdapter; private Intent intent; private String name; private String model_id; private TextView titleTextView; //private ArrayList<String> selected_colors; // private int tag; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_color); titleTextView = (TextView)findViewById(R.id.title_text); titleTextView.setText("选择颜色"); TextView titleTextView = (TextView) findViewById(R.id.title_text); intent = getIntent(); name = intent.getStringExtra("name"); model_id = intent.getStringExtra("model_id"); //selected_colors = intent.getStringArrayListExtra("selected_colors"); DatabaseHelperColor helperColor = DatabaseHelperColor.getHelper(this); try { colorList = helperColor.getDao().queryBuilder().where() .eq("model_id", model_id).query(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } titleTextView.setText(name); listView = (ListView) findViewById(R.id.select_color_listview); mycarColorAdapter = new CarColorAdapter(this, R.layout.item_color, colorList); listView.setAdapter(mycarColorAdapter); listView.setOnItemClickListener(listener); } protected OnItemClickListener listener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub // System.out.println("position:"+arg2); CheckBox checkBox = (CheckBox) arg1 .findViewById(R.id.car_color_checkBox); checkBox.toggle(); mycarColorAdapter.getIsSelected().put(arg2, checkBox.isChecked()); } }; @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); setResult(RESULT_CANCELED, intent); this.finish(); } public void exitClick(View view) { // intent.putExtra("result", position); ArrayList<String> colors = new ArrayList<String>(); Iterator<Integer> iter = mycarColorAdapter.getIsSelected().keySet() .iterator(); while (iter.hasNext()) { Integer key = iter.next(); Boolean value = mycarColorAdapter.getIsSelected().get(key); if (value == true) { colors.add(colorList.get(key).getId()); } } intent.putStringArrayListExtra("colors", colors); setResult(RESULT_OK, intent); this.finish(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); MobclickAgent.onPause(this); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); MobclickAgent.onResume(this); } }
UTF-8
Java
3,735
java
SelectCarColorActivity.java
Java
[]
null
[]
package com.cettco.buycar.activity; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.cettco.buycar.R; import com.cettco.buycar.adapter.CarColorAdapter; import com.cettco.buycar.entity.CarColorEntity; import com.cettco.buycar.entity.CarColorListEntity; import com.cettco.buycar.utils.db.DatabaseHelperColor; import com.google.gson.Gson; import com.umeng.analytics.MobclickAgent; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; public class SelectCarColorActivity extends Activity { private List<CarColorEntity> colorList; private ListView listView; private CarColorAdapter mycarColorAdapter; private Intent intent; private String name; private String model_id; private TextView titleTextView; //private ArrayList<String> selected_colors; // private int tag; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_color); titleTextView = (TextView)findViewById(R.id.title_text); titleTextView.setText("选择颜色"); TextView titleTextView = (TextView) findViewById(R.id.title_text); intent = getIntent(); name = intent.getStringExtra("name"); model_id = intent.getStringExtra("model_id"); //selected_colors = intent.getStringArrayListExtra("selected_colors"); DatabaseHelperColor helperColor = DatabaseHelperColor.getHelper(this); try { colorList = helperColor.getDao().queryBuilder().where() .eq("model_id", model_id).query(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } titleTextView.setText(name); listView = (ListView) findViewById(R.id.select_color_listview); mycarColorAdapter = new CarColorAdapter(this, R.layout.item_color, colorList); listView.setAdapter(mycarColorAdapter); listView.setOnItemClickListener(listener); } protected OnItemClickListener listener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub // System.out.println("position:"+arg2); CheckBox checkBox = (CheckBox) arg1 .findViewById(R.id.car_color_checkBox); checkBox.toggle(); mycarColorAdapter.getIsSelected().put(arg2, checkBox.isChecked()); } }; @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); setResult(RESULT_CANCELED, intent); this.finish(); } public void exitClick(View view) { // intent.putExtra("result", position); ArrayList<String> colors = new ArrayList<String>(); Iterator<Integer> iter = mycarColorAdapter.getIsSelected().keySet() .iterator(); while (iter.hasNext()) { Integer key = iter.next(); Boolean value = mycarColorAdapter.getIsSelected().get(key); if (value == true) { colors.add(colorList.get(key).getId()); } } intent.putStringArrayListExtra("colors", colors); setResult(RESULT_OK, intent); this.finish(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); MobclickAgent.onPause(this); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); MobclickAgent.onResume(this); } }
3,735
0.7282
0.726053
119
29.319328
19.930523
72
false
false
0
0
0
0
0
0
2.07563
false
false
14
26b89093ba4d56e8ee7803195bf389adaee79041
3,745,211,489,602
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Entertainment/vine_source/src/co/vine/android/SettingsFragment$6.java
9734fac48dbc17e8e65750388ede5502f0424286
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
2018-03-23T04:15:18.480000
2015-12-19T01:29:58
2015-12-19T01:29:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package co.vine.android; import android.view.View; import android.widget.AdapterView; // Referenced classes of package co.vine.android: // SettingsFragment class this._cls0 implements android.widget.electedListener { final SettingsFragment this$0; public void onItemSelected(AdapterView adapterview, View view, int i, long l) { SettingsFragment.access$1202(SettingsFragment.this, SettingsFragment.access$1300(SettingsFragment.this).getEditionCode(i)); } public void onNothingSelected(AdapterView adapterview) { } itionsSpinnerAdapter() { this$0 = SettingsFragment.this; super(); } }
UTF-8
Java
844
java
SettingsFragment$6.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9997097849845886, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package co.vine.android; import android.view.View; import android.widget.AdapterView; // Referenced classes of package co.vine.android: // SettingsFragment class this._cls0 implements android.widget.electedListener { final SettingsFragment this$0; public void onItemSelected(AdapterView adapterview, View view, int i, long l) { SettingsFragment.access$1202(SettingsFragment.this, SettingsFragment.access$1300(SettingsFragment.this).getEditionCode(i)); } public void onNothingSelected(AdapterView adapterview) { } itionsSpinnerAdapter() { this$0 = SettingsFragment.this; super(); } }
834
0.71564
0.694313
33
24.575758
29.465984
131
false
false
0
0
0
0
0
0
0.333333
false
false
14
1c7894db5eb3754c9d9a1540cb78a43e083c2d95
7,078,106,128,785
35866b73337b94e8adbdf13c19415ec8f5f1cc63
/JAVA-SE Applications/annotation/AnnotationTest.java
d9a45d42f6e0c7d7e579d31af79ffc5bf4ebb74d
[]
no_license
debiprasadmishra50/All-Core-Java-Applications---JAVA-SE
https://github.com/debiprasadmishra50/All-Core-Java-Applications---JAVA-SE
fe7080cbf3c21e18bc02b56f5adbccd98d4599ae
c8cbcac0257357035122e91575772ecb84545236
refs/heads/master
2022-11-11T20:56:05.011000
2020-06-28T08:10:17
2020-06-28T08:10:17
275,537,700
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package annotation; public class AnnotationTest { @MyAnnotation public void fun() { } }
UTF-8
Java
97
java
AnnotationTest.java
Java
[]
null
[]
package annotation; public class AnnotationTest { @MyAnnotation public void fun() { } }
97
0.690722
0.690722
10
8.7
9.602604
28
false
false
0
0
0
0
0
0
0.7
false
false
14
006fd0177c80f22328f6538a182626e7539cf20c
33,174,327,421,937
2b4a3f102d31948d8fb12f495d71782666a284f8
/Pony Game/src/characters/PinkiePie.java
0a8acbacb9711f024584352e5883937109bf86c5
[]
no_license
churgethoth/HorseHelper
https://github.com/churgethoth/HorseHelper
602c0fcb7051dd787e11a1295d64931387220d54
0b5e54623736e3521047ef610c65aaf1bcdd702d
refs/heads/master
2019-01-21T23:40:28.543000
2013-08-04T14:32:14
2013-08-04T14:32:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package characters; import abilities.Ability.AbilityType; public class PinkiePie implements Workable { public AbilityType getPrimaryStat() { return AbilityType.CHARISMA; } public void randomActivity() { } public void staminaActivity() { } public void agilityActivity() { } public void logicActivity() { } public void creativityActivity() { } public void wisdomActivity() { } public void charismaActivity() { } public void socialActivity() { } }
UTF-8
Java
522
java
PinkiePie.java
Java
[]
null
[]
package characters; import abilities.Ability.AbilityType; public class PinkiePie implements Workable { public AbilityType getPrimaryStat() { return AbilityType.CHARISMA; } public void randomActivity() { } public void staminaActivity() { } public void agilityActivity() { } public void logicActivity() { } public void creativityActivity() { } public void wisdomActivity() { } public void charismaActivity() { } public void socialActivity() { } }
522
0.657088
0.657088
40
11.05
15.254426
44
false
false
0
0
0
0
0
0
0.575
false
false
14
15c9f0e0fa922479a07df29c87207d667b473439
19,301,583,036,359
3b2c1d9e4735e323a9b53671a5c86901603976a9
/InsertionSortList.java
cc8e577a8f4589aeb9fc5b4a68751452e2a7d870
[]
no_license
huMonster/leetcode-Java
https://github.com/huMonster/leetcode-Java
d053bd0b8a94689ee95b516d8596686041032aa1
714f70ca040cdac44a5dd6423e2e6be9d42edf74
refs/heads/master
2023-04-19T03:12:29.374000
2021-05-08T09:03:54
2021-05-08T09:03:54
290,502,653
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.algorithm.leetcode; import com.test.utils.ListNode; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @Description 147 InsertionSortList 对链表进行插入排序 * @Author Monster * @Date 2020/9/27 11:23 * @Version 1.0 */ public class InsertionSortList { /** * 遍历链表,逐一对比 * * @param head * @return */ public ListNode insertionSortList(ListNode head) { if(head == null) return null; // 设置虚拟头节点 ListNode dummy = new ListNode(0); dummy.next = head; // 初始时head链表的第一个节点为前置节点pre ListNode pre = head; // 第二个节点为当前节点cur ListNode cur = pre.next; while(cur != null){ if(cur.val < pre.val){ // temp指向虚拟头节点, ListNode temp = dummy; // 找到比当前节点大的前一个节点 for(;cur.val > temp.next.val;temp = temp.next); // 交换 pre.next = cur.next; // cur.next不能直接指向pre,否则会丢失temp到pre之间的节点 cur.next = temp.next; temp.next = cur; // 将前置节点的下一节点作为当前节点继续遍历 cur = pre.next; } else { pre = pre.next; cur = cur.next; } } return dummy.next; } /** * 将链表转换为List,排序后,又转换成链表 * * @param head * @return */ public ListNode insertionSortList2(ListNode head) { List<Integer> record = new ArrayList<>(); ListNode cur = head; while (cur != null){ record.add(cur.val); cur = cur.next; } Collections.sort(record); ListNode resNode = head; for (int i = 0; i < record.size(); i++) { resNode.val = record.get(i); resNode = resNode.next; } return head; } public static void main(String[] args) { int[] arr = {4, 2, 1, 3}; ListNode node = ListNode.createNode(arr); ListNode.printNode(new InsertionSortList().insertionSortList2(node)); } }
UTF-8
Java
2,417
java
InsertionSortList.java
Java
[ { "context": "iption 147 InsertionSortList 对链表进行插入排序\r\n * @Author Monster\r\n * @Date 2020/9/27 11:23\r\n * @Version 1.0\r\n ", "end": 224, "score": 0.7970702052116394, "start": 221, "tag": "NAME", "value": "Mon" }, { "context": "on 147 InsertionSortList 对链表进行插入排序\r\n * @Author Monster\r\n * @Date 2020/9/27 11:23\r\n * @Version 1.0\r\n */\r\n", "end": 228, "score": 0.5289969444274902, "start": 224, "tag": "USERNAME", "value": "ster" } ]
null
[]
package com.algorithm.leetcode; import com.test.utils.ListNode; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @Description 147 InsertionSortList 对链表进行插入排序 * @Author Monster * @Date 2020/9/27 11:23 * @Version 1.0 */ public class InsertionSortList { /** * 遍历链表,逐一对比 * * @param head * @return */ public ListNode insertionSortList(ListNode head) { if(head == null) return null; // 设置虚拟头节点 ListNode dummy = new ListNode(0); dummy.next = head; // 初始时head链表的第一个节点为前置节点pre ListNode pre = head; // 第二个节点为当前节点cur ListNode cur = pre.next; while(cur != null){ if(cur.val < pre.val){ // temp指向虚拟头节点, ListNode temp = dummy; // 找到比当前节点大的前一个节点 for(;cur.val > temp.next.val;temp = temp.next); // 交换 pre.next = cur.next; // cur.next不能直接指向pre,否则会丢失temp到pre之间的节点 cur.next = temp.next; temp.next = cur; // 将前置节点的下一节点作为当前节点继续遍历 cur = pre.next; } else { pre = pre.next; cur = cur.next; } } return dummy.next; } /** * 将链表转换为List,排序后,又转换成链表 * * @param head * @return */ public ListNode insertionSortList2(ListNode head) { List<Integer> record = new ArrayList<>(); ListNode cur = head; while (cur != null){ record.add(cur.val); cur = cur.next; } Collections.sort(record); ListNode resNode = head; for (int i = 0; i < record.size(); i++) { resNode.val = record.get(i); resNode = resNode.next; } return head; } public static void main(String[] args) { int[] arr = {4, 2, 1, 3}; ListNode node = ListNode.createNode(arr); ListNode.printNode(new InsertionSortList().insertionSortList2(node)); } }
2,417
0.494673
0.483557
81
24.654322
16.591059
77
false
false
0
0
0
0
0
0
0.481481
false
false
14
fcc89d225b57a4fa3b8327ad224ad28b7cda067b
30,133,490,592,024
5636dfdf491da08874b93418726fb1a2176e298b
/codebase/l09-architektur/02-schichten/src/main/java/layers/business/CustomerService.java
8262ad4493062c36ac737d68a254253c3b05ff1b
[]
no_license
SimonGrad/Vorlesung-GUI-2021
https://github.com/SimonGrad/Vorlesung-GUI-2021
f0cc8f25e3eb8fd65db3887acb2f25e25971f985
b768e1bd42d5e859cab2fe6aac239cd62806cbce
refs/heads/master
2023-05-22T17:17:06.411000
2021-06-16T16:54:48
2021-06-16T16:54:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package layers.business; public interface CustomerService { }
UTF-8
Java
63
java
CustomerService.java
Java
[]
null
[]
package layers.business; public interface CustomerService { }
63
0.809524
0.809524
4
14.75
14.686303
34
false
false
0
0
0
0
0
0
0.25
false
false
14
d4cda0377a959ba50ec58516f5003afb306e4946
7,533,372,673,271
eecd834c02459d264bd96c3003fe492c0c155d1b
/app/src/main/java/com/rigelr/watchedmovie/AboutActivity.java
6c2dc3131d56f95923535b24dad6bd77df115091
[]
no_license
rigelr/movie74
https://github.com/rigelr/movie74
66bd03bb62d89025b7f70a0db83e57cca56c374f
e924759667d3b9eb303d709a48e59a50ac7ac6da
refs/heads/master
2022-04-13T09:10:26.562000
2020-04-08T14:02:37
2020-04-08T14:02:37
249,360,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rigelr.watchedmovie; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class AboutActivity extends AppCompatActivity { String number = "08159324415" ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); } public void handleRequest(View view) { Intent request = new Intent(this, RequestActivity.class); startActivity(request); } public void handleSaran(View view) { Intent intent = new Intent(Intent.ACTION_SENDTO); // This ensures only SMS apps respond intent.setData(Uri.parse("smsto:"+number)); intent.putExtra("sms_body", "Hello saya mau kasih saran buat 74 movie tentang"); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } // Intent call = new Intent(Intent. ACTION_DIAL); // call.setData(Uri. fromParts("tel",number,null)); // startActivity(call); } }
UTF-8
Java
1,297
java
AboutActivity.java
Java
[]
null
[]
package com.rigelr.watchedmovie; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class AboutActivity extends AppCompatActivity { String number = "08159324415" ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); } public void handleRequest(View view) { Intent request = new Intent(this, RequestActivity.class); startActivity(request); } public void handleSaran(View view) { Intent intent = new Intent(Intent.ACTION_SENDTO); // This ensures only SMS apps respond intent.setData(Uri.parse("smsto:"+number)); intent.putExtra("sms_body", "Hello saya mau kasih saran buat 74 movie tentang"); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } // Intent call = new Intent(Intent. ACTION_DIAL); // call.setData(Uri. fromParts("tel",number,null)); // startActivity(call); } }
1,297
0.696993
0.68697
41
30.634146
22.731472
88
false
false
0
0
0
0
0
0
0.634146
false
false
14
22d2857161d33ebffe9e8cd45713cf1b2d246b28
7,533,372,670,021
5f239db0a528f79c97bcb02a112891d27299327b
/Automation/src/Monu/printLinks.java
1e6b640248fe9aadb43e2ffa18cbbd2d000d3d0c
[]
no_license
Monishamercy7/Automation
https://github.com/Monishamercy7/Automation
d5a839baff0c531c7aeb4d8014f5c873c764dcbe
d476242982427e6c5fd3226522e7cfbcc7f2d0c8
refs/heads/master
2023-05-06T15:24:25.638000
2021-05-29T14:11:15
2021-05-29T14:11:15
371,989,473
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Monu; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class printLinks { static { System.setProperty("webdriver.gecko.driver", "C:\\Users\\Monisha\\eclipse-workspace\\Automation\\Drivers1\\geckodriver.exe"); System.setProperty("webdriver.chrome.driver", "C:\\Users\\Monisha\\eclipse-workspace\\Automation\\Drivers1\\chromedriver.exe"); } public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get("https://www.selenium.dev/downloads/"); List<WebElement> allLinks = driver.findElements(By.xpath("//a")); int count = allLinks.size(); System.out.println(count); for(int i=0; i<count; i++) { WebElement link = allLinks.get(i); String text = link.getText(); System.out.println(text); } Thread.sleep(1000); driver.close(); } }
UTF-8
Java
978
java
printLinks.java
Java
[]
null
[]
package Monu; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class printLinks { static { System.setProperty("webdriver.gecko.driver", "C:\\Users\\Monisha\\eclipse-workspace\\Automation\\Drivers1\\geckodriver.exe"); System.setProperty("webdriver.chrome.driver", "C:\\Users\\Monisha\\eclipse-workspace\\Automation\\Drivers1\\chromedriver.exe"); } public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get("https://www.selenium.dev/downloads/"); List<WebElement> allLinks = driver.findElements(By.xpath("//a")); int count = allLinks.size(); System.out.println(count); for(int i=0; i<count; i++) { WebElement link = allLinks.get(i); String text = link.getText(); System.out.println(text); } Thread.sleep(1000); driver.close(); } }
978
0.723926
0.716769
33
28.636364
31.731657
129
false
false
0
0
0
0
0
0
1.939394
false
false
14
b6e4256a2b92b1c35f72939a330535985ea49d69
7,533,372,672,733
a901abdca092650e0eb277f04c988200796b1d7d
/aart-main/aart-web/src/main/java/edu/ku/cete/model/test/TaskVariantContentFrameworkDetailDao.java
4ff31507dbe2a5794a3ea156e7790da366d992a4
[]
no_license
krishnamohankaruturi/secret
https://github.com/krishnamohankaruturi/secret
5acafbde49b9fa9e24f89534d14e7b01f863f775
4da83d113d3620d4c2c84002fecbe4bdd759c1a2
refs/heads/master
2022-03-24T22:09:41.325000
2019-11-15T12:14:07
2019-11-15T12:14:07
219,771,956
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ku.cete.model.test; import edu.ku.cete.domain.test.TaskVariantContentFrameworkDetail; import edu.ku.cete.domain.test.TaskVariantContentFrameworkDetailExample; import edu.ku.cete.domain.test.TaskVariantContentFrameworkDetailKey; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TaskVariantContentFrameworkDetailDao { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int countByExample(TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int deleteByExample(TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int deleteByPrimaryKey(TaskVariantContentFrameworkDetailKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int insert(TaskVariantContentFrameworkDetail record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int insertSelective(TaskVariantContentFrameworkDetail record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ List<TaskVariantContentFrameworkDetail> selectByExample(TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ TaskVariantContentFrameworkDetail selectByPrimaryKey(TaskVariantContentFrameworkDetailKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByExampleSelective(@Param("record") TaskVariantContentFrameworkDetail record, @Param("example") TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByExample(@Param("record") TaskVariantContentFrameworkDetail record, @Param("example") TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByPrimaryKeySelective(TaskVariantContentFrameworkDetail record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByPrimaryKey(TaskVariantContentFrameworkDetail record); /** * @param taskVariantContentFrameworkDetailExample {@link TaskVariantContentFrameworkDetailExample} * @return {@link List} */ List<TaskVariantContentFrameworkDetail> selectExtendedByExample( TaskVariantContentFrameworkDetailExample taskVariantContentFrameworkDetailExample); }
UTF-8
Java
4,140
java
TaskVariantContentFrameworkDetailDao.java
Java
[]
null
[]
package edu.ku.cete.model.test; import edu.ku.cete.domain.test.TaskVariantContentFrameworkDetail; import edu.ku.cete.domain.test.TaskVariantContentFrameworkDetailExample; import edu.ku.cete.domain.test.TaskVariantContentFrameworkDetailKey; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TaskVariantContentFrameworkDetailDao { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int countByExample(TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int deleteByExample(TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int deleteByPrimaryKey(TaskVariantContentFrameworkDetailKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int insert(TaskVariantContentFrameworkDetail record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int insertSelective(TaskVariantContentFrameworkDetail record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ List<TaskVariantContentFrameworkDetail> selectByExample(TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ TaskVariantContentFrameworkDetail selectByPrimaryKey(TaskVariantContentFrameworkDetailKey key); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByExampleSelective(@Param("record") TaskVariantContentFrameworkDetail record, @Param("example") TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByExample(@Param("record") TaskVariantContentFrameworkDetail record, @Param("example") TaskVariantContentFrameworkDetailExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByPrimaryKeySelective(TaskVariantContentFrameworkDetail record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table public.taskvariantcontentframeworkdetail * * @mbggenerated Thu Oct 25 19:34:56 CDT 2012 */ int updateByPrimaryKey(TaskVariantContentFrameworkDetail record); /** * @param taskVariantContentFrameworkDetailExample {@link TaskVariantContentFrameworkDetailExample} * @return {@link List} */ List<TaskVariantContentFrameworkDetail> selectExtendedByExample( TaskVariantContentFrameworkDetailExample taskVariantContentFrameworkDetailExample); }
4,140
0.747343
0.715459
104
38.817307
37.534794
160
false
false
0
0
0
0
0
0
0.221154
false
false
14
a5c5a7cb20a94c051a18df10e8e97a311e9f1004
21,483,426,483,239
b765ff986f0cd8ae206fde13105321838e246a0a
/Inspect/app/src/main/java/com/growingio_rewriter/d/a/d/B.java
8286d630a1d3cb5c928ca11f306c9a27f39c5bc0
[]
no_license
piece-the-world/inspect
https://github.com/piece-the-world/inspect
fe3036409b20ba66343815c3c5c9f4b0b768c355
a660dd65d7f40501d95429f8d2b126bd8f59b8db
refs/heads/master
2020-11-29T15:28:39.406000
2016-10-09T06:24:32
2016-10-09T06:24:32
66,539,462
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Decompiled with CFR 0_115. */ package com.growingio.d.a.d; import com.growingio.d.a.d.b; import com.growingio.d.a.v; public class B extends b { public int h; public v i; public B(int n2, v v2, String string) { this(327680, n2, v2, string); if (this.getClass() != B.class) { throw new IllegalStateException(); } } public B(int n2, int n3, v v2, String string) { super(n2, string); this.h = n3; this.i = v2; } }
UTF-8
Java
506
java
B.java
Java
[]
null
[]
/* * Decompiled with CFR 0_115. */ package com.growingio.d.a.d; import com.growingio.d.a.d.b; import com.growingio.d.a.v; public class B extends b { public int h; public v i; public B(int n2, v v2, String string) { this(327680, n2, v2, string); if (this.getClass() != B.class) { throw new IllegalStateException(); } } public B(int n2, int n3, v v2, String string) { super(n2, string); this.h = n3; this.i = v2; } }
506
0.551383
0.511858
26
18.423077
15.736222
51
false
false
0
0
0
0
0
0
0.730769
false
false
14
6d2af43e5debb8205f3381ea8bff0d7cdf876e2a
22,995,254,952,951
0c1b67ef108ea4f221038293859f06679492e002
/SecondLectureEncapsulation/FirstAndReserveTeam/Person.java
004ef5d4a6a958284db0d48d25c8ca153b2814d2
[]
no_license
krasimirvasilev1/Java-8-OOPBasic
https://github.com/krasimirvasilev1/Java-8-OOPBasic
7417452a16ba34cff8cad8b82cf8335115a20c49
d15298b8d205b07eab65e7efce89fe1e6c7e7a0a
refs/heads/master
2021-05-07T01:31:20.408000
2018-01-06T17:29:37
2018-01-06T17:29:37
110,358,140
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package SecondLectureEncapsulation.FirstAndReserveTeam; public class Person { private String firstName; private String secondName; private int age; private double salary; public int getAge() { return age; } public Person(String firstName, String secondName, int age, double salary) { this.firstName = firstName; this.secondName = secondName; this.age = age; this.salary = salary; } }
UTF-8
Java
459
java
Person.java
Java
[ { "context": " return age;\n }\n\n public Person(String firstName, String secondName, int age, double salary) {\n ", "end": 276, "score": 0.5268657207489014, "start": 267, "tag": "NAME", "value": "firstName" }, { "context": "int age, double salary) {\n this.firstName = firstName;\n this.secondName = secondName;\n th", "end": 357, "score": 0.9834656715393066, "start": 348, "tag": "NAME", "value": "firstName" }, { "context": "s.firstName = firstName;\n this.secondName = secondName;\n this.age = age;\n this.salary ", "end": 391, "score": 0.8977556228637695, "start": 385, "tag": "NAME", "value": "second" } ]
null
[]
package SecondLectureEncapsulation.FirstAndReserveTeam; public class Person { private String firstName; private String secondName; private int age; private double salary; public int getAge() { return age; } public Person(String firstName, String secondName, int age, double salary) { this.firstName = firstName; this.secondName = secondName; this.age = age; this.salary = salary; } }
459
0.660131
0.660131
19
23.157894
19.860733
80
false
false
0
0
0
0
0
0
0.684211
false
false
14
81bc404fa7567834f9a9700f969d7163f538cd6b
11,269,994,225,163
84125a032c2b2e150f62616c15f0089016aca05d
/src/com/prep2020/medium/Problem454.java
d32755d8ccf48ba6bd055d8a29b0ed21994c9747
[]
no_license
achowdhury80/leetcode
https://github.com/achowdhury80/leetcode
c577acc1bc8bce3da0c99e12d6d447c74fbed5c3
5ec97794cc5617cd7f35bafb058ada502ee7d802
refs/heads/master
2023-02-06T01:08:49.888000
2023-01-22T03:23:37
2023-01-22T03:23:37
115,574,715
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.prep2020.medium; import java.util.HashMap; import java.util.Map; public class Problem454 { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { if(A == null || A.length == 0 || B == null || B.length == 0 || C == null || C.length == 0 || D == null || D.length == 0) return 0; int n = A.length; Map<Long, Integer> abSum = new HashMap<>(); Map<Long, Integer> cdSum = new HashMap<>(); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { long sum = A[i] + B[j]; abSum.put(sum, abSum.getOrDefault(sum, 0) + 1); } for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { long sum = C[i] + D[j]; cdSum.put(sum, cdSum.getOrDefault(sum, 0) + 1); } int result = 0; for(long key : abSum.keySet()){ if(cdSum.containsKey(0 - key)){ result += abSum.get(key) * cdSum.get(0 - key); } } return result; } }
UTF-8
Java
965
java
Problem454.java
Java
[]
null
[]
package com.prep2020.medium; import java.util.HashMap; import java.util.Map; public class Problem454 { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { if(A == null || A.length == 0 || B == null || B.length == 0 || C == null || C.length == 0 || D == null || D.length == 0) return 0; int n = A.length; Map<Long, Integer> abSum = new HashMap<>(); Map<Long, Integer> cdSum = new HashMap<>(); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { long sum = A[i] + B[j]; abSum.put(sum, abSum.getOrDefault(sum, 0) + 1); } for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) { long sum = C[i] + D[j]; cdSum.put(sum, cdSum.getOrDefault(sum, 0) + 1); } int result = 0; for(long key : abSum.keySet()){ if(cdSum.containsKey(0 - key)){ result += abSum.get(key) * cdSum.get(0 - key); } } return result; } }
965
0.493264
0.46943
32
29.15625
22.649654
107
false
false
0
0
0
0
0
0
2.15625
false
false
14
ec1bcde89068efddaa850107f6d9a66ab7dd3845
16,063,177,724,564
f25d2c59b30e103f1b9dc9b569c2c64cad3e2e9d
/src/test/java/de/skuzzle/enforcer/restrictimports/formatting/MatchFormatterImplTest.java
90c0b23d9da31f54f4c45dc592e9aa848abf689e
[ "MIT" ]
permissive
schillingr/restrict-imports-enforcer-rule
https://github.com/schillingr/restrict-imports-enforcer-rule
59f578480bf46c342ca157defdf8b9ee933b3477
9e33071a9b06bb7079076bbddddcec163697e0a7
refs/heads/master
2020-04-10T19:33:49.207000
2018-11-08T16:40:18
2018-11-08T16:40:18
161,239,666
0
0
MIT
true
2018-12-10T21:38:14
2018-12-10T21:38:13
2018-12-09T13:36:24
2018-11-08T16:40:21
235
0
0
0
null
false
null
package de.skuzzle.enforcer.restrictimports.formatting; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.net.URL; import java.nio.file.Path; import java.util.Collection; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import de.skuzzle.enforcer.restrictimports.analyze.AnalyzeResult; import de.skuzzle.enforcer.restrictimports.analyze.BannedImportGroup; import de.skuzzle.enforcer.restrictimports.analyze.MatchedFile; import de.skuzzle.enforcer.restrictimports.analyze.PackagePattern; public class MatchFormatterImplTest { private final MatchFormatter subject = MatchFormatter.getInstance(); @Test public void testFormatWithReason() throws Exception { final BannedImportGroup group = BannedImportGroup.builder() .withBasePackages("**") .withBannedImports("java.util.*") .withReason("Some reason") .build(); final URL resourceDirUrl = getClass().getResource("/SampleJavaFile.java"); final File resourceDirFile = new File(resourceDirUrl.toURI()); final Path root = resourceDirFile.toPath().getParent(); final Path sourceFile = root.resolve("SampleJavaFile.java"); final Collection<Path> roots = ImmutableList.of(root); final AnalyzeResult analyzeResult = AnalyzeResult.builder() .withMatches(MatchedFile.forSourceFile(sourceFile) .matchedBy(group) .withMatchAt(3, "java.util.ArrayList", PackagePattern.parse("java.util.*"))) .build(); final String formatted = subject.formatMatches(roots, analyzeResult); assertThat(formatted).isEqualTo("\nBanned imports detected:\n" + "Reason: Some reason\n" + "\tin file: SampleJavaFile.java\n" + "\t\tjava.util.ArrayList (Line: 3, Matched by: java.util.*)\n"); } }
UTF-8
Java
2,001
java
MatchFormatterImplTest.java
Java
[]
null
[]
package de.skuzzle.enforcer.restrictimports.formatting; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.net.URL; import java.nio.file.Path; import java.util.Collection; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import de.skuzzle.enforcer.restrictimports.analyze.AnalyzeResult; import de.skuzzle.enforcer.restrictimports.analyze.BannedImportGroup; import de.skuzzle.enforcer.restrictimports.analyze.MatchedFile; import de.skuzzle.enforcer.restrictimports.analyze.PackagePattern; public class MatchFormatterImplTest { private final MatchFormatter subject = MatchFormatter.getInstance(); @Test public void testFormatWithReason() throws Exception { final BannedImportGroup group = BannedImportGroup.builder() .withBasePackages("**") .withBannedImports("java.util.*") .withReason("Some reason") .build(); final URL resourceDirUrl = getClass().getResource("/SampleJavaFile.java"); final File resourceDirFile = new File(resourceDirUrl.toURI()); final Path root = resourceDirFile.toPath().getParent(); final Path sourceFile = root.resolve("SampleJavaFile.java"); final Collection<Path> roots = ImmutableList.of(root); final AnalyzeResult analyzeResult = AnalyzeResult.builder() .withMatches(MatchedFile.forSourceFile(sourceFile) .matchedBy(group) .withMatchAt(3, "java.util.ArrayList", PackagePattern.parse("java.util.*"))) .build(); final String formatted = subject.formatMatches(roots, analyzeResult); assertThat(formatted).isEqualTo("\nBanned imports detected:\n" + "Reason: Some reason\n" + "\tin file: SampleJavaFile.java\n" + "\t\tjava.util.ArrayList (Line: 3, Matched by: java.util.*)\n"); } }
2,001
0.671664
0.670665
51
38.235294
28.379494
82
false
false
0
0
0
0
0
0
0.509804
false
false
14
b0e5f9bea7c7c05742ec2dfd80fd0ea77ecee1b3
22,754,736,760,573
129046c5b5dd17325ef12ae86f52f5984f782007
/src/models/strStatusWork.java
21d6212a7b8583548ee29f1b0c70f5fa85df281e
[]
no_license
pokedotdev/work-to-do
https://github.com/pokedotdev/work-to-do
77442cf8be87824b96e0f6a6bed6d6a97db8e699
dd6b873c6f434b6f54e9861223e08f7709f6737b
refs/heads/master
2022-04-27T22:45:42.852000
2019-05-21T23:01:09
2019-05-21T23:01:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; import exceptions.Validations; import exceptions.expEmptyString; public class strStatusWork { private int id; private String status; public strStatusWork(int id, String status) throws expEmptyString { new Validations().emptyString(status); this.id = id; this.status = status; } public int getId() { return id; } public String getStatus() { return status; } public void setStatus(String status) throws expEmptyString { new Validations().emptyString(status); this.status = status; } }
UTF-8
Java
606
java
strStatusWork.java
Java
[]
null
[]
package models; import exceptions.Validations; import exceptions.expEmptyString; public class strStatusWork { private int id; private String status; public strStatusWork(int id, String status) throws expEmptyString { new Validations().emptyString(status); this.id = id; this.status = status; } public int getId() { return id; } public String getStatus() { return status; } public void setStatus(String status) throws expEmptyString { new Validations().emptyString(status); this.status = status; } }
606
0.641914
0.641914
29
19.896551
19.035982
71
false
false
0
0
0
0
0
0
0.448276
false
false
14
24a4551ddd9c1f78cbc1286f86d7636539e5e672
5,497,558,181,020
30e3c91f23aaa6127ee3e520becc443701e18faa
/sources/com/bytedance/android/livesdkapi/depend/p438f/C8630a.java
e6ab7231924982be41bb98e74aba2e0107817d7e
[]
no_license
jakesyl/tishtosh_source
https://github.com/jakesyl/tishtosh_source
521d4ab2bc28325519cf84422cce9c5709339b1f
c88d8f6fc6147fc08dfda6bd6d8540156278fa5d
refs/heads/master
2022-09-10T17:19:16.637000
2020-05-25T06:06:31
2020-05-25T06:06:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bytedance.android.livesdkapi.depend.p438f; import com.p683ss.android.ugc.aweme.experiment.ProfileUiInitOptimizeEnterThreshold; import java.util.Map; /* renamed from: com.bytedance.android.livesdkapi.depend.f.a */ public class C8630a<T> { /* renamed from: a */ public String f23612a; /* renamed from: b */ public String f23613b; /* renamed from: c */ public T f23614c; /* renamed from: d */ public Class<T> f23615d; /* renamed from: a */ public T mo10345a() { return C8631b.m17033a(this); } /* renamed from: a */ public void mo10346a(T t) { String str = this.f23613b; if (t == null) { C8631b.m17032a(str).edit().remove(this.f23612a).apply(); } else if (this.f23615d == Boolean.class) { C8631b.m17032a(str).edit().putBoolean(this.f23612a, ((Boolean) t).booleanValue()).apply(); } else if (this.f23615d == Integer.class) { C8631b.m17032a(str).edit().putInt(this.f23612a, ((Integer) t).intValue()).apply(); } else if (this.f23615d == Float.class) { C8631b.m17032a(str).edit().putFloat(this.f23612a, ((Float) t).floatValue()).apply(); } else if (this.f23615d == Long.class) { C8631b.m17032a(str).edit().putLong(this.f23612a, ((Long) t).longValue()).apply(); } else if (this.f23615d == Double.class) { C8631b.m17032a(str).edit().putString(this.f23612a, String.valueOf(((Double) t).doubleValue())).apply(); } else if (this.f23615d == String.class) { C8631b.m17032a(str).edit().putString(this.f23612a, (String) t).apply(); } else { Map map = (Map) C8631b.f23616a.get(str); if (map != null) { map.put(this.f23612a, t); } C8631b.m17032a(str).edit().putString(this.f23612a, C8631b.f23617b.mo34889b(t)).apply(); } } public C8630a(String str, T t) { this("tt_live_sdk", str, t.getClass(), t); } public C8630a(String str, String str2, T t) { this(str, str2, t.getClass(), t); } private C8630a(String str, String str2, Class<T> cls, T t) { this.f23613b = str; this.f23612a = str2; this.f23614c = t; this.f23615d = cls; if (t == null) { if (this.f23615d == Integer.class || this.f23615d == Short.class) { this.f23614c = Integer.valueOf(0); } else if (this.f23615d == Long.class) { this.f23614c = Long.valueOf(0); } else if (this.f23615d == Double.class) { this.f23614c = Double.valueOf(ProfileUiInitOptimizeEnterThreshold.DEFAULT); } else if (this.f23615d == Float.class) { this.f23614c = Float.valueOf(0.0f); } else if (this.f23615d == Boolean.class) { this.f23614c = Boolean.valueOf(false); } } } }
UTF-8
Java
2,940
java
C8630a.java
Java
[]
null
[]
package com.bytedance.android.livesdkapi.depend.p438f; import com.p683ss.android.ugc.aweme.experiment.ProfileUiInitOptimizeEnterThreshold; import java.util.Map; /* renamed from: com.bytedance.android.livesdkapi.depend.f.a */ public class C8630a<T> { /* renamed from: a */ public String f23612a; /* renamed from: b */ public String f23613b; /* renamed from: c */ public T f23614c; /* renamed from: d */ public Class<T> f23615d; /* renamed from: a */ public T mo10345a() { return C8631b.m17033a(this); } /* renamed from: a */ public void mo10346a(T t) { String str = this.f23613b; if (t == null) { C8631b.m17032a(str).edit().remove(this.f23612a).apply(); } else if (this.f23615d == Boolean.class) { C8631b.m17032a(str).edit().putBoolean(this.f23612a, ((Boolean) t).booleanValue()).apply(); } else if (this.f23615d == Integer.class) { C8631b.m17032a(str).edit().putInt(this.f23612a, ((Integer) t).intValue()).apply(); } else if (this.f23615d == Float.class) { C8631b.m17032a(str).edit().putFloat(this.f23612a, ((Float) t).floatValue()).apply(); } else if (this.f23615d == Long.class) { C8631b.m17032a(str).edit().putLong(this.f23612a, ((Long) t).longValue()).apply(); } else if (this.f23615d == Double.class) { C8631b.m17032a(str).edit().putString(this.f23612a, String.valueOf(((Double) t).doubleValue())).apply(); } else if (this.f23615d == String.class) { C8631b.m17032a(str).edit().putString(this.f23612a, (String) t).apply(); } else { Map map = (Map) C8631b.f23616a.get(str); if (map != null) { map.put(this.f23612a, t); } C8631b.m17032a(str).edit().putString(this.f23612a, C8631b.f23617b.mo34889b(t)).apply(); } } public C8630a(String str, T t) { this("tt_live_sdk", str, t.getClass(), t); } public C8630a(String str, String str2, T t) { this(str, str2, t.getClass(), t); } private C8630a(String str, String str2, Class<T> cls, T t) { this.f23613b = str; this.f23612a = str2; this.f23614c = t; this.f23615d = cls; if (t == null) { if (this.f23615d == Integer.class || this.f23615d == Short.class) { this.f23614c = Integer.valueOf(0); } else if (this.f23615d == Long.class) { this.f23614c = Long.valueOf(0); } else if (this.f23615d == Double.class) { this.f23614c = Double.valueOf(ProfileUiInitOptimizeEnterThreshold.DEFAULT); } else if (this.f23615d == Float.class) { this.f23614c = Float.valueOf(0.0f); } else if (this.f23615d == Boolean.class) { this.f23614c = Boolean.valueOf(false); } } } }
2,940
0.568707
0.460204
79
36.215191
29.004004
115
false
false
0
0
0
0
0
0
0.658228
false
false
14